@synap-core/eve 0.1.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.
Files changed (64) hide show
  1. package/README.md +251 -0
  2. package/dist/add-R6RGUYER.js +22 -0
  3. package/dist/add-R6RGUYER.js.map +1 -0
  4. package/dist/auth-7FFZNARZ-4OIRGZ7R.js +31 -0
  5. package/dist/auth-7FFZNARZ-4OIRGZ7R.js.map +1 -0
  6. package/dist/chunk-22RIHU4J.js +975 -0
  7. package/dist/chunk-22RIHU4J.js.map +1 -0
  8. package/dist/chunk-23XQDB7K.js +1773 -0
  9. package/dist/chunk-23XQDB7K.js.map +1 -0
  10. package/dist/chunk-5TBV2VHZ.js +6067 -0
  11. package/dist/chunk-5TBV2VHZ.js.map +1 -0
  12. package/dist/chunk-D7P3IYYR.js +44 -0
  13. package/dist/chunk-D7P3IYYR.js.map +1 -0
  14. package/dist/chunk-EHPC7CKE.js +757 -0
  15. package/dist/chunk-EHPC7CKE.js.map +1 -0
  16. package/dist/chunk-FAE5UZFE.js +17 -0
  17. package/dist/chunk-FAE5UZFE.js.map +1 -0
  18. package/dist/chunk-HRF6TNXX.js +53 -0
  19. package/dist/chunk-HRF6TNXX.js.map +1 -0
  20. package/dist/chunk-HVJEW7TU.js +495 -0
  21. package/dist/chunk-HVJEW7TU.js.map +1 -0
  22. package/dist/chunk-JO5H5G6U.js +1529 -0
  23. package/dist/chunk-JO5H5G6U.js.map +1 -0
  24. package/dist/chunk-MUEQNBE6.js +1140 -0
  25. package/dist/chunk-MUEQNBE6.js.map +1 -0
  26. package/dist/chunk-O5WTCVMZ.js +3391 -0
  27. package/dist/chunk-O5WTCVMZ.js.map +1 -0
  28. package/dist/chunk-ROKIQIEX.js +65 -0
  29. package/dist/chunk-ROKIQIEX.js.map +1 -0
  30. package/dist/chunk-T7GCAJK5.js +4895 -0
  31. package/dist/chunk-T7GCAJK5.js.map +1 -0
  32. package/dist/chunk-UOQWJ3S4.js +138 -0
  33. package/dist/chunk-UOQWJ3S4.js.map +1 -0
  34. package/dist/chunk-YQWV5W4U.js +3479 -0
  35. package/dist/chunk-YQWV5W4U.js.map +1 -0
  36. package/dist/chunk-ZPDNZRVW.js +272 -0
  37. package/dist/chunk-ZPDNZRVW.js.map +1 -0
  38. package/dist/config-store-KTOWIKAS-XVZHNPKW.js +11 -0
  39. package/dist/config-store-KTOWIKAS-XVZHNPKW.js.map +1 -0
  40. package/dist/dist-2VRFSXMO.js +40 -0
  41. package/dist/dist-2VRFSXMO.js.map +1 -0
  42. package/dist/dist-C2QB4IKT.js +340 -0
  43. package/dist/dist-C2QB4IKT.js.map +1 -0
  44. package/dist/dist-DEIUVZ57.js +299 -0
  45. package/dist/dist-DEIUVZ57.js.map +1 -0
  46. package/dist/dist-DSKHGECB.js +36 -0
  47. package/dist/dist-DSKHGECB.js.map +1 -0
  48. package/dist/dist-GN2DN7CI.js +95 -0
  49. package/dist/dist-GN2DN7CI.js.map +1 -0
  50. package/dist/dist-TZL4XW2R.js +58 -0
  51. package/dist/dist-TZL4XW2R.js.map +1 -0
  52. package/dist/dist-ZP2APOYV.js +53 -0
  53. package/dist/dist-ZP2APOYV.js.map +1 -0
  54. package/dist/index.js +15083 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/operational-5RT6AZJI-ZEMPD32Q.js +12 -0
  57. package/dist/operational-5RT6AZJI-ZEMPD32Q.js.map +1 -0
  58. package/dist/reconcile-A4I3Z7VX-GQMEN4GC.js +12 -0
  59. package/dist/reconcile-A4I3Z7VX-GQMEN4GC.js.map +1 -0
  60. package/dist/rsshub-GOJBTNOD-UNNVKBFL.js +18 -0
  61. package/dist/rsshub-GOJBTNOD-UNNVKBFL.js.map +1 -0
  62. package/dist/synap-image-install-X36REYQ5-UGO4MAOP.js +17 -0
  63. package/dist/synap-image-install-X36REYQ5-UGO4MAOP.js.map +1 -0
  64. package/package.json +44 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js","../src/index.ts","../../cli-kit/src/index.ts","../../@eve/builder/dist/index.js","../../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs","../src/commands/status.ts","../src/commands/doctor.ts","../src/lib/probe-routes.ts","../src/lib/diagnose-route.ts","../src/lib/doctor-runners.ts","../src/lib/git.ts","../src/commands/grow.ts","../src/commands/lifecycle/birth.ts","../src/commands/lifecycle/install.ts","../src/commands/setup-admin.ts","../src/commands/setup.ts","../src/commands/remove.ts","../src/commands/debug/logs.ts","../src/commands/debug/inspect.ts","../src/commands/debug/operational.ts","../src/commands/manage/config-cmd.ts","../src/commands/manage/backup-update.ts","../src/commands/manage/purge.ts","../src/commands/mode.ts","../src/commands/auth.ts","../src/commands/ai.ts","../src/commands/openwebui.ts","../src/commands/ui.ts","../src/commands/domain.ts","../src/commands/intent.ts","../src/commands/deploy.ts","../src/commands/login.ts","../src/commands/ls.ts","../src/commands/synap.ts","../src/commands/connectors.ts","../src/commands/capabilities.ts","../src/commands/capability-catalog.ts","../src/commands/capability-definitions.ts"],"sourcesContent":["'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n CLOSE_TIMEOUT: 30000,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [options.isServer=false] Create the instance in either\n * server or client mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n */\n constructor(options) {\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._maxPayload = this._options.maxPayload | 0;\n this._isServer = !!this._options.isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n CLOSE_TIMEOUT,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._closeTimeout = options.closeTimeout;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n closeTimeout: CLOSE_TIMEOUT,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n websocket._closeTimeout = opts.closeTimeout;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate({\n ...opts.perMessageDeflate,\n isServer: false,\n maxPayload: opts.maxPayload\n });\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n websocket._closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\n\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n closeTimeout: CLOSE_TIMEOUT,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate({\n ...this.options.perMessageDeflate,\n isServer: true,\n maxPayload: this.options.maxPayload\n });\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, join, resolve } from 'node:path';\nimport { setGlobalCliFlags } from '@eve/cli-kit';\nimport { migrateSetupProfileToSecrets } from '@eve/lifecycle';\nimport { registerBrainCommands } from '@eve/brain';\nimport { registerArmsCommands } from '@eve/arms';\nimport { registerLegsCommands } from '@eve/legs';\nimport { registerEyesCommands } from '@eve/eyes';\nimport { registerBuilderCommands } from '@eve/builder';\nimport { statusCommand } from './commands/status.js';\nimport { doctorCommand } from './commands/doctor.js';\nimport { growCommand } from './commands/grow.js';\nimport { birthCommand } from './commands/lifecycle/birth.js';\nimport { installCommand } from './commands/lifecycle/install.js';\nimport { setupCommand } from './commands/setup.js';\nimport { runInstall } from './commands/lifecycle/install.js';\nimport { addCommand } from './commands/add.js';\nimport { removeCommand } from './commands/remove.js';\nimport { logsCommand } from './commands/debug/logs.js';\nimport { inspectCommand } from './commands/debug/inspect.js';\nimport { debugCommand } from './commands/debug/operational.js';\nimport { configCommands } from './commands/manage/config-cmd.js';\nimport { backupUpdateCommands } from './commands/manage/backup-update.js';\nimport { purgeCommand } from './commands/manage/purge.js';\nimport { modeCommands } from './commands/mode.js';\nimport { authCommand } from './commands/auth.js';\nimport { aiCommandGroup } from './commands/ai.js';\nimport { openwebuiCommand } from './commands/openwebui.js';\nimport { uiCommand } from './commands/ui.js';\nimport { domainCommand } from './commands/domain.js';\nimport { intentCommand } from './commands/intent.js';\nimport { deployCommand } from './commands/deploy.js';\nimport { loginCommand } from './commands/login.js';\nimport { lsCommand } from './commands/ls.js';\nimport { synapCommand } from './commands/synap.js';\nimport { connectorsCommand } from './commands/connectors.js';\nimport { capabilitiesCommand } from './commands/capabilities.js';\nimport { colors, emojis } from './lib/ui.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst pkg = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8')) as { version: string };\n\n// The globally installed `eve` binary can be invoked from any directory — in\n// particular from a Synap deploy directory during recovery. Keep Eve's own\n// state rooted at its installation unless an operator explicitly overrides it.\nconst bundledEveHome = resolve(__dirname, '../../..');\nif (\n !process.env.EVE_HOME &&\n existsSync(join(bundledEveHome, 'packages', 'eve-cli', 'package.json'))\n) {\n process.env.EVE_HOME = bundledEveHome;\n}\nconst eveHome = process.env.EVE_HOME ?? process.cwd();\n\n// Warn when invoked via `npx eve` — npx downloads the published npm package,\n// ignoring the locally-installed build at /usr/local/bin/eve. Any fixes or\n// updates shipped via `eve update eve` / `git pull + build` won't be visible\n// until the user switches to the installed binary.\nif (process.env.npm_execpath?.includes('npx') || process.env.npm_lifecycle_script?.startsWith('npx')) {\n process.stderr.write(\n '\\n⚠️ You are running Eve via `npx eve` which downloads the published npm package.\\n' +\n ' This bypasses any local updates. Use the installed binary instead:\\n' +\n ' eve <command>\\n' +\n ' If `eve` is not found, run: bash /opt/eve/scripts/self-update.sh\\n\\n',\n );\n}\n\nconst program = new Command();\n\nprogram.configureHelp({\n sortSubcommands: true,\n sortOptions: true,\n});\n\nprogram\n .name('eve')\n .description(`${emojis.entity} Eve — Entity Creation System`)\n .version(pkg.version, '-v, --version')\n .option('--json', 'Machine-readable output where supported')\n .option('-y, --yes', 'Non-interactive / assume confirm')\n .option('--verbose', 'Verbose logs')\n .hook('preAction', async () => {\n const o = program.opts() as { json?: boolean; yes?: boolean; verbose?: boolean };\n setGlobalCliFlags({\n json: Boolean(o.json),\n nonInteractive: Boolean(o.yes),\n verbose: Boolean(o.verbose),\n });\n // Idempotent: catch up `.eve/secrets.json` from `.eve/setup-profile.json`\n // (the wizard's user-friendly answers) before any command reads secrets.\n // Without this, `domainHint` from the wizard stays trapped in setup-profile\n // and `secrets.domain.primary` stays null — making every downstream\n // resolver (`resolveSynapUrl`, `resolveHubBaseUrl`) silently return empty\n // and skipping skill/knowledge/tools pushes into OpenWebUI.\n // No-op when secrets already has the fields. Failures are non-fatal:\n // we never want a cosmetic migration to block install/update/sync.\n try {\n await migrateSetupProfileToSecrets(eveHome);\n } catch {\n // intentional swallow\n }\n });\n\n// Header/banner is rendered inside the custom helpInformation() override below.\n\n// --- Lifecycle ---\nsetupCommand(program);\ninstallCommand(program);\naddCommand(program);\nremoveCommand(program);\ndeployCommand(program);\nsynapCommand(program);\nconnectorsCommand(program);\ncapabilitiesCommand(program);\nloginCommand(program);\nlsCommand(program);\n\nprogram\n .command('init')\n .description('Alias for `eve install` — composable installer')\n .option('--components <list>', 'Comma-separated component IDs')\n .option('--domain <host>', 'Public hostname', 'localhost')\n .option('--email <email>', \"Let's Encrypt email\")\n .option('--model <model>', 'Ollama model', 'llama3.1:8b')\n .option('--synap-repo <path>', 'Path to synap-backend checkout')\n .option('--from-image', 'Install Synap from Docker image')\n .option('--admin-email <email>', 'Admin bootstrap email')\n .option('--admin-password <secret>', 'Admin password (preseed mode)')\n .option('--admin-bootstrap-mode <mode>', 'token | preseed')\n .option('--dry-run', 'Print plan without executing')\n .action(async (opts: {\n components?: string;\n domain?: string;\n email?: string;\n model?: string;\n synapRepo?: string;\n fromImage?: boolean;\n adminEmail?: string;\n adminPassword?: string;\n adminBootstrapMode?: 'token' | 'preseed';\n dryRun?: boolean;\n }) => {\n try {\n await runInstall({\n components: opts.components ? opts.components.split(',').map(s => s.trim()) : undefined,\n domain: opts.domain,\n email: opts.email,\n model: opts.model,\n synapRepo: opts.synapRepo,\n fromImage: opts.fromImage,\n adminEmail: opts.adminEmail,\n adminPassword: opts.adminPassword,\n adminBootstrapMode: opts.adminBootstrapMode,\n dryRun: opts.dryRun,\n });\n } catch (err) {\n console.error(String(err));\n process.exit(1);\n }\n });\n\nbirthCommand(program);\nstatusCommand(program);\ngrowCommand(program);\n\n// --- Debug ---\ndoctorCommand(program);\nlogsCommand(program);\ninspectCommand(program);\ndebugCommand(program);\n\n// --- Management ---\nconfigCommands(program);\nbackupUpdateCommands(program);\nmodeCommands(program);\nauthCommand(program);\npurgeCommand(program);\n\n// --- AI ---\naiCommandGroup(program);\n\n// --- OpenWebUI ---\nopenwebuiCommand(program);\n\n// --- UI ---\nuiCommand(program);\n\n// --- Domain ---\ndomainCommand(program);\n\n// --- Intent (background_tasks) ---\nintentCommand(program);\n\n// --- Organs ---\nconst brain = program.command('brain').description('Intelligence & memory (Synap, Ollama)');\nregisterBrainCommands(brain);\n\nconst arms = program.command('arms').description('Action — OpenClaw (agent messaging layer)');\nregisterArmsCommands(arms);\n\nconst eyes = program.command('eyes').description('Perception — RSSHub');\nregisterEyesCommands(eyes);\n\nconst legs = program.command('legs').description('Exposure — Traefik & domains');\nregisterLegsCommands(legs);\n\nconst builder = program.command('builder').description('Creation — OpenCode / OpenClaude / Dokploy');\nregisterBuilderCommands(builder);\n\n// ---------------------------------------------------------------------------\n// Help visibility: hide redundant/niche commands from default `eve --help`\n// while keeping them fully runnable. They reappear via `eve help-all`.\n// ---------------------------------------------------------------------------\n\nconst HIDDEN_FROM_DEFAULT_HELP = new Set([\n 'init', // alias for `install` — hide the duplicate entry\n 'setup', // niche guided 3-path wizard\n 'birth', // bare-metal provisioning (placeholder)\n 'grow', // semantic overlap with `add`\n 'purge', // destructive — keep out of default help\n 'inspect', // power-user debug\n 'brain', // organ wrapper (delegates to install/status)\n 'arms',\n 'eyes',\n 'legs',\n 'builder',\n]);\n\nfor (const cmd of program.commands) {\n if (HIDDEN_FROM_DEFAULT_HELP.has(cmd.name())) {\n (cmd as Command & { hidden?: boolean }).hidden = true;\n }\n}\n\n// Categorized help renderer — used by both default `--help` and `help-all`.\n// `showHidden=true` includes hidden commands grouped under their categories.\ntype HelpCategory = { title: string; commands: string[] };\n\nconst DEFAULT_CATEGORIES: HelpCategory[] = [\n { title: 'Lifecycle', commands: ['install', 'update', 'add', 'remove'] },\n { title: 'Status', commands: ['status', 'doctor'] },\n { title: 'Operations', commands: ['logs', 'restart', 'recreate', 'backup'] },\n { title: 'Configuration', commands: ['config', 'domain', 'mode', 'auth', 'ai'] },\n { title: 'UI', commands: ['ui'] },\n];\n\nconst HIDDEN_CATEGORIES: HelpCategory[] = [\n { title: 'Lifecycle (hidden)', commands: ['init', 'setup', 'birth', 'grow'] },\n { title: 'Debug (hidden)', commands: ['inspect', 'purge'] },\n { title: 'Organs (hidden)', commands: ['brain', 'arms', 'eyes', 'legs', 'builder'] },\n];\n\nfunction shortDesc(s: string): string {\n // First sentence only; clamp to 70 chars to keep the help screen tight.\n const firstSentence = s.split(/(?<=\\.)\\s|\\.\\s/)[0].trim();\n const base = firstSentence.length > 0 ? firstSentence : s;\n return base.length > 70 ? base.slice(0, 67).trimEnd() + '…' : base;\n}\n\nfunction describeCommand(name: string): { label: string; desc: string } | null {\n const cmd = program.commands.find((c) => c.name() === name);\n if (!cmd) return null;\n const aliases = cmd.aliases();\n const label = aliases.length > 0 ? `${cmd.name()} (${aliases.join(', ')})` : cmd.name();\n return { label, desc: shortDesc(cmd.description()) };\n}\n\nfunction renderCategories(categories: HelpCategory[]): string {\n const labelWidth = 16;\n const lines: string[] = [];\n for (const cat of categories) {\n const rows: string[] = [];\n for (const name of cat.commands) {\n const info = describeCommand(name);\n if (!info) continue;\n const label = info.label.padEnd(labelWidth);\n rows.push(` ${colors.primary(label)} ${colors.muted(info.desc)}`);\n }\n if (rows.length === 0) continue;\n lines.push('');\n lines.push(colors.primary.bold(`${cat.title}:`));\n lines.push(...rows);\n }\n return lines.join('\\n');\n}\n\nfunction buildHelpString(showHidden: boolean): string {\n // Header (banner + organ symbology) — branding stays\n const header =\n `\\n${colors.primary.bold('Eve — sovereign stack installer & operator')}\\n\\n` +\n `${emojis.brain} Brain Synap + data stores + optional Ollama\\n` +\n `${emojis.arms} Arms OpenClaw (agent messaging layer)\\n` +\n `${emojis.builder} Builder OpenCode / OpenClaude / Dokploy\\n` +\n `${emojis.eyes} Eyes RSSHub\\n` +\n `${emojis.legs} Legs Traefik / domains\\n`;\n\n const usage =\n `\\n${colors.muted('Usage:')} eve [options] [command]\\n` +\n `${colors.muted('Flags:')} ${colors.primary('--help-all')} ${colors.muted('(full list)')} ` +\n `${colors.primary('-v')} ${colors.muted('version')} ` +\n `${colors.primary('--json -y --verbose')} ${colors.muted('(see <command> --help)')}\\n`;\n const globalOpts = '';\n\n const main = renderCategories(DEFAULT_CATEGORIES);\n const hidden = showHidden ? '\\n\\n' + renderCategories(HIDDEN_CATEGORIES) : '';\n\n const footer = showHidden\n ? `\\n\\n${colors.muted('These commands are hidden from default help but remain runnable.')}\\n` +\n `${colors.muted('Run')} ${colors.primary('eve <command> --help')} ${colors.muted('for command-specific help.')}\\n`\n : `\\n\\n${colors.muted('Run')} ${colors.primary('eve --help-all')} ${colors.muted('to see all commands including legacy and niche options.')}\\n` +\n `${colors.muted('Run')} ${colors.primary('eve <command> --help')} ${colors.muted('for command-specific help.')}\\n`;\n\n return header + usage + globalOpts + main + hidden + footer;\n}\n\n// Override top-level help output with our categorized layout. Subcommands\n// keep commander's default help renderer (helpInformation is per-command).\nprogram.helpInformation = function (): string {\n const argvHasHelpAll = process.argv.slice(2).includes('--help-all');\n let optsHelpAll = false;\n try {\n optsHelpAll = Boolean((program.opts() as { helpAll?: boolean }).helpAll);\n } catch {\n // opts() may throw before parse — fall back to argv inspection\n }\n return buildHelpString(argvHasHelpAll || optsHelpAll);\n};\n\n// `--help-all` flag — toggles the hidden categories in the help output.\nprogram.option('--help-all', 'Show all commands including legacy/niche');\n\n// Also expose `eve help-all` as a top-level command for discoverability.\nprogram\n .command('help-all')\n .description('Show all commands including legacy/niche')\n .action(() => {\n process.stdout.write(buildHelpString(true));\n });\n\n// If user passed --help-all without --help, still show the full help and exit.\nconst argv = process.argv.slice(2);\nif (argv.includes('--help-all') && !argv.includes('--help') && !argv.includes('-h') && !argv.includes('help-all')) {\n process.stdout.write(buildHelpString(true));\n process.exit(0);\n}\n\nprocess.on('unhandledRejection', (reason: unknown) => {\n console.error('Unhandled:', reason);\n process.exit(1);\n});\n\nprogram.parse();\n\nif (!process.argv.slice(2).length) {\n program.outputHelp();\n}\n","import chalk from 'chalk';\nimport ora, { type Ora } from 'ora';\n\nexport type JsonRecord = Record<string, unknown>;\n\nexport const theme = {\n primary: chalk.hex('#6366f1'),\n success: chalk.green,\n warn: chalk.yellow,\n error: chalk.red,\n info: chalk.blue,\n muted: chalk.gray,\n};\n\nexport interface GlobalCliFlags {\n json?: boolean;\n nonInteractive?: boolean;\n verbose?: boolean;\n}\n\nlet globalFlags: GlobalCliFlags = {};\n\nexport function setGlobalCliFlags(flags: GlobalCliFlags): void {\n globalFlags = { ...flags };\n}\n\nexport function getGlobalCliFlags(): GlobalCliFlags {\n return { ...globalFlags };\n}\n\nexport function outputJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n\nexport function outputLine(message: string, kind: 'info' | 'success' | 'warn' | 'error' | 'muted' = 'info'): void {\n if (globalFlags.json) return;\n const fn = theme[kind] ?? theme.info;\n console.log(fn(message));\n}\n\n/**\n * Run an async step with an ora spinner; on failure rethrows after stop().\n */\nexport async function runStep<T>(label: string, fn: () => Promise<T>, verbose?: boolean): Promise<T> {\n if (globalFlags.json) {\n return fn();\n }\n const spinner: Ora = ora(label).start();\n try {\n const result = await fn();\n spinner.succeed(label);\n return result;\n } catch (e) {\n spinner.fail(label);\n const msg = e instanceof Error ? e.message : String(e);\n if (verbose || globalFlags.verbose) {\n console.error(e);\n } else {\n console.error(theme.error(msg));\n }\n throw e;\n }\n}\n","// src/lib/opencode.ts\nimport { spawn } from \"child_process\";\nimport { existsSync, mkdirSync, writeFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport { readEveSecrets, writeBuilderProjectEnv, ensureEveSkillsLayout, defaultSkillsDir } from \"@eve/dna\";\nvar OpenCodeService = class {\n isInstalled = false;\n projectPath = null;\n async install() {\n console.log(\"Installing OpenCode...\");\n const check = spawn(\"sh\", [\"-c\", \"which opencode\"], { stdio: [\"pipe\", \"pipe\", \"ignore\"] });\n await new Promise((resolve, reject) => {\n check.on(\"close\", (code) => {\n if (code === 0) {\n console.log(\"OpenCode already installed\");\n resolve();\n } else {\n console.log(\"Installing OpenCode CLI...\");\n const npm = spawn(\"sh\", [\"-c\", \"npm install -g @opencode/cli\"], {\n stdio: \"inherit\"\n });\n npm.on(\"close\", (code2) => {\n if (code2 && code2 !== 0) reject(new Error(`npm install failed with code ${code2}`));\n else resolve();\n });\n npm.on(\"error\", reject);\n }\n });\n check.on(\"error\", reject);\n });\n this.isInstalled = true;\n console.log(\"OpenCode installed successfully\");\n }\n async initProject(name, template) {\n if (!this.isInstalled) {\n await this.install();\n }\n console.log(`Initializing OpenCode project: ${name}`);\n const secrets = await readEveSecrets(process.cwd());\n const workspaceRoot = secrets?.builder?.workspaceDir ?? join(homedir(), \".eve\", \"workspace\");\n mkdirSync(workspaceRoot, { recursive: true });\n const projectDir = join(workspaceRoot, name);\n if (!existsSync(projectDir)) {\n mkdirSync(projectDir, { recursive: true });\n }\n this.projectPath = projectDir;\n const config = {\n name,\n template: template || \"default\",\n version: \"0.1.0\",\n createdAt: (/* @__PURE__ */ new Date()).toISOString(),\n features: [\"docs\", \"website\", \"blog\"]\n };\n writeFileSync(\n join(projectDir, \"opencode.config.json\"),\n JSON.stringify(config, null, 2)\n );\n const dirs = [\"src\", \"docs\", \"public\", \"templates\"];\n for (const dir of dirs) {\n mkdirSync(join(projectDir, dir), { recursive: true });\n }\n writeFileSync(\n join(projectDir, \"src\", \"index.md\"),\n `# ${name}\n\nGenerated by OpenCode via eve Builder\n`\n );\n const skillsDir = secrets?.builder?.skillsDir ?? defaultSkillsDir();\n ensureEveSkillsLayout(skillsDir);\n await writeBuilderProjectEnv(projectDir, process.cwd());\n console.log(`Project initialized at: ${projectDir}`);\n }\n async generate() {\n if (!this.projectPath) {\n throw new Error(\"No project initialized. Call initProject first.\");\n }\n console.log(\"Generating content with OpenCode...\");\n return new Promise((resolve, reject) => {\n const cmd = `opencode generate`;\n const proc = spawn(\"sh\", [\"-c\", cmd], {\n cwd: this.projectPath ?? void 0,\n stdio: [\"inherit\", \"inherit\", \"inherit\"]\n });\n proc.on(\"close\", (code) => {\n if (code === 0) {\n console.log(\"Content generated successfully\");\n resolve();\n } else {\n const err = new Error(`Generation exited with code ${code ?? 1}`);\n console.error(err);\n reject(err);\n }\n });\n proc.on(\"error\", reject);\n });\n }\n async build() {\n if (!this.projectPath) {\n throw new Error(\"No project initialized. Call initProject first.\");\n }\n console.log(\"Building OpenCode project...\");\n return new Promise((resolve, reject) => {\n const cmd = `opencode build`;\n const proc = spawn(\"sh\", [\"-c\", cmd], {\n cwd: this.projectPath ?? void 0,\n stdio: [\"inherit\", \"inherit\", \"inherit\"]\n });\n proc.on(\"close\", (code) => {\n if (code === 0) {\n console.log(\"Build completed successfully\");\n resolve();\n } else {\n const err = new Error(`Build exited with code ${code ?? 1}`);\n console.error(err);\n reject(err);\n }\n });\n proc.on(\"error\", reject);\n });\n }\n getProjectPath() {\n return this.projectPath;\n }\n};\n\n// src/lib/openclaude.ts\nimport { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from \"fs\";\nimport { join as join2 } from \"path\";\nimport { readEveSecrets as readEveSecrets2 } from \"@eve/dna\";\nvar OpenClaudeService = class {\n isInstalled = false;\n _configured = false;\n configPath = null;\n /**\n * @deprecated Hermes daemon handles task execution now.\n * This method only prints a deprecation warning.\n */\n async install() {\n console.warn(\"[OpenClaude] WARNING: OpenClaudeService is deprecated. Use Hermes daemon instead.\");\n console.log(\"OpenClaude is available via system PATH if installed separately.\");\n this.isInstalled = true;\n }\n /**\n * @deprecated Hermes reads its config from .eve/hermes-state.json.\n * This method only saves a deprecation notice.\n */\n async configure(brainUrl) {\n console.warn(\"[OpenClaude] WARNING: OpenClaudeService is deprecated. Configure Hermes daemon instead.\");\n const secrets = await readEveSecrets2(process.cwd());\n const resolvedBrainUrl = brainUrl || secrets?.builder?.openclaudeUrl || secrets?.inference?.gatewayUrl || secrets?.inference?.ollamaUrl || \"http://127.0.0.1:11434\";\n console.log(`Legacy config: brain URL = ${resolvedBrainUrl}`);\n const configDir = join2(process.cwd(), \".eve\");\n if (!existsSync2(configDir)) {\n mkdirSync2(configDir, { recursive: true });\n }\n const configPath = join2(configDir, \"openclaude.json\");\n this.configPath = configPath;\n this._configured = true;\n if (!existsSync2(configPath)) {\n const legacyConfig = {\n brainUrl: resolvedBrainUrl,\n deprecated: true,\n deprecationNotice: \"Use Hermes daemon instead. See: eve builder hermes start\",\n createdAt: (/* @__PURE__ */ new Date()).toISOString()\n };\n writeFileSync2(configPath, JSON.stringify(legacyConfig, null, 2));\n }\n console.log(\"OpenClaude legacy config saved (deprecated).\");\n }\n /**\n * @deprecated Hermes daemon handles lifecycle now.\n */\n async start() {\n console.warn(\"[OpenClaude] WARNING: OpenClaudeService is deprecated. Use Hermes daemon instead.\");\n if (this.configPath && existsSync2(this.configPath)) {\n console.log(`Config loaded from: ${this.configPath}`);\n }\n }\n /**\n * @deprecated No-op. Use Hermes daemon + TaskExecutor.\n */\n async generateCode(prompt) {\n console.warn(\"[OpenClaude] WARNING: OpenClaudeService is deprecated.\");\n console.log(\"This method is a no-op. Use Hermes daemon for task execution.\");\n return `// Deprecated: Use Hermes daemon instead. Original prompt was: ${prompt}`;\n }\n getConfig() {\n if (this.configPath && existsSync2(this.configPath)) {\n return JSON.parse(readFileSync2(this.configPath, \"utf-8\"));\n }\n return { deprecated: true };\n }\n isConfigured() {\n return this._configured;\n }\n};\n\n// src/lib/dokploy.ts\nimport { execSync } from \"child_process\";\nimport { existsSync as existsSync3, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3, readFileSync as readFileSync3 } from \"fs\";\nimport { join as join3 } from \"path\";\nimport { readEveSecrets as readEveSecrets3, writeEveSecrets } from \"@eve/dna\";\nvar DokployService = class {\n isInstalled = false;\n apiUrl = null;\n apiKey = null;\n projects = /* @__PURE__ */ new Map();\n async install() {\n console.log(\"Installing Dokploy...\");\n try {\n execSync(\"which dokploy\", { stdio: \"ignore\" });\n console.log(\"Dokploy CLI already installed\");\n } catch {\n console.log(\"Installing Dokploy CLI...\");\n execSync(\"npm install -g dokploy\", { stdio: \"inherit\" });\n }\n try {\n const response = await fetch(\"http://localhost:3000/api/health\");\n if (response.ok) {\n console.log(\"Dokploy server is running on localhost:3000\");\n this.apiUrl = \"http://localhost:3000\";\n this.isInstalled = true;\n }\n } catch {\n console.log(\"Dokploy server not detected locally\");\n console.log(\"You can set up Dokploy at https://dokploy.com/\");\n this.isInstalled = true;\n }\n await this.loadConfig();\n console.log(\"Dokploy installation completed\");\n }\n async loadConfig() {\n const configDir = join3(process.cwd(), \".eve\");\n const configPath = join3(configDir, \"dokploy.json\");\n if (existsSync3(configPath)) {\n const config = JSON.parse(readFileSync3(configPath, \"utf-8\"));\n this.apiUrl = config.apiUrl || this.apiUrl;\n this.apiKey = config.apiKey;\n }\n const secrets = await readEveSecrets3(process.cwd());\n this.apiUrl = secrets?.builder?.dokployApiUrl ?? this.apiUrl;\n this.apiKey = secrets?.builder?.dokployApiKey ?? this.apiKey;\n }\n async saveConfig() {\n const configDir = join3(process.cwd(), \".eve\");\n if (!existsSync3(configDir)) {\n mkdirSync3(configDir, { recursive: true });\n }\n writeFileSync3(\n join3(configDir, \"dokploy.json\"),\n JSON.stringify({\n apiUrl: this.apiUrl,\n apiKey: this.apiKey,\n updatedAt: (/* @__PURE__ */ new Date()).toISOString()\n }, null, 2)\n );\n const secrets = await readEveSecrets3(process.cwd());\n await writeEveSecrets(\n {\n builder: {\n dokployApiUrl: this.apiUrl ?? void 0,\n dokployApiKey: this.apiKey ?? void 0,\n dokployWebhookUrl: secrets?.builder?.dokployWebhookUrl ?? process.env.DOKPLOY_WEBHOOK_URL ?? void 0\n }\n },\n process.cwd()\n );\n }\n async createProject(name) {\n if (!this.isInstalled) {\n await this.install();\n }\n console.log(`Creating Dokploy project: ${name}`);\n const project = {\n id: `proj_${Date.now()}`,\n name,\n status: \"stopped\"\n };\n this.projects.set(project.id, project);\n const configDir = join3(process.cwd(), \".eve\");\n if (!existsSync3(configDir)) {\n mkdirSync3(configDir, { recursive: true });\n }\n const projectsPath = join3(configDir, \"dokploy-projects.json\");\n const existing = existsSync3(projectsPath) ? JSON.parse(readFileSync3(projectsPath, \"utf-8\")) : {};\n existing[project.id] = project;\n writeFileSync3(projectsPath, JSON.stringify(existing, null, 2));\n console.log(`Project created with ID: ${project.id}`);\n }\n async deploy(projectId) {\n const project = this.projects.get(projectId);\n if (!project) {\n const projectsPath2 = join3(process.cwd(), \".eve\", \"dokploy-projects.json\");\n if (existsSync3(projectsPath2)) {\n const all2 = JSON.parse(readFileSync3(projectsPath2, \"utf-8\"));\n if (all2[projectId]) {\n Object.assign(project || {}, all2[projectId]);\n }\n }\n if (!project) {\n throw new Error(`Project not found: ${projectId}`);\n }\n }\n console.log(`Deploying project: ${project.name}`);\n project.status = \"deploying\";\n await new Promise((resolve) => setTimeout(resolve, 2e3));\n project.status = \"running\";\n project.lastDeployed = /* @__PURE__ */ new Date();\n project.url = `https://${project.name}.dokploy.app`;\n this.projects.set(projectId, project);\n const projectsPath = join3(process.cwd(), \".eve\", \"dokploy-projects.json\");\n const all = existsSync3(projectsPath) ? JSON.parse(readFileSync3(projectsPath, \"utf-8\")) : {};\n all[projectId] = project;\n writeFileSync3(projectsPath, JSON.stringify(all, null, 2));\n console.log(`Project deployed successfully at: ${project.url}`);\n }\n async getStatus() {\n const projects = [];\n const projectsPath = join3(process.cwd(), \".eve\", \"dokploy-projects.json\");\n if (existsSync3(projectsPath)) {\n const all = JSON.parse(readFileSync3(projectsPath, \"utf-8\"));\n for (const [id, proj] of Object.entries(all)) {\n projects.push(proj);\n }\n }\n let running = false;\n try {\n if (this.apiUrl) {\n const response = await fetch(`${this.apiUrl}/api/health`, {\n signal: AbortSignal.timeout(3e3)\n });\n running = response.ok;\n }\n } catch {\n running = false;\n }\n return {\n installed: this.isInstalled,\n running,\n version: \"1.0.0\",\n projects\n };\n }\n async configureDomain(domain) {\n console.log(`Configuring domain: ${domain}`);\n const configDir = join3(process.cwd(), \".eve\");\n if (!existsSync3(configDir)) {\n mkdirSync3(configDir, { recursive: true });\n }\n const domainPath = join3(configDir, \"dokploy-domain.json\");\n writeFileSync3(domainPath, JSON.stringify({\n domain,\n configuredAt: (/* @__PURE__ */ new Date()).toISOString()\n }, null, 2));\n console.log(`Domain configured: ${domain}`);\n console.log(\"Note: DNS records need to be updated to point to Dokploy server\");\n }\n getProject(projectId) {\n return this.projects.get(projectId);\n }\n listProjects() {\n return Array.from(this.projects.values());\n }\n};\n\n// src/lib/claudecode.ts\nimport { execSync as execSync2 } from \"child_process\";\nimport { mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from \"fs\";\nimport { join as join4 } from \"path\";\nimport {\n readEveSecrets as readEveSecrets4,\n copySynapSkillIntoClaudeProject,\n writeClaudeCodeSettings,\n defaultSkillsDir as defaultSkillsDir3\n} from \"@eve/dna\";\nvar ClaudeCodeService = class {\n installed = false;\n async install() {\n try {\n execSync2(\"which claude\", { stdio: \"ignore\" });\n this.installed = true;\n console.log(\"Claude Code (claude) already on PATH\");\n return;\n } catch {\n }\n try {\n console.log(\"Installing Claude Code via npm (@anthropic-ai/claude-code)\\u2026\");\n console.log(\"Tip: for native install see https://code.claude.com/docs/en/setup\");\n execSync2(\"npm install -g @anthropic-ai/claude-code\", { stdio: \"inherit\" });\n this.installed = true;\n } catch (e) {\n console.warn(\"Claude Code install failed:\", e instanceof Error ? e.message : e);\n throw e;\n }\n }\n /**\n * Writes `.claude/settings.json` (env for Hub) + copies synap skill into `.claude/skills/synap/`.\n * See: https://code.claude.com/docs/en/settings\n */\n async configureProject(projectDir, cwd = process.cwd()) {\n if (!this.installed) await this.install();\n const secrets = await readEveSecrets4(cwd);\n const skillsDir = secrets?.builder?.skillsDir ?? defaultSkillsDir3();\n await writeClaudeCodeSettings(projectDir, cwd);\n copySynapSkillIntoClaudeProject(projectDir, skillsDir);\n const readme = join4(projectDir, \".claude\", \"README.eve.md\");\n mkdirSync4(join4(projectDir, \".claude\"), { recursive: true });\n writeFileSync4(\n readme,\n [\n \"# Eve + Claude Code\",\n \"\",\n \"- Session commands: `/skills`, `/mcp`, `/context` (see Claude Code docs).\",\n \"- Hub env is in `settings.json` \\u2192 `env` (SYNAP_API_URL, SYNAP_API_KEY, HUB_BASE_URL).\",\n \"- Add MCP: `claude mcp add --transport http \\u2026` (see https://code.claude.com/docs/en/mcp ).\",\n \"\"\n ].join(\"\\n\"),\n \"utf-8\"\n );\n console.log(\"Claude Code project wiring: .claude/settings.json + .claude/skills/synap/\");\n }\n};\n\n// src/lib/builder-organ.ts\nimport { copyFileSync, existsSync as existsSync6, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from \"fs\";\nimport { join as join6 } from \"path\";\nimport { writeBuilderProjectEnv as writeBuilderProjectEnv3 } from \"@eve/dna\";\n\n// src/lib/project-paths.ts\nimport { existsSync as existsSync5, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from \"fs\";\nimport { homedir as homedir2 } from \"os\";\nimport { join as join5 } from \"path\";\nimport { readEveSecrets as readEveSecrets5, writeBuilderProjectEnv as writeBuilderProjectEnv2 } from \"@eve/dna\";\nasync function resolveBuilderProjectDir(name, cwd = process.cwd()) {\n const secrets = await readEveSecrets5(cwd);\n const workspaceRoot = secrets?.builder?.workspaceDir ?? join5(homedir2(), \".eve\", \"workspace\");\n mkdirSync5(workspaceRoot, { recursive: true });\n const projectDir = join5(workspaceRoot, name);\n if (!existsSync5(projectDir)) {\n mkdirSync5(projectDir, { recursive: true });\n }\n return projectDir;\n}\nasync function scaffoldNonOpencodeProject(name, cwd = process.cwd()) {\n const projectDir = await resolveBuilderProjectDir(name, cwd);\n await writeBuilderProjectEnv2(projectDir, cwd);\n const readme = join5(projectDir, \"README.md\");\n if (!existsSync5(readme)) {\n writeFileSync5(\n readme,\n `# ${name}\n\nEve builder project (OpenCode not selected). Use Claude Code or OpenClaude in this directory.\n`,\n \"utf-8\"\n );\n }\n return projectDir;\n}\n\n// src/lib/builder-organ.ts\nasync function runBuilderOrganSetup(opts) {\n const cwd = opts.cwd ?? process.cwd();\n const { name, engines, template, brainUrl, withDokploy = false } = opts;\n const opencode = new OpenCodeService();\n const openclaude = new OpenClaudeService();\n const claudecode = new ClaudeCodeService();\n const dokploy = new DokployService();\n if (withDokploy) {\n await dokploy.install();\n }\n if (engines.has(\"opencode\")) await opencode.install();\n if (engines.has(\"openclaude\")) await openclaude.install();\n if (engines.has(\"claudecode\")) await claudecode.install();\n let projectDir;\n if (engines.has(\"opencode\")) {\n await opencode.initProject(name, template);\n projectDir = opencode.getProjectPath();\n } else {\n projectDir = await scaffoldNonOpencodeProject(name, cwd);\n }\n if (engines.has(\"openclaude\")) {\n await openclaude.configure(brainUrl || \"\");\n await openclaude.start();\n const rootCfg = join6(cwd, \".eve\", \"openclaude.json\");\n const projEve = join6(projectDir, \".eve\");\n if (existsSync6(rootCfg)) {\n mkdirSync6(projEve, { recursive: true });\n copyFileSync(rootCfg, join6(projEve, \"openclaude.json\"));\n }\n }\n await writeBuilderProjectEnv3(projectDir, cwd);\n if (engines.has(\"claudecode\")) {\n await claudecode.configureProject(projectDir, cwd);\n }\n if (withDokploy) {\n await dokploy.createProject(name);\n }\n const eveDir = join6(cwd, \".eve\");\n if (!existsSync6(eveDir)) {\n mkdirSync6(eveDir, { recursive: true });\n }\n const entityState = {\n type: \"builder_project\",\n name,\n template: template || \"default\",\n engines: [...engines],\n brainUrl: brainUrl || openclaude.getConfig()?.brainUrl || null,\n components: {\n opencode: { selected: engines.has(\"opencode\"), projectPath: engines.has(\"opencode\") ? projectDir : null },\n openclaude: { selected: engines.has(\"openclaude\"), configured: openclaude.isConfigured() },\n claudecode: { selected: engines.has(\"claudecode\") },\n dokploy: withDokploy ? { enabled: true, installed: true, projectName: name } : { enabled: false, skipped: true }\n },\n projectPath: projectDir,\n createdAt: (/* @__PURE__ */ new Date()).toISOString(),\n status: \"initialized\"\n };\n writeFileSync6(join6(eveDir, \"builder-state.json\"), JSON.stringify(entityState, null, 2));\n return {\n projectDir,\n engines: [...engines],\n dokployUsed: withDokploy\n };\n}\n\n// src/commands/init.ts\nimport { readSetupProfile } from \"@eve/dna\";\nfunction parseEngines(raw, profileDefault) {\n const v = (raw ?? \"all\").trim().toLowerCase();\n if (!v || v === \"all\") {\n return /* @__PURE__ */ new Set([\"opencode\", \"openclaude\", \"claudecode\"]);\n }\n const set = /* @__PURE__ */ new Set();\n for (const part of v.split(\",\")) {\n const p = part.trim().toLowerCase();\n if (p === \"opencode\" || p === \"openclaude\" || p === \"claudecode\" || p === \"claude_code\" || p === \"claude-code\") {\n set.add(p === \"claude_code\" || p === \"claude-code\" ? \"claudecode\" : p);\n }\n }\n if (set.size === 0 && profileDefault) {\n const d = profileDefault.trim().toLowerCase();\n if (d === \"opencode\" || d === \"openclaude\" || d === \"claudecode\") set.add(d);\n }\n if (set.size === 0) {\n return /* @__PURE__ */ new Set([\"opencode\", \"openclaude\", \"claudecode\"]);\n }\n return set;\n}\nfunction initCommand(program) {\n program.command(\"init <name>\").description(\n \"Builder organ first: OpenCode + OpenClaude + Claude Code (Hub .env + skills). Traefik / Pangolin / Dokploy are separate \\u2014 use --with-dokploy only if you want Dokploy.\"\n ).option(\"--template <template>\", \"Project template (website, docs, app)\").option(\"--brain-url <url>\", \"Brain/Ollama URL for OpenClaude (defaults to .eve/secrets)\").option(\n \"--engines <list>\",\n \"Comma list or all: opencode,openclaude,claudecode (Claude Code). Default all.\",\n \"all\"\n ).option(\n \"--with-dokploy\",\n \"Install Dokploy CLI and create a project (optional; often skipped in favour of webhooks or static hosting)\"\n ).action(\n async (name, options) => {\n console.log(`Initializing Builder organ: ${name}`);\n console.log(\"\");\n const sp = await readSetupProfile(process.cwd());\n const engines = parseEngines(options.engines, sp?.builderEngine);\n const withDokploy = Boolean(options.withDokploy);\n try {\n console.log(\"\\u{1F4E6} Step 1: Engines (central Hub + skills wiring)\");\n console.log(\"-------------------------------------------\");\n console.log(`Engines: ${[...engines].join(\", \")}`);\n console.log(`Dokploy: ${withDokploy ? \"yes (--with-dokploy)\" : \"skipped (use DOKPLOY_WEBHOOK_URL in .env or eve builder stack)\"}\n`);\n if (sp?.profile === \"data_pod\") {\n console.log(\n \"Note: setup profile is data_pod \\u2014 use inference gateway URL for OpenClaude --brain-url if needed (e.g. http://127.0.0.1:11435).\\n\"\n );\n }\n console.log(\"\\u{1F3D7}\\uFE0F Step 2: Project tree + .env + skills\\u2026\");\n console.log(\"-------------------------------------------\");\n const { projectDir, dokployUsed } = await runBuilderOrganSetup({\n name,\n cwd: process.cwd(),\n engines,\n template: options.template,\n brainUrl: options.brainUrl,\n withDokploy\n });\n console.log(\"\\u2705 Builder organ ready\");\n console.log(\"\");\n console.log(`Project path: ${projectDir}`);\n console.log(\" .env \\u2014 SYNAP_API_URL, SYNAP_API_KEY, HUB_BASE_URL, EVE_SKILLS_DIR, DOKPLOY_WEBHOOK_URL\");\n if (engines.has(\"claudecode\")) {\n console.log(\" .claude/settings.json + .claude/skills/synap/ \\u2014 Claude Code\");\n }\n console.log(\"\");\n console.log(\"Next (still in Builder):\");\n console.log(` cd \"${projectDir}\"`);\n if (engines.has(\"opencode\")) console.log(\" eve builder generate\");\n if (engines.has(\"openclaude\")) console.log(' eve builder code \"<prompt>\"');\n if (engines.has(\"claudecode\")) console.log(\" claude # Claude Code in this directory\");\n if (dokployUsed) console.log(\" eve builder deploy\");\n else\n console.log(\n \" eve builder deploy # only if you used --with-dokploy; else use your webhook / CI\"\n );\n console.log(\" eve builder sandbox up # optional isolated Node + workspace\");\n console.log(\"\");\n console.log(\"Then (other Eve organs \\u2014 order as you like):\");\n console.log(\" eve setup | eve legs setup | eve legs newt up | eve builder stack up\");\n console.log(\"\");\n } catch (error) {\n console.error(\"\\u274C Initialization failed:\", error);\n process.exit(1);\n }\n }\n );\n}\n\n// src/commands/deploy.ts\nimport { existsSync as existsSync7, readFileSync as readFileSync4 } from \"fs\";\nimport { join as join7 } from \"path\";\nfunction deployCommand(program) {\n program.command(\"deploy [project]\").description(\"Deploy project via Dokploy\").option(\"--domain <domain>\", \"Custom domain for deployment\").option(\"--env <vars...>\", \"Environment variables (KEY=value)\").action(async (projectName, options) => {\n console.log(\"\\u{1F680} Deploying with Dokploy\");\n console.log(\"\");\n const dokploy = new DokployService();\n try {\n await dokploy.install();\n const statePath = join7(process.cwd(), \".eve\", \"builder-state.json\");\n let projectId = null;\n if (existsSync7(statePath)) {\n const state = JSON.parse(readFileSync4(statePath, \"utf-8\"));\n if (!projectName && state.components?.dokploy?.skipped) {\n console.log(\n \"This workspace was initialized without Dokploy (--with-dokploy not used).\\nDeploy using DOKPLOY_WEBHOOK_URL from .env, your CI, or re-run:\\n eve builder init <name> --with-dokploy\\n\"\n );\n process.exit(1);\n }\n if (projectName) {\n const status2 = await dokploy.getStatus();\n const found = status2.projects.find((p) => p.name === projectName);\n if (found) {\n projectId = found.id;\n }\n } else if (state.components?.dokploy?.projectName) {\n const status2 = await dokploy.getStatus();\n const found = status2.projects.find(\n (p) => p.name === state.components?.dokploy?.projectName\n );\n if (found) {\n projectId = found.id;\n }\n }\n }\n if (!projectId) {\n if (projectName) {\n console.log(`Creating new Dokploy project: ${projectName}`);\n await dokploy.createProject(projectName);\n const status2 = await dokploy.getStatus();\n const newProject = status2.projects.find((p) => p.name === projectName);\n if (newProject) {\n projectId = newProject.id;\n }\n } else {\n throw new Error(\n 'No project specified. Run \"eve builder init <name>\" first or provide a project name.'\n );\n }\n }\n if (!projectId) {\n throw new Error(\"Could not determine project to deploy\");\n }\n if (options.domain) {\n console.log(`Configuring custom domain: ${options.domain}`);\n await dokploy.configureDomain(options.domain);\n }\n if (options.env && options.env.length > 0) {\n console.log(\"Setting environment variables:\");\n for (const envVar of options.env) {\n const [key, value] = envVar.split(\"=\");\n if (key && value) {\n console.log(` ${key}=${\"*\".repeat(value.length)}`);\n }\n }\n }\n console.log(\"\");\n console.log(\"Starting deployment...\");\n console.log(\"-------------------------------------------\");\n await dokploy.deploy(projectId);\n const status = await dokploy.getStatus();\n const project = status.projects.find((p) => p.id === projectId);\n console.log(\"-------------------------------------------\");\n console.log(\"\\u2705 Deployment successful!\");\n console.log(\"\");\n if (project?.url) {\n console.log(`\\u{1F310} Project URL: ${project.url}`);\n }\n if (options.domain) {\n console.log(`\\u{1F517} Custom Domain: https://${options.domain}`);\n }\n console.log(\"\");\n console.log(\"Deployment status:\", project?.status);\n } catch (error) {\n console.error(\"\\u274C Deployment failed:\", error);\n process.exit(1);\n }\n });\n}\n\n// src/commands/stack.ts\nimport { existsSync as existsSync8, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from \"fs\";\nimport { join as join8 } from \"path\";\nimport { execSync as execSync3 } from \"child_process\";\nvar COMPOSE = `services:\n eve-builder-site:\n image: nginx:alpine\n container_name: eve-builder-site\n restart: unless-stopped\n ports:\n - \"127.0.0.1:9080:80\"\n volumes:\n - \\${EVE_BUILDER_SITE_DIR}:/usr/share/nginx/html:ro\n networks:\n - eve-network\n\nnetworks:\n eve-network:\n external: true\n`.trim();\nfunction composePath(cwd) {\n return join8(cwd, \".eve\", \"builder-docker-compose.yml\");\n}\nfunction defaultSiteDir(cwd) {\n return join8(cwd, \".eve\", \"builder-site\", \"public\");\n}\nfunction ensureSiteContent(siteDir) {\n mkdirSync7(siteDir, { recursive: true });\n const index = join8(siteDir, \"index.html\");\n if (!existsSync8(index)) {\n writeFileSync7(\n index,\n `<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"/><title>Eve Builder</title></head><body><h1>Builder base site</h1><p>Static root for OpenCode output. Served at http://127.0.0.1:9080</p></body></html>\n`\n );\n }\n}\nfunction stackCommand(program) {\n const stack = program.command(\"stack\").description(\"Nginx base site stack (Docker, eve-network, :9080)\");\n stack.command(\"up\").description(\"Start nginx static site container\").action(() => {\n const cwd = process.cwd();\n const siteDir = defaultSiteDir(cwd);\n ensureSiteContent(siteDir);\n mkdirSync7(join8(cwd, \".eve\"), { recursive: true });\n writeFileSync7(composePath(cwd), COMPOSE, \"utf-8\");\n try {\n execSync3(\"docker network create eve-network\", { stdio: \"ignore\" });\n } catch {\n }\n const env = { ...process.env, EVE_BUILDER_SITE_DIR: siteDir };\n execSync3(`docker compose -f \"${composePath(cwd)}\" up -d`, {\n stdio: \"inherit\",\n cwd,\n env\n });\n console.log(`\nBuilder site: http://127.0.0.1:9080 (files under ${siteDir})`);\n });\n stack.command(\"down\").description(\"Stop nginx static site container\").action(() => {\n const cwd = process.cwd();\n const siteDir = defaultSiteDir(cwd);\n const env = { ...process.env, EVE_BUILDER_SITE_DIR: siteDir };\n if (!existsSync8(composePath(cwd))) {\n console.log(\"No generated compose file. Run: eve builder stack up\");\n return;\n }\n execSync3(`docker compose -f \"${composePath(cwd)}\" down`, {\n stdio: \"inherit\",\n cwd,\n env\n });\n });\n stack.command(\"status\").description(\"Show builder stack container status\").action(() => {\n try {\n execSync3(\n 'docker ps -a --filter name=eve-builder-site --format \"table {{.Names}}\\\\t{{.Status}}\\\\t{{.Ports}}\"',\n { stdio: \"inherit\" }\n );\n } catch {\n console.log(\"No eve-builder-site container (run: eve builder stack up)\");\n }\n });\n}\n\n// src/commands/sandbox.ts\nimport { existsSync as existsSync9, mkdirSync as mkdirSync8, writeFileSync as writeFileSync8 } from \"fs\";\nimport { join as join9 } from \"path\";\nimport { execSync as execSync4 } from \"child_process\";\nimport { writeSandboxEnvFile } from \"@eve/dna\";\nvar COMPOSE2 = `services:\n eve-builder-sandbox:\n image: node:22-bookworm-slim\n container_name: eve-builder-sandbox\n restart: unless-stopped\n working_dir: /workspace\n env_file:\n - \\${EVE_SANDBOX_ENV_FILE}\n volumes:\n - \\${EVE_WORKSPACE_DIR}:/workspace:rw\n command: [\"bash\", \"-lc\", \"echo 'Eve builder sandbox ready. Example: docker exec -it eve-builder-sandbox bash' && tail -f /dev/null\"]\n networks:\n - eve-network\n\nnetworks:\n eve-network:\n external: true\n`.trim();\nfunction composePath2(cwd) {\n return join9(cwd, \".eve\", \"builder-sandbox-compose.yml\");\n}\nfunction sandboxCommand(program) {\n const sb = program.command(\"sandbox\").description(\"OpenCode-friendly Node sandbox (workspace RW only, eve-network)\");\n sb.command(\"prepare\").description(\"Write .eve/sandbox.env from secrets (no container start)\").action(async () => {\n const cwd = process.cwd();\n const p = await writeSandboxEnvFile(cwd);\n console.log(`Wrote ${p}`);\n });\n sb.command(\"up\").description(\"Start sandbox container (requires docker, eve-network)\").action(async () => {\n const cwd = process.cwd();\n const envFile = await writeSandboxEnvFile(cwd);\n mkdirSync8(join9(cwd, \".eve\"), { recursive: true });\n writeFileSync8(composePath2(cwd), COMPOSE2, \"utf-8\");\n try {\n execSync4(\"docker network create eve-network\", { stdio: \"ignore\" });\n } catch {\n }\n const env = {\n ...process.env,\n EVE_SANDBOX_ENV_FILE: envFile\n };\n execSync4(`docker compose -f \"${composePath2(cwd)}\" up -d`, {\n stdio: \"inherit\",\n cwd,\n env\n });\n console.log(\"\\nSandbox: docker exec -it eve-builder-sandbox bash\");\n console.log(\"Then: npx @opencode/cli \\u2026 (install as needed). Env is in container from sandbox.env\\n\");\n });\n sb.command(\"down\").description(\"Stop sandbox container\").action(() => {\n const cwd = process.cwd();\n if (!existsSync9(composePath2(cwd))) {\n console.log(\"No sandbox compose. Run: eve builder sandbox up\");\n return;\n }\n execSync4(`docker compose -f \"${composePath2(cwd)}\" down`, { stdio: \"inherit\", cwd });\n });\n sb.command(\"status\").description(\"Show sandbox container status\").action(() => {\n try {\n execSync4(\n 'docker ps -a --filter name=eve-builder-sandbox --format \"table {{.Names}}\\\\t{{.Status}}\\\\t{{.Ports}}\"',\n { stdio: \"inherit\" }\n );\n } catch {\n console.log(\"No eve-builder-sandbox container\");\n }\n });\n}\n\n// src/commands/hermes.ts\nfunction registerHermesCommands(yargs) {\n return yargs.command(\"status\", \"Show Hermes daemon status\", () => {\n }, () => {\n console.log(\"[Hermes] Hermes is managed by Docker.\");\n console.log(\" Use `docker logs eve-brain-hermes` to view logs.\");\n });\n}\n\n// src/commands/codex.ts\nimport { readEveSecrets as readEveSecrets6, readAgentKeyOrLegacy, resolveHubBaseUrl as resolveHubBaseUrl2 } from \"@eve/dna\";\n\n// src/lib/t3code-client.ts\nimport { WebSocket } from \"ws\";\nvar T3CodeClient = class {\n constructor(config) {\n this.config = config;\n }\n config;\n async runTurn(params) {\n const turnTimeout = params.timeoutMs ?? this.config.turnTimeoutMs ?? 45 * 6e4;\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(this.config.url, {\n headers: this.config.apiKey ? { Authorization: `Bearer ${this.config.apiKey}` } : {}\n });\n let sessionId = null;\n let msgId = 0;\n const nextId = () => ++msgId;\n let turnSent = false;\n let settled = false;\n const timeoutHandle = setTimeout(() => {\n finish(new Error(`T3Code turn timed out after ${Math.round(turnTimeout / 6e4)}min`));\n }, turnTimeout);\n const finish = (result) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutHandle);\n try {\n ws.close(1e3);\n } catch {\n }\n if (result instanceof Error) reject(result);\n else resolve(result);\n };\n const send = (payload) => {\n ws.send(JSON.stringify({ jsonrpc: \"2.0\", ...payload }));\n };\n ws.on(\"open\", () => {\n send({\n id: nextId(),\n method: \"orchestration.dispatchCommand\",\n params: {\n command: \"providers.startSession\",\n params: { providerId: \"codex\", runtimeMode: \"full-access\", cwd: params.cwd }\n }\n });\n });\n ws.on(\"message\", (data) => {\n let msg;\n try {\n msg = JSON.parse(data.toString());\n } catch {\n return;\n }\n if (!turnSent && msg.id !== void 0) {\n if (msg.error) {\n finish(new Error(`T3Code startSession error: ${msg.error.message}`));\n return;\n }\n const r = msg.result;\n if (r?.sessionId) {\n sessionId = r.sessionId;\n turnSent = true;\n send({\n id: nextId(),\n method: \"orchestration.dispatchCommand\",\n params: {\n command: \"providers.sendTurn\",\n params: {\n sessionId,\n messages: params.messages,\n ...params.resumeCursor ? { resumeCursor: params.resumeCursor } : {}\n }\n }\n });\n }\n return;\n }\n if (msg.method && (msg.method.includes(\"delta\") || msg.method.includes(\"progress\"))) {\n params.onProgress?.(msg.params);\n return;\n }\n if (msg.method === \"turn/completed\" || msg.method === \"session.turn.complete\") {\n const p = msg.params;\n finish({\n resumeCursor: p.resumeCursor,\n output: p.output ?? [],\n sessionId: p.sessionId ?? sessionId ?? \"\"\n });\n return;\n }\n if (msg.error && turnSent) {\n finish(new Error(`T3Code sendTurn error: ${msg.error.message}`));\n }\n });\n ws.on(\"error\", (err) => finish(err));\n ws.on(\"close\", (code) => {\n if (!settled && code !== 1e3) {\n finish(new Error(`T3Code WebSocket closed unexpectedly (code ${code})`));\n }\n });\n });\n }\n};\n\n// src/lib/codex-pipeline.ts\nvar PHASE_NEXT_STATUS = {\n executing: \"verifying\",\n verifying: \"awaiting_review\",\n debugging: \"verifying\"\n};\nvar PHASE_TIMEOUT_MS = {\n executing: 45 * 6e4,\n verifying: 15 * 6e4,\n debugging: 45 * 6e4\n};\nvar CodexPipeline = class {\n client;\n hubBaseUrl;\n apiKey;\n constructor(config) {\n this.client = new T3CodeClient({ url: config.t3codeUrl, apiKey: config.t3codeApiKey });\n this.hubBaseUrl = config.hubBaseUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n }\n async runPhase(featureId, phase) {\n let feature;\n try {\n feature = await this.fetchFeature(featureId);\n } catch (err) {\n console.error(`[CodexPipeline] Failed to fetch feature ${featureId}:`, err);\n return;\n }\n const props = feature.properties ?? {};\n const cwd = props.t3code_cwd;\n if (!cwd) {\n console.error(\n `[CodexPipeline] Feature ${featureId} has no t3code_cwd \\u2014 cannot run ${phase}`\n );\n await this.updateFeature(featureId, {\n agent_status: \"error\",\n error_reason: \"t3code_cwd_missing\"\n });\n return;\n }\n console.log(`[CodexPipeline] ${phase} \\u2192 feature ${featureId} (cwd: ${cwd})`);\n const prompt = buildPrompt(phase, feature.title ?? \"Untitled\", props);\n const resumeCursor = props.t3code_resume_cursor;\n let result;\n try {\n result = await this.client.runTurn({\n cwd,\n messages: [{ role: \"user\", content: prompt }],\n resumeCursor,\n timeoutMs: PHASE_TIMEOUT_MS[phase],\n onProgress: () => process.stdout.write(\".\")\n });\n process.stdout.write(\"\\n\");\n } catch (err) {\n console.error(`[CodexPipeline] ${phase} failed for feature ${featureId}:`, err);\n await this.updateFeature(featureId, {\n agent_status: \"error\",\n error_reason: `${phase}_failed`,\n error_detail: err.message\n });\n return;\n }\n const summary = extractSummary(result.output);\n const updates = {\n agent_status: PHASE_NEXT_STATUS[phase],\n t3code_resume_cursor: result.resumeCursor\n };\n if (phase === \"executing\") updates.execution_summary = summary;\n if (phase === \"verifying\") updates.verification_report = summary;\n if (phase === \"debugging\") updates.debug_summary = summary;\n await this.updateFeature(featureId, updates);\n console.log(`[CodexPipeline] ${phase} complete \\u2192 ${PHASE_NEXT_STATUS[phase]}`);\n const channelId = props.entityChannelId;\n if (channelId) {\n await this.postToChannel(channelId, `**${phase}** complete:\n${summary.slice(0, 500)}`);\n }\n }\n async fetchFeature(id) {\n const res = await fetch(`${this.hubBaseUrl}/entities/${id}`, {\n headers: { Authorization: `Bearer ${this.apiKey}` }\n });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n return res.json();\n }\n async updateFeature(id, properties) {\n await fetch(`${this.hubBaseUrl}/entities/${id}`, {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ properties })\n }).catch((err) => console.warn(\"[CodexPipeline] Update failed:\", err));\n }\n async postToChannel(channelId, content) {\n await fetch(`${this.hubBaseUrl}/channels/${channelId}/messages`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ content })\n }).catch(() => {\n });\n }\n};\nfunction buildPrompt(phase, title, props) {\n const lines = [`## Feature: ${title}`];\n if (phase === \"executing\") {\n if (props.description) lines.push(\"\", \"### Description\", \"\", String(props.description));\n if (props.acceptance_criteria)\n lines.push(\"\", \"### Acceptance Criteria\", \"\", String(props.acceptance_criteria));\n if (props.plan) lines.push(\"\", \"### Implementation Plan\", \"\", String(props.plan));\n lines.push(\n \"\",\n \"Execute every step of the implementation plan exactly as written.\",\n \"Do not add scope beyond what is specified.\",\n \"Write tests for new functionality. Run them before finishing.\",\n \"When done, provide a concise execution summary listing files changed.\"\n );\n }\n if (phase === \"verifying\") {\n if (props.acceptance_criteria)\n lines.push(\"\", \"### Acceptance Criteria\", \"\", String(props.acceptance_criteria));\n if (props.execution_summary)\n lines.push(\"\", \"### Execution Summary\", \"\", String(props.execution_summary));\n lines.push(\n \"\",\n \"Run the full quality suite: tests, type checker, linter.\",\n \"Report results with a clear PASS or FAIL verdict.\",\n \"Include details of any failures: file, line number, error message.\",\n \"Do NOT fix anything \\u2014 only report.\"\n );\n }\n if (phase === \"debugging\") {\n if (props.verification_report)\n lines.push(\"\", \"### Verification Report (issues to fix)\", \"\", String(props.verification_report));\n if (props.execution_summary)\n lines.push(\"\", \"### Previous Execution Summary\", \"\", String(props.execution_summary));\n lines.push(\n \"\",\n \"Fix each issue listed in the verification report. Be surgical \\u2014 only touch what is broken.\",\n \"Do not refactor or improve unrelated code.\",\n \"When done, list what was fixed and why.\"\n );\n }\n return lines.join(\"\\n\");\n}\nfunction extractSummary(output) {\n const texts = output.map((item) => item?.text ?? item?.content ?? \"\").filter(Boolean);\n return texts.join(\"\\n\").trim() || \"Phase completed\";\n}\n\n// src/lib/task-poll.ts\nvar TaskPoller = class {\n config;\n lastSince = \"0\";\n retryCount = 0;\n currentBackoff = 0;\n _running = false;\n constructor(config) {\n this.config = config;\n }\n get running() {\n return this._running;\n }\n /**\n * Poll Synap for new/updated tasks for a single assigned agent.\n * Uses the entity router with filters: profileSlug=task, assignedAgentId=<id>.\n *\n * Defaults to 'hermes' for backwards compat. For multi-personality polling\n * pass the personality user ID. Note: `lastSince` is shared across all\n * assignees because the underlying cursor is monotonic across the event log.\n * The simple N+1 loop in HermesDaemon advances it once per cycle.\n */\n async pollTasks(assignedAgentId = \"hermes\") {\n const url = new URL(`${this.config.apiUrl}/api/hub/entities`);\n url.searchParams.set(\"profileSlug\", \"task\");\n url.searchParams.set(\"assignedAgentId\", assignedAgentId);\n url.searchParams.set(\"since\", this.lastSince);\n url.searchParams.set(\"limit\", \"50\");\n try {\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Authorization\": `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n }\n });\n if (response.ok) {\n const data = await response.json();\n this.retryCount = 0;\n this.currentBackoff = 0;\n this.lastSince = data.since || this.lastSince;\n return { tasks: data.tasks || [], since: data.since };\n }\n if (response.status === 429 || response.status >= 500) {\n this.retryCount++;\n this.currentBackoff = Math.min(\n this.config.intervalMs * Math.pow(this.config.backoffMultiplier, this.retryCount),\n 5 * 60 * 1e3\n // Cap at 5 minutes\n );\n throw new TransientError(`HTTP ${response.status}: ${response.statusText}`);\n }\n throw new PollError(`HTTP ${response.status}: ${response.statusText}`);\n } catch (error) {\n if (error instanceof TransientError) {\n if (this.retryCount >= this.config.maxRetries) {\n throw new PollError(`Max retries (${this.config.maxRetries}) exceeded after transient error`);\n }\n throw error;\n }\n if (error instanceof PollError) throw error;\n throw new PollError(`Network error: ${error.message}`);\n }\n }\n /**\n * Poll for tasks across multiple assignees (orchestrator + personalities).\n * Implementation: N+1 fetch calls per cycle. Simple. Works on any pod with\n * the existing `/entities?assignedAgentId=...` endpoint.\n *\n * Upgrade path: when a `?assignedAgentIdIn=a,b,c` filter ships on the pod,\n * collapse this into a single call without changing the daemon-side API.\n */\n async pollTasksForMany(assignedAgentIds) {\n const aggregated = [];\n let latestSince = this.lastSince;\n for (const id of assignedAgentIds) {\n const resp = await this.pollTasks(id);\n aggregated.push(...resp.tasks);\n if (resp.since && resp.since > latestSince) latestSince = resp.since;\n }\n return { tasks: aggregated, since: latestSince };\n }\n /**\n * Hub REST: list agents whose parentAgentId == userId.\n *\n * Response shape: `[{ id, name, agentType }]`. The backend deliberately\n * does NOT return the full agentMetadata blob — only the agentType slug\n * we need for routing.\n */\n async listChildAgents(parentUserId) {\n const url = new URL(`${this.config.apiUrl}/api/hub/agent-users`);\n url.searchParams.set(\"parentUserId\", parentUserId);\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Authorization\": `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n }\n });\n if (!response.ok) {\n throw new PollError(\n `listChildAgents failed: HTTP ${response.status} ${response.statusText}`\n );\n }\n const data = await response.json();\n return data ?? [];\n }\n /**\n * Hub REST: list agent users that are members of a workspace.\n *\n * Used as a fallback discovery path when personalities are provisioned as\n * workspace-scoped agent users (no parentAgentId set) rather than children\n * of the Hermes orchestrator user.\n */\n async listWorkspaceAgentUsers(workspaceId) {\n const url = new URL(`${this.config.apiUrl}/api/hub/agent-users`);\n url.searchParams.set(\"workspaceId\", workspaceId);\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Authorization\": `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n }\n });\n if (!response.ok) {\n throw new PollError(\n `listWorkspaceAgentUsers failed: HTTP ${response.status} ${response.statusText}`\n );\n }\n const data = await response.json();\n return (data ?? []).map((row) => ({\n id: row.id,\n name: row.name,\n agentType: row.agentMetadata?.agentType ?? null\n }));\n }\n /** Hub REST: fetch agent_configs row for (userId, workspaceId, agentType). */\n async getAgentConfig(params) {\n const url = new URL(`${this.config.apiUrl}/api/hub/agent-configs`);\n url.searchParams.set(\"userId\", params.userId);\n if (params.workspaceId) url.searchParams.set(\"workspaceId\", params.workspaceId);\n if (params.agentType) url.searchParams.set(\"agentType\", params.agentType);\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n \"Authorization\": `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n }\n });\n if (!response.ok) {\n return null;\n }\n const rows = await response.json();\n if (!Array.isArray(rows) || rows.length === 0) return null;\n return rows[0];\n }\n /** Submit task result back to Synap. */\n async submitResult(taskId, result) {\n const url = `${this.config.apiUrl}/api/hub/entities/tasks/${taskId}`;\n try {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {\n \"Authorization\": `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ result, status: \"done\" })\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n /** Update task status on Synap. */\n async updateTaskStatus(taskId, status) {\n const url = `${this.config.apiUrl}/api/hub/entities/tasks/${taskId}`;\n try {\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {\n \"Authorization\": `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ status })\n });\n return response.ok;\n } catch {\n return false;\n }\n }\n /** Wait for backoff period (used by daemon loop). */\n getBackoffMs() {\n return this.currentBackoff;\n }\n resetCursor() {\n this.lastSince = \"0\";\n this.retryCount = 0;\n this.currentBackoff = 0;\n }\n /** Create a Synap memory note with the given content. Best-effort — returns false on failure. */\n async createMemoryNote(params) {\n try {\n const res = await fetch(`${this.config.apiUrl}/api/hub/entities`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.config.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n profileSlug: \"note\",\n content: params.content,\n ...params.userId ? { userId: params.userId } : {},\n metadata: params.metadata ?? {}\n })\n });\n return res.ok;\n } catch {\n return false;\n }\n }\n};\nvar PollError = class extends Error {\n constructor(message) {\n super(message);\n this.name = \"PollError\";\n }\n};\nvar TransientError = class extends Error {\n constructor(message) {\n super(message);\n this.name = \"TransientError\";\n }\n};\n\n// src/lib/codex-feature-poller.ts\nvar CODE_PHASES = [\"executing\", \"verifying\", \"debugging\"];\nvar PHASE_TIMEOUT_MS2 = {\n executing: 45 * 6e4,\n verifying: 15 * 6e4,\n debugging: 45 * 6e4\n};\nvar CodexFeaturePoller = class {\n pipeline;\n hubBaseUrl;\n apiKey;\n pollIntervalMs;\n active = /* @__PURE__ */ new Set();\n // featureId:phase in-flight\n running = false;\n constructor(config) {\n this.hubBaseUrl = config.hubBaseUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.pollIntervalMs = config.pollIntervalMs ?? 15e3;\n this.pipeline = new CodexPipeline({\n t3codeUrl: config.t3codeUrl,\n t3codeApiKey: config.t3codeApiKey,\n hubBaseUrl: config.hubBaseUrl,\n apiKey: config.apiKey\n });\n }\n async start() {\n this.running = true;\n console.log(`[CodexPoller] Started \\u2014 polling every ${this.pollIntervalMs / 1e3}s`);\n console.log(`[CodexPoller] Handling phases: ${CODE_PHASES.join(\", \")}`);\n while (this.running) {\n try {\n await this.tick();\n } catch (err) {\n if (!(err instanceof TransientError)) {\n console.error(\"[CodexPoller] Tick error:\", err);\n }\n }\n await sleep(this.pollIntervalMs);\n }\n console.log(\"[CodexPoller] Stopped\");\n }\n stop() {\n this.running = false;\n }\n async tick() {\n await this.checkTimeouts();\n const features = await this.fetchCodePhaseFeatures();\n for (const feature of features) {\n const phase = feature.properties.agent_status;\n const key = `${feature.id}:${phase}`;\n if (this.active.has(key)) continue;\n this.active.add(key);\n await this.markDispatched(feature.id, phase);\n this.pipeline.runPhase(feature.id, phase).catch(\n (err) => console.error(`[CodexPoller] runPhase failed for feature ${feature.id}:`, err)\n ).finally(() => this.active.delete(key));\n }\n }\n async fetchCodePhaseFeatures() {\n const url = new URL(`${this.hubBaseUrl}/entities`);\n url.searchParams.set(\"profileSlug\", \"devplane_feature\");\n url.searchParams.set(\"limit\", \"5\");\n let res;\n try {\n res = await fetch(url.toString(), {\n headers: { Authorization: `Bearer ${this.apiKey}` }\n });\n } catch (err) {\n throw new TransientError(`Network error: ${err.message}`);\n }\n if (res.status === 429 || res.status >= 500) throw new TransientError(`HTTP ${res.status}`);\n if (!res.ok) throw new PollError(`HTTP ${res.status}: ${res.statusText}`);\n const data = await res.json();\n return (data.entities ?? []).filter(\n (e) => CODE_PHASES.includes(e.properties.agent_status)\n );\n }\n async checkTimeouts() {\n const url = new URL(`${this.hubBaseUrl}/entities`);\n url.searchParams.set(\"profileSlug\", \"devplane_feature\");\n url.searchParams.set(\"agentStatus\", \"dispatched\");\n url.searchParams.set(\"limit\", \"20\");\n try {\n const res = await fetch(url.toString(), {\n headers: { Authorization: `Bearer ${this.apiKey}` }\n });\n if (!res.ok) return;\n const data = await res.json();\n for (const feature of data.entities ?? []) {\n const phase = feature.properties.agent_phase;\n const dispatchedAt = feature.properties.dispatched_at;\n if (!phase || !CODE_PHASES.includes(phase)) continue;\n if (!dispatchedAt) continue;\n const age = Date.now() - new Date(dispatchedAt).getTime();\n const timeout = PHASE_TIMEOUT_MS2[phase];\n if (age > timeout) {\n console.warn(\n `[CodexPoller] ${phase} timed out for feature ${feature.id} (${Math.round(age / 6e4)}min)`\n );\n await this.markError(feature.id, `${phase}_timeout`);\n }\n }\n } catch {\n }\n }\n async markDispatched(featureId, phase) {\n await this.patch(featureId, {\n agent_status: \"dispatched\",\n agent_phase: phase,\n dispatched_at: (/* @__PURE__ */ new Date()).toISOString()\n });\n }\n async markError(featureId, reason) {\n await this.patch(featureId, { agent_status: \"error\", error_reason: reason });\n }\n async patch(featureId, properties) {\n await fetch(`${this.hubBaseUrl}/entities/${featureId}`, {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ properties })\n }).catch(() => {\n });\n }\n};\nfunction sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// src/commands/codex.ts\nvar CODE_PHASES2 = [\"executing\", \"verifying\", \"debugging\"];\nfunction registerCodexCommands(parentCmd) {\n const codex = parentCmd.command(\"codex\").description(\"Codex code-execution engine via T3 Code\");\n codex.command(\"daemon\").description(\n \"Start the Codex feature-polling daemon.\\nHandles executing / verifying / debugging pipeline phases via T3 Code.\\nRequires: secrets.builder.t3code.url and a valid agent API key.\"\n ).option(\"--poll-interval <ms>\", \"Poll interval in milliseconds\", \"15000\").action(async (opts) => {\n const secrets = await readEveSecrets6();\n const t3cfg = secrets?.builder?.t3code;\n if (!t3cfg?.url) {\n console.error(\n \"[codex daemon] T3 Code URL not configured.\\nSet it with: eve config set builder.t3code.url ws://<host>:<port>\"\n );\n process.exit(1);\n }\n const hubBaseUrl = resolveHubBaseUrl2(secrets);\n if (!hubBaseUrl) {\n console.error(\"[codex daemon] Synap pod URL not configured. Run: eve setup\");\n process.exit(1);\n }\n const apiKey = await readAgentKeyOrLegacy(\"codex\");\n if (!apiKey) {\n console.error(\"[codex daemon] No agent API key found. Run: eve setup\");\n process.exit(1);\n }\n const poller = new CodexFeaturePoller({\n hubBaseUrl,\n apiKey,\n t3codeUrl: t3cfg.url,\n t3codeApiKey: t3cfg.apiKey,\n pollIntervalMs: parseInt(opts.pollInterval, 10)\n });\n process.on(\"SIGINT\", () => {\n poller.stop();\n process.exit(0);\n });\n process.on(\"SIGTERM\", () => {\n poller.stop();\n process.exit(0);\n });\n await poller.start();\n });\n codex.command(\"run <featureId> <phase>\").description(\n \"Run a single code phase for a feature (one-shot, no polling).\\nValid phases: executing | verifying | debugging\"\n ).action(async (featureId, phase) => {\n if (!CODE_PHASES2.includes(phase)) {\n console.error(`Invalid phase: \"${phase}\". Must be one of: ${CODE_PHASES2.join(\", \")}`);\n process.exit(1);\n }\n const secrets = await readEveSecrets6();\n const t3cfg = secrets?.builder?.t3code;\n if (!t3cfg?.url) {\n console.error(\"[codex run] T3 Code URL not configured.\");\n process.exit(1);\n }\n const hubBaseUrl = resolveHubBaseUrl2(secrets);\n if (!hubBaseUrl) {\n console.error(\"[codex run] Synap pod URL not configured.\");\n process.exit(1);\n }\n const apiKey = await readAgentKeyOrLegacy(\"codex\");\n if (!apiKey) {\n console.error(\"[codex run] No agent API key found.\");\n process.exit(1);\n }\n const pipeline = new CodexPipeline({\n t3codeUrl: t3cfg.url,\n t3codeApiKey: t3cfg.apiKey,\n hubBaseUrl,\n apiKey\n });\n await pipeline.runPhase(featureId, phase);\n console.log(\"Done.\");\n });\n codex.command(\"status\").description(\"Show T3 Code configuration status\").action(async () => {\n const secrets = await readEveSecrets6();\n const t3cfg = secrets?.builder?.t3code;\n const hubBaseUrl = resolveHubBaseUrl2(secrets);\n console.log(\"T3 Code configuration:\");\n console.log(` URL: ${t3cfg?.url ?? \"(not set)\"}`);\n console.log(` API key: ${t3cfg?.apiKey ? \"(set)\" : \"(not set)\"}`);\n console.log(` Hub: ${hubBaseUrl ?? \"(not set)\"}`);\n });\n}\n\n// src/lib/pipeline-personalities.ts\nvar CONTEXT_GATHERER_PROMPT = `You are the Context Gatherer \\u2014 the first phase of a DevPlane automated pipeline. Your job is to collect every piece of information the downstream Planner and Executor will need to implement a feature correctly.\n\n## What to do\n\n1. **Read the feature spec** \\u2014 the feature entity's title, description, and any messages in its AI channel. Understand what is being built and why.\n2. **Read the linked app's tech stack** \\u2014 use synap_entity_search or synap_search to find the linked application and its technology stack, framework, language, and architecture notes.\n3. **Read decision records** \\u2014 search for decision_records related to the app or feature domain. These capture past architectural choices you must respect.\n4. **Read best practices** \\u2014 search for best_practices documents that apply to this codebase or domain.\n5. **Read codebase maps** \\u2014 if available, read codebase_map documents to understand the project structure, key modules, and file organization.\n6. **Resolve the repo path** \\u2014 search for the devplane_service entity linked to this feature (via relations or the feature's linkedServiceId property). Read its \\`repoLocalPath\\` property (e.g. \\`/opt/synap/synap-app\\`). Then update the feature entity using synap_entity_update to set its \\`t3code_cwd\\` property to that path. This is required so T3 Code knows where to find the code on the server. If no service is linked or \\`repoLocalPath\\` is empty, note it in Open Questions.\n\n## Output\n\nWrite a comprehensive structured context document to the feature's AI channel using synap_channel_message. The document MUST have these sections:\n\n### Feature Summary\n- What is being built (1-2 paragraphs)\n- Key requirements and constraints\n- Success criteria\n\n### Tech Stack\n- Framework, language, runtime versions\n- Key dependencies and libraries\n- Database, caching, infrastructure\n\n### Relevant Decision Records\n- Summarize each relevant decision and its implications for this feature\n\n### Best Practices\n- List applicable coding standards, patterns, and conventions\n\n### Codebase Touch Points\n- Modules and packages likely to be modified or created (derived from codebase_map entities and decision records)\n- Existing patterns to follow\n- Integration points with other modules\n\n### Open Questions\n- Anything ambiguous or missing that the Planner should clarify\n\n## Rules\n- Be thorough \\u2014 the Planner and Executor depend entirely on your output\n- Do NOT write any code or implementation details \\u2014 that is the Planner's job\n- If information is missing, note it in Open Questions rather than guessing\n- Use markdown formatting throughout`;\nvar PLANNER_PROMPT = `You are the Planner \\u2014 the second phase of a DevPlane automated pipeline. Your job is to read the Context Gatherer's output and produce a detailed, actionable implementation plan.\n\n## What to do\n\n1. **Read the context document** from the feature's AI channel (written by the Context Gatherer).\n2. **Understand the full scope** \\u2014 what needs to be built, what constraints exist, what patterns to follow.\n3. **Create a numbered implementation plan** \\u2014 each task must be specific enough that the Executor can follow it without ambiguity.\n\n## Plan format\n\nEach task in the plan MUST include:\n- **Task number** (1, 2, 3...)\n- **Description** \\u2014 what to do, in specific terms\n- **File(s)** \\u2014 which files to modify or create (full paths)\n- **Approach** \\u2014 how to implement it (patterns, APIs, data structures)\n- **Test coverage** \\u2014 what tests to write or update\n\n## Output\n\nWrite the implementation plan as a document to the feature's AI channel using synap_channel_message. Format it as a numbered list with the sections above for each task.\n\nAfter writing the plan, create a Synap Proposal entity using synap_entity_create with:\n- profileSlug: \"proposal\" (or the appropriate proposal type)\n- name: \"Implementation Plan: [feature title]\"\n- properties: { planType: \"feature_plan\", phase: \"planning\" }\n- workspaceId: the feature's workspace\n\nThen update the feature entity with the proposal ID using synap_entity_update, setting plan_proposal_id to the created proposal's ID.\n\n## Rules\n- Be specific \\u2014 vague tasks cause failures downstream\n- Each task should be independently implementable\n- Respect the constraints and patterns from the context document\n- Do NOT write any code \\u2014 that is the Executor's job\n- Include test planning for every task\n- If the plan requires more than 10 tasks, group them into phases`;\nvar EXECUTOR_PROMPT = `You are the Executor \\u2014 the third phase of a DevPlane automated pipeline. Your job is to implement the code changes specified in the approved implementation plan.\n\n## What to do\n\n1. **Read the approved implementation plan** from the feature's AI channel.\n2. **Read the context document** from the Context Gatherer for reference.\n3. **Implement every task in order** \\u2014 follow the plan exactly.\n\n## Rules\n- Follow the plan step by step \\u2014 do NOT deviate without good reason\n- If you hit a blocker (missing dependency, unclear spec, conflicting constraints), write it to the AI channel and STOP \\u2014 do not guess\n- Do NOT invent scope beyond what the plan specifies\n- Follow existing code patterns, naming conventions, and architecture\n- Write tests for new functionality\n- Update existing tests if you modify behavior\n- Commit to a feature branch with clear, descriptive commit messages\n- Group related changes into logical commits\n\n## After implementation\n\nWrite a brief execution summary to the feature's AI channel including:\n- Tasks completed (by number from the plan)\n- Files changed (created, modified, deleted)\n- Any deviations from the plan and why\n- Known issues or follow-up items\n\n## Important\n- You are working in the local repository \\u2014 make real file changes\n- Use the filesystem tools to read, write, and edit files\n- Run tests locally before committing\n- If the plan says to create a file, create it with proper structure\n- If the plan says to modify a file, preserve existing functionality`;\nvar VERIFIER_PROMPT = `You are the Verifier \\u2014 the fourth phase of a DevPlane automated pipeline. Your job is to run the full quality suite and report results.\n\n## What to do\n\n1. **Run tests** \\u2014 execute the project's test suite (npm test, yarn test, pnpm test, or whatever the project uses).\n2. **Run type checker** \\u2014 execute the TypeScript/Flow type checker (npx tsc --noEmit, or equivalent).\n3. **Run linter** \\u2014 execute the linter (npm run lint, or equivalent).\n\n## Output\n\nWrite a structured verification report to the feature's AI channel using synap_channel_message with these exact sections:\n\n### Test Results\n- Command run\n- Pass/fail status\n- Number of tests passed/failed/skipped\n- Details of any failures (file, test name, error message)\n\n### Type Check\n- Command run\n- Pass/fail status\n- List of type errors (file, line, description) if any\n\n### Lint\n- Command run\n- Pass/fail status\n- List of lint issues (file, line, rule, description) if any\n\n### Overall Verdict\n- **PASS** \\u2014 all checks passed\n- **FAIL** \\u2014 one or more checks failed\n\n### Required Fixes (if FAIL)\n- Specific actions needed to resolve each failure\n- File paths and line numbers\n\n## Rules\n- Do NOT fix any issues \\u2014 only report them\n- Be precise with file paths and line numbers\n- If a command doesn't exist (no test script configured), note that and mark it as SKIPPED\n- Run each check independently \\u2014 a test failure should not prevent type checking\n- Include the exact commands you ran so they can be reproduced`;\nvar DEPLOYER_PROMPT = `You are the Deployer \\u2014 the fifth and final phase of a DevPlane automated pipeline. Your job is to trigger the staging deployment and monitor it to completion.\n\n## What to do\n\n1. **Identify the target** \\u2014 determine which app/environment to deploy to from the feature context.\n2. **Trigger the deployment** \\u2014 use the Coolify API, recipe, or CLI to start a staging deploy.\n3. **Monitor the deploy** \\u2014 poll the deployment status until it completes or fails.\n4. **Report the result** \\u2014 write the outcome to the feature's AI channel.\n\n## Deployment methods\n\nTry these in order:\n1. **Coolify API** \\u2014 if COOLIFY_URL and COOLIFY_API_KEY are available in env, use the Coolify REST API to trigger a deploy.\n2. **Coolify CLI** \\u2014 if the coolify CLI is installed, use it to trigger the deploy.\n3. **Dokploy** \\u2014 if using Dokploy, trigger the deploy via the DokployService or API.\n4. **Manual command** \\u2014 if a deploy script exists (npm run deploy, etc.), run it.\n\n## Output\n\nWrite a deployment report to the feature's AI channel using synap_channel_message with these sections:\n\n### Deployment Details\n- Target environment (staging/production)\n- Deployment method used\n- Start time\n\n### Status\n- **SUCCESS** \\u2014 deployment completed\n- **FAILED** \\u2014 deployment failed\n\n### Result\n- Deployment URL (if successful)\n- Build log excerpt (if failed \\u2014 last 20-30 lines)\n- Error message (if failed)\n\n### Recommended Next Steps\n- If successful: \"Feature is live on staging. Request human review.\"\n- If failed: specific actions to resolve the failure\n\n## Rules\n- Only deploy to staging \\u2014 never production\n- If you cannot find a deployment mechanism, report it clearly\n- Include enough log context for debugging if the deploy fails\n- Do not retry failed deploys automatically \\u2014 report and stop`;\nvar PIPELINE_PERSONALITIES = {\n \"context-gatherer\": {\n slug: \"context-gatherer\",\n displayName: \"Context Gatherer\",\n model: \"claude-sonnet-4-20250514\",\n systemPrompt: CONTEXT_GATHERER_PROMPT,\n toolWhitelist: [\"synap_orient\", \"synap_entity_search\", \"synap_entity_get\", \"synap_entity_update\", \"synap_document_read\", \"synap_document_create\", \"synap_channel_message\", \"synap_channel_get\", \"synap_knowledge_read\", \"synap_search\", \"synap_relation_list\"],\n maxSteps: 30\n },\n planner: {\n slug: \"planner\",\n displayName: \"Planner\",\n model: \"claude-sonnet-4-20250514\",\n systemPrompt: PLANNER_PROMPT,\n toolWhitelist: [\"read\", \"grep\", \"synap_orient\", \"synap_entity_search\", \"synap_entity_get\", \"synap_entity_create\", \"synap_entity_update\", \"synap_document_read\", \"synap_document_create\", \"synap_channel_message\", \"synap_channel_get\", \"synap_knowledge_read\"],\n maxSteps: 25\n },\n executor: {\n slug: \"executor\",\n displayName: \"Executor\",\n model: \"claude-opus-4-20250514\",\n systemPrompt: EXECUTOR_PROMPT,\n toolWhitelist: [],\n maxSteps: 50\n },\n verifier: {\n slug: \"verifier\",\n displayName: \"Verifier\",\n model: \"claude-sonnet-4-20250514\",\n systemPrompt: VERIFIER_PROMPT,\n toolWhitelist: [\"bash\", \"read\", \"grep\", \"synap_channel_message\", \"synap_channel_get\"],\n maxSteps: 15\n },\n deployer: {\n slug: \"deployer\",\n displayName: \"Deployer\",\n model: \"claude-sonnet-4-20250514\",\n systemPrompt: DEPLOYER_PROMPT,\n toolWhitelist: [\"bash\", \"read\", \"synap_channel_message\", \"synap_channel_get\"],\n maxSteps: 20\n }\n};\n\n// src/lib/feature-poll.ts\nvar PHASE_RUNNING_STATUS = {\n gather: \"gathering_context\",\n plan: \"planning\",\n execute: \"executing\",\n verify: \"verifying\",\n deploy: \"deploying\"\n};\nvar PHASE_SUCCESS_STATUS = {\n gather: \"idle\",\n // triggers plan on next poll\n plan: \"awaiting_plan_approval\",\n // human Gate 1\n execute: \"idle\",\n // triggers verify on next poll\n verify: \"awaiting_deploy_approval\",\n // human Gate 2\n deploy: \"done\"\n};\nvar PHASE_PERSONALITY = {\n gather: \"context-gatherer\",\n plan: \"planner\",\n execute: \"executor\",\n verify: \"verifier\",\n deploy: \"deployer\"\n};\nfunction buildPipelineTask(entity, phase, profileSlug) {\n const now = (/* @__PURE__ */ new Date()).toISOString();\n const personality = PIPELINE_PERSONALITIES[PHASE_PERSONALITY[phase]];\n return {\n id: `pipeline:${entity.id}:${phase}:${Date.now()}`,\n title: `[${phase}] ${entity.title}`,\n description: personality?.systemPrompt,\n type: phase === \"execute\" ? \"code-gen\" : \"custom\",\n assignedAgentId: PHASE_PERSONALITY[phase],\n status: \"pending\",\n priority: \"high\",\n context: {\n isPipelineTask: true,\n phase,\n featureId: entity.id,\n entityId: entity.id,\n entityType: profileSlug,\n workspaceId: entity.workspaceId,\n contextDocId: entity.properties.context_doc_id ?? void 0,\n planProposalId: entity.properties.plan_proposal_id ?? void 0,\n engine: phase === \"execute\" ? \"claudecode\" : void 0,\n env: {\n HERMES_ENTITY_ID: entity.id,\n HERMES_ENTITY_TYPE: profileSlug,\n HERMES_WORKSPACE_ID: entity.workspaceId,\n HERMES_CONTEXT_DOC_ID: entity.properties.context_doc_id ?? \"\",\n HERMES_PLAN_PROPOSAL_ID: entity.properties.plan_proposal_id ?? \"\"\n }\n },\n metadata: {\n createdAt: now,\n updatedAt: now\n }\n };\n}\nfunction resolveTriggerPhase(entity, entityStatusKey) {\n const entityStatus = entity.properties[entityStatusKey];\n if (entityStatus !== \"in-progress\") return null;\n const { context_doc_id, plan_proposal_id, last_completed_phase } = entity.properties;\n if (!context_doc_id) return \"gather\";\n if (!plan_proposal_id) return \"plan\";\n const last = last_completed_phase ?? null;\n if (last !== \"execute\" && last !== \"verify\") return \"execute\";\n if (last === \"execute\") return \"verify\";\n if (last === \"verify\") return \"deploy\";\n return null;\n}\nvar FeaturePoller = class {\n apiBase;\n apiKey;\n workspaceId;\n queue;\n pollIntervalMs;\n maxRetries;\n backoffMultiplier;\n profileSlug;\n entityStatusKey;\n lastSince = \"0\";\n retryCount = 0;\n currentBackoff = 0;\n /** entityId → last known agent_status, to detect transitions into \"idle\" */\n lastKnownAgentStatus = /* @__PURE__ */ new Map();\n /** entityId:phase combinations already enqueued this daemon lifetime */\n enqueuedCombinations = /* @__PURE__ */ new Set();\n constructor(config) {\n this.apiBase = config.apiBase;\n this.apiKey = config.apiKey;\n this.workspaceId = config.workspaceId;\n this.queue = config.queue;\n this.pollIntervalMs = config.pollIntervalMs ?? 3e4;\n this.maxRetries = config.maxRetries ?? 5;\n this.backoffMultiplier = config.backoffMultiplier ?? 2;\n this.profileSlug = config.profileSlug ?? \"devplane_feature\";\n this.entityStatusKey = config.entityStatusKey ?? \"featureStatus\";\n }\n getBackoffMs() {\n return this.currentBackoff;\n }\n resetCursor() {\n this.lastSince = \"0\";\n this.retryCount = 0;\n this.currentBackoff = 0;\n }\n async updateFeatureAgentStatus(featureId, agentStatus) {\n const url = `${this.apiBase}/api/hub/entities/${featureId}`;\n try {\n await fetch(url, {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({ properties: { agent_status: agentStatus } })\n });\n } catch (error) {\n console.warn(\n `[FeaturePoller] Failed to update agent_status for ${featureId}: ${error.message}`\n );\n }\n }\n phaseRunningStatus(phase) {\n return PHASE_RUNNING_STATUS[phase];\n }\n phaseSuccessStatus(phase) {\n return PHASE_SUCCESS_STATUS[phase];\n }\n async pollOnce() {\n const url = new URL(`${this.apiBase}/api/hub/entities`);\n url.searchParams.set(\"profileSlug\", this.profileSlug);\n if (this.workspaceId) url.searchParams.set(\"workspaceId\", this.workspaceId);\n url.searchParams.set(\"since\", this.lastSince);\n url.searchParams.set(\"limit\", \"100\");\n let data;\n try {\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\"\n }\n });\n if (response.ok) {\n data = await response.json();\n this.retryCount = 0;\n this.currentBackoff = 0;\n this.lastSince = data.since || this.lastSince;\n } else if (response.status === 429 || response.status >= 500) {\n this.retryCount++;\n this.currentBackoff = Math.min(\n this.pollIntervalMs * Math.pow(this.backoffMultiplier, this.retryCount),\n 5 * 60 * 1e3\n );\n throw new TransientError(`HTTP ${response.status}: ${response.statusText}`);\n } else {\n throw new PollError(`HTTP ${response.status}: ${response.statusText}`);\n }\n } catch (error) {\n if (error instanceof TransientError) {\n if (this.retryCount >= this.maxRetries) {\n throw new PollError(\n `[FeaturePoller] Max retries (${this.maxRetries}) exceeded after transient error`\n );\n }\n throw error;\n }\n if (error instanceof PollError) throw error;\n throw new PollError(`[FeaturePoller] Network error: ${error.message}`);\n }\n const entities = data.entities ?? [];\n let enqueued = 0;\n for (const entity of entities) {\n const agentStatus = entity.properties.agent_status ?? \"idle\";\n if (agentStatus !== \"idle\") {\n this.lastKnownAgentStatus.set(entity.id, agentStatus);\n continue;\n }\n const prevStatus = this.lastKnownAgentStatus.get(entity.id);\n this.lastKnownAgentStatus.set(entity.id, agentStatus);\n if (prevStatus === \"blocked\" && agentStatus === \"idle\") {\n [\"gather\", \"plan\", \"execute\", \"verify\", \"deploy\"].forEach(\n (p) => this.enqueuedCombinations.delete(`${entity.id}:${p}`)\n );\n }\n if (prevStatus === \"idle\") continue;\n const phase = resolveTriggerPhase(entity, this.entityStatusKey);\n if (!phase) continue;\n const dedupKey = `${entity.id}:${phase}`;\n if (this.enqueuedCombinations.has(dedupKey)) continue;\n const task = buildPipelineTask(entity, phase, this.profileSlug);\n const accepted = this.queue.enqueue(task);\n if (accepted) {\n this.enqueuedCombinations.add(dedupKey);\n enqueued++;\n console.log(\n `[FeaturePoller] Enqueued ${phase} task for entity ${entity.id} (\"${entity.title}\")`\n );\n } else {\n console.warn(\n `[FeaturePoller] Queue full \\u2014 skipped ${phase} task for entity ${entity.id}`\n );\n }\n }\n return enqueued;\n }\n};\n\n// src/lib/task-queue.ts\nvar PRIORITY_ORDER = {\n critical: 4,\n high: 3,\n medium: 2,\n low: 1\n};\nvar TaskQueue = class {\n queue = [];\n maxSize;\n constructor(maxSize = 100) {\n this.maxSize = maxSize;\n }\n /** Add a task to the queue. Returns false if queue is full. */\n enqueue(task) {\n if (this.queue.length >= this.maxSize) {\n return false;\n }\n const index = this.queue.findIndex(\n (t) => PRIORITY_ORDER[t.priority] < PRIORITY_ORDER[task.priority]\n );\n if (index === -1) {\n this.queue.push(task);\n } else {\n this.queue.splice(index, 0, task);\n }\n return true;\n }\n /** Remove and return the highest-priority task. */\n dequeue() {\n return this.queue.shift();\n }\n /** Peek at the next task without removing it. */\n peek() {\n return this.queue[0];\n }\n /** Number of tasks in the queue. */\n get size() {\n return this.queue.length;\n }\n /** Whether the queue is empty. */\n get isEmpty() {\n return this.queue.length === 0;\n }\n /** Whether the queue is full. */\n get isFull() {\n return this.queue.length >= this.maxSize;\n }\n /** Clear all tasks from the queue. */\n clear() {\n this.queue = [];\n }\n /** Return a copy of all tasks ordered by priority. */\n toArray() {\n return [...this.queue];\n }\n};\n\n// src/lib/background-intent.ts\nimport {\n isValidEveBackgroundAction,\n listEveBackgroundActions,\n readAgentKeyOrLegacy as readAgentKeyOrLegacy2,\n readEveSecrets as readEveSecrets7,\n resolveSynapUrl\n} from \"@eve/dna\";\nvar BackgroundIntentError = class extends Error {\n kind;\n httpStatus;\n raw;\n /** Set when kind === \"proposed\" (HTTP 202). */\n proposalId;\n /** Set when kind === \"invalid_action\" — the registry as the backend sees it. */\n validActions;\n constructor(opts) {\n super(opts.message);\n this.name = \"BackgroundIntentError\";\n this.kind = opts.kind;\n this.httpStatus = opts.httpStatus;\n this.raw = opts.raw;\n this.proposalId = opts.proposalId;\n this.validActions = opts.validActions;\n }\n};\nasync function resolveAuth(opts) {\n if (opts.auth) {\n if (!opts.auth.podUrl || !opts.auth.apiKey) {\n throw new BackgroundIntentError({\n kind: \"no_auth\",\n message: \"auth.podUrl and auth.apiKey are required\",\n httpStatus: 0\n });\n }\n return opts.auth;\n }\n const cwd = opts.cwd ?? process.env.EVE_HOME ?? process.cwd();\n const secrets = await readEveSecrets7(cwd);\n const podUrl = resolveSynapUrl(secrets);\n if (!podUrl) {\n throw new BackgroundIntentError({\n kind: \"no_auth\",\n message: \"Cannot resolve Synap pod URL \\u2014 run `eve install` or set domain.primary in secrets.json\",\n httpStatus: 0\n });\n }\n const apiKey = await readAgentKeyOrLegacy2(\"eve\", cwd);\n if (!apiKey) {\n throw new BackgroundIntentError({\n kind: \"no_auth\",\n message: \"No eve agent key on disk \\u2014 run `eve auth provision --agent eve`\",\n httpStatus: 0\n });\n }\n return { podUrl, apiKey };\n}\nfunction hubUrl(podUrl, path) {\n const base = podUrl.replace(/\\/+$/, \"\");\n return `${base}/api/hub${path.startsWith(\"/\") ? path : `/${path}`}`;\n}\nfunction authHeaders(apiKey) {\n return {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\"\n };\n}\nasync function parseJson(res) {\n const text = await res.text();\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\nfunction intoError(status, body, fallback) {\n if (status === 401 || status === 403) {\n return new BackgroundIntentError({\n kind: \"unauthorized\",\n message: extractMessage(body) ?? `unauthorized (${status})`,\n httpStatus: status,\n raw: body\n });\n }\n if (status === 404) {\n return new BackgroundIntentError({\n kind: \"not_found\",\n message: extractMessage(body) ?? \"not found\",\n httpStatus: status,\n raw: body\n });\n }\n if (status === 400 && isInvalidActionBody(body)) {\n const obj = body;\n return new BackgroundIntentError({\n kind: \"invalid_action\",\n message: typeof obj.error === \"string\" ? obj.error : \"invalid action\",\n httpStatus: 400,\n raw: body,\n validActions: Array.isArray(obj.validActions) ? obj.validActions : void 0\n });\n }\n if (status === 400) {\n return new BackgroundIntentError({\n kind: \"validation\",\n message: extractMessage(body) ?? \"invalid request\",\n httpStatus: 400,\n raw: body\n });\n }\n if (status === 202 && isProposedBody(body)) {\n const obj = body;\n return new BackgroundIntentError({\n kind: \"proposed\",\n message: \"Proposal created \\u2014 pending approval\",\n httpStatus: 202,\n raw: body,\n proposalId: typeof obj.proposalId === \"string\" ? obj.proposalId : void 0\n });\n }\n return new BackgroundIntentError({\n kind: \"backend\",\n message: extractMessage(body) ?? `${fallback} (HTTP ${status})`,\n httpStatus: status,\n raw: body\n });\n}\nfunction isInvalidActionBody(body) {\n return typeof body === \"object\" && body !== null && \"error\" in body && \"validActions\" in body;\n}\nfunction isProposedBody(body) {\n return typeof body === \"object\" && body !== null && body.status === \"proposed\";\n}\nfunction extractMessage(body) {\n if (typeof body === \"string\") return body;\n if (typeof body !== \"object\" || body === null) return null;\n const obj = body;\n if (typeof obj.error === \"string\") return obj.error;\n if (typeof obj.message === \"string\") return obj.message;\n return null;\n}\nasync function doFetch(url, init) {\n let res;\n try {\n res = await fetch(url, init);\n } catch (err) {\n throw new BackgroundIntentError({\n kind: \"transport\",\n message: `network error: ${err instanceof Error ? err.message : String(err)}`,\n httpStatus: 0\n });\n }\n const body = await parseJson(res);\n return { status: res.status, body };\n}\nasync function recordIntent(opts) {\n if (!isValidEveBackgroundAction(opts.action)) {\n throw new BackgroundIntentError({\n kind: \"invalid_action\",\n message: `Unknown action \"${opts.action}\"`,\n httpStatus: 0,\n validActions: listEveBackgroundActions()\n });\n }\n const auth = await resolveAuth(opts);\n const body = {\n name: opts.name,\n type: opts.type,\n action: opts.action\n };\n if (opts.description !== void 0) body.description = opts.description;\n if (opts.schedule !== void 0) body.schedule = opts.schedule;\n if (opts.workspaceId !== void 0) body.workspaceId = opts.workspaceId;\n if (opts.context !== void 0) body.context = opts.context;\n const { status, body: payload } = await doFetch(\n hubUrl(auth.podUrl, \"/background-tasks\"),\n {\n method: \"POST\",\n headers: {\n ...authHeaders(auth.apiKey),\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(body)\n }\n );\n if (status === 200) {\n const obj = payload;\n if (typeof obj?.id !== \"string\") {\n throw new BackgroundIntentError({\n kind: \"backend\",\n message: \"POST /background-tasks did not return an id\",\n httpStatus: status,\n raw: payload\n });\n }\n return getIntent({ id: obj.id, auth });\n }\n throw intoError(status, payload, \"failed to create background task\");\n}\nasync function listIntents(opts) {\n const auth = await resolveAuth(opts);\n const url = new URL(hubUrl(auth.podUrl, \"/background-tasks\"));\n if (opts.status) url.searchParams.set(\"status\", opts.status);\n if (opts.type) url.searchParams.set(\"type\", opts.type);\n if (opts.workspaceId) url.searchParams.set(\"workspaceId\", opts.workspaceId);\n if (opts.limit !== void 0) url.searchParams.set(\"limit\", String(opts.limit));\n if (opts.offset !== void 0) url.searchParams.set(\"offset\", String(opts.offset));\n const { status, body } = await doFetch(url.toString(), {\n method: \"GET\",\n headers: authHeaders(auth.apiKey)\n });\n if (status !== 200) {\n throw intoError(status, body, \"failed to list background tasks\");\n }\n const obj = body;\n return Array.isArray(obj?.tasks) ? obj.tasks : [];\n}\nasync function getIntent(opts) {\n const auth = await resolveAuth(opts);\n const { status, body } = await doFetch(\n hubUrl(auth.podUrl, `/background-tasks/${encodeURIComponent(opts.id)}`),\n { method: \"GET\", headers: authHeaders(auth.apiKey) }\n );\n if (status === 200) {\n const obj = body;\n if (!obj?.task) {\n throw new BackgroundIntentError({\n kind: \"backend\",\n message: \"GET /background-tasks/:id returned no `task` field\",\n httpStatus: status,\n raw: body\n });\n }\n return obj.task;\n }\n throw intoError(status, body, \"failed to fetch background task\");\n}\nasync function updateIntent(opts) {\n if (opts.patch.action !== void 0 && !isValidEveBackgroundAction(opts.patch.action)) {\n throw new BackgroundIntentError({\n kind: \"invalid_action\",\n message: `Unknown action \"${opts.patch.action}\"`,\n httpStatus: 0,\n validActions: listEveBackgroundActions()\n });\n }\n const auth = await resolveAuth(opts);\n const { status, body } = await doFetch(\n hubUrl(auth.podUrl, `/background-tasks/${encodeURIComponent(opts.id)}`),\n {\n method: \"PATCH\",\n headers: {\n ...authHeaders(auth.apiKey),\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(opts.patch)\n }\n );\n if (status === 200) {\n return getIntent({ id: opts.id, auth });\n }\n throw intoError(status, body, \"failed to update background task\");\n}\nasync function pauseIntent(opts) {\n return updateIntent({ ...opts, patch: { status: \"paused\" } });\n}\nasync function resumeIntent(opts) {\n return updateIntent({ ...opts, patch: { status: \"active\" } });\n}\nasync function removeIntent(opts) {\n const auth = await resolveAuth(opts);\n const { status, body } = await doFetch(\n hubUrl(auth.podUrl, `/background-tasks/${encodeURIComponent(opts.id)}`),\n { method: \"DELETE\", headers: authHeaders(auth.apiKey) }\n );\n if (status === 200) return;\n throw intoError(status, body, \"failed to delete background task\");\n}\n\n// src/index.ts\nvar Builder = class {\n opencode;\n openclaude;\n dokploy;\n claudecode;\n constructor() {\n this.opencode = new OpenCodeService();\n this.openclaude = new OpenClaudeService();\n this.dokploy = new DokployService();\n this.claudecode = new ClaudeCodeService();\n }\n /**\n * Legacy programmatic init — same as `eve builder init` (Builder organ first).\n * @param withDokploy default false (Dokploy is optional / often overkill).\n */\n async init(name, template, brainUrl, withDokploy = false) {\n await runBuilderOrganSetup({\n name,\n cwd: process.cwd(),\n engines: /* @__PURE__ */ new Set([\"opencode\", \"openclaude\", \"claudecode\"]),\n template,\n brainUrl: brainUrl || \"http://localhost:11434\",\n withDokploy\n });\n }\n async generate() {\n await this.opencode.generate();\n }\n async build() {\n await this.opencode.build();\n }\n async generateCode(prompt) {\n return this.openclaude.generateCode(prompt);\n }\n async deploy(projectId) {\n const id = projectId || this.dokploy.listProjects()[0]?.id;\n if (!id) {\n throw new Error(\"No project to deploy\");\n }\n await this.dokploy.deploy(id);\n }\n async getStatus() {\n return {\n opencode: this.opencode.getProjectPath(),\n openclaude: {\n configured: this.openclaude.isConfigured(),\n brainUrl: this.openclaude.getConfig()?.brainUrl || null\n },\n dokploy: await this.dokploy.getStatus()\n };\n }\n};\nfunction registerBuilderCommands(builder) {\n initCommand(builder);\n deployCommand(builder);\n stackCommand(builder);\n sandboxCommand(builder);\n registerHermesCommands(builder);\n registerCodexCommands(builder);\n builder.command(\"generate\").description(\"Generate content with OpenCode\").action(async () => {\n const builder2 = new Builder();\n await builder2.opencode.generate();\n });\n builder.command(\"code <prompt>\").description(\"Generate code with OpenClaude (Ollama). For Claude Code use the `claude` CLI in your project.\").option(\"--output <file>\", \"Output file path\").option(\"--engine <e>\", \"openclaude (default only \\u2014 Ollama path)\", \"openclaude\").action(async (prompt, options) => {\n if (options.engine && options.engine !== \"openclaude\") {\n console.error(\"Only --engine openclaude is supported here. Use: claude (Claude Code) in the project directory.\");\n process.exit(1);\n }\n const builder2 = new Builder();\n await builder2.openclaude.start();\n const code = await builder2.openclaude.generateCode(prompt);\n if (options.output) {\n const { writeFileSync: writeFileSync9 } = await import(\"fs\");\n writeFileSync9(options.output, code);\n console.log(`Code written to: ${options.output}`);\n } else {\n console.log(\"\\n--- Generated Code ---\\n\");\n console.log(code);\n console.log(\"\\n--- End of Code ---\\n\");\n }\n });\n builder.command(\"status\").description(\"Check builder status\").action(async () => {\n const builder2 = new Builder();\n const status = await builder2.getStatus();\n console.log(\"Builder Status\");\n console.log(\"==============\");\n console.log(\"\");\n console.log(\"OpenCode:\");\n console.log(` Project: ${status.opencode || \"Not initialized\"}`);\n console.log(\"\");\n console.log(\"OpenClaude:\");\n console.log(` Configured: ${status.openclaude.configured}`);\n console.log(` Brain URL: ${status.openclaude.brainUrl || \"Not set\"}`);\n console.log(\"\");\n console.log(\"Dokploy:\");\n console.log(` Installed: ${status.dokploy.installed}`);\n console.log(` Running: ${status.dokploy.running}`);\n console.log(` Version: ${status.dokploy.version || \"Unknown\"}`);\n console.log(` Projects: ${status.dokploy.projects.length}`);\n if (status.dokploy.projects.length > 0) {\n console.log(\" Project List:\");\n for (const proj of status.dokploy.projects) {\n console.log(` - ${proj.name} (${proj.status})`);\n if (proj.url) {\n console.log(` URL: ${proj.url}`);\n }\n }\n }\n });\n}\nvar index_default = Builder;\nexport {\n BackgroundIntentError,\n Builder,\n ClaudeCodeService,\n CodexFeaturePoller,\n CodexPipeline,\n DokployService,\n FeaturePoller,\n OpenClaudeService,\n OpenCodeService,\n PIPELINE_PERSONALITIES,\n T3CodeClient,\n TaskPoller,\n TaskQueue,\n index_default as default,\n deployCommand,\n getIntent,\n initCommand,\n listIntents,\n pauseIntent,\n recordIntent,\n registerBuilderCommands,\n registerCodexCommands,\n registerHermesCommands,\n removeIntent,\n resolveBuilderProjectDir,\n resumeIntent,\n runBuilderOrganSetup,\n scaffoldNonOpencodeProject,\n updateIntent\n};\n","import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n createWebSocketStream,\n extension,\n PerMessageDeflate,\n Receiver,\n Sender,\n subprotocol,\n WebSocket,\n WebSocketServer\n};\n\nexport default WebSocket;\n","import { Command } from 'commander';\nimport Table from 'cli-table3';\nimport { execSync } from 'child_process';\nimport { entityStateManager, type Organ, COMPONENTS } from '@eve/dna';\nimport { getGlobalCliFlags } from '@eve/cli-kit';\nimport {\n colors,\n emojis,\n printKeyValue,\n formatOrgan,\n printBox,\n} from '../lib/ui.js';\n\n// 'eve-brain-synap-proxy' is a synthetic alias resolved via docker label lookup\n// in getLiveContainerState() — the real container is synap-backend-backend-1.\nconst ORGAN_CONTAINERS: Record<Organ, string[]> = {\n brain: ['eve-brain-synap-proxy', 'eve-brain-ollama'],\n arms: ['eve-arms-openclaw'],\n builder: [],\n eyes: ['eve-eyes-rsshub'],\n legs: ['eve-legs-traefik'],\n};\n\ninterface LiveContainerState {\n running: Set<string>;\n all: Set<string>;\n}\n\nfunction getLiveContainerState(): LiveContainerState {\n const running = new Set<string>();\n const all = new Set<string>();\n try {\n const outRunning = execSync('docker ps --format \"{{.Names}}\"', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n for (const n of outRunning.split('\\n').filter(Boolean)) running.add(n.trim());\n } catch {}\n try {\n const outAll = execSync('docker ps -a --format \"{{.Names}}\"', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n for (const n of outAll.split('\\n').filter(Boolean)) all.add(n.trim());\n } catch {}\n // Also detect synap-backend containers (different naming from synap compose)\n try {\n const synapName = execSync(\n `docker ps --filter \"label=com.docker.compose.project=synap-backend\" --filter \"label=com.docker.compose.service=backend\" --format \"{{.Names}}\"`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim().split('\\n')[0]?.trim();\n if (synapName) running.add('eve-brain-synap-proxy');\n } catch {}\n try {\n const synapNameAll = execSync(\n `docker ps -a --filter \"label=com.docker.compose.project=synap-backend\" --filter \"label=com.docker.compose.service=backend\" --format \"{{.Names}}\"`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim().split('\\n')[0]?.trim();\n if (synapNameAll) all.add('eve-brain-synap-proxy');\n } catch {}\n return { running, all };\n}\n\nfunction getOrganLiveState(organ: Organ, state: LiveContainerState): 'running' | 'partial' | 'stopped' | 'not-installed' | 'unknown' {\n const containers = ORGAN_CONTAINERS[organ];\n if (containers.length === 0) return 'unknown';\n const runningCount = containers.filter(c => state.running.has(c)).length;\n if (runningCount === containers.length) return 'running';\n if (runningCount > 0) return 'partial';\n const existsCount = containers.filter(c => state.all.has(c)).length;\n if (existsCount === 0) return 'not-installed';\n return 'stopped';\n}\n\nexport function statusCommand(program: Command): void {\n program\n .command('status')\n .alias('s')\n .description('Show comprehensive entity status')\n .option('-w, --watch', 'Watch mode - continuously update')\n .option('-j, --json', 'Output as JSON')\n .action(async (options) => {\n try {\n if (options.watch) {\n await watchStatus();\n } else {\n await showStatus(Boolean(options.json || getGlobalCliFlags().json));\n }\n } catch (error) {\n console.error(colors.error('Failed to get entity status:'), error);\n process.exit(1);\n }\n });\n}\n\nasync function showStatus(json = false): Promise<void> {\n const state = await entityStateManager.getState();\n\n if (json) {\n console.log(JSON.stringify(state, null, 2));\n return;\n }\n\n const liveContainers = getLiveContainerState();\n\n // Header\n console.log();\n console.log(colors.primary.bold(`${emojis.entity} Entity Status`));\n console.log(colors.primary('═'.repeat(50)));\n console.log();\n\n // Entity Info\n printKeyValue('Entity Name', state.metadata.entityName || 'Unnamed');\n printKeyValue('Version', state.version);\n printKeyValue('Initialized', new Date(state.initializedAt).toLocaleDateString());\n printKeyValue('AI Model', state.aiModel === 'none' ? 'Not configured' : state.aiModel);\n\n if (state.metadata.lastBootTime) {\n printKeyValue('Last Boot', new Date(state.metadata.lastBootTime).toLocaleString());\n }\n console.log();\n\n // Organ Status Table\n const table = new Table({\n head: [\n colors.primary.bold('Organ'),\n colors.primary.bold('Status'),\n colors.primary.bold('Live'),\n colors.primary.bold('Version'),\n colors.primary.bold('Last Check'),\n ],\n colWidths: [15, 12, 10, 12, 22],\n style: {\n head: [],\n border: ['grey'],\n },\n });\n\n const organs: Organ[] = ['brain', 'arms', 'builder', 'eyes', 'legs'];\n\n for (const organ of organs) {\n const organState = state.organs[organ];\n const statusColor = getStatusColor(organState.state);\n const liveState = getOrganLiveState(organ, liveContainers);\n\n let liveLabel: string;\n if (liveState === 'running') liveLabel = colors.success('● up');\n else if (liveState === 'partial') liveLabel = colors.warning('◑ partial');\n else if (liveState === 'stopped') liveLabel = colors.error('○ down');\n else if (liveState === 'not-installed') liveLabel = colors.muted('✗ none');\n else liveLabel = colors.muted('—');\n\n table.push([\n formatOrgan(organ),\n statusColor(organState.state),\n liveLabel,\n organState.version || '-',\n organState.lastChecked\n ? new Date(organState.lastChecked).toLocaleString()\n : 'Never',\n ]);\n }\n\n console.log(table.toString());\n console.log();\n\n // (Component-level details shown in the live \"Components\" section below — see showComponentOverview)\n\n // Summary\n const readyCount = organs.filter(o => state.organs[o].state === 'ready').length;\n const percent = Math.round((readyCount / organs.length) * 100);\n \n printBox('Completeness', [\n `${colors.info('Progress:')} ${readyCount}/${organs.length} organs ready (${percent}%)`,\n '',\n getCompletenessBar(percent),\n ]);\n\n // Stale-state warning — state.json says ready but containers are down or missing\n const FIX_COMMANDS: Record<Organ, string> = {\n brain: 'npx eve brain init --synap-repo /path/to/synap-backend',\n arms: 'npx eve install --components=arms',\n builder: 'npx eve install --components=builder',\n eyes: 'npx eve install --components=eyes',\n legs: 'npx eve install --components=legs',\n };\n const RESTART_COMMANDS: Record<Organ, string> = {\n brain: 'docker start $(docker ps -a --filter \"label=com.docker.compose.project=synap-backend\" --filter \"label=com.docker.compose.service=backend\" -q)',\n arms: 'docker start eve-arms-openclaw',\n builder: 'docker start eve-builder-hermes eve-builder-t3code && eve builder codex daemon',\n eyes: 'docker start eve-eyes-rsshub',\n legs: 'docker start eve-legs-traefik',\n };\n\n const staleOrgans = organs.filter(o => {\n const live = getOrganLiveState(o, liveContainers);\n return state.organs[o].state === 'ready' && (live === 'stopped' || live === 'not-installed');\n });\n const notInstalledOrgans = organs.filter(o =>\n state.organs[o].state === 'ready' && getOrganLiveState(o, liveContainers) === 'not-installed',\n );\n const missingOrgans = organs.filter(o => state.organs[o].state === 'missing');\n\n if (staleOrgans.length > 0 || missingOrgans.length > 0) {\n console.log();\n console.log(colors.warning.bold(`${emojis.info} Action needed:`));\n for (const organ of staleOrgans) {\n const isNotInstalled = notInstalledOrgans.includes(organ);\n if (isNotInstalled) {\n console.log(` ${colors.error('✗')} ${formatOrgan(organ)} — never installed or container removed`);\n console.log(` ${colors.muted('→')} ${colors.info(FIX_COMMANDS[organ])}`);\n } else {\n console.log(` ${colors.error('○')} ${formatOrgan(organ)} — container stopped`);\n console.log(` ${colors.muted('→')} ${colors.info(RESTART_COMMANDS[organ])}`);\n }\n }\n for (const organ of missingOrgans) {\n console.log(` ${colors.muted('→')} Install ${formatOrgan(organ)}: ${colors.info(FIX_COMMANDS[organ])}`);\n }\n }\n\n // ─── Component overview: installed | recommended | available ────────────\n await showComponentOverview();\n\n console.log();\n}\n\n/**\n * Three-bucket component view: what's installed (with health), what we\n * recommend installing next, what else is available.\n */\nasync function showComponentOverview(): Promise<void> {\n const installed = await entityStateManager.getInstalledComponents();\n const liveContainers = getLiveContainerState();\n\n // Reconcile stored state with reality. For each registry component with a\n // service, classify by what's actually running (not just state.json).\n const componentLiveState = new Map<string, 'running' | 'missing' | 'no-service'>();\n for (const comp of COMPONENTS) {\n if (!comp.service) {\n componentLiveState.set(comp.id, 'no-service');\n continue;\n }\n componentLiveState.set(\n comp.id,\n liveContainers.running.has(comp.service.containerName) ? 'running' : 'missing',\n );\n }\n\n // Bucket components\n const installedComps = COMPONENTS.filter(c => installed.includes(c.id));\n const availableComps = COMPONENTS.filter(c => !installed.includes(c.id));\n\n // Recommendation logic — opinionated suggestions based on what's already in place\n const recommendations: Array<{ id: string; reason: string }> = [];\n if (installed.includes('synap') && !installed.includes('openclaw')) {\n recommendations.push({ id: 'openclaw', reason: 'gives your data pod an AI agent layer' });\n }\n if (installed.includes('synap') && !installed.includes('rsshub')) {\n recommendations.push({ id: 'rsshub', reason: 'turns websites into feeds your AI can read' });\n }\n if (installed.includes('synap') && !installed.includes('openwebui')) {\n recommendations.push({ id: 'openwebui', reason: 'self-hosted chat UI wired to your AI' });\n }\n if (!installed.includes('synap') && installed.includes('traefik')) {\n recommendations.push({ id: 'synap', reason: 'the data pod — your sovereign second brain' });\n }\n const recommendedIds = new Set(recommendations.map(r => r.id));\n\n console.log();\n console.log(colors.primary.bold(`${emojis.entity} Components`));\n console.log(colors.muted('─'.repeat(60)));\n\n // Installed — show with live status. Stale entries (state.json says ready\n // but container is missing) are flagged so the user knows reality differs\n // from the stored state.\n if (installedComps.length > 0) {\n console.log();\n console.log(colors.success.bold(' Installed'));\n for (const comp of installedComps) {\n const live = componentLiveState.get(comp.id);\n let dot: string;\n let suffix: string;\n if (live === 'running') {\n dot = colors.success('●');\n suffix = '';\n } else if (live === 'missing') {\n dot = colors.error('●');\n suffix = colors.error(' (container not running)');\n } else {\n // no-service component (hermes, dokploy, opencode, openclaude)\n dot = colors.muted('●');\n suffix = '';\n }\n console.log(` ${dot} ${comp.emoji} ${comp.label.padEnd(20)} ${colors.muted(comp.description.split('.')[0])}${suffix}`);\n }\n // Stale-state hint\n const stale = installedComps.filter(c => componentLiveState.get(c.id) === 'missing');\n if (stale.length > 0) {\n console.log();\n console.log(colors.warning(` ⚠ ${stale.length} component(s) are marked installed but their containers are missing.`));\n console.log(colors.muted(` Re-install: ${colors.info(`eve add ${stale.map(c => c.id).join(' ')}`)}`));\n console.log(colors.muted(` Or run: ${colors.info('eve doctor')} ${colors.muted('to investigate')}`));\n }\n }\n\n // Recommended next\n if (recommendations.length > 0) {\n console.log();\n console.log(colors.warning.bold(' Recommended next'));\n for (const rec of recommendations) {\n const comp = COMPONENTS.find(c => c.id === rec.id)!;\n console.log(` ${colors.warning('○')} ${comp.emoji} ${comp.label.padEnd(20)} ${colors.muted(rec.reason)}`);\n console.log(` ${colors.muted('→')} ${colors.info(`eve add ${comp.id}`)}`);\n }\n }\n\n // Available (excluding already-recommended)\n const otherAvailable = availableComps.filter(c => !recommendedIds.has(c.id));\n if (otherAvailable.length > 0) {\n console.log();\n console.log(colors.muted.bold(' Also available'));\n for (const comp of otherAvailable) {\n const reqs = comp.requires?.length\n ? colors.muted(` (requires: ${comp.requires.join(', ')})`)\n : '';\n console.log(` ${colors.muted('○')} ${comp.emoji} ${comp.label.padEnd(20)} ${colors.muted(comp.description.split('.')[0])}${reqs}`);\n }\n console.log();\n console.log(colors.muted(` Install any with: ${colors.info('eve add <component-id>')}`));\n }\n}\n\nasync function watchStatus(): Promise<void> {\n console.log(colors.info('Watching entity status (press Ctrl+C to exit)...\\n'));\n \n // Initial display\n await showStatus();\n \n // Set up interval\n const interval = setInterval(async () => {\n // Clear previous output\n console.log('\\x1b[2J\\x1b[0f');\n await showStatus();\n console.log(colors.muted('\\n(Updating every 2 seconds. Press Ctrl+C to exit)'));\n }, 2000);\n\n // Handle exit\n process.on('SIGINT', () => {\n clearInterval(interval);\n console.log('\\n' + colors.success('Watch mode stopped'));\n process.exit(0);\n });\n}\n\nfunction getStatusColor(state: string): (text: string) => string {\n switch (state) {\n case 'ready':\n return colors.success;\n case 'installing':\n return colors.info;\n case 'error':\n return colors.error;\n case 'stopped':\n return colors.warning;\n default:\n return colors.muted;\n }\n}\n\nfunction getCompletenessBar(percent: number): string {\n const width = 30;\n const filled = Math.round((percent / 100) * width);\n const empty = width - filled;\n \n const bar = '█'.repeat(filled) + '░'.repeat(empty);\n let color = colors.error;\n if (percent >= 60) color = colors.warning;\n if (percent >= 80) color = colors.info;\n if (percent === 100) color = colors.success;\n \n return color(bar) + colors.muted(` ${percent}%`);\n}\n","import { Command } from 'commander';\nimport { execa } from 'execa';\nimport { execSync } from 'node:child_process';\nimport {\n entityStateManager,\n type Organ,\n COMPONENTS,\n readAgentKey,\n readEveSecrets,\n resolveSynapUrlOnHost,\n getAccessUrls,\n hasAnyProvider,\n} from '@eve/dna';\nimport { verifyComponent } from '@eve/legs';\nimport { runDoctorChecks, runHubProtocolProbes, type HubProtocolDiagnostic } from '@eve/lifecycle';\nimport { probeRoutes, probeVerdict, type RouteProbe } from '../lib/probe-routes.js';\nimport { diagnoseFailedRoute, type DeepDiagnostic } from '../lib/diagnose-route.js';\nimport { buildPodRunner } from '../lib/doctor-runners.js';\nimport { probeGitHttps } from '../lib/git.js';\nimport {\n waitForHealth,\n getAdminJwtPostHealth,\n listModelSources,\n} from '@eve/dna';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printWarning,\n printInfo,\n formatOrgan,\n createSpinner,\n} from '../lib/ui.js';\n\ninterface CheckResult {\n name: string;\n /**\n * `skip` is rendered with the warning glyph but a \"skipped\" message —\n * distinct from `warn` (\"something is sub-optimal\") and `fail` (\"broken\").\n * The aggregate counter at the bottom still groups skip+warn together.\n */\n status: 'pass' | 'fail' | 'warn' | 'skip';\n message: string;\n fix?: string;\n /**\n * Deep diagnostic data for failed routes — when present, the renderer\n * indents a sub-section under the row showing what we learned about the\n * upstream. Only set on route-check rows; other checks leave this undef.\n */\n deep?: DeepDiagnostic;\n}\n\nexport function doctorCommand(program: Command): void {\n program\n .command('doctor')\n .alias('doc')\n .description('Run comprehensive diagnostics on the entity')\n .option('-v, --verbose', 'Show verbose output')\n .option(\n '--skip-probes',\n 'Skip the Hub Protocol probes (idempotency, SSE, sub-tokens). Useful when debugging unrelated checks — the SSE probe alone takes up to 35s.',\n )\n .action(async (options) => {\n try {\n await runDiagnostics({\n verbose: Boolean(options.verbose),\n skipProbes: Boolean(options.skipProbes),\n });\n } catch (error) {\n printError('Diagnostics failed: ' + String(error));\n process.exit(1);\n }\n });\n}\n\ninterface DoctorOptions {\n verbose: boolean;\n skipProbes: boolean;\n}\n\nasync function runDiagnostics(opts: DoctorOptions = { verbose: false, skipProbes: false }): Promise<void> {\n const { verbose, skipProbes } = opts;\n console.log();\n printHeader('Entity Diagnostics', emojis.info);\n console.log();\n\n const checks: CheckResult[] = [];\n\n // Check 1: Docker\n const dockerCheck = createSpinner('Checking Docker...');\n dockerCheck.start();\n try {\n await execa('docker', ['version']);\n dockerCheck.succeed('Docker is running');\n checks.push({ name: 'Docker', status: 'pass', message: 'Docker daemon is running' });\n } catch {\n dockerCheck.fail('Docker is not running');\n checks.push({ \n name: 'Docker', \n status: 'fail', \n message: 'Docker daemon is not running',\n fix: 'Start Docker Desktop or run: sudo systemctl start docker'\n });\n }\n\n // Check 2: Docker Compose\n const composeCheck = createSpinner('Checking Docker Compose...');\n composeCheck.start();\n try {\n await execa('docker', ['compose', 'version']);\n composeCheck.succeed('Docker Compose is available');\n checks.push({ name: 'Docker Compose', status: 'pass', message: 'Docker Compose is installed' });\n } catch {\n composeCheck.fail('Docker Compose not found');\n checks.push({ \n name: 'Docker Compose', \n status: 'fail', \n message: 'Docker Compose is not installed',\n fix: 'Install Docker Compose: https://docs.docker.com/compose/install/'\n });\n }\n\n // Check 3: Network\n const networkCheck = createSpinner('Checking eve-network...');\n networkCheck.start();\n try {\n const { stdout } = await execa('docker', ['network', 'ls', '--format', '{{.Name}}']);\n if (stdout.includes('eve-network')) {\n networkCheck.succeed('eve-network exists');\n checks.push({ name: 'Network', status: 'pass', message: 'eve-network is created' });\n } else {\n networkCheck.warn('eve-network not found');\n checks.push({ \n name: 'Network', \n status: 'warn', \n message: 'eve-network does not exist',\n fix: 'eve init will create it automatically'\n });\n }\n } catch {\n networkCheck.fail('Cannot check networks');\n checks.push({ name: 'Network', status: 'fail', message: 'Failed to check Docker networks' });\n }\n\n // Check 3b: the UPDATE path.\n //\n // Asserted against a PUBLIC third-party repo (github.com/git/git.git) on\n // purpose: that removes credentials and repo permissions from the equation,\n // so a failure can only be this host's HTTP stack. Without this probe the\n // symptom — `git pull` prompting for a GitHub username — reads as an expired\n // token and sends operators hunting for a PAT that was never the problem.\n const gitCheck = createSpinner('Checking git update path...');\n gitCheck.start();\n const gitProbe = await probeGitHttps();\n if (gitProbe.ok && !gitProbe.http11Needed) {\n gitCheck.succeed('git over HTTPS works');\n checks.push({ name: 'Git update path', status: 'pass', message: 'git can fetch over HTTPS' });\n } else if (gitProbe.ok) {\n gitCheck.warn('git needs HTTP/1.1');\n checks.push({\n name: 'Git update path',\n status: 'warn',\n message:\n 'git over HTTP/2 returns a spurious 401 on this host (public repos included) — HTTP/1.1 works. ' +\n 'Known Debian 12 regression in libcurl 7.88.1-10+deb12u15.',\n fix: 'git config --global http.version HTTP/1.1',\n });\n } else {\n gitCheck.fail('git cannot fetch over HTTPS');\n checks.push({\n name: 'Git update path',\n status: 'fail',\n message: `git cannot reach github.com over HTTPS: ${gitProbe.message}`,\n fix: 'Check outbound HTTPS from this host. Updates via `eve synap deploy` will fail until this is fixed.',\n });\n }\n\n // Check 4: Live Docker containers — driven by registry, only check what's installed\n const installed = await entityStateManager.getInstalledComponents().catch(() => [] as string[]);\n const expectedContainers = COMPONENTS\n .filter(c => installed.includes(c.id) && c.service)\n .map(c => ({ name: c.service!.containerName, organ: c.organ ?? c.id, label: c.label }));\n\n const containerCheck = createSpinner('Checking installed containers...');\n containerCheck.start();\n try {\n const { stdout: psOut } = await execa('docker', [\n 'ps', '--format', '{{.Names}}\\t{{.Status}}',\n ]);\n const running = new Map<string, string>();\n for (const line of psOut.split('\\n').filter(Boolean)) {\n const [name, ...statusParts] = line.split('\\t');\n if (name) running.set(name.trim(), statusParts.join(' ').trim());\n }\n\n const { stdout: allOut } = await execa('docker', [\n 'ps', '-a', '--format', '{{.Names}}\\t{{.Status}}',\n ]);\n const all = new Map<string, string>();\n for (const line of allOut.split('\\n').filter(Boolean)) {\n const [name, ...statusParts] = line.split('\\t');\n if (name) all.set(name.trim(), statusParts.join(' ').trim());\n }\n\n containerCheck.succeed('Container check complete');\n for (const c of expectedContainers) {\n if (running.has(c.name)) {\n checks.push({\n name: c.name,\n status: 'pass',\n message: `Running — ${running.get(c.name)}`,\n });\n } else if (all.has(c.name)) {\n checks.push({\n name: c.name,\n status: 'fail',\n message: `Stopped — ${all.get(c.name)}`,\n fix: `docker start ${c.name}`,\n });\n } else {\n checks.push({\n name: c.name,\n status: 'warn',\n message: 'Not found — container missing',\n fix: `eve add ${c.organ}`,\n });\n }\n }\n } catch {\n containerCheck.fail('Could not query Docker containers');\n checks.push({ name: 'Containers', status: 'fail', message: 'docker ps failed — is Docker running?' });\n }\n\n // Check 4b: Network reachability — for each installed component with a service,\n // verify Traefik can actually reach it. Catches the openclaw-class 502 bug\n // (container is up, on the network, but bound to wrong interface or not yet ready).\n const reachabilityCheck = createSpinner('Probing service reachability from Traefik...');\n reachabilityCheck.start();\n try {\n for (const c of COMPONENTS) {\n if (!c.service || !installed.includes(c.id)) continue;\n const result = await verifyComponent(c.id);\n if (result.ok) {\n checks.push({ name: `${c.label} reachability`, status: 'pass', message: result.summary });\n } else {\n const failed = result.checks.find(ch => !ch.ok);\n checks.push({\n name: `${c.label} reachability`,\n status: 'fail',\n message: failed?.detail ?? result.summary,\n fix: `docker logs ${c.service.containerName} --tail 30`,\n });\n }\n }\n reachabilityCheck.succeed('Reachability check complete');\n } catch (err) {\n reachabilityCheck.warn('Could not probe reachability');\n }\n\n // Check 4b-bis: Hub Protocol probes — ONLY meaningful once we know the\n // Synap container is up. The probes themselves handle a missing\n // URL/key gracefully (each row reports `skip`), but running them when\n // the container is obviously stopped is just noise. We also skip the\n // whole block when `--skip-probes` is set so users debugging an\n // unrelated check don't sit through ~35s of SSE wait time.\n const secrets = await readEveSecrets(process.cwd());\n const synapInstalled = installed.includes('synap');\n\n if (synapInstalled && !skipProbes) {\n const synapApiUrl = await resolveSynapUrlOnHost(secrets);\n // Doctor probes use the \"eve\" agent's key — that agent is reserved\n // for our own diagnostics + dashboard probes, so failures here\n // never tell us whether OpenClaw or Hermes are healthy. Fall back\n // to the legacy `synap.apiKey` only if the per-agent record is\n // missing (e.g. fresh install hasn't migrated yet).\n const eveAgent = await readAgentKey('eve', process.cwd());\n const synapApiKey = eveAgent?.hubApiKey ?? secrets?.synap?.apiKey ?? '';\n\n if (!synapApiUrl || !synapApiKey) {\n // Skipped — synap not configured locally. NOT a failure: the user\n // may have installed Synap on a different host and be running the\n // CLI against a remote pod via env vars they haven't set yet.\n checks.push({\n name: 'Synap Hub Protocol probes',\n status: 'skip',\n message: 'skipped — no eve agent key in secrets.json (or pod URL missing)',\n fix: 'Run `eve auth provision` to mint missing agent keys, or `eve add synap` for a fresh install.',\n });\n } else {\n const probeSpinner = createSpinner('Running Hub Protocol probes (≤35s)...');\n probeSpinner.start();\n let diagnostics: HubProtocolDiagnostic[] = [];\n // Pick transport ONCE based on where we're running. On pod host\n // → docker-exec (direct, no DNS/cert dependency). Off-host →\n // fetch on the public URL. No automatic fallback.\n const transportNotes: string[] = [];\n const runner = buildPodRunner((note) => transportNotes.push(note));\n try {\n diagnostics = await runHubProtocolProbes({\n synapUrl: synapApiUrl,\n apiKey: synapApiKey,\n runner,\n });\n const noteSuffix = transportNotes.length > 0 ? ` — ${transportNotes[0]}` : '';\n probeSpinner.succeed(`Hub Protocol probes complete (${diagnostics.length} run)${noteSuffix}`);\n } catch (err) {\n probeSpinner.fail('Hub Protocol probes failed to run');\n checks.push({\n name: 'Hub Protocol probes',\n status: 'fail',\n message: err instanceof Error ? err.message : String(err),\n });\n }\n\n for (const diag of diagnostics) {\n // `skip` rows from the lifecycle module flow through unchanged —\n // the renderer shows them with the warning glyph + \"skipped\"\n // label so users see them as informational, not as broken.\n checks.push({\n name: diag.name,\n status: diag.status,\n message: diag.message,\n fix: diag.fix,\n });\n }\n }\n } else if (synapInstalled && skipProbes) {\n checks.push({\n name: 'Hub Protocol probes',\n status: 'skip',\n message: 'skipped (--skip-probes)',\n });\n }\n\n // Check 4b-ter: Builder workspace seed. Compares the locally-recorded\n // workspaceId against what the pod returns for the Builder template's\n // proposalId. One probe — three possible outcomes:\n // - pass: secrets has a workspaceId AND it matches the pod's row.\n // - warn: secrets is empty OR the pod row drifted — fixable by `eve update`.\n // - skip: not enough info (no synap, no eve key, no pod URL).\n if (synapInstalled) {\n const builderId = secrets?.builder?.workspaceId?.trim();\n const synapApiUrl = await resolveSynapUrlOnHost(secrets);\n const eveAgent = await readAgentKey('eve', process.cwd());\n const synapApiKey = eveAgent?.hubApiKey ?? secrets?.synap?.apiKey ?? '';\n\n if (!synapApiUrl || !synapApiKey) {\n checks.push({\n name: 'Builder workspace',\n status: 'skip',\n message: 'skipped — no eve agent key or pod URL configured',\n });\n } else if (!builderId) {\n checks.push({\n name: 'Builder workspace',\n status: 'warn',\n message: 'No workspaceId recorded in secrets.builder.workspaceId',\n fix: 'eve update synap # re-runs ensureBuilderWorkspace()',\n });\n } else {\n try {\n const probeUrl = `${synapApiUrl.replace(/\\/+$/, '')}/api/hub/workspaces/${encodeURIComponent(builderId)}`;\n const res = await fetch(probeUrl, {\n headers: {\n Authorization: `Bearer ${synapApiKey}`,\n Accept: 'application/json',\n },\n signal: AbortSignal.timeout(5_000),\n });\n if (res.ok) {\n checks.push({\n name: 'Builder workspace',\n status: 'pass',\n message: `Pod confirms workspaceId ${builderId.slice(0, 8)}…`,\n });\n } else if (res.status === 404) {\n checks.push({\n name: 'Builder workspace',\n status: 'warn',\n message: `Pod has no workspace ${builderId.slice(0, 8)}… (drift)`,\n fix: 'eve update synap # reseeds the Builder workspace',\n });\n } else {\n checks.push({\n name: 'Builder workspace',\n status: 'warn',\n message: `Pod returned ${res.status} when probing ${builderId.slice(0, 8)}…`,\n fix: 'eve auth status && eve update synap',\n });\n }\n } catch (err) {\n checks.push({\n name: 'Builder workspace',\n status: 'warn',\n message: `Could not probe pod (${err instanceof Error ? err.message : String(err)})`,\n });\n }\n }\n }\n\n // Check 4c: Domain & route health (only if a domain is configured)\n if (secrets?.domain?.primary) {\n const routeCheck = createSpinner(`Probing domain routes (${secrets.domain.primary})...`);\n routeCheck.start();\n try {\n const urls = getAccessUrls(secrets, installed);\n const probes: RouteProbe[] = probeRoutes(urls);\n routeCheck.succeed(`Probed ${probes.length} route(s)`);\n\n // Route check + deep diagnostic for failed routes only. We never\n // run `diagnoseFailedRoute` on a healthy route — its docker probes\n // cost ~1s each, and a healthy multi-route stack would multiply\n // that needlessly.\n for (const p of probes) {\n if (p.outcome === 'ok') {\n checks.push({ name: `route: ${p.host}`, status: 'pass', message: `${p.httpStatus} reachable` });\n continue;\n }\n\n let row: CheckResult;\n if (p.outcome === 'upstream-down') {\n row = {\n name: `route: ${p.host}`,\n status: 'fail',\n message: `${p.httpStatus} — Traefik connected, upstream returned a non-success response`,\n fix: 'See deep diagnostic below for the matched cause.',\n };\n } else if (p.outcome === 'not-routing') {\n row = {\n name: `route: ${p.host}`,\n status: 'fail',\n message: 'Traefik returned 404 — no router matched',\n fix: 'eve domain repair',\n };\n } else if (p.outcome === 'dns-missing') {\n row = {\n name: `route: ${p.host}`,\n status: 'warn',\n message: `No DNS A record for ${p.host}`,\n fix: 'Create A record at your registrar pointing to your server IP',\n };\n } else if (p.outcome === 'dns-wrong') {\n row = {\n name: `route: ${p.host}`,\n status: 'warn',\n message: `DNS resolves to ${p.dnsResolved} (not this server)`,\n fix: 'Update A record at your registrar',\n };\n } else {\n // 'timeout'\n row = {\n name: `route: ${p.host}`,\n status: 'fail',\n message: 'Request timed out — Traefik may be down or unreachable',\n fix: 'See deep diagnostic below.',\n };\n }\n\n // Deep diagnostic for upstream-down / not-routing / timeout — DNS\n // problems aren't the upstream's fault, so skip the docker probes\n // there (the probe-from-Traefik would just confirm \"yes Traefik\n // works, your DNS is wrong\" which the row already says).\n if (p.outcome === 'upstream-down' || p.outcome === 'not-routing' || p.outcome === 'timeout') {\n try {\n row.deep = await diagnoseFailedRoute(p);\n } catch {\n // Deep diagnostic is best-effort enrichment — never let a\n // failure here demote the actual route check.\n }\n }\n checks.push(row);\n }\n\n const verdict = probeVerdict(probes);\n if (verdict !== 'ok') {\n // Pull aside one summary check for visibility\n checks.push({\n name: 'Domain routes',\n status: verdict === 'broken' ? 'fail' : 'warn',\n message: verdict === 'broken' ? 'No routes reachable' : 'Some routes failing',\n });\n }\n } catch {\n routeCheck.fail('Could not probe domain routes');\n }\n }\n\n // Check 4d: AI provider wiring\n const aiCheck = createSpinner('Checking AI provider wiring...');\n aiCheck.start();\n try {\n const aiSecrets = secrets ?? await readEveSecrets(process.cwd());\n if (!hasAnyProvider(aiSecrets)) {\n const aiConsumers = ['synap', 'openclaw', 'openwebui'];\n const willUseAi = installed.some(c => aiConsumers.includes(c));\n if (willUseAi) {\n aiCheck.warn('No AI provider configured');\n checks.push({\n name: 'AI provider',\n status: 'warn',\n message: 'No provider key in secrets.ai.providers',\n fix: 'eve ai providers add anthropic --api-key <key>',\n });\n } else {\n aiCheck.succeed('No AI provider configured (no AI-consuming components installed yet)');\n }\n } else {\n aiCheck.succeed('AI provider configured');\n\n // Verify each AI-consuming component is actually wired\n // OpenClaw — check for auth-profiles.json inside the container\n if (installed.includes('openclaw')) {\n try {\n const out = execSync(\n `docker exec eve-arms-openclaw test -f /home/node/.openclaw/agents/main/agent/auth-profiles.json && echo OK || echo MISSING`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim();\n if (out === 'OK') {\n checks.push({ name: 'OpenClaw AI wiring', status: 'pass', message: 'auth-profiles.json present in container' });\n } else {\n checks.push({\n name: 'OpenClaw AI wiring',\n status: 'fail',\n message: 'auth-profiles.json missing — agent loop will fail',\n fix: 'eve ai apply',\n });\n }\n } catch {\n checks.push({\n name: 'OpenClaw AI wiring',\n status: 'warn',\n message: 'Could not check (container not running?)',\n fix: 'docker start eve-arms-openclaw',\n });\n }\n }\n\n // Open WebUI — check that .env mentions SYNAP_IS_URL\n if (installed.includes('openwebui')) {\n try {\n const { existsSync, readFileSync } = await import('node:fs');\n const envPath = '/opt/openwebui/.env';\n if (existsSync(envPath)) {\n const content = readFileSync(envPath, 'utf-8');\n if (content.includes('SYNAP_IS_URL') && content.includes('SYNAP_API_KEY')) {\n checks.push({ name: 'Open WebUI AI wiring', status: 'pass', message: '.env points at Synap IS' });\n } else {\n checks.push({\n name: 'Open WebUI AI wiring',\n status: 'warn',\n message: '.env missing SYNAP_IS_URL/SYNAP_API_KEY',\n fix: 'eve ai apply',\n });\n }\n }\n } catch { /* non-fatal */ }\n }\n\n // Open WebUI — verify model sources are actually registered via the admin API\n if (installed.includes('openwebui')) {\n const owuiSourceSpinner = createSpinner('Probing OpenWebUI model source registration…');\n owuiSourceSpinner.start();\n try {\n // Short health budget — doctor shouldn't block for 60 s on OWUI.\n const healthy = await waitForHealth(undefined, 3); // 3 × 5 s = 15 s max\n if (!healthy) {\n owuiSourceSpinner.warn('OpenWebUI not reachable — skipping model source check');\n checks.push({\n name: 'Open WebUI model sources',\n status: 'warn',\n message: 'OpenWebUI health endpoint did not respond within 15 s — container may be starting',\n fix: 'docker start hestia-openwebui (or wait and re-run `eve doctor`)',\n });\n } else {\n const jwt = await getAdminJwtPostHealth();\n if (!jwt) {\n owuiSourceSpinner.warn('Could not forge admin JWT');\n checks.push({\n name: 'Open WebUI model sources',\n status: 'warn',\n message: 'Admin JWT could not be forged — WEBUI_SECRET_KEY missing or no admin user in DB',\n fix: 'Check /opt/openwebui/.env has WEBUI_SECRET_KEY; if missing: eve ai apply',\n });\n } else {\n const sources = await listModelSources(jwt);\n const hasSynap = sources.some(\n s => s.url.includes('eve-brain-synap') || s.url.includes(':4000'),\n );\n if (hasSynap) {\n owuiSourceSpinner.succeed(`Open WebUI model sources: ${sources.length} registered`);\n checks.push({\n name: 'Open WebUI model sources',\n status: 'pass',\n message: `${sources.length} source(s) registered — Synap IS present in model picker`,\n });\n } else {\n owuiSourceSpinner.fail('Synap IS missing from OpenWebUI model sources');\n checks.push({\n name: 'Open WebUI model sources',\n status: 'fail',\n message: `${sources.length} source(s) registered but Synap IS is not among them — users see only Ollama`,\n fix: 'eve openwebui sync',\n });\n }\n }\n }\n } catch {\n owuiSourceSpinner.warn('Could not probe OpenWebUI model sources');\n }\n }\n\n // Synap IS — check that deploy/.env has at least one provider key\n if (installed.includes('synap')) {\n try {\n const { existsSync, readFileSync } = await import('node:fs');\n const deployDir = process.env.SYNAP_DEPLOY_DIR ?? '/opt/synap-backend/deploy';\n const envPath = `${deployDir}/.env`;\n if (existsSync(envPath)) {\n const content = readFileSync(envPath, 'utf-8');\n const hasKey = /^(OPENAI|ANTHROPIC|OPENROUTER)_API_KEY=.+/m.test(content);\n if (hasKey) {\n checks.push({ name: 'Synap IS AI wiring', status: 'pass', message: 'upstream provider key in deploy/.env' });\n } else {\n checks.push({\n name: 'Synap IS AI wiring',\n status: 'warn',\n message: 'No upstream provider key in Synap deploy/.env',\n fix: 'eve ai apply',\n });\n }\n }\n } catch { /* non-fatal */ }\n }\n }\n } catch {\n aiCheck.fail('AI wiring check failed');\n }\n\n // Check 5: Entity State\n const stateCheck = createSpinner('Checking entity state...');\n stateCheck.start();\n try {\n const state = await entityStateManager.getState();\n stateCheck.succeed('Entity state is accessible');\n\n // Check each organ\n const organs: Organ[] = ['brain', 'arms', 'builder', 'eyes', 'legs'];\n for (const organ of organs) {\n const organState = state.organs[organ];\n if (organState.state === 'ready') {\n checks.push({\n name: `${formatOrgan(organ)} (state)`,\n status: 'pass',\n message: 'Organ marked ready in state'\n });\n } else if (organState.state === 'error') {\n checks.push({\n name: `${formatOrgan(organ)} (state)`,\n status: 'fail',\n message: organState.errorMessage || 'Organ has errors',\n fix: `eve install --components=${organ}`,\n });\n } else if (organState.state === 'missing') {\n checks.push({\n name: `${formatOrgan(organ)} (state)`,\n status: 'warn',\n message: 'Organ not installed',\n fix: `eve install --components=${organ}`,\n });\n }\n }\n // Extra check: T3 Code container running but codex daemon not active\n try {\n const { execSync } = await import('child_process');\n const t3Running = execSync(\n `docker inspect -f '{{.State.Running}}' eve-builder-t3code 2>/dev/null || echo false`,\n { encoding: 'utf-8' }\n ).trim() === 'true';\n if (t3Running) {\n const daemonActive = (() => {\n try {\n const out = execSync(\n `docker exec eve-builder-hermes sh -c 'pgrep -f \"codex.js daemon\" >/dev/null 2>&1 && echo yes || echo no' 2>/dev/null || echo no`,\n { encoding: 'utf-8' }\n ).trim();\n return out === 'yes';\n } catch { return false; }\n })();\n if (!daemonActive) {\n checks.push({\n name: 'Codex daemon',\n status: 'warn',\n message: 'T3 Code container is running but codex feature-poller daemon is not active',\n fix: 'eve builder codex daemon',\n });\n } else {\n checks.push({ name: 'Codex daemon', status: 'pass', message: 'Codex daemon is active' });\n }\n }\n } catch { /* non-fatal */ }\n } catch (error) {\n stateCheck.fail('Cannot read entity state');\n checks.push({ name: 'Entity State', status: 'fail', message: 'Failed to read state' });\n }\n\n try {\n const coreChecks = await runDoctorChecks();\n const existing = new Set(checks.map((check) => check.name));\n for (const check of coreChecks) {\n const name = `Core: ${check.name}`;\n if (existing.has(name)) continue;\n existing.add(name);\n checks.push({\n name,\n status: check.status,\n message: check.message,\n fix: check.fix,\n });\n }\n } catch (error) {\n checks.push({\n name: 'Operational core',\n status: 'warn',\n message: `Shared doctor runner unavailable: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Print results\n console.log();\n printHeader('Diagnostic Results', emojis.info);\n console.log();\n\n const passed = checks.filter(c => c.status === 'pass').length;\n const failed = checks.filter(c => c.status === 'fail').length;\n // `skip` and `warn` both render with the warning glyph and roll into\n // the same \"warnings\" counter — the visual distinction is in the\n // accompanying message (\"skipped — ...\" vs the warn explanation).\n const warnings = checks.filter(c => c.status === 'warn' || c.status === 'skip').length;\n\n for (const check of checks) {\n const icon = check.status === 'pass'\n ? emojis.check\n : check.status === 'fail'\n ? emojis.cross\n : emojis.warning;\n const color = check.status === 'pass'\n ? colors.success\n : check.status === 'fail'\n ? colors.error\n : colors.warning;\n\n console.log(`${color(icon)} ${check.name}`);\n if (verbose || check.status !== 'pass') {\n console.log(colors.muted(` ${check.message}`));\n if (check.fix) {\n console.log(colors.info(` Fix: ${check.fix}`));\n }\n }\n if (check.deep) renderDeepDiagnostic(check.deep);\n }\n\n console.log();\n console.log(colors.primary('─'.repeat(50)));\n console.log(`${colors.success(`${passed} passed`)}, ${colors.error(`${failed} failed`)}, ${colors.warning(`${warnings} warnings`)}`);\n\n // Overall status\n if (failed === 0 && warnings === 0) {\n console.log();\n printSuccess('Entity is healthy! All checks passed.');\n } else if (failed === 0) {\n console.log();\n printWarning('Entity has warnings but is functional.');\n } else {\n console.log();\n printError(`Entity has ${failed} issue(s) that need attention.`);\n printInfo(' Follow the Fix hints above, or run: eve inspect');\n }\n console.log();\n}\n\n/**\n * Render the deep-diagnostic block under a failing route. The format mirrors\n * the spec: a \"Deep diagnostic:\" header, a probe-from-Traefik line, a log\n * patterns sub-section, and a single \"Recommended fix:\" footer. Indented\n * two spaces so it visually nests under the parent route check.\n */\nfunction renderDeepDiagnostic(deep: DeepDiagnostic): void {\n const indent = ' ';\n const subIndent = indent + ' ';\n console.log(colors.muted(`${indent}Deep diagnostic:`));\n\n // Probe-from-Traefik line ────────────────────────────────────────────────\n if (deep.upstreamContainer) {\n console.log(colors.muted(`${subIndent}From inside eve-legs-traefik:`));\n const probe = deep.upstreamProbe;\n let line = probe.summary;\n if (probe.contentPreview) {\n line += `\\n${subIndent} preview: ${probe.contentPreview}`;\n }\n const probeColor = probe.status === 'connected' ? colors.success : colors.warning;\n console.log(probeColor(`${subIndent} ${line}`));\n } else {\n console.log(colors.muted(`${subIndent}${deep.upstreamProbe.summary}`));\n }\n\n // Matched log patterns ───────────────────────────────────────────────────\n if (deep.upstreamContainer) {\n if (deep.matchedPatterns.length > 0) {\n console.log(\n colors.muted(\n `${subIndent}Upstream container logs (last ${deep.logLineCount} lines, matched ${deep.matchedPatterns.length} pattern${deep.matchedPatterns.length === 1 ? '' : 's'}):`,\n ),\n );\n for (const m of deep.matchedPatterns) {\n console.log(colors.warning(`${subIndent} [${m.tag}] ${m.explanation} (line ${m.lineNumber}).`));\n console.log(colors.muted(`${subIndent} > ${m.matchedLine}`));\n }\n } else if (deep.logLineCount > 0) {\n console.log(colors.muted(`${subIndent}Upstream container logs (last ${deep.logLineCount} lines): no known issue matched.`));\n } else {\n console.log(colors.muted(`${subIndent}Upstream container logs: could not read (container missing or docker unreachable).`));\n }\n }\n\n // Recommended fix ────────────────────────────────────────────────────────\n console.log(colors.info(`${subIndent}Recommended fix:`));\n console.log(colors.info(`${subIndent} ${deep.recommendedFix}`));\n}\n","/**\n * Shared route-probing utilities used by `eve domain set`, `eve domain check`,\n * and `eve doctor`. Tests Traefik routing end-to-end with the right Host\n * header, plus DNS resolution per subdomain.\n */\n\nimport { execSync } from 'node:child_process';\nimport type { ServiceAccess } from '@eve/dna';\nimport { getServerIp } from '@eve/dna';\n\nexport interface RouteProbe {\n /** Service id (eve-dashboard, pod, openclaw, …). */\n id: string;\n /** Host header used (e.g. eve.hyperray.shop). */\n host: string;\n /** HTTP status code returned by Traefik via curl. 'timeout' if no response. */\n httpStatus: string;\n /** Resolved DNS A record (or null if unresolved). */\n dnsResolved: string | null;\n /** True when DNS resolves to this server's public IP. */\n dnsCorrect: boolean;\n /** High-level outcome: ok | upstream-down | not-routing | dns-missing | dns-wrong. */\n outcome: 'ok' | 'upstream-down' | 'not-routing' | 'dns-missing' | 'dns-wrong' | 'timeout';\n}\n\n/** Probe every route in `urls` end-to-end. Synchronous + fast (4s curl timeout). */\nexport function probeRoutes(urls: ServiceAccess[]): RouteProbe[] {\n const serverIp = getServerIp();\n const out: RouteProbe[] = [];\n\n for (const svc of urls) {\n if (!svc.domainUrl) continue;\n const host = svc.domainUrl.replace(/^https?:\\/\\//, '').split('/')[0];\n\n // 1. HTTP probe via Traefik on localhost:80\n let httpStatus = '???';\n try {\n httpStatus = execSync(\n `curl -s -o /dev/null -w \"%{http_code}\" --max-time 4 -H \"Host: ${host}\" http://localhost:80/`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim();\n } catch { httpStatus = 'timeout'; }\n\n // 2. DNS resolution\n let dnsResolved: string | null = null;\n try {\n const out = execSync(`getent hosts ${host} 2>/dev/null | awk '{print $1}' | head -1`, {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n if (out) dnsResolved = out;\n } catch { /* ignore */ }\n if (!dnsResolved) {\n try {\n const out = execSync(`dig +short ${host} | head -1`, {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n if (out) dnsResolved = out;\n } catch { /* ignore */ }\n }\n\n const dnsCorrect = !!serverIp && dnsResolved === serverIp;\n\n // 3. Classify outcome\n let outcome: RouteProbe['outcome'];\n if (!dnsResolved) {\n outcome = 'dns-missing';\n } else if (!dnsCorrect) {\n outcome = 'dns-wrong';\n } else if (httpStatus === 'timeout') {\n outcome = 'timeout';\n } else if (httpStatus === '404') {\n outcome = 'not-routing';\n } else if (httpStatus === '502' || httpStatus === '503' || httpStatus === '504') {\n outcome = 'upstream-down';\n } else {\n outcome = 'ok';\n }\n\n out.push({ id: svc.id, host, httpStatus, dnsResolved, dnsCorrect, outcome });\n }\n\n return out;\n}\n\n/** Human-readable summary line for one probe. */\nexport function probeSummary(p: RouteProbe): string {\n switch (p.outcome) {\n case 'ok': return `${p.httpStatus} — reachable`;\n case 'upstream-down': return `${p.httpStatus} — route OK, upstream not responding`;\n case 'not-routing': return `${p.httpStatus} — Traefik has no rule matching this host`;\n case 'dns-missing': return `DNS not configured (no A record for ${p.host})`;\n case 'dns-wrong': return `DNS points to ${p.dnsResolved} (expected this server)`;\n case 'timeout': return `request timed out`;\n }\n}\n\n/** Aggregate verdict: ok | partial | broken. */\nexport function probeVerdict(probes: RouteProbe[]): 'ok' | 'partial' | 'broken' {\n if (probes.length === 0) return 'ok';\n const okCount = probes.filter(p => p.outcome === 'ok').length;\n if (okCount === probes.length) return 'ok';\n if (okCount === 0) return 'broken';\n return 'partial';\n}\n","/**\n * Deep diagnostics for failing Traefik routes.\n *\n * When `eve doctor` finds a route returning 502/503/504/timeout, the generic\n * \"upstream not responding\" message isn't a diagnosis — it's a description\n * of the symptom. The doctor knows which container backs that route, so it\n * should:\n *\n * 1. Probe FROM inside Traefik's network to the upstream container by\n * its docker-network hostname. This distinguishes \"Traefik can't see\n * the upstream\" from \"the upstream itself is broken\".\n * 2. Read the upstream container's last 50 log lines.\n * 3. Match those lines against a pattern library of known issues we've\n * hit in the field — auth-token regen, missing API key, OOM, etc.\n *\n * The result is rendered as a sub-section under the failed route so the\n * user gets a real next-step instead of having to ssh in and tail logs\n * themselves.\n *\n * Cost budget: each invocation runs 2 docker exec calls (~1s total wall\n * clock). We only ever call this from a route that's ALREADY failed —\n * never on the happy path — so the overhead is bounded by the number\n * of failing routes, not the total route count.\n */\n\nimport { execSync } from 'node:child_process';\nimport { COMPONENTS } from '@eve/dna';\nimport type { RouteProbe } from './probe-routes.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface DeepDiagnostic {\n /**\n * Outcome of the probe-from-Traefik step. `pending` only appears on the\n * shell return type if we couldn't even attempt the probe (no upstream\n * mapping known); the renderer treats that as a no-op.\n */\n upstreamProbe: {\n status: 'connected' | 'refused' | 'dns-failed' | 'timeout' | 'http-error' | 'unknown' | 'skipped';\n /** Short, single-line summary suitable for inline display. */\n summary: string;\n /** When the upstream returned bytes, the first ~200 chars (newline-stripped). */\n contentPreview?: string;\n };\n /** Matched log patterns, ordered most-specific first. */\n matchedPatterns: PatternMatch[];\n /** Raw log line count read (zero when we couldn't fetch logs). */\n logLineCount: number;\n /** The upstream container we examined. null when we don't know what it is. */\n upstreamContainer: string | null;\n /**\n * One single recommended fix command — picked from the highest-priority\n * matched pattern. When no pattern matched, this is a generic fallback.\n */\n recommendedFix: string;\n}\n\ninterface PatternMatch {\n /** Short tag shown in the rendered output (e.g. \"openclaw-auth-token\"). */\n tag: string;\n /** Human-readable explanation of what the matched line means. */\n explanation: string;\n /** The exact line from the log that matched (truncated to 160 chars). */\n matchedLine: string;\n /** 1-based index into the captured log buffer. */\n lineNumber: number;\n /** Suggested fix specific to this pattern. */\n fix: string;\n}\n\n// ---------------------------------------------------------------------------\n// Route → upstream mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Hard-coded fallback map for routes whose subdomain doesn't match a\n * `ServiceInfo.subdomain` exactly. Rare today (the registry already covers\n * pod / openclaw / feeds / chat / eve), but listed for the audit trail\n * called out in the task brief.\n */\nconst FALLBACK_ROUTE_TO_CONTAINER: Record<string, { container: string; port: number }> = {\n pod: { container: 'synap-backend-backend-1', port: 4000 },\n openclaw: { container: 'eve-arms-openclaw', port: 18789 },\n feeds: { container: 'eve-eyes-rsshub', port: 1200 },\n chat: { container: 'hestia-openwebui', port: 8080 },\n eve: { container: 'eve-dashboard', port: 3000 },\n};\n\n/** Resolve a failed route to (container, port) by component-registry lookup. */\nfunction resolveUpstream(route: RouteProbe): { container: string; port: number } | null {\n // First try the registry — it's the source of truth.\n const fromRegistry = COMPONENTS.find(c => c.service?.subdomain && c.id === route.id);\n if (fromRegistry?.service) {\n return {\n container: fromRegistry.service.containerName,\n port: fromRegistry.service.internalPort,\n };\n }\n\n // Fallback: derive subdomain from hostname (`openclaw.example.com` → `openclaw`).\n const subdomain = route.host.split('.')[0];\n const sd = FALLBACK_ROUTE_TO_CONTAINER[subdomain];\n if (sd) return sd;\n\n // Last-ditch: scan registry for matching subdomain.\n const bySubdomain = COMPONENTS.find(c => c.service?.subdomain === subdomain);\n if (bySubdomain?.service) {\n return {\n container: bySubdomain.service.containerName,\n port: bySubdomain.service.internalPort,\n };\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Pattern library — most specific first\n// ---------------------------------------------------------------------------\n\n/**\n * Runtime context fed to patterns that want richer signals than the log\n * buffer alone. Read once per `diagnoseFailedRoute` call (one `docker\n * inspect`) and shared across every pattern check for that container.\n *\n * Currently only `sigterm-loop` consumes the context (to suppress\n * false-positives on healthy containers that received a single SIGTERM\n * during a normal `eve update`). Adding more context-aware patterns\n * means extending this shape and the `gather` helper that fills it in.\n */\ninterface PatternContext {\n /** `docker inspect --format '{{.RestartCount}}'`. -1 if unreadable. */\n restartCount: number;\n /** Wall-clock seconds since `StartedAt`. -1 if unreadable. */\n uptimeSec: number;\n}\n\ninterface KnownPattern {\n tag: string;\n /**\n * Optional component scope. When set, the pattern only fires if the\n * upstream container matches. Avoids false positives like an OpenAI-key\n * pattern matching a log line in a totally unrelated container that\n * happened to mention OpenAI.\n */\n scopeContainer?: string;\n /** Compiled regex tested against each log line. First-match-wins per pattern. */\n match: RegExp;\n explanation: string;\n fix: string;\n /**\n * Higher = checked first. When two patterns match the same line, the\n * one with higher priority is preferred. Within the same priority,\n * the first to appear in the log wins.\n */\n priority: number;\n /**\n * Optional richer match function. When set, the pattern's regex is\n * evaluated FIRST (so we don't pay the cost of a custom callback on\n * every line); on a hit, `confirm` is called to either accept or\n * reject the match using the line index, full log buffer, and\n * runtime context. Returning `false` discards the hit and the\n * matcher continues scanning. Used by `sigterm-loop` to avoid\n * firing on a single, expected SIGTERM during a normal restart.\n */\n confirm?: (args: {\n line: string;\n lineIndex: number;\n logLines: string[];\n context: PatternContext;\n }) => boolean;\n}\n\nconst KNOWN_PATTERNS: KnownPattern[] = [\n // Most specific OpenClaw failure modes ────────────────────────────────────\n {\n tag: 'openclaw-auth-regen',\n scopeContainer: 'eve-arms-openclaw',\n match: /auth token was missing|Generated a new token/i,\n explanation:\n 'OpenClaw regenerated its auth token. Public domain origin probably no longer in `gateway.controlUi.allowedOrigins`.',\n fix:\n 'Run `eve mode reconcile-openclaw` if available; otherwise `docker restart eve-arms-openclaw eve-legs-traefik && eve doctor`.',\n priority: 100,\n },\n {\n tag: 'openclaw-no-openai',\n scopeContainer: 'eve-arms-openclaw',\n match: /No API key found for provider \"openai\"/i,\n explanation: 'OpenClaw needs an OpenAI key but none is wired in.',\n fix:\n '`eve ai providers add openai --api-key <key> && eve ai apply` — or switch to Ollama via `eve ai set-service openclaw ollama && eve ai apply`.',\n priority: 95,\n },\n // Process-level failures ──────────────────────────────────────────────────\n {\n tag: 'oom-killed',\n match: /out of memory|OOMKilled|killed[: ]/i,\n explanation: 'Container was OOM-killed by the kernel.',\n fix: 'Increase the memory limit in the components compose file or free system memory.',\n priority: 90,\n },\n {\n tag: 'eaddrinuse',\n match: /EADDRINUSE/i,\n explanation: 'Port collision — another process is using the bind port.',\n fix: 'Stop the conflicting process, then restart the container.',\n priority: 85,\n },\n {\n tag: 'permission-denied',\n match: /(permission denied|EACCES)/i,\n explanation: 'File or volume permission issue at startup.',\n fix: 'Check the volume mounts ownership: `docker exec <container> ls -la /data`.',\n priority: 80,\n },\n {\n tag: 'connection-refused',\n match: /ECONNREFUSED|connection refused/i,\n explanation: 'Upstream not listening on the expected port — startup script may not have bound yet.',\n fix: 'Wait 10s and re-run `eve doctor`. If it persists, check the container startup script.',\n priority: 75,\n },\n // Lifecycle / runtime ─────────────────────────────────────────────────────\n {\n tag: 'migration-running',\n match: /\\bMigration\\b|\\brunning migrations\\b|\\bmigrate(?:\\.ts)?\\b/,\n explanation: 'Schema migration appears to be running mid-startup.',\n fix: 'Wait 30s and re-run `eve doctor` — the container should accept traffic once migrations finish.',\n priority: 70,\n },\n {\n tag: 'healthcheck-failing',\n match: /healthcheck failing|unhealthy|health[- ]check failed/i,\n explanation: 'Healthcheck endpoint is unreachable.',\n fix: \"Inspect the container's HEALTHCHECK config: `docker inspect <container> --format '{{json .Config.Healthcheck}}'`.\",\n priority: 65,\n },\n {\n tag: 'sigterm-loop',\n match: /SIGTERM received|shutting down|received signal terminat(ed|ing)/i,\n explanation: 'Container is restart-looping (received SIGTERM near the end of its log).',\n fix: 'Check the components full log: `eve logs <component>`. Look for the line right BEFORE SIGTERM.',\n priority: 60,\n /**\n * Suppress false positives. A single SIGTERM during a normal `eve\n * update` is expected — the container is told to stop, then a fresh\n * one is started. Old behavior fired the pattern on any single match\n * near the tail of the log and lit up healthy containers (uptime 5\n * minutes, 0 restarts) with a misleading \"restart-looping\" warning.\n *\n * New rule, two cumulative gates:\n *\n * (1) The Docker runtime says the container is healthy. If\n * `RestartCount === 0` AND uptime > 60s, this is NOT a loop\n * regardless of what the logs say. Skip the pattern entirely.\n *\n * (2) When the runtime can't tell us (inspect failed) OR the\n * runtime DOES suggest something is off, require strong\n * log signal: either MULTIPLE SIGTERMs in the captured\n * window (≥2) OR a SIGTERM in the LAST 5 lines (very\n * recent kill suggests an in-progress crash).\n */\n confirm: ({ line, lineIndex, logLines, context }) => {\n // Gate 1 — runtime says we're fine.\n if (context.restartCount === 0 && context.uptimeSec > 60) return false;\n\n // Gate 2 — log strength.\n const sigtermPattern = /SIGTERM received|shutting down|received signal terminat(ed|ing)/i;\n let count = 0;\n for (const l of logLines) {\n if (sigtermPattern.test(l)) count += 1;\n if (count >= 2) break;\n }\n if (count >= 2) return true;\n\n // Single hit — only trust it if it's very near the tail (last 5 lines).\n const distanceFromEnd = logLines.length - 1 - lineIndex;\n void line; // intentionally unused — `lineIndex` already pinpoints the hit\n return distanceFromEnd >= 0 && distanceFromEnd < 5;\n },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Run a deep diagnostic on a failed route. Caller decides what counts as\n * \"failed\" — typically anything where `RouteProbe.outcome !== 'ok'`. We\n * never run this for healthy routes (cost budget).\n *\n * Returns one `DeepDiagnostic` describing what we learned about the\n * upstream. The function NEVER throws — every failure mode (missing\n * docker, container removed, log read timeout) becomes part of the\n * returned shape.\n */\nexport async function diagnoseFailedRoute(route: RouteProbe): Promise<DeepDiagnostic> {\n const upstream = resolveUpstream(route);\n if (!upstream) {\n return {\n upstreamProbe: {\n status: 'unknown',\n summary: `No upstream mapping known for route ${route.host} — registry has no matching component.`,\n },\n matchedPatterns: [],\n logLineCount: 0,\n upstreamContainer: null,\n recommendedFix:\n `Run \\`docker logs <container> --tail 50\\` for whatever container should back ${route.host}.`,\n };\n }\n\n const upstreamProbe = probeFromTraefik(upstream.container, upstream.port);\n const logBuffer = readUpstreamLogs(upstream.container);\n const context = gatherPatternContext(upstream.container);\n const matchedPatterns = matchLogPatterns(upstream.container, logBuffer, context);\n\n const recommendedFix = matchedPatterns.length > 0\n ? matchedPatterns[0].fix\n : `No known issue matched in last ${logBuffer.length} log lines. Run \\`eve logs ${upstream.container}\\` for the full log.`;\n\n return {\n upstreamProbe,\n matchedPatterns,\n logLineCount: logBuffer.length,\n upstreamContainer: upstream.container,\n recommendedFix,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Probe helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Probe the upstream from inside Traefik's network so we test the same path\n * Traefik takes. We use `wget -q -O -` (the busybox-y form is portable across\n * Alpine images) with a hard timeout. Disambiguating the failure mode is the\n * point of this probe — \"DNS failed\" tells the user the network is wrong;\n * \"refused\" tells them the container isn't listening; \"connected\" tells them\n * the upstream is fine and Traefik's config is the problem.\n */\nfunction probeFromTraefik(container: string, port: number): DeepDiagnostic['upstreamProbe'] {\n const url = `http://${container}:${port}`;\n // Spawn synchronously so we get a clean stdout/stderr/exit triple. Hard\n // 6s wall-clock cap (5s network timeout + 1s startup margin).\n let stdout = '';\n let stderr = '';\n let exitCode = -1;\n try {\n stdout = execSync(\n `docker exec eve-legs-traefik sh -c 'wget -q -O - --timeout=5 ${url} 2>&1 || echo \"WGET_EXIT=$?\"'`,\n { encoding: 'utf-8', timeout: 6000, stdio: ['pipe', 'pipe', 'pipe'] },\n );\n exitCode = 0;\n } catch (err: unknown) {\n // execSync throws when exit != 0 OR on timeout. Unpack what we can.\n if (typeof err === 'object' && err !== null) {\n const e = err as { status?: number; stdout?: Buffer | string; stderr?: Buffer | string };\n exitCode = e.status ?? -1;\n stdout = typeof e.stdout === 'string' ? e.stdout : e.stdout?.toString('utf-8') ?? '';\n stderr = typeof e.stderr === 'string' ? e.stderr : e.stderr?.toString('utf-8') ?? '';\n }\n }\n\n const combined = (stdout + '\\n' + stderr).trim();\n\n // Most reliable wins: explicit error strings from wget/getaddrinfo.\n if (/bad address|nslookup|getaddrinfo|name or service not known|could not resolve/i.test(combined)) {\n return {\n status: 'dns-failed',\n summary: `DNS lookup failed for ${container} from inside Traefik — container not on eve-network`,\n };\n }\n if (/connection refused/i.test(combined)) {\n return {\n status: 'refused',\n summary: `${container}:${port} refused connection — process not listening on that port`,\n };\n }\n if (/timed out|timeout/i.test(combined) && exitCode !== 0) {\n return {\n status: 'timeout',\n summary: `Connection to ${container}:${port} timed out — container is up but unresponsive`,\n };\n }\n\n // We got bytes — interpret as either a successful probe (exit 0) or\n // an HTTP error from wget that returned a body anyway.\n if (exitCode === 0 && stdout.length > 0) {\n const preview = stdout.replace(/\\s+/g, ' ').trim().slice(0, 200);\n return {\n status: 'connected',\n summary: `Connected to ${container}:${port} from Traefik — upstream is reachable`,\n contentPreview: preview,\n };\n }\n\n if (combined.length > 0) {\n return {\n status: 'http-error',\n summary: `${container}:${port} reachable but returned an error: ${combined.slice(0, 160)}`,\n };\n }\n\n return {\n status: 'unknown',\n summary: `Could not probe ${container}:${port} from inside Traefik (exit ${exitCode})`,\n };\n}\n\n/**\n * Read the upstream's last 50 log lines via `docker logs`. Returns an\n * array of lines (no trailing newlines). Empty array on any failure —\n * the caller renders the empty state cleanly.\n */\nfunction readUpstreamLogs(container: string): string[] {\n try {\n const out = execSync(`docker logs ${container} --tail 50 2>&1`, {\n encoding: 'utf-8',\n timeout: 4000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return out.split(/\\r?\\n/).filter(l => l.length > 0);\n } catch {\n return [];\n }\n}\n\n/**\n * Walk the log buffer once per pattern (priority-ordered) and collect every\n * match. We dedup by tag (a single tag matches at most once — multiple line\n * hits within the same pattern aren't useful to render). Within a tag, we\n * keep the FIRST hit so the line number points at the originating event,\n * not the latest restart-loop echo.\n *\n * Patterns may opt into context-aware matching via a `confirm()` callback.\n * The regex still runs first (cheap path), and `confirm` only fires when\n * a line matches — keeping the per-line cost low. See `KnownPattern.confirm`.\n */\nfunction matchLogPatterns(\n container: string,\n logLines: string[],\n context: PatternContext,\n): PatternMatch[] {\n const matches: PatternMatch[] = [];\n const seenTags = new Set<string>();\n\n // Priority-sort once so \"most specific first\" is meaningful.\n const ordered = [...KNOWN_PATTERNS].sort((a, b) => b.priority - a.priority);\n\n for (const pattern of ordered) {\n if (seenTags.has(pattern.tag)) continue;\n if (pattern.scopeContainer && pattern.scopeContainer !== container) continue;\n for (let i = 0; i < logLines.length; i += 1) {\n const line = logLines[i];\n if (!pattern.match.test(line)) continue;\n\n // Optional confirmation gate — used by sigterm-loop to suppress\n // false positives on a single, expected SIGTERM during normal\n // shutdown.\n if (pattern.confirm && !pattern.confirm({ line, lineIndex: i, logLines, context })) {\n continue;\n }\n\n matches.push({\n tag: pattern.tag,\n explanation: pattern.explanation,\n matchedLine: line.length > 160 ? `${line.slice(0, 160)}…` : line,\n lineNumber: i + 1,\n fix: pattern.fix,\n });\n seenTags.add(pattern.tag);\n break;\n }\n }\n\n return matches;\n}\n\n/**\n * Gather the runtime context patterns may consult. One `docker inspect`\n * call per failed route — bounded cost, never invoked for healthy routes.\n *\n * Format string returns `<RestartCount>|<StartedAt>` so we get both fields\n * in a single shell-out. Anything that goes wrong (container missing,\n * docker daemon down, parse error) returns sentinel `-1`s, and the\n * patterns that consume the context treat those as \"unknown\" — they\n * fall back to log-only signals.\n */\nfunction gatherPatternContext(container: string): PatternContext {\n try {\n const out = execSync(\n `docker inspect ${container} --format '{{.RestartCount}}|{{.State.StartedAt}}'`,\n { encoding: 'utf-8', timeout: 4000, stdio: ['pipe', 'pipe', 'pipe'] },\n ).trim();\n\n const [restartStr, startedAtStr] = out.split('|');\n const restartCount = Number.parseInt(restartStr, 10);\n\n let uptimeSec = -1;\n if (startedAtStr) {\n const startedMs = Date.parse(startedAtStr);\n if (Number.isFinite(startedMs)) {\n uptimeSec = Math.max(0, Math.floor((Date.now() - startedMs) / 1000));\n }\n }\n\n return {\n restartCount: Number.isFinite(restartCount) ? restartCount : -1,\n uptimeSec,\n };\n } catch {\n return { restartCount: -1, uptimeSec: -1 };\n }\n}\n","/**\n * CLI-side IDoctorRunner implementations for `eve doctor` and `eve auth`.\n *\n * # Two runners, one decision\n *\n * The CLI talks to its OWN pod's synap-backend. We pick a transport ONCE\n * at startup based on where we're running:\n *\n * • **On the pod host** (synap-backend container is here):\n * `DockerExecRunner` execs into the synap-backend container itself\n * and runs a tiny inline Node script (`docker exec -i <c> node -e ...`)\n * that calls `fetch('http://127.0.0.1:4000/...')`. No DNS, no Traefik,\n * no TLS, no firewall — and crucially no BusyBox/wget either. The\n * synap-backend image runs Node 20-alpine, which has native fetch, so\n * we use the same HTTP client the app itself uses.\n *\n * • **Off the pod host** (managing a remote pod from a laptop):\n * `FetchRunner` against the public Traefik URL. The only option, but\n * it requires DNS + cert + traefik routing to all be healthy.\n *\n * `buildPodRunner()` makes the decision and returns the right one. There\n * is NO automatic fallback between them: the choice is a property of\n * WHERE we run, not a recoverable state. If the synap container is\n * detected but exec fails mid-call, we surface a clear error instead of\n * silently retrying via the slower public path (which often won't work\n * from inside the pod host either — split-DNS, firewall, cert pending).\n *\n * # Why we don't use wget anymore\n *\n * The previous version of `DockerExecRunner` shelled into the synap\n * container and ran BusyBox `wget`. That worked, *mostly*, but BusyBox\n * supports a tiny, idiosyncratic subset of wget's flags and silently\n * misbehaves on the wrong arg form (`--header=` is dropped, `--post-data`\n * space-form is dropped, `--method` doesn't exist, etc.). We chased\n * intermittent 404s and \"wrong status code\" bugs for two days that\n * turned out to be BusyBox quirks, not real backend errors. Replacing\n * `wget` with `node -e 'fetch(...)'` removes the entire failure surface:\n * one inline script, no shell escaping (body via stdin), arbitrary\n * methods supported natively, JSON envelope back. Don't reintroduce wget.\n *\n * # `FallbackRunner` is retained but UNUSED in production\n *\n * Kept for the test suite and as a generic primitive someone might want\n * later. Never wire it into the CLI's happy path.\n */\n\nimport { execSync } from \"node:child_process\";\nimport { execa, type ResultPromise } from \"execa\";\nimport {\n FetchRunner,\n isFetchTransportError,\n type DoctorRunnerResponse,\n type DoctorRunnerStream,\n type IDoctorRunner,\n} from \"@eve/lifecycle\";\n\n// ---------------------------------------------------------------------------\n// Synap container detection + URL planning\n// ---------------------------------------------------------------------------\n\n/**\n * Names the synap-backend container is known to register under, depending\n * on which deploy path created it. We probe in order; first match wins.\n */\nconst SYNAP_BACKEND_CONTAINER_CANDIDATES: ReadonlyArray<string> = [\n \"synap-backend-backend-1\",\n \"synap-backend\",\n \"synap-backend-1\",\n];\n\nlet cachedSynapContainer: string | null | undefined;\n\n/**\n * Returns the name of a running synap-backend container, or null if none.\n *\n * Cached for the life of the process because (a) the container's running\n * state is stable for the duration of any single CLI command and (b) every\n * `docker inspect` call is ~50ms — without the cache a single probe-heavy\n * command (`eve doctor`) would burn seconds on redundant checks.\n *\n * Tests can reset the cache via `resetSynapContainerCache()`.\n */\nexport function findRunningSynapContainer(): string | null {\n if (cachedSynapContainer !== undefined) return cachedSynapContainer;\n for (const name of SYNAP_BACKEND_CONTAINER_CANDIDATES) {\n try {\n // `execSync` is imported at module top — using `require()` here was\n // a long-standing bug: this file is bundled as ESM, where `require`\n // is undefined, so every iteration silently threw ReferenceError,\n // the catch swallowed it, and the function ALWAYS returned null on\n // the pod host. That cascaded into `buildPodRunner` always picking\n // `FetchRunner`, which hit the public URL through Traefik (or\n // whatever http/https mismatch existed) and got 404 — the famous\n // \"POST /api/hub/setup/agent not available — backend version too\n // old\" red herring that wasn't a backend issue at all.\n execSync(`docker inspect --format='{{.State.Running}}' ${name}`, {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: 3000,\n });\n cachedSynapContainer = name;\n return name;\n } catch {\n // try next\n }\n }\n cachedSynapContainer = null;\n return null;\n}\n\n/** Test hook — reset the container detection cache. */\nexport function resetSynapContainerCache(): void {\n cachedSynapContainer = undefined;\n}\n\nexport interface ExecPlan {\n /** Container we'll exec INTO. */\n container: string;\n /** URL the in-container Node script will fetch. */\n url: string;\n}\n\n/**\n * Plan a `docker exec` request to reach synap-backend.\n *\n * This runner is single-purpose: every URL passed here is meant for THIS\n * pod's API. The hostname in the input is irrelevant — whether the caller\n * resolved `https://pod.example.com/...` or `http://127.0.0.1:4000/...`,\n * we only care about path + query. We always exec INTO the synap-backend\n * container itself and call `127.0.0.1:4000` — bypassing DNS, Traefik,\n * TLS, the host network, and any of a dozen other moving parts that\n * could fail in between.\n *\n * Pinning to `127.0.0.1` (not `localhost`) is deliberate: Alpine's\n * `/etc/hosts` maps `localhost` to BOTH `::1` and `127.0.0.1`. The Node\n * HTTP listener binds to `0.0.0.0` (IPv4-only), so any IPv6 attempt\n * comes back ECONNREFUSED — which we previously misdiagnosed as\n * \"backend is dead.\" Pin to IPv4.\n *\n * Returns null if no synap-backend container is running locally; the\n * caller (`DockerExecRunner`) surfaces this as a transport error.\n */\nexport function planExecRequest(url: string): ExecPlan | null {\n const synap = findRunningSynapContainer();\n if (!synap) return null;\n\n let path = \"/\";\n let search = \"\";\n try {\n const parsed = new URL(url);\n path = parsed.pathname || \"/\";\n search = parsed.search;\n } catch {\n // Unparseable — fall through with a bare path. fetch will produce\n // a useful error if the input was truly nonsense.\n }\n\n return {\n container: synap,\n url: `http://127.0.0.1:4000${path}${search}`,\n };\n}\n\n// ---------------------------------------------------------------------------\n// DockerExecRunner — runs HTTP requests via Node's native fetch inside the\n// synap-backend container (image is node:20-alpine, fetch is built in).\n// ---------------------------------------------------------------------------\n\n/**\n * Sentinel that separates the JSON status envelope from streaming body\n * bytes when the in-container script is run in streaming mode. Chosen to\n * be highly unlikely to appear in a JSON header line (it starts with a\n * literal newline).\n */\nconst STREAM_BODY_SENTINEL = \"\\n---SYNAP-BODY---\\n\";\n\n/**\n * Build the `docker exec` argv that runs a small inline Node script inside\n * the synap-backend container. The script:\n *\n * 1. Reads the request body from stdin (so callers that POST a payload\n * avoid shell escaping entirely — the body is a stream of bytes,\n * never an argv element).\n * 2. Calls `fetch(URL, { method, headers, body, signal })` with an\n * AbortController wired to a hard timeout.\n * 3. **Non-streaming mode**: writes a single JSON envelope to stdout —\n * `{ status, body, headers, error? }`. The host parses it and\n * returns a `DoctorRunnerResponse`.\n * 4. **Streaming mode**: writes the JSON envelope (status + headers)\n * followed by the body sentinel, then pipes the response body\n * chunk-by-chunk to stdout. The host reads stdout, splits on the\n * sentinel, and yields the rest as the SSE stream.\n *\n * The script is passed to `node -e` as a SINGLE argv element, so there\n * is no shell to escape — quotes and newlines inside the script are\n * literal. All call-site values (URL, method, headers, timeout) are\n * embedded via `JSON.stringify`, which produces valid JS literals.\n *\n * `-i` is required so docker exec attaches stdin (the body channel).\n */\ntype ExecArgs =\n | { container: string; argv: string[]; stdin: string; supported: true }\n | { supported: false; reason: string };\n\nexport function buildExecArgs(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n headers: Record<string, string>,\n body: string | undefined,\n timeoutMs: number,\n container: string,\n streaming: boolean,\n): ExecArgs {\n const script = buildNodeFetchScript(method, url, headers, !!body, timeoutMs, streaming);\n return {\n supported: true,\n container,\n argv: [\"exec\", \"-i\", container, \"node\", \"-e\", script],\n // Body always goes via stdin — even on GET (empty string closes the pipe).\n stdin: body ?? \"\",\n };\n}\n\n/**\n * Compose the inline Node script. Call-site values are injected via\n * JSON.stringify (safe to embed inside JS source — JSON is a subset of JS).\n *\n * Why all helpers are inlined: docker exec runs this as a one-shot\n * `node -e <script>` invocation with no module resolution, no top-level\n * await, no `require` (we're running plain `node -e`, no bundler). Keep\n * it self-contained.\n */\nfunction buildNodeFetchScript(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n headers: Record<string, string>,\n hasBody: boolean,\n timeoutMs: number,\n streaming: boolean,\n): string {\n const consts =\n `const URL_=${JSON.stringify(url)};` +\n `const METHOD=${JSON.stringify(method)};` +\n `const HEADERS=${JSON.stringify(headers)};` +\n `const TIMEOUT_MS=${timeoutMs};` +\n `const HAS_BODY=${hasBody ? \"true\" : \"false\"};`;\n\n // Common prefix: collect stdin into `b`, then run main when it closes.\n const prelude =\n `let b='';` +\n `process.stdin.on('data',c=>{b+=c;});` +\n `process.stdin.on('end',async()=>{` +\n `const ac=new AbortController();` +\n `const tid=setTimeout(()=>ac.abort(),TIMEOUT_MS);` +\n `try{` +\n `const r=await fetch(URL_,{method:METHOD,headers:HEADERS,body:HAS_BODY?b:undefined,signal:ac.signal});`;\n\n if (streaming) {\n // Streaming: write envelope + sentinel, then pipe body chunks raw.\n return (\n consts +\n prelude +\n `const env={status:r.status,headers:Object.fromEntries(r.headers)};` +\n `process.stdout.write(JSON.stringify(env)+${JSON.stringify(STREAM_BODY_SENTINEL)});` +\n `if(r.body){` +\n `const reader=r.body.getReader();` +\n `while(true){` +\n `const{done,value}=await reader.read();` +\n `if(done)break;` +\n `process.stdout.write(Buffer.from(value));` +\n `}` +\n `}` +\n `}catch(e){` +\n `process.stdout.write(JSON.stringify({status:0,headers:{},error:String(e&&e.message||e)})+${JSON.stringify(STREAM_BODY_SENTINEL)});` +\n `}finally{clearTimeout(tid);}` +\n `});`\n );\n }\n\n // Non-streaming: read full body, write single JSON envelope.\n return (\n consts +\n prelude +\n `const t=await r.text();` +\n `process.stdout.write(JSON.stringify({status:r.status,body:t,headers:Object.fromEntries(r.headers)}));` +\n `}catch(e){` +\n `process.stdout.write(JSON.stringify({status:0,body:'',headers:{},error:String(e&&e.message||e)}));` +\n `}finally{clearTimeout(tid);}` +\n `});`\n );\n}\n\nexport class DockerExecRunner implements IDoctorRunner {\n readonly name = \"docker-exec\";\n\n async httpGet(\n url: string,\n headers: Record<string, string>,\n opts: { signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<DoctorRunnerResponse> {\n return this.invoke(\"GET\", url, headers, undefined, opts);\n }\n\n async httpPost(\n url: string,\n headers: Record<string, string>,\n body: string,\n opts: { signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<DoctorRunnerResponse> {\n return this.invoke(\"POST\", url, headers, body, opts);\n }\n\n async httpDelete(\n url: string,\n headers: Record<string, string>,\n opts: { signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<DoctorRunnerResponse> {\n return this.invoke(\"DELETE\", url, headers, undefined, opts);\n }\n\n private async invoke(\n method: \"GET\" | \"POST\" | \"DELETE\",\n url: string,\n headers: Record<string, string>,\n body: string | undefined,\n opts: { signal?: AbortSignal; timeoutMs?: number },\n ): Promise<DoctorRunnerResponse> {\n const plan = planExecRequest(url);\n if (!plan) {\n return {\n status: 0,\n body: \"\",\n headers: {},\n error: \"no synap-backend container available for docker-exec — run on the pod host or use FetchRunner\",\n };\n }\n const timeoutMs = opts.timeoutMs ?? 6_000;\n // Hard wall-clock cap on the docker exec itself — fetch's AbortController\n // is the inner timeout (and produces a clean error envelope). We give\n // docker exec startup a few extra seconds so the inner timeout fires\n // first when the upstream is slow.\n const execTimeoutMs = timeoutMs + 4_000;\n\n const built = buildExecArgs(method, plan.url, headers, body, timeoutMs, plan.container, false);\n if (!built.supported) {\n return { status: 0, body: \"\", headers: {}, error: built.reason };\n }\n\n // Optional verbose mode — `EVE_DEBUG_RUNNER=1 eve <cmd>` prints what\n // we're about to run + the response. Off by default; never touches\n // happy-path performance. Critical when a probe fails and we need to\n // see what the runner actually did.\n const debug = process.env.EVE_DEBUG_RUNNER === \"1\";\n if (debug) {\n // Print the docker prefix only — the full inline script is long\n // and noisy. The script's behavior is a function of (method, url,\n // headers, body), all of which are visible from the surrounding\n // command flow.\n const prefix = built.argv.slice(0, 5).join(\" \");\n process.stderr.write(\n `[debug-runner] exec: docker ${prefix} <node-script> stdin=${built.stdin.length}b method=${method} url=${plan.url}\\n`,\n );\n }\n\n try {\n const res = await execa(\"docker\", built.argv, {\n timeout: execTimeoutMs,\n cancelSignal: opts.signal,\n reject: false,\n input: built.stdin,\n encoding: \"utf8\",\n });\n\n const stdout = typeof res.stdout === \"string\" ? res.stdout : \"\";\n const stderr = typeof res.stderr === \"string\" ? res.stderr : \"\";\n\n if (debug) {\n process.stderr.write(\n `[debug-runner] exitCode=${res.exitCode} stdout(${stdout.length}b)=${JSON.stringify(stdout.slice(0, 300))} stderr(${stderr.length}b)=${JSON.stringify(stderr.slice(0, 300))}\\n`,\n );\n }\n\n // Happy path: stdout is a JSON envelope produced by our inline\n // script. Anything else means the script never ran (no node? no\n // container? docker exec failed?). Surface stderr in that case —\n // it'll have the docker error message.\n try {\n const parsed = JSON.parse(stdout) as {\n status: number;\n body?: string;\n headers?: Record<string, string>;\n error?: string;\n };\n return {\n status: parsed.status,\n body: parsed.body ?? \"\",\n headers: parsed.headers ?? {},\n error: parsed.error,\n };\n } catch {\n return {\n status: 0,\n body: \"\",\n headers: {},\n error:\n stderr.trim().slice(0, 240) ||\n `node-exec produced no JSON envelope (exit ${res.exitCode ?? -1})`,\n };\n }\n } catch (err) {\n // execa throws when the process is killed (timeout, abort signal).\n const e = err as { timedOut?: boolean; isCanceled?: boolean; message?: string };\n const reason = e.timedOut ? \"timeout\" : e.isCanceled ? \"aborted\" : (e.message || \"exec failed\");\n return { status: 0, body: \"\", headers: {}, error: reason };\n }\n }\n\n async httpStream(\n url: string,\n headers: Record<string, string>,\n opts: { signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<DoctorRunnerStream> {\n const plan = planExecRequest(url);\n if (!plan) {\n return {\n ok: false,\n status: 0,\n headers: {},\n close: async () => { /* nothing to close */ },\n error: \"no synap-backend container available for docker-exec\",\n };\n }\n const timeoutMs = opts.timeoutMs ?? 35_000;\n const built = buildExecArgs(\"GET\", plan.url, headers, undefined, timeoutMs, plan.container, true);\n if (!built.supported) {\n return {\n ok: false,\n status: 0,\n headers: {},\n close: async () => { /* nothing to close */ },\n error: built.reason,\n };\n }\n\n let child: ResultPromise<{ encoding: \"utf8\"; reject: false }>;\n try {\n child = execa(\"docker\", built.argv, {\n encoding: \"utf8\",\n reject: false,\n // Stream timeout = caller's timeout + grace. The inner script\n // also has its own AbortController on the same budget.\n timeout: timeoutMs + 4_000,\n cancelSignal: opts.signal,\n // Close stdin immediately — streaming is GET-only, no body.\n input: \"\",\n });\n } catch (err) {\n return {\n ok: false,\n status: 0,\n headers: {},\n close: async () => { /* nothing */ },\n error: err instanceof Error ? err.message : \"exec failed\",\n };\n }\n\n const stdout = child.stdout;\n if (!stdout) {\n try { child.kill(\"SIGKILL\"); } catch { /* ignore */ }\n return {\n ok: false,\n status: 0,\n headers: {},\n close: async () => { await child.catch(() => null); },\n error: \"no stdout pipe on docker exec subprocess\",\n };\n }\n stdout.setEncoding(\"utf8\");\n\n // Read stdout until we see the body sentinel. Everything before is\n // the JSON envelope; everything after is the streamed response body.\n //\n // The envelope is wrapped in `state` so TypeScript's control-flow\n // analysis doesn't collapse the post-await type to `never`. With a\n // bare `let envelope = null`, TS sees no synchronous reassignment\n // (the closures' assignments happen via callbacks it can't track)\n // and narrows the variable to `null` forever — making the success\n // branch unreachable from its perspective. Property-on-object\n // assignments aren't narrowed the same way, so this stays correct.\n type Envelope = { status: number; headers: Record<string, string>; error?: string };\n const state: { envelope: Envelope | null; leftover: string; pre: string } = {\n envelope: null,\n leftover: \"\",\n pre: \"\",\n };\n\n const onSentinel = new Promise<void>((resolve) => {\n const handler = (chunk: string) => {\n state.pre += chunk;\n const idx = state.pre.indexOf(STREAM_BODY_SENTINEL);\n if (idx < 0) return;\n\n const headerJson = state.pre.slice(0, idx);\n try {\n state.envelope = JSON.parse(headerJson);\n } catch {\n state.envelope = {\n status: 0,\n headers: {},\n error: `bad envelope: ${headerJson.slice(0, 200)}`,\n };\n }\n state.leftover = state.pre.slice(idx + STREAM_BODY_SENTINEL.length);\n stdout.removeListener(\"data\", handler);\n resolve();\n };\n stdout.on(\"data\", handler);\n });\n\n const headerWaitMs = Math.min(8_000, timeoutMs);\n const onTimeout = new Promise<void>((resolve) => {\n const t = setTimeout(() => {\n if (!state.envelope) {\n state.envelope = { status: 0, headers: {}, error: \"timed out waiting for envelope\" };\n }\n resolve();\n }, headerWaitMs);\n t.unref?.();\n });\n const onExit = child.then((result) => {\n if (!state.envelope) {\n state.envelope = {\n status: 0,\n headers: {},\n error: `subprocess exited before envelope (exit ${result?.exitCode ?? -1})`,\n };\n }\n });\n\n await Promise.race([onSentinel, onTimeout, onExit]);\n\n const env = state.envelope;\n if (!env || env.status === 0) {\n try { child.kill(\"SIGKILL\"); } catch { /* ignore */ }\n return {\n ok: false,\n status: 0,\n headers: env?.headers ?? {},\n close: async () => { await child.catch(() => null); },\n error: env?.error ?? \"unknown stream failure\",\n };\n }\n\n let closed = false;\n const close = async () => {\n if (closed) return;\n closed = true;\n try { child.kill(\"SIGTERM\"); } catch { /* ignore */ }\n await child.catch(() => null);\n };\n\n const leftover = state.leftover;\n async function* iterate(): AsyncGenerator<string> {\n if (leftover) yield leftover;\n for await (const chunk of stdout) {\n if (closed) return;\n yield typeof chunk === \"string\" ? chunk : chunk.toString();\n }\n }\n\n return {\n ok: true,\n status: env.status,\n headers: env.headers,\n chunks: iterate(),\n close,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// FallbackRunner — fetch first, swap to docker-exec on transport failure\n// ---------------------------------------------------------------------------\n\n/**\n * Wraps a primary runner (FetchRunner) and falls back to a secondary\n * runner (DockerExecRunner) when the primary hits a transport error.\n * The swap is sticky — once we've decided fetch can't reach the host,\n * we route every subsequent call through docker exec, no point retrying.\n *\n * The optional `onSwap` callback fires exactly once. The CLI wires this\n * to a stderr log line so the user sees why the probes are still working\n * despite an unreachable URL.\n */\nexport class FallbackRunner implements IDoctorRunner {\n readonly name = \"fallback\";\n\n private active: IDoctorRunner;\n private swapped = false;\n\n constructor(\n private readonly primary: IDoctorRunner,\n private readonly secondary: IDoctorRunner,\n private readonly onSwap?: (note: string) => void,\n ) {\n this.active = primary;\n }\n\n /** Force a swap — useful for tests and for callers that want to start in fallback mode. */\n forceSwap(reason: string): void {\n if (this.swapped) return;\n this.swapped = true;\n this.active = this.secondary;\n this.onSwap?.(`note: routing probes through ${this.secondary.name} (${reason})`);\n }\n\n private async withFallback<T extends DoctorRunnerResponse>(\n invoke: (runner: IDoctorRunner) => Promise<T>,\n ): Promise<T> {\n if (this.swapped) return invoke(this.active);\n\n const res = await invoke(this.active);\n if (res.status === 0 && this.shouldSwap(res.error)) {\n this.forceSwap(\"host loopback unreachable\");\n return invoke(this.active);\n }\n return res;\n }\n\n private shouldSwap(error: string | undefined): boolean {\n if (!error) return false;\n // Match the same set FetchRunner reports as transport errors. The\n // primary FetchRunner already filters via `isFetchTransportError`\n // when it shapes the error; we rely on the message containing one\n // of the codes, OR being one of fetch's well-known fallbacks.\n if (/ECONNREFUSED|EHOSTUNREACH|ENOTFOUND|EAI_AGAIN/i.test(error)) return true;\n // Native fetch on Node 20+ surfaces transport errors as the literal\n // string \"fetch failed\" with the cause buried in a `cause` property\n // we can't see at this layer. Treat it as a swap signal — the\n // worst case is one wasted docker exec for something that was\n // genuinely a server-side error, but the host-unreachable case\n // is way more common in the deployment we're hardening against.\n if (/fetch failed/i.test(error)) return true;\n // On hosts with no port mapping, fetch can hang until timeout\n // instead of getting a quick RST (e.g. when the host firewall\n // silently drops the SYN, or when Node tries IPv6 first). The\n // user-visible symptom is \"(timeout)\" not \"ECONNREFUSED\". Treat\n // any timeout / aborted-by-deadline as a transport failure too —\n // we'd rather waste one docker exec than report the probe as dead.\n if (/timeout|timed out|TimeoutError|AbortError|aborted|signal aborted|ETIMEDOUT/i.test(error)) return true;\n return false;\n }\n\n async httpGet(\n url: string,\n headers: Record<string, string>,\n opts?: { signal?: AbortSignal; timeoutMs?: number },\n ): Promise<DoctorRunnerResponse> {\n return this.withFallback(r => r.httpGet(url, headers, opts));\n }\n\n async httpPost(\n url: string,\n headers: Record<string, string>,\n body: string,\n opts?: { signal?: AbortSignal; timeoutMs?: number },\n ): Promise<DoctorRunnerResponse> {\n return this.withFallback(r => r.httpPost(url, headers, body, opts));\n }\n\n async httpDelete(\n url: string,\n headers: Record<string, string>,\n opts?: { signal?: AbortSignal; timeoutMs?: number },\n ): Promise<DoctorRunnerResponse> {\n return this.withFallback(r => r.httpDelete(url, headers, opts));\n }\n\n async httpStream(\n url: string,\n headers: Record<string, string>,\n opts?: { signal?: AbortSignal; timeoutMs?: number },\n ): Promise<DoctorRunnerStream> {\n if (this.swapped) return this.active.httpStream(url, headers, opts);\n\n const res = await this.active.httpStream(url, headers, opts);\n if (!res.ok && res.status === 0 && this.shouldSwap(res.error)) {\n await res.close();\n this.forceSwap(\"host loopback unreachable\");\n return this.active.httpStream(url, headers, opts);\n }\n return res;\n }\n}\n\n// Re-export the parts the CLI's doctor command consumes.\nexport { FetchRunner, isFetchTransportError };\n\n// ---------------------------------------------------------------------------\n// Pod transport — always FetchRunner, URL chooses the path\n// ---------------------------------------------------------------------------\n\n/**\n * The runner the CLI uses to talk to this pod's API.\n *\n * # One transport, two URLs\n *\n * Earlier versions of this file picked between `DockerExecRunner` and\n * `FetchRunner` based on whether the synap container was running\n * locally. That bought us nothing: the docker-exec path needed its own\n * BusyBox/Node-script gymnastics, and we already had to support\n * FetchRunner for the off-host case. So we collapsed it.\n *\n * Now the on-host vs off-host distinction lives entirely in the URL:\n *\n * - **On the pod host** — `resolveSynapUrlOnHost(secrets)` returns\n * `http://127.0.0.1:14000` (the loopback port published by Eve's\n * `docker-compose.override.yml`). Plain HTTP via FetchRunner; no\n * DNS, no TLS, no Traefik, no firewall to traverse.\n *\n * - **Off the pod host** — `resolveSynapUrlOnHost(secrets)` falls\n * back to the public Traefik URL. Same FetchRunner, same code path.\n *\n * The transport is the same in both cases — that's the whole point.\n * Bytes go through Node's native `fetch`, status codes are real HTTP\n * status codes, the request/response cycle is observable, and there's\n * no `docker exec` cold-start cost on every call.\n *\n * `DockerExecRunner` stays exported — `eve doctor` uses it as a\n * break-glass diagnostic (\"can the synap container respond on its own\n * loopback even when host loopback fails?\"). Don't wire it back into\n * the happy path. See\n * `synap-team-docs/content/team/devops/eve-cli-transports.mdx` for the\n * full transport-selection design.\n *\n * `onTransportNote` is an optional hook so callers can surface which\n * URL was picked — the doctor uses it to print \"using loopback\" or\n * \"using public URL\" alongside its summary. The note is computed by\n * resolving the URL ourselves; callers who don't pass a sink get the\n * note on stderr (one line, never spammy).\n */\n/** Tracks whether we've already printed the transport note this process. */\nlet stderrNoteEmitted = false;\n\nexport function buildPodRunner(\n onTransportNote?: (note: string) => void,\n): IDoctorRunner {\n if (onTransportNote) {\n // Sink-based callers (the doctor) get the note every time. It's\n // their responsibility to decide whether to print or aggregate.\n onTransportNote(synthesizeTransportNote());\n } else if (!stderrNoteEmitted && !process.env.EVE_QUIET_TRANSPORT) {\n // Stderr-based fallback: print once per process. `eve auth provision`\n // builds the runner once per agent (4 agents = 4 calls), and the\n // note is identical every time — emitting four copies is just noise.\n stderrNoteEmitted = true;\n process.stderr.write(`ℹ️ ${synthesizeTransportNote()}\\n`);\n }\n return new FetchRunner();\n}\n\n/** Test hook — reset the once-per-process gate. */\nexport function resetTransportNoteGate(): void {\n stderrNoteEmitted = false;\n}\n\n/**\n * Build a one-line description of which URL the CLI is most likely\n * about to use. Pure heuristic — actual URL selection happens in\n * `resolveSynapUrlOnHost(secrets)`, so this is just for the user-facing\n * note. We check the synap container detection (cheap) without\n * actually doing the loopback probe (also cheap, but async — and the\n * note is fire-and-forget so we don't want to make callers await).\n */\nfunction synthesizeTransportNote(): string {\n const synap = findRunningSynapContainer();\n return synap\n ? `synap container ${synap} detected — CLI will prefer loopback if reachable`\n : \"no synap container detected — CLI will use public URL via Traefik\";\n}\n","/**\n * The ONE door for every git invocation the CLI makes.\n *\n * # Why this file exists\n *\n * Two production defects, both found on 2026-09-02 while root-causing a\n * `git pull` that had started prompting `Username for 'https://github.com'`\n * on all three Synap hosts:\n *\n * 1. **The install path was prompt-proof; the update path was not.**\n * `setup.ts` cloned with `credential.interactive=never` AND\n * `GIT_TERMINAL_PROMPT=0`, so it could never hang. `synap.ts` ran a bare\n * `git pull --rebase`. Invoked non-interactively (the eve dashboard, a\n * cron, `ssh host 'eve synap deploy'`) that BLOCKS ON STDIN FOREVER,\n * because git's fallback for \"I need credentials\" is to read a TTY that\n * isn't there. A server-side CLI must never be able to reach that state\n * — hence `gitEnv()` / `HARDENED_ARGS`, applied by `runGit()` to every\n * call, with no opt-out.\n *\n * 2. **A failed pull was misreported and the build continued anyway.**\n * The old catch said `'Git pull failed (may be uncommitted changes) —\n * continuing'` for ANY error. On 2026-09-02 that sentence would have\n * been shown for an HTTP-layer failure, and the build would then have\n * run against a stale checkout and reported success. That is exactly\n * the defect class `synap-backend/deploy/verify-deploy.sh` was written\n * to catch. `syncRepo()` therefore CLASSIFIES the failure and the caller\n * fails closed on everything that is not a genuinely dirty tree.\n *\n * # The HTTP/1.1 retry is not superstition\n *\n * Debian 12's `libcurl3-gnutls` 7.88.1-10+deb12u15 (shipped by\n * unattended-upgrades on 2026-07-12) breaks git's protocol-v2 flow over\n * HTTP/2 on the SECOND request:\n *\n * GET /<repo>.git/info/refs?service=git-upload-pack -> HTTP/2 200\n * POST /<repo>.git/git-upload-pack -> HTTP/2 401\n * www-authenticate: Basic realm=\"GitHub\"\n *\n * Git sees the 401, concludes it needs credentials, and prompts — even for a\n * PUBLIC repository the very same box can read anonymously one request\n * earlier. The tell that it is the HTTP stack and not your token: a public\n * third-party repo (`github.com/git/git.git`) 401s identically.\n * `-c http.version=HTTP/1.1` and `-c protocol.version=0` both fix it.\n *\n * So an `auth`-classified failure is retried ONCE over HTTP/1.1. If the\n * retry succeeds, the diagnosis is certain (it was the transport, not the\n * credentials) and we say so. If it fails too, the credentials really are\n * the problem and the caller gets `auth` with an honest message.\n * `ensureGitHttpFloor()` makes the workaround permanent for the host.\n */\n\nimport { execa } from 'execa';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\n// ---------------------------------------------------------------------------\n// Non-interactivity floor\n// ---------------------------------------------------------------------------\n\n/**\n * Every environment variable git (and the helpers it spawns) consults before\n * falling back to a TTY prompt. Setting all of them is deliberate: git tries\n * `GIT_ASKPASS`, then `core.askPass`, then `SSH_ASKPASS`, and only then the\n * terminal — plugging one hole leaves the others open.\n */\nexport function gitEnv(extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {\n return {\n ...process.env,\n GIT_TERMINAL_PROMPT: '0',\n GIT_ASKPASS: 'echo',\n SSH_ASKPASS: 'echo',\n SSH_ASKPASS_REQUIRE: 'never',\n GCM_INTERACTIVE: 'never',\n ...extra,\n };\n}\n\n/** Config-level twin of `gitEnv()`, for the paths env vars don't cover. */\nexport const HARDENED_ARGS: ReadonlyArray<string> = [\n '-c',\n 'credential.interactive=never',\n '-c',\n 'core.askPass=',\n];\n\n/** The workaround for the deb12u15 libcurl regression documented above. */\nexport const HTTP11_ARGS: ReadonlyArray<string> = ['-c', 'http.version=HTTP/1.1'];\n\nexport interface GitResult {\n ok: boolean;\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/**\n * Run git with the non-interactivity floor applied. NEVER shells out to git\n * any other way — `runGit` is the only door, so no future call site can\n * re-introduce a prompt that hangs a headless deploy.\n */\nexport async function runGit(\n args: string[],\n opts: { cwd?: string; http11?: boolean; timeoutMs?: number } = {},\n): Promise<GitResult> {\n const full = [...HARDENED_ARGS, ...(opts.http11 ? HTTP11_ARGS : []), ...args];\n try {\n const res = await execa('git', full, {\n cwd: opts.cwd,\n env: gitEnv(),\n timeout: opts.timeoutMs ?? 120_000,\n reject: false,\n stdin: 'ignore',\n });\n return {\n ok: res.exitCode === 0,\n stdout: (res.stdout ?? '').toString(),\n stderr: (res.stderr ?? '').toString(),\n exitCode: res.exitCode ?? 1,\n };\n } catch (err) {\n return { ok: false, stdout: '', stderr: err instanceof Error ? err.message : String(err), exitCode: 1 };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Failure classification\n// ---------------------------------------------------------------------------\n\n/**\n * What actually went wrong. The whole point of this union is that the caller\n * can distinguish `dirty` (benign — local edits, keep going) from everything\n * else (the remote was never reached, so a build would run on stale code).\n */\nexport type GitFailureKind =\n | 'auth'\n | 'network'\n | 'no-remote'\n | 'not-a-repo'\n | 'conflict'\n | 'dirty'\n | 'unknown';\n\nexport function classifyGitFailure(stderr: string): GitFailureKind {\n const s = stderr.toLowerCase();\n if (s.includes('not a git repository')) return 'not-a-repo';\n if (s.includes(\"does not appear to be a git repository\") || s.includes('no such remote'))\n return 'no-remote';\n if (\n s.includes('could not read username') ||\n s.includes('could not read password') ||\n s.includes('authentication failed') ||\n s.includes('permission denied (publickey)') ||\n s.includes('terminal prompts disabled') ||\n s.includes('403 forbidden') ||\n s.includes('401')\n )\n return 'auth';\n if (\n s.includes('could not resolve host') ||\n s.includes('connection timed out') ||\n s.includes('connection refused') ||\n s.includes('network is unreachable') ||\n s.includes('ssl') ||\n s.includes('unable to access')\n )\n return 'network';\n if (\n s.includes('local changes') ||\n s.includes('would be overwritten') ||\n s.includes('cannot pull with rebase') ||\n s.includes('unstaged changes')\n )\n return 'dirty';\n if (s.includes('conflict') || s.includes('automatic merge failed')) return 'conflict';\n return 'unknown';\n}\n\n// ---------------------------------------------------------------------------\n// The update door\n// ---------------------------------------------------------------------------\n\nexport type SyncOutcome =\n /** Fetched and fast-forwarded (or already current). Safe to build. */\n | { kind: 'updated'; from: string; to: string; note?: string }\n /** Remote reached and current, but the working tree has local edits. */\n | { kind: 'dirty'; files: string[]; note?: string }\n /** Remote NOT reached, or the merge failed. NEVER safe to build. */\n | { kind: 'failed'; reason: GitFailureKind; message: string; fix: string };\n\nconst FIXES: Record<GitFailureKind, string> = {\n auth: 'Run `eve doctor` for the full diagnosis of this host\\'s git update path.',\n network: 'Check outbound HTTPS/SSH to the git host from this machine.',\n 'no-remote':\n 'This checkout has no `origin`. It was most likely created by the tarball fallback or by rsync. ' +\n 'Add one: `git remote add origin <url>`.',\n 'not-a-repo': 'This directory is not a git checkout. Re-run `eve setup`, or point at a real checkout.',\n conflict: 'Resolve the merge conflict in the checkout, then re-run.',\n dirty: 'Commit, stash, or discard the local changes in the checkout.',\n unknown: 'Inspect the git output above.',\n};\n\n/**\n * Turn a `could not read Username` into a determination instead of a guess.\n *\n * The same stderr covers two unrelated causes, and telling them apart is a\n * single probe against a PUBLIC third-party repo:\n * • the probe ALSO fails -> this host's HTTP stack is broken; credentials\n * were never the problem (the deb12u15 libcurl regression);\n * • the probe succeeds -> git works fine here, so this particular remote\n * really does need credentials it does not have.\n */\nasync function explainAuthFailure(remoteUrl: string): Promise<string> {\n const probe = await probeGitHttps();\n if (!probe.ok) {\n return (\n \"git cannot fetch a PUBLIC repo on this host either, so this is NOT about credentials — \" +\n \"it is this machine's HTTP stack. Check outbound HTTPS to github.com.\"\n );\n }\n if (probe.http11Needed) {\n return (\n 'git over HTTP/2 is broken on this host (a public repo fails the same way, HTTP/1.1 works) — ' +\n 'this is the Debian 12 libcurl 7.88.1-10+deb12u15 regression, NOT your credentials. ' +\n 'Fix permanently: `git config --global http.version HTTP/1.1`.'\n );\n }\n const ssh = toSshRemote(remoteUrl);\n return (\n `git works fine on this host (a public repo fetches cleanly), so ${remoteUrl} genuinely ` +\n 'needs credentials this machine does not have. Either switch the remote to SSH — ' +\n (ssh ? `\\`git remote set-url origin ${ssh}\\`` : '`git remote set-url origin git@github.com:<org>/<repo>.git`') +\n ' — with a key registered on the git host, or configure a PAT with a PERSISTED helper ' +\n '(`git config --global credential.helper store`; the default `cache` helper lives in RAM ' +\n 'and evaporates, which is why an HTTPS pull can work today and prompt tomorrow).'\n );\n}\n\n/** `https://github.com/org/repo.git` -> `git@github.com:org/repo.git` */\nexport function toSshRemote(url: string): string | null {\n const m = /^https:\\/\\/([^/]+)\\/(.+?)(?:\\.git)?$/.exec(url.trim());\n return m ? `git@${m[1]}:${m[2]}.git` : null;\n}\n\n/**\n * Fetch + fast-forward a checkout, honestly.\n *\n * Contract: a `failed` outcome means the remote was NOT reached (or the\n * merge did not land) and the checkout is therefore at an unknown/stale\n * commit. Callers MUST fail closed on it — building anyway is how a deploy\n * silently ships old code and still reports success.\n */\nexport async function syncRepo(dir: string): Promise<SyncOutcome> {\n if (!existsSync(join(dir, '.git'))) {\n return {\n kind: 'failed',\n reason: 'not-a-repo',\n message: `${dir} is not a git checkout (no .git directory)`,\n fix: FIXES['not-a-repo'],\n };\n }\n\n const remote = await runGit(['remote', 'get-url', 'origin'], { cwd: dir });\n if (!remote.ok) {\n return {\n kind: 'failed',\n reason: 'no-remote',\n message: `${dir} has no 'origin' remote — nothing to pull from`,\n fix: FIXES['no-remote'],\n };\n }\n\n const before = (await runGit(['rev-parse', 'HEAD'], { cwd: dir })).stdout.trim();\n\n // Fetch first, as its own step. `pull` conflates \"could not reach the\n // remote\" with \"could not merge\"; separating them is what lets us tell\n // the operator which of the two actually happened.\n let http11 = false;\n let note: string | undefined;\n let fetch = await runGit(['fetch', '--prune', 'origin'], { cwd: dir });\n if (!fetch.ok && classifyGitFailure(fetch.stderr) === 'auth') {\n // The deb12u15 libcurl regression presents as a 401. Retrying over\n // HTTP/1.1 is the falsification test AND the fix in one move.\n const retry = await runGit(['fetch', '--prune', 'origin'], { cwd: dir, http11: true });\n if (retry.ok) {\n http11 = true;\n note =\n 'fetched over HTTP/1.1 — the default HTTP/2 path returned a spurious 401. ' +\n 'Make it permanent with `git config --global http.version HTTP/1.1`.';\n fetch = retry;\n }\n }\n if (!fetch.ok) {\n const reason = classifyGitFailure(fetch.stderr);\n return {\n kind: 'failed',\n reason,\n message: fetch.stderr.trim() || `git fetch failed in ${dir}`,\n // `auth` is the one reason where the same stderr has two completely\n // different causes — a broken HTTP stack, or genuinely missing\n // credentials for a private repo. Determine which, rather than making\n // the operator guess: that guess is what cost a day on 2026-09-02.\n fix: reason === 'auth' ? await explainAuthFailure(remote.stdout.trim()) : FIXES[reason],\n };\n }\n\n // Remote reached. Only now can local state be the blocker — and only now\n // is \"uncommitted changes\" an honest thing to say.\n const dirtyOut = (await runGit(['status', '--porcelain', '--untracked-files=no'], { cwd: dir }))\n .stdout;\n const dirtyFiles = dirtyOut.split('\\n').map((l) => l.trim()).filter(Boolean);\n if (dirtyFiles.length > 0) {\n return { kind: 'dirty', files: dirtyFiles, note };\n }\n\n const merge = await runGit(['merge', '--ff-only', '@{u}'], { cwd: dir, http11 });\n if (!merge.ok) {\n const reason = classifyGitFailure(merge.stderr);\n return {\n kind: 'failed',\n reason: reason === 'unknown' ? 'conflict' : reason,\n message: merge.stderr.trim() || `fast-forward failed in ${dir}`,\n fix: FIXES[reason === 'unknown' ? 'conflict' : reason],\n };\n }\n\n const after = (await runGit(['rev-parse', 'HEAD'], { cwd: dir })).stdout.trim();\n return { kind: 'updated', from: before.slice(0, 8), to: after.slice(0, 8), note };\n}\n\n// ---------------------------------------------------------------------------\n// Provisioning floor + doctor probe\n// ---------------------------------------------------------------------------\n\n/**\n * Probe whether git-over-HTTPS works on this host at all, using a PUBLIC\n * third-party repo. Using someone else's repo is the point: it removes\n * credentials and repo permissions from the equation, so a failure can only\n * be the local HTTP stack.\n */\nexport async function probeGitHttps(): Promise<\n { ok: true; http11Needed: boolean } | { ok: false; message: string }\n> {\n const url = 'https://github.com/git/git.git';\n const direct = await runGit(['ls-remote', url, 'HEAD'], { timeoutMs: 30_000 });\n if (direct.ok) return { ok: true, http11Needed: false };\n const via11 = await runGit(['ls-remote', url, 'HEAD'], { http11: true, timeoutMs: 30_000 });\n if (via11.ok) return { ok: true, http11Needed: true };\n return { ok: false, message: direct.stderr.trim() || 'git ls-remote failed' };\n}\n\n/**\n * Pin `http.version=HTTP/1.1` globally IF (and only if) this host needs it.\n * Called from provisioning so a freshly-imaged Debian 12 pod is never born\n * with a broken update path. Idempotent; a no-op on a healthy host, so it\n * costs nothing to run every time.\n */\nexport async function ensureGitHttpFloor(): Promise<\n { changed: false; reason: 'healthy' | 'already-set' | 'unfixable' } | { changed: true }\n> {\n const existing = await runGit(['config', '--global', '--get', 'http.version']);\n if (existing.ok && existing.stdout.trim() === 'HTTP/1.1') {\n return { changed: false, reason: 'already-set' };\n }\n const probe = await probeGitHttps();\n if (probe.ok && !probe.http11Needed) return { changed: false, reason: 'healthy' };\n if (!probe.ok) return { changed: false, reason: 'unfixable' };\n await runGit(['config', '--global', 'http.version', 'HTTP/1.1']);\n return { changed: true };\n}\n\n/**\n * Clone, prompt-proof, with a public-tarball fallback.\n *\n * The fallback previously left a directory with NO `.git` at all, which\n * silently destroyed the UPDATE door: the next `eve synap deploy` had\n * nothing to pull from. (That is the observed state of `/opt/synap/*` on\n * synap-personal: 11 checkouts, zero remotes.) So after extracting, we\n * `git init` + `remote add origin` + fetch, leaving a real checkout behind.\n */\nexport async function cloneOrFetchTarball(opts: {\n repoUrl: string;\n tarballUrl: string;\n targetDir: string;\n tmpDir: string;\n log?: (msg: string) => void;\n}): Promise<{ via: 'clone' | 'tarball'; gitUsable: boolean }> {\n const { repoUrl, tarballUrl, targetDir, tmpDir, log = () => {} } = opts;\n\n let clone = await runGit(['clone', '--depth', '1', repoUrl, targetDir]);\n if (!clone.ok && classifyGitFailure(clone.stderr) === 'auth') {\n log('git clone hit a 401 — retrying over HTTP/1.1 (known Debian libcurl regression) …');\n clone = await runGit(['clone', '--depth', '1', repoUrl, targetDir], { http11: true });\n }\n if (clone.ok) return { via: 'clone', gitUsable: true };\n\n log('git clone failed; falling back to the public archive from codeload.github.com …');\n const { mkdir, rm } = await import('node:fs/promises');\n const archivePath = join(tmpDir, `synap-backend-${Date.now()}.tar.gz`);\n try {\n await mkdir(targetDir, { recursive: true });\n await execa('curl', ['-fsSL', tarballUrl, '-o', archivePath], { stdio: 'inherit' });\n await execa('tar', ['-xzf', archivePath, '--strip-components', '1', '-C', targetDir], {\n stdio: 'inherit',\n });\n } finally {\n await rm(archivePath, { force: true }).catch(() => undefined);\n }\n\n // Give the tarball a remote so the update door still exists next time.\n const init = await runGit(['init'], { cwd: targetDir });\n const wired =\n init.ok && (await runGit(['remote', 'add', 'origin', repoUrl], { cwd: targetDir })).ok;\n if (wired) {\n log(`Wired origin -> ${repoUrl} so \\`eve synap deploy\\` can update this checkout later.`);\n } else {\n log('WARNING: could not wire an origin remote — this checkout will not be git-updatable.');\n }\n return { via: 'tarball', gitUsable: wired };\n}\n","import { Command } from 'commander';\nimport { confirm, select, isCancel } from '@clack/prompts';\nimport { entityStateManager, type Organ } from '@eve/dna';\nimport { runAdd } from './add.js';\nimport {\n colors,\n emojis,\n printHeader,\n printError,\n printInfo,\n} from '../lib/ui.js';\n\nexport function growCommand(program: Command): void {\n const grow = program\n .command('grow')\n .description('Grow the entity by developing new capabilities')\n .action(async () => {\n await interactiveGrow();\n });\n\n grow\n .command('organ')\n .description('Add a new organ to the entity')\n .argument('[organ]', 'Organ: brain | arms | builder | eyes | legs')\n .option('--dry-run', 'Print planned steps only (no install)')\n .option('--with-ai', 'When growing brain, include Ollama')\n .action(async (organ: string | undefined, options: { dryRun?: boolean; withAi?: boolean }) => {\n if (organ) {\n await growOrgan(organ, options);\n } else {\n await interactiveGrow();\n }\n });\n\n grow\n .command('capability')\n .description('Add a new capability to an existing organ')\n .action(async () => {\n await growCapability();\n });\n}\n\nasync function interactiveGrow(): Promise<void> {\n console.log();\n console.log(colors.primary.bold(`${emojis.sparkles} Eve Entity Growth`));\n console.log();\n\n const state = await entityStateManager.getState();\n\n printHeader('Current Entity State', emojis.entity);\n console.log();\n\n const organs = ['brain', 'arms', 'builder', 'eyes', 'legs'] as const;\n for (const organ of organs) {\n const status = state.organs[organ].state;\n const icon = status === 'ready' ? emojis.check : status === 'missing' ? '○' : '◐';\n const color = status === 'ready' ? colors.success : status === 'missing' ? colors.muted : colors.warning;\n console.log(` ${color(icon)} ${organ.charAt(0).toUpperCase() + organ.slice(1)}: ${color(status)}`);\n }\n\n console.log();\n\n const action = await select({\n message: 'What would you like to grow?',\n options: [\n { value: 'brain', label: '🧠 Brain - Intelligence & Memory', hint: 'Core AI and data services' },\n { value: 'arms', label: '🦾 Arms - Action & Tools', hint: 'AI assistant and MCP servers' },\n { value: 'eyes', label: '👁️ Eyes - Perception', hint: 'RSS feeds and monitoring' },\n { value: 'legs', label: '🦿 Legs - Exposure', hint: 'Traefik and domain routing' },\n { value: 'builder', label: '🏗️ Builder - Creation', hint: 'Development and deployment tools' },\n ],\n });\n\n if (isCancel(action)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n if (typeof action === 'string') {\n let withAi = false;\n if (action === 'brain') {\n const ai = await confirm({\n message: 'Include local AI (Ollama)?',\n initialValue: false,\n });\n if (isCancel(ai)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n withAi = Boolean(ai);\n }\n await growOrgan(action, {\n dryRun: false,\n withAi,\n });\n }\n}\n\n// Map organ names to component IDs for delegation to `eve add`\nconst ORGAN_TO_COMPONENT: Record<string, string> = {\n brain: 'synap',\n arms: 'openclaw',\n eyes: 'rsshub',\n legs: 'traefik',\n builder: 't3code',\n};\n\nasync function growOrgan(\n organ: string,\n options: { dryRun?: boolean; withAi?: boolean }\n): Promise<void> {\n const valid: Organ[] = ['brain', 'arms', 'builder', 'eyes', 'legs'];\n if (!valid.includes(organ as Organ)) {\n printError(`Unknown organ: ${organ}. Use: ${valid.join(', ')}`);\n process.exitCode = 1;\n return;\n }\n\n const componentId = ORGAN_TO_COMPONENT[organ];\n\n console.log();\n printHeader(`Growing ${organ.charAt(0).toUpperCase() + organ.slice(1)}`, emojis.sparkles);\n console.log();\n\n if (options.dryRun) {\n printInfo(`Would run: eve add ${componentId}`);\n return;\n }\n\n const shouldProceed = await confirm({\n message: `Install the ${organ} organ (eve add ${componentId})?`,\n initialValue: true,\n });\n\n if (isCancel(shouldProceed) || !shouldProceed) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n\n await runAdd(componentId, {});\n}\n\nasync function growCapability(): Promise<void> {\n const state = await entityStateManager.getState();\n\n const organ = await select({\n message: 'Which organ would you like to enhance?',\n options: [\n { value: 'brain', label: '🧠 Brain', hint: state.organs.brain.state === 'ready' ? 'Installed' : 'Not installed' },\n { value: 'arms', label: '🦾 Arms', hint: state.organs.arms.state === 'ready' ? 'Installed' : 'Not installed' },\n ],\n });\n\n if (isCancel(organ)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n if (typeof organ === 'string') {\n if (state.organs[organ as Organ].state !== 'ready') {\n printError(`${organ} organ is not installed. Run: eve grow organ ${organ}`);\n return;\n }\n\n printInfo(`Enhancing ${organ} capabilities... (coming soon)`);\n }\n}\n\n","import { Command } from 'commander';\nimport { printInfo, printError } from '../../lib/ui.js';\n\nexport function birthCommand(program: Command): void {\n const birth = program.command('birth').description('Bare-metal provisioning (USB) and host install scripts');\n\n birth\n .command('usb')\n .description('Create a bootable USB with Ventoy + autoinstall (coming soon)')\n .action(async () => {\n printInfo('USB creation script not yet implemented. This will use a Ventoy-based autoinstall profile.');\n });\n\n birth\n .command('install')\n .description('Run server install script (coming soon)')\n .option('--phase <n>', 'Run only phase1 | phase2 | phase3 | all', 'all')\n .action(async (_opts: { phase?: string }) => {\n printInfo('Install script not yet implemented. Use `eve setup` for the current install flow.');\n });\n}\n","import type { Command } from 'commander';\nimport { confirm, select, multiselect, isCancel, intro, outro, note, log } from '@clack/prompts';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport {\n entityStateManager,\n type SetupProfileKind,\n writeSetupProfile,\n type EveSecrets,\n readEveSecrets,\n writeEveSecrets,\n ensureEveSkillsLayout,\n defaultSkillsDir,\n ensureSecretValue,\n getServerIp,\n hasAnyProvider,\n type WireAiResult,\n} from '@eve/dna';\nimport { getGlobalCliFlags, outputJson } from '@eve/cli-kit';\nimport { runBrainInit, runInferenceInit, resolveSynapDelegate } from '@eve/brain';\nimport { runLegsProxySetup } from '@eve/legs';\nimport { probeAdminStatus } from '../setup-admin.js';\nimport { text } from '@clack/prompts';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n createSpinner,\n} from '../../lib/ui.js';\nimport {\n COMPONENTS,\n type ComponentInfo,\n resolveComponent,\n selectedIds,\n allComponentIds,\n addonComponentIds,\n} from '../../lib/components.js';\nimport { RSSHubService } from '@eve/eyes';\nimport {\n runBackendPreflight,\n provisionAllAgents,\n materializeTargets,\n gatherInstallConfig,\n defaultPrompts,\n InstallConfigError,\n type ResolvedInstallConfig,\n} from '@eve/lifecycle';\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface InstallOptions {\n components?: string[];\n domain?: string;\n email?: string;\n model?: string;\n adminEmail?: string;\n adminPassword?: string;\n adminBootstrapMode?: 'preseed' | 'token';\n tunnel?: 'pangolin' | 'cloudflare';\n tunnelDomain?: string;\n aiMode?: 'local' | 'provider' | 'hybrid';\n aiProvider?: 'ollama' | 'openrouter' | 'anthropic' | 'openai';\n fallbackProvider?: 'ollama' | 'openrouter' | 'anthropic' | 'openai';\n withOpenclaw?: boolean;\n withRsshub?: boolean;\n fromImage?: boolean;\n fromSource?: boolean;\n skipHardware?: boolean;\n skipInteractive?: boolean;\n nvidiaSmi?: boolean;\n synapRepo?: string;\n /** Skip writing setup profile & secrets */\n dryRun?: boolean;\n}\n\n/**\n * Core install orchestrator. Resolves which components to install and\n * runs the appropriate service initialisation functions.\n *\n * This function is the shared implementation behind both the interactive\n * `eve install` wizard and the CLI-flag-driven non-interactive mode.\n */\nexport async function runInstall(opts: InstallOptions): Promise<void> {\n const flags = getGlobalCliFlags();\n const jsonMode = Boolean(flags.json);\n const nonInteractive = Boolean(flags.nonInteractive) || Boolean(opts.skipInteractive);\n\n // -----------------------------------------------------------------\n // 1. Determine which components to install\n // -----------------------------------------------------------------\n let componentSet: Record<string, boolean>;\n\n if (opts.components && opts.components.length > 0) {\n // Non-interactive: explicit component list\n componentSet = {};\n for (const id of opts.components) {\n const comp = COMPONENTS.find(c => c.id === id);\n if (!comp) {\n throw new Error(`Unknown component: ${id}. Available: ${COMPONENTS.map(c => c.id).join(', ')}`);\n }\n componentSet[id] = true;\n }\n } else if (nonInteractive) {\n // Non-interactive without --components: infer from legacy profile logic\n // Default: synap only (data_pod equivalent)\n componentSet = { traefik: true, synap: true };\n } else {\n // Interactive wizard\n componentSet = await interactiveComponentSelect();\n if (isCancel(componentSet)) {\n console.log(colors.muted('Installation cancelled.'));\n return;\n }\n }\n\n // Always ensure infrastructure\n for (const comp of COMPONENTS) {\n if (comp.alwaysInstall) {\n componentSet[comp.id] = true;\n }\n }\n\n const installList = selectedIds(componentSet);\n\n // -----------------------------------------------------------------\n // 2. Resolve shared settings — single funnel via gatherInstallConfig.\n //\n // Per-field source chain: flag → env → secrets.json → discovered →\n // saved-profile (off here) → interactive prompt → typed default.\n // Missing required fields in non-interactive mode throw a single\n // structured InstallConfigError instead of late `process.exit(1)`s.\n // -----------------------------------------------------------------\n let cfg: ResolvedInstallConfig;\n try {\n cfg = await gatherInstallConfig({\n cwd: process.cwd(),\n flags: {\n components: installList,\n // Commander defaults --domain to \"localhost\". Treat that as \"no\n // explicit choice\" so the resolver can promote a value from secrets.\n domain: opts.domain && opts.domain !== 'localhost' ? opts.domain : undefined,\n email: opts.email,\n adminEmail: opts.adminEmail,\n adminPassword: opts.adminPassword,\n adminBootstrapMode: opts.adminBootstrapMode,\n fromImage: opts.fromImage,\n fromSource: opts.fromSource,\n withOpenclaw: opts.withOpenclaw,\n withRsshub: opts.withRsshub,\n aiMode: opts.aiMode,\n aiProvider: opts.aiProvider,\n fallbackProvider: opts.fallbackProvider,\n tunnel: opts.tunnel,\n tunnelDomain: opts.tunnelDomain,\n },\n interactive: !nonInteractive && !jsonMode,\n loadSavedProfile: false,\n prompts: defaultPrompts,\n });\n } catch (err) {\n if (err instanceof InstallConfigError) {\n printError(err.message);\n process.exit(1);\n }\n throw err;\n }\n\n // Reflect resolved values back onto opts so the rest of the function\n // (buildInstallSteps, recap, post-install hooks) reads the canonical\n // values without taking a second resolution path.\n const domain = cfg.domain;\n const email = cfg.email;\n const withOpenclaw = cfg.withOpenclaw;\n const withRsshub = cfg.withRsshub;\n opts.domain = domain;\n opts.email = email;\n opts.withOpenclaw = withOpenclaw;\n opts.withRsshub = withRsshub;\n opts.adminEmail = cfg.adminEmail;\n opts.adminPassword = cfg.adminPassword;\n opts.adminBootstrapMode = cfg.adminBootstrapMode;\n opts.fromImage = cfg.installMode === 'from_image';\n opts.fromSource = cfg.installMode === 'from_source';\n opts.tunnel = cfg.tunnel?.provider;\n opts.tunnelDomain = cfg.tunnel?.domain;\n\n // Infer legacy profile for setup-profile.json backward compat\n const legacyProfile = inferLegacyProfile(installList);\n\n // -----------------------------------------------------------------\n // 3. Pre-flight checks\n // -----------------------------------------------------------------\n if (!opts.dryRun) {\n const spinner = createSpinner('Checking prerequisites...');\n spinner.start();\n\n // Resolve docker to its full path — execa has a restricted PATH that may not include /usr/local/bin\n let dockerPath = 'docker';\n try {\n const { stdout } = await execa('which', ['docker']);\n if (stdout) dockerPath = stdout;\n } catch {\n // Fallback to common Docker install paths\n const candidates = [\n '/usr/local/bin/docker',\n '/usr/bin/docker',\n '/usr/bin/containerd',\n ];\n for (const c of candidates) {\n if (existsSync(c)) {\n dockerPath = c;\n break;\n }\n }\n }\n\n // Try docker — retry with delay for daemon startup\n let dockerOk = false;\n for (let attempt = 0; attempt < 8; attempt++) {\n try {\n await execa(dockerPath, ['version']);\n dockerOk = true;\n break;\n } catch {\n if (attempt < 7) {\n await new Promise(resolve => setTimeout(resolve, 3000));\n }\n }\n }\n\n if (dockerOk) {\n spinner.succeed('Docker is running');\n }\n\n if (!dockerOk) {\n spinner.fail('Docker is not running');\n console.log();\n printError('Eve requires Docker to manage containers.');\n console.log();\n if (process.platform === 'darwin') {\n printInfo('macOS: Install Docker Desktop and start it, then run:');\n printInfo(' open -a Docker');\n } else if (process.platform === 'win32') {\n printInfo('Windows: Install Docker Desktop and start the app.');\n } else {\n printInfo('Docker is installed but the daemon is not responding.');\n printInfo('Make sure it is running:');\n printInfo(' sudo systemctl status docker');\n console.log();\n printInfo('If not running, start it:');\n printInfo(' sudo systemctl start docker');\n printInfo(' # wait ~5 seconds for it to initialize');\n console.log();\n printInfo('If Docker is not installed, run:');\n printInfo(' curl -fsSL https://get.docker.com | sudo bash');\n }\n console.log();\n process.exit(1);\n }\n }\n\n // -----------------------------------------------------------------\n // 4. Write setup profile & secrets\n // -----------------------------------------------------------------\n if (!opts.dryRun) {\n const cwd = process.cwd();\n const skillsDir = defaultSkillsDir();\n\n const setupProfile: Parameters<typeof writeSetupProfile>[0] = {\n profile: legacyProfile,\n source: nonInteractive ? 'cli' : 'wizard',\n domainHint: domain,\n };\n if (opts.tunnel) {\n setupProfile.tunnelProvider = opts.tunnel;\n }\n if (opts.tunnelDomain) {\n setupProfile.tunnelDomain = opts.tunnelDomain;\n }\n await writeSetupProfile(setupProfile, cwd);\n\n // Secrets\n const prevSecrets = await readEveSecrets(cwd);\n const merge: EveSecrets = {\n version: '1',\n updatedAt: new Date().toISOString(),\n ai: {\n mode: opts.aiMode || 'hybrid',\n defaultProvider: opts.aiProvider,\n fallbackProvider: opts.fallbackProvider,\n syncToSynap: true,\n providers: [],\n },\n };\n\n if (componentSet['synap']) {\n merge.synap = {\n apiUrl: prevSecrets?.synap?.apiUrl || 'http://127.0.0.1:4000',\n apiKey: ensureSecretValue(prevSecrets?.synap?.apiKey || process.env.SYNAP_API_KEY || process.env.OPENCLAW_SYNAP_API_KEY || ''),\n hubBaseUrl: prevSecrets?.synap?.hubBaseUrl,\n };\n }\n\n if (componentSet['ollama'] || componentSet['synap']) {\n merge.inference = {\n ollamaUrl: componentSet['ollama'] ? 'http://127.0.0.1:11434' : 'http://127.0.0.1:11434',\n gatewayUrl: 'http://127.0.0.1:11435',\n };\n }\n\n // Persist resolved domain → secrets.json. This is the single source of\n // truth for `domain.primary/ssl/email` (consumed by preflight,\n // runBrainInit, eve domain commands). Without this write, every later\n // command would re-prompt for the same values.\n if (cfg.domain && cfg.domain !== 'localhost') {\n merge.domain = {\n primary: cfg.domain,\n ssl: cfg.ssl,\n email: cfg.email,\n };\n }\n\n await writeEveSecrets(merge, cwd);\n ensureEveSkillsLayout(skillsDir);\n }\n\n // -----------------------------------------------------------------\n // 5. Print install plan\n // -----------------------------------------------------------------\n if (!jsonMode) {\n console.log();\n printHeader('Eve Install Plan', emojis.entity);\n console.log();\n for (const comp of COMPONENTS) {\n if (!componentSet[comp.id]) continue;\n const tag = comp.alwaysInstall ? colors.muted(' [infrastructure]') : '';\n console.log(` ${colors.success(emojis.check)} ${colors.primary.bold(comp.label)} ${colors.muted(comp.description.split('\\n')[0])}${tag}`);\n }\n console.log();\n const sourceTag = (k: keyof typeof cfg.source) => {\n const s = cfg.source[k];\n return s && s !== 'flag' && s !== 'prompt' ? colors.muted(` (${s})`) : '';\n };\n printInfo(\n `Domain: ${colors.info(domain)}${sourceTag('domain')}` +\n ` SSL: ${colors.info(cfg.ssl ? 'Let\\'s Encrypt' : 'off (proxy or HTTP)')}${sourceTag('ssl')}` +\n (email ? ` TLS email: ${colors.info(email)}${sourceTag('email')}` : ''),\n );\n console.log();\n }\n\n if (opts.dryRun) {\n if (jsonMode) {\n outputJson({ ok: true, components: installList });\n }\n return;\n }\n\n // -----------------------------------------------------------------\n // 6. Execute installations — best-effort. A failed step doesn't stop\n // the run; we collect failures, mark affected components as\n // not-installed, and surface everything in the recap with hints.\n // -----------------------------------------------------------------\n const steps = buildInstallSteps(installList, opts);\n const skippedComponents = new Set<string>();\n const failedComponents = new Set<string>();\n const failures: InstallFailure[] = [];\n\n for (const step of steps) {\n if (jsonMode) {\n console.error(`[install] ${step.label}`);\n }\n const spinner = createSpinner(step.label);\n spinner.start();\n try {\n await step.fn();\n if (step.skips?.length) {\n spinner.warn(`${step.label} — skipped (no repo found)`);\n step.skips.forEach(c => skippedComponents.add(c));\n } else {\n spinner.succeed(step.label);\n }\n } catch (err) {\n spinner.fail(step.label);\n const error = err instanceof Error ? err : new Error(String(err));\n const componentIds = step.componentIds ?? [];\n const hint = detectInstallHint(error);\n componentIds.forEach((c) => failedComponents.add(c));\n failures.push({ label: step.label, componentIds, error, hint });\n\n // Print failure detail INLINE so the operator sees what broke\n // immediately — not buried in the recap 5 steps later. The recap\n // still shows the consolidated list at the end.\n if (!jsonMode) {\n const firstLine = error.message.split('\\n')[0] ?? '(no error message)';\n printError(` ${firstLine}`);\n if (hint) {\n for (const line of hint.split('\\n')) {\n console.log(` ${colors.warning(line)}`);\n }\n }\n console.log(colors.muted(` Continuing with the next step…`));\n console.log();\n }\n }\n }\n\n // -----------------------------------------------------------------\n // 7. Update entity state & setup profile\n // -----------------------------------------------------------------\n const installedComponents = installList.filter(\n (c) => !skippedComponents.has(c) && !failedComponents.has(c),\n );\n await updateEntityStateFromComponents(installedComponents, opts);\n\n // -----------------------------------------------------------------\n // 7b. (removed) Domain prompt has moved to upfront resolution via\n // gatherInstallConfig — no post-install domain prompt needed.\n // -----------------------------------------------------------------\n\n // -----------------------------------------------------------------\n // 7c. Optional: AI provider setup (interactive only)\n // -----------------------------------------------------------------\n if (!jsonMode && !opts.skipInteractive) {\n await maybeOfferAiProviderSetup(installedComponents);\n }\n\n // -----------------------------------------------------------------\n // 7d. Auto-provision Synap agent keys (best-effort, always-on)\n // -----------------------------------------------------------------\n if (!jsonMode && installedComponents.includes('synap')) {\n await runPostInstallProvision(installedComponents);\n }\n\n // -----------------------------------------------------------------\n // 8. Final recap — context-aware. Always shown so failures are\n // surfaced alongside what did succeed.\n // -----------------------------------------------------------------\n if (!jsonMode) {\n await printInstallationRecap(installedComponents, failures);\n } else {\n outputJson({\n ok: failures.length === 0,\n components: installList,\n installed: installedComponents,\n failed: failures.map((f) => ({\n label: f.label,\n components: f.componentIds,\n error: f.error.message,\n hint: f.hint,\n })),\n });\n }\n\n // Exit non-zero on any failure so CI / scripted callers see the signal.\n // The recap above already explained what broke + what to try next.\n if (failures.length > 0) {\n process.exitCode = 1;\n }\n}\n\n/**\n * After install: try to reach the backend and mint agent keys automatically.\n *\n * Three outcomes:\n * 1. Success → agent keys are ready, operators can use Eve immediately.\n * 2. Admin needed → print the setup URL and the command to run next.\n * 3. Backend not ready → print actionable command with no blocking wait.\n *\n * Never throws — install should never fail at this step.\n */\nasync function runPostInstallProvision(installedComponents: string[]): Promise<void> {\n console.log();\n const spinner = createSpinner('Connecting Eve agents to Synap…');\n spinner.start();\n\n let synapUrl: string;\n let provisioningToken: string;\n try {\n const preflight = await runBackendPreflight({ cwd: process.cwd() });\n synapUrl = preflight.synapUrl;\n provisioningToken = preflight.provisioningToken;\n } catch (err) {\n spinner.warn('Backend not reachable yet (still starting up)');\n console.log();\n printInfo('Once it\\'s up, run:');\n console.log(` ${colors.info('eve auth provision')}`);\n printInfo('This will create your first admin account and mint agent API keys.');\n return;\n }\n\n const adminStatus = await probeAdminStatus();\n if (adminStatus === 'needed') {\n spinner.warn('Backend is up — first admin account required');\n const secrets = await readEveSecrets(process.cwd());\n const domain = secrets?.domain?.primary;\n const ssl = secrets?.domain?.ssl !== false;\n const protocol = ssl ? 'https' : 'http';\n const setupUrl = domain ? `${protocol}://pod.${domain}/setup` : `${synapUrl}/setup`;\n console.log();\n printInfo('1. Create your admin account at:');\n console.log(` ${colors.primary.bold(setupUrl)}`);\n console.log();\n printInfo('2. Then run:');\n console.log(` ${colors.info('eve auth provision')}`);\n printInfo(' This mints API keys so Eve\\'s services can talk to Synap.');\n return;\n }\n\n const results = await provisionAllAgents({\n installedComponentIds: installedComponents,\n deployDir: process.cwd(),\n reason: 'post-install',\n synapUrl,\n provisioningToken,\n skipIfPresent: true,\n });\n\n const ok = results.filter(r => r.provisioned);\n const failed = results.filter(r => !r.provisioned);\n\n if (failed.length === 0) {\n spinner.succeed(`Agent keys ready (${ok.length} agent${ok.length === 1 ? '' : 's'} provisioned)`);\n } else if (ok.length > 0) {\n spinner.warn(`${ok.length} agent${ok.length === 1 ? '' : 's'} provisioned, ${failed.length} failed`);\n for (const f of failed) {\n printWarning(` ${f.agentType}: ${f.reason.split('\\n')[0]}`);\n }\n console.log();\n printInfo(`Retry with: ${colors.info('eve auth provision')}`);\n } else {\n spinner.warn('Agent provisioning failed');\n const topReason = results[0]?.provisioned === false ? results[0].reason : '';\n if (topReason.includes('404') || topReason.includes('backend version')) {\n console.log();\n printInfo('Backend image is outdated. Run:');\n console.log(` ${colors.info('eve update synap && eve auth provision')}`);\n } else {\n console.log();\n printInfo(`Reason: ${topReason.split('\\n')[0] || 'unknown'}`);\n printInfo(`Retry with: ${colors.info('eve auth provision')}`);\n }\n }\n}\n\n/**\n * Final summary at the end of `eve install`. Tells the user clearly:\n * - What was installed (with health if available)\n * - What FAILED, with operator-actionable hints\n * - Where to access it (domain if set, IP:port otherwise — domain preferred)\n * - The dashboard key (so they can log in)\n * - What's left to do (only what's actually missing)\n */\nasync function printInstallationRecap(\n installedComponents: string[],\n failures: InstallFailure[] = [],\n): Promise<void> {\n const secrets = await readEveSecrets(process.cwd());\n const serverIp = getServerIp();\n const domain = secrets?.domain?.primary;\n const ssl = secrets?.domain?.ssl !== false;\n const protocol = ssl ? 'https' : 'http';\n const hasAi = hasAnyProvider(secrets);\n const dashboardSecret = secrets?.dashboard?.secret;\n\n // Pick the best UI URL based on what's configured. Domain > IP > localhost.\n const uiUrl = domain\n ? `${protocol}://eve.${domain}`\n : serverIp\n ? `http://${serverIp}:7979`\n : `http://localhost:7979`;\n\n const headerColor = failures.length > 0 ? colors.warning : colors.success;\n const headerIcon = failures.length > 0 ? '⚠' : '✓';\n const headerText = failures.length > 0\n ? `Eve installation finished with ${failures.length} issue${failures.length === 1 ? '' : 's'}`\n : 'Eve installation complete';\n\n console.log();\n console.log(headerColor.bold('━'.repeat(60)));\n console.log(headerColor.bold(` ${headerIcon} ${headerText}`));\n console.log(headerColor.bold('━'.repeat(60)));\n console.log();\n\n // What was installed\n console.log(colors.primary.bold(' Installed components'));\n if (installedComponents.length === 0) {\n console.log(colors.muted(' (none — every step failed; see Issues below)'));\n }\n for (const id of installedComponents) {\n const comp = COMPONENTS.find(c => c.id === id);\n if (!comp) continue;\n const subdomainHint = domain && comp.service?.subdomain\n ? colors.muted(` → ${protocol}://${comp.service.subdomain}.${domain}`)\n : '';\n console.log(` ${colors.success('●')} ${comp.emoji} ${comp.label.padEnd(22)} ${subdomainHint}`);\n }\n\n // What failed — print each step with its hint, before the dashboard\n // section so the operator sees blockers first.\n if (failures.length > 0) {\n console.log();\n console.log(colors.warning.bold(' Issues encountered'));\n for (const f of failures) {\n const compTag = f.componentIds.length > 0\n ? colors.muted(` [${f.componentIds.join(', ')}]`)\n : '';\n console.log(` ${colors.error('✗')} ${f.label}${compTag}`);\n console.log(` ${colors.muted('error:')} ${f.error.message.split('\\n')[0]}`);\n if (f.hint) {\n for (const line of f.hint.split('\\n')) {\n console.log(` ${colors.warning(line)}`);\n }\n }\n }\n }\n\n // Open the dashboard\n console.log();\n console.log(colors.primary.bold(' Open your dashboard'));\n console.log(` ${colors.primary.bold(uiUrl)}`);\n if (dashboardSecret) {\n console.log(` ${colors.muted('Login key:')} ${colors.primary(dashboardSecret)}`);\n }\n if (!domain) {\n console.log(colors.warning(` ! No domain set — using direct IP. For HTTPS access, run: eve domain set <yourdomain> --ssl --email <you@example.com>`));\n } else if (!ssl) {\n console.log(colors.warning(` ! Domain set but SSL not enabled — re-run \"eve domain set ${domain} --ssl\" to provision certs`));\n }\n\n // Builder workspace — surfaced when `ensureBuilderWorkspace` has\n // already run (post-install or post-update hook). Silent when absent\n // so a fresh install that hasn't reached `eve auth provision` yet\n // doesn't show a misleading half-state.\n const builderWorkspaceId = secrets?.builder?.workspaceId;\n if (builderWorkspaceId) {\n console.log(` ${colors.muted('Builder workspace:')} ${colors.primary(builderWorkspaceId)}`);\n }\n\n // What's left to do — only show what's actually missing\n const todos: Array<{ label: string; cmd: string; severity: 'must' | 'recommended' }> = [];\n\n if (!domain) {\n todos.push({\n label: 'Configure a public domain so you can access the dashboard from anywhere',\n cmd: 'eve domain set <yourdomain> --ssl --email <you@example.com>',\n severity: 'recommended',\n });\n }\n if (!hasAi) {\n const aiConsumers = ['synap', 'openclaw', 'openwebui'];\n if (installedComponents.some(c => aiConsumers.includes(c))) {\n todos.push({\n label: 'Add an AI provider — OpenClaw / Open WebUI / agents are idle without one',\n cmd: 'eve ai providers add anthropic --api-key sk-ant-...',\n severity: 'must',\n });\n }\n }\n // Dashboard auto-restarts via Docker's `--restart unless-stopped` policy,\n // so no manual systemd setup is needed anymore.\n\n if (todos.length > 0) {\n console.log();\n console.log(colors.primary.bold(' Next steps'));\n for (const t of todos) {\n const dot = t.severity === 'must' ? colors.error('●') : colors.warning('●');\n console.log(` ${dot} ${t.label}`);\n console.log(` ${colors.muted('→')} ${colors.info(t.cmd)}`);\n }\n }\n\n // Quick reference\n console.log();\n console.log(colors.muted(' Quick reference'));\n console.log(colors.muted(` eve status check what's running`));\n console.log(colors.muted(` eve doctor full health diagnostic`));\n console.log(colors.muted(` eve add <component> install another component`));\n if (domain) {\n console.log(colors.muted(` eve domain check verify all routes`));\n }\n if (installedComponents.includes('synap')) {\n console.log(colors.muted(` eve auth provision mint/refresh agent keys`));\n console.log(colors.muted(` eve auth status check key health per agent`));\n }\n console.log();\n console.log(colors.success.bold('━'.repeat(60)));\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Optional post-install steps (interactive prompts)\n// ---------------------------------------------------------------------------\n\n/**\n * Offer to configure an AI provider so OpenClaw / Open WebUI / agents work\n * out of the box. Skips silently if a provider is already configured.\n *\n * The provider key is stored once in `secrets.ai.providers[]` and then\n * propagated to every installed component via `wireComponentAi()`. This is\n * the moment that turns Synap IS into the canonical AI hub.\n */\nasync function maybeOfferAiProviderSetup(installedComponents: string[]): Promise<void> {\n const existing = await readEveSecrets(process.cwd());\n if (hasAnyProvider(existing)) return; // already configured\n\n // Only worth prompting if at least one component will consume AI\n const aiConsumers = ['synap', 'openclaw', 'openwebui', 'hermes', 'opencode', 'openclaude'];\n const willUseAi = installedComponents.some(c => aiConsumers.includes(c));\n if (!willUseAi) return;\n\n console.log();\n console.log(colors.muted('Eve uses Synap IS as the central AI hub. Other components (OpenClaw,'));\n console.log(colors.muted('Open WebUI, agents) route through it — so you only set this once.'));\n console.log();\n\n const providerChoice = await select({\n message: 'Which AI provider do you want to use?',\n options: [\n { value: 'anthropic', label: 'Anthropic (Claude) — recommended', hint: 'best quality' },\n { value: 'openai', label: 'OpenAI (GPT-5/4)' },\n { value: 'openrouter', label: 'OpenRouter (multi-provider)' },\n { value: 'ollama', label: 'Ollama only (local, free)', hint: 'requires ollama component' },\n { value: 'skip', label: 'Skip — configure later with `eve ai providers add`' },\n ],\n initialValue: 'anthropic',\n });\n\n if (isCancel(providerChoice) || providerChoice === 'skip') {\n printInfo('You can configure your AI provider later with: eve ai providers add <id> --api-key <key>');\n return;\n }\n\n // Ollama-only doesn't need a key\n if (providerChoice === 'ollama') {\n await writeEveSecrets({\n ai: {\n defaultProvider: 'ollama',\n providers: [{ id: 'ollama', enabled: true }],\n },\n });\n printSuccess('Ollama set as default provider (no API key needed).');\n return;\n }\n\n // Cloud provider — get API key\n const apiKey = await text({\n message: `Paste your ${providerChoice} API key:`,\n placeholder: providerChoice === 'anthropic' ? 'sk-ant-...' : providerChoice === 'openai' ? 'sk-...' : 'sk-or-...',\n validate: (v) => v && v.trim().length > 8 ? undefined : 'API key is required',\n });\n if (isCancel(apiKey)) {\n printInfo('Skipped. Configure later with: eve ai providers add ' + providerChoice + ' --api-key <key>');\n return;\n }\n\n // Default model per provider. OpenRouter has no useful default — must ask.\n // Anthropic/OpenAI have sensible recent defaults the user can refine in the\n // dashboard later.\n const DEFAULT_MODELS: Record<string, string> = {\n anthropic: 'claude-sonnet-4-7',\n openai: 'gpt-5',\n openrouter: 'anthropic/claude-sonnet-4-7',\n };\n\n let defaultModel: string = DEFAULT_MODELS[providerChoice as string];\n if (providerChoice === 'openrouter') {\n const modelInput = await text({\n message: 'Default model on OpenRouter:',\n placeholder: 'anthropic/claude-sonnet-4-7',\n initialValue: 'anthropic/claude-sonnet-4-7',\n validate: (v) => v && v.includes('/') ? undefined : 'Use the form provider/model (e.g. anthropic/claude-sonnet-4-7)',\n });\n if (isCancel(modelInput)) {\n printInfo('Skipped — no default model set. Configure in the dashboard later.');\n return;\n }\n defaultModel = modelInput.trim();\n } else {\n // Show the default and let the user override\n const modelInput = await text({\n message: `Default model (press enter to use \"${defaultModel}\"):`,\n placeholder: defaultModel,\n initialValue: defaultModel,\n });\n if (!isCancel(modelInput) && modelInput.trim()) {\n defaultModel = modelInput.trim();\n }\n }\n\n await writeEveSecrets({\n ai: {\n defaultProvider: providerChoice as 'anthropic' | 'openai' | 'openrouter',\n providers: [{\n id: providerChoice as 'anthropic' | 'openai' | 'openrouter',\n enabled: true,\n apiKey: apiKey.trim(),\n defaultModel,\n }],\n },\n });\n printSuccess(`${providerChoice} (${defaultModel}) saved.`);\n\n // Auto-wire every installed component so they pick up the new key\n console.log();\n const spinner = createSpinner('Wiring AI provider into installed components...');\n spinner.start();\n const updated = await readEveSecrets(process.cwd());\n const [materialized] = await materializeTargets(updated, ['ai-wiring'], { components: installedComponents });\n const results = Array.isArray(materialized?.details?.results)\n ? materialized.details.results as WireAiResult[]\n : [];\n const ok = results.filter(r => r.outcome === 'ok').length;\n const failed = results.filter(r => r.outcome === 'failed');\n\n if (failed.length === 0) {\n spinner.succeed(`AI wiring applied to ${ok} component(s)`);\n } else {\n spinner.warn(`AI wiring partially applied (${ok} ok, ${failed.length} failed)`);\n for (const r of failed) {\n printWarning(` • ${r.id}: ${r.summary}${r.detail ? ' — ' + r.detail : ''}`);\n }\n }\n\n // Point the user at the dashboard for richer config\n console.log();\n printInfo('Configure model, fallback provider, and multiple providers in the dashboard:');\n printInfo(' eve ui → open the dashboard, navigate to \"AI Providers\"');\n}\n\n// ---------------------------------------------------------------------------\n// Step builder\n// ---------------------------------------------------------------------------\n\ninterface InstallStep {\n label: string;\n /** Components to mark as skipped (not installed) rather than ready */\n skips?: string[];\n /** Components this step installs — used to mark them as failed if `fn` throws. */\n componentIds?: string[];\n fn: () => Promise<void>;\n}\n\ninterface InstallFailure {\n label: string;\n componentIds: string[];\n error: Error;\n /** Operator-actionable hint inferred from the error pattern. */\n hint?: string;\n}\n\n/**\n * Inspect an install error message and emit an operator-actionable hint.\n * Best-effort string match — returns undefined when nothing recognized.\n */\nfunction detectInstallHint(err: Error): string | undefined {\n const msg = err.message ?? \"\";\n\n // Port collision. Most common when Eve's Traefik is already on 80/443\n // and Synap's Caddy tries to claim them too — two reverse proxies can't\n // share ports. RSSHub on 1200 hits the same problem when an earlier\n // attempt already started it.\n const portMatch = msg.match(/Bind for [0-9.:]*:(\\d+) failed: port is already allocated/);\n if (portMatch) {\n const port = portMatch[1];\n const isWebPort = port === \"80\" || port === \"443\";\n if (isWebPort) {\n return [\n `Port ${port} is already bound on this host (likely by Eve's Traefik).`,\n ` → If Eve and Synap share the host, route Synap behind Traefik instead of letting Caddy claim ${port}.`,\n ` → Quick check: \\`docker ps --format '{{.Names}}\\\\t{{.Ports}}' | grep ':${port}'\\``,\n ` → Stop the conflicting service, then re-run \\`eve update synap\\`.`,\n ].join(\"\\n\");\n }\n if (port === \"1200\") {\n return [\n `Port 1200 is already bound — RSSHub from a previous run is still up.`,\n ` → \\`docker ps | grep rsshub\\` to identify the existing container.`,\n ` → \\`docker rm -f synap-backend-rsshub\\` then re-run \\`eve update synap\\`.`,\n ].join(\"\\n\");\n }\n return `Port ${port} is already bound — check \\`sudo lsof -iTCP:${port} -sTCP:LISTEN\\`.`;\n }\n\n if (/permission denied|EACCES/i.test(msg)) {\n return \"Permission denied — try `sudo` or check file ownership.\";\n }\n if (/no space left|ENOSPC/i.test(msg)) {\n return \"Disk full — free space (try `docker system prune -a`) and re-run.\";\n }\n if (/network .* not found|driver failed programming/i.test(msg)) {\n return \"Docker network issue — check `docker network ls` and `eve doctor`.\";\n }\n if (/synap install exited \\d+/.test(msg)) {\n return \"synap CLI failed — see logs above. Re-run with `eve update synap` after fixing the underlying issue.\";\n }\n return undefined;\n}\n\nfunction buildInstallSteps(\n components: string[],\n opts: InstallOptions,\n): InstallStep[] {\n const steps: InstallStep[] = [];\n\n const hasSynap = components.includes('synap');\n const hasOllama = components.includes('ollama');\n const hasTraefik = components.includes('traefik');\n const hasOpenclaw = components.includes('openclaw');\n const hasRsshub = components.includes('rsshub');\n const hasHermes = components.includes('hermes');\n const hasDokploy = components.includes('dokploy');\n const hasOpenCode = components.includes('opencode');\n const hasOpenClaude = components.includes('openclaude');\n const hasBuilder = hasHermes || hasDokploy || hasOpenCode || hasOpenClaude;\n const hasTunnel = opts.tunnel;\n\n // 1. Traefik\n if (hasTraefik) {\n steps.push({\n label: 'Setting up Traefik routing...',\n componentIds: ['traefik'],\n async fn() {\n const domain = opts.domain || 'localhost';\n await runLegsProxySetup({\n domain: hasSynap ? domain : undefined,\n tunnel: opts.tunnel,\n tunnelDomain: opts.tunnelDomain,\n ssl: hasSynap && domain !== 'localhost',\n standalone: true,\n });\n },\n });\n }\n\n // 2. Synap\n if (hasSynap) {\n const synapRepo = opts.synapRepo || process.env.SYNAP_REPO_ROOT;\n const delegate = resolveSynapDelegate();\n const resolvedRepo = synapRepo || delegate?.repoRoot;\n\n if (resolvedRepo) {\n steps.push({\n label: 'Installing Synap Data Pod...',\n componentIds: ['synap'],\n async fn() {\n await runBrainInit({\n synapRepo: resolvedRepo,\n domain: opts.domain,\n email: opts.email,\n adminBootstrapMode: opts.adminBootstrapMode || 'token',\n adminEmail: opts.adminEmail,\n adminPassword: opts.adminPassword,\n fromImage: opts.fromImage,\n fromSource: opts.fromSource,\n withOpenclaw: false,\n withRsshub: opts.withRsshub || hasRsshub,\n withAi: false,\n });\n },\n });\n } else {\n // No synap repo — install from Docker image automatically\n steps.push({\n label: 'Installing Synap Data Pod (from Docker image)...',\n componentIds: ['synap'],\n async fn() {\n await runBrainInit({\n domain: opts.domain,\n email: opts.email,\n adminBootstrapMode: opts.adminBootstrapMode || 'token',\n adminEmail: opts.adminEmail,\n adminPassword: opts.adminPassword,\n });\n },\n });\n }\n }\n\n // 3. Ollama\n if (hasOllama) {\n steps.push({\n label: 'Setting up Ollama + AI gateway...',\n componentIds: ['ollama'],\n async fn() {\n await runInferenceInit({\n model: opts.model || 'llama3.1:8b',\n withGateway: true,\n internalOllamaOnly: hasSynap,\n });\n },\n });\n }\n\n // 4. OpenClaw (Docker lifecycle + synap-cli wiring when available)\n if (hasOpenclaw) {\n steps.push({\n label: 'Setting up OpenClaw...',\n componentIds: ['openclaw'],\n async fn() {\n const { OpenClawService } = await import('@eve/arms');\n\n const ollamaUrl = 'http://127.0.0.1:11434';\n const openclaw = new OpenClawService();\n\n // Pull and start OpenClaw container\n await openclaw.install();\n await openclaw.configure(ollamaUrl);\n await openclaw.start();\n\n // If we have a synap-backend checkout AND synap was installed,\n // delegate wiring to synap-cli (skill install, entity seed, IS config)\n const synapPod = resolveSynapDelegate();\n if (synapPod && hasSynap) {\n console.log(' Delegating Synap↔OpenClaw wiring to synap-cli...');\n try {\n // Check if pod-config exists (from prior init/connect)\n const { homedir } = await import('node:os');\n const { existsSync } = await import('node:fs');\n const podConfigPath = join(homedir(), '.synap', 'pod-config.json');\n if (existsSync(podConfigPath)) {\n await spawnAsync('npx', ['-p', '@synap-core/cli', 'synap', 'finish', '--skip-ai-key', '--skip-domain'], {\n env: { ...process.env, SYNAP_DEPLOY_DIR: synapPod.deployDir },\n cwd: synapPod.repoRoot,\n });\n } else {\n console.log(' No pod-config found — skipping synap-cli finish.');\n console.log(' Run \"synap connect --target=openclaw\" then \"synap finish\" manually for full wiring.');\n }\n } catch (err) {\n console.log(` synap-cli finish warning: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n },\n });\n }\n\n // 5. RSSHub\n if (hasRsshub) {\n steps.push({\n label: 'Setting up RSSHub...',\n componentIds: ['rsshub'],\n async fn() {\n const rsshub = new RSSHubService();\n await rsshub.install();\n await rsshub.start();\n },\n });\n }\n\n // 6. Hermes daemon\n if (hasHermes) {\n steps.push({\n label: 'Setting up Hermes daemon...',\n componentIds: ['hermes'],\n async fn() {\n await materializeTargets(null, ['hermes-env']);\n // Container is managed by the Eve compose stack — no extra start needed;\n // the env file written above is picked up on next docker compose up.\n console.log(' Hermes env file written to .eve/hermes.env');\n console.log(' Start with: docker compose up -d hermes');\n },\n });\n }\n\n // 7. Eve Dashboard (always-installed UI). Builds the local Docker image\n // from packages/eve-dashboard/Dockerfile and runs it on eve-network so\n // Traefik can route eve.<domain> to it by container name.\n if (components.includes('eve-dashboard')) {\n steps.push({\n label: 'Building & starting Eve Dashboard...',\n componentIds: ['eve-dashboard'],\n async fn() {\n const { randomBytes } = await import('node:crypto');\n const { readEveSecrets, writeEveSecrets } = await import('@eve/dna');\n const { installDashboardContainer } = await import('@eve/legs');\n\n const secrets = await readEveSecrets(process.cwd());\n let secret = secrets?.dashboard?.secret;\n if (!secret) {\n secret = randomBytes(32).toString('hex');\n await writeEveSecrets({ dashboard: { secret, port: 7979 } });\n console.log();\n console.log(colors.primary.bold('Dashboard key generated — save this somewhere safe:'));\n console.log(colors.muted('─'.repeat(66)));\n console.log(colors.primary.bold(secret));\n console.log(colors.muted('─'.repeat(66)));\n }\n installDashboardContainer({\n workspaceRoot: process.cwd(),\n secret,\n });\n },\n });\n }\n\n // 8. Nango\n const hasNango = components.includes('nango');\n if (hasNango) {\n steps.push({\n label: 'Setting up Nango OAuth platform...',\n componentIds: ['nango'],\n async fn() {\n const { runAdd } = await import('../add.js');\n await runAdd('nango', {});\n },\n });\n }\n\n // 9. Claude Code CLI\n const hasClaudeCode = components.includes('claude-code');\n if (hasClaudeCode) {\n steps.push({\n label: 'Installing Claude Code CLI...',\n componentIds: ['claude-code'],\n async fn() {\n const { execSync } = await import('node:child_process');\n execSync('npm install -g @anthropic-ai/claude-code', { stdio: 'inherit' });\n },\n });\n }\n\n // 10. Open WebUI\n const hasOpenWebUI = components.includes('openwebui');\n if (hasOpenWebUI) {\n steps.push({\n label: 'Setting up Open WebUI...',\n componentIds: ['openwebui'],\n async fn() {\n const { mkdirSync, writeFileSync, existsSync } = await import('node:fs');\n const { join: pathJoin } = await import('node:path');\n const { readEveSecrets } = await import('@eve/dna');\n const { randomBytes } = await import('node:crypto');\n\n const deployDir = '/opt/openwebui';\n mkdirSync(deployDir, { recursive: true });\n\n const secrets = await readEveSecrets(process.cwd());\n const synapApiKey = secrets?.synap?.apiKey ?? process.env.SYNAP_API_KEY ?? '';\n const isUrl = process.env.SYNAP_IS_URL ?? 'http://intelligence-hub:3001';\n\n const envPath = pathJoin(deployDir, '.env');\n if (!existsSync(envPath)) {\n writeFileSync(envPath, [\n '# Open WebUI — generated by Eve CLI',\n `SYNAP_API_KEY=${synapApiKey}`,\n `SYNAP_IS_URL=${isUrl}`,\n `WEBUI_SECRET_KEY=${randomBytes(32).toString('hex')}`,\n `ENABLE_SIGNUP=true`,\n `DEFAULT_USER_ROLE=user`,\n ].join('\\n'), { mode: 0o600 });\n }\n console.log(` Open WebUI config written to ${deployDir}`);\n console.log(' Start with: docker compose --profile openwebui up -d');\n },\n });\n }\n\n return steps;\n}\n\n// ---------------------------------------------------------------------------\n// Entity state\n// ---------------------------------------------------------------------------\n\nasync function updateEntityStateFromComponents(\n components: string[],\n opts: InstallOptions,\n): Promise<void> {\n const organMap: Record<string, 'brain' | 'arms' | 'builder' | 'eyes' | 'legs'> = {\n synap: 'brain',\n ollama: 'brain',\n openclaw: 'arms',\n nango: 'arms',\n hermes: 'arms',\n rsshub: 'eyes',\n traefik: 'legs',\n dokploy: 'builder',\n opencode: 'builder',\n openclaude: 'builder',\n 'claude-code': 'builder',\n };\n\n for (const compId of components) {\n const organ = organMap[compId];\n if (organ) {\n await entityStateManager.updateOrgan(organ, 'ready', { version: '0.1.0' });\n }\n await entityStateManager.updateComponentEntry(compId, {\n state: 'ready',\n version: '0.1.0',\n managedBy: 'eve',\n });\n }\n\n // Update setup profile v2\n await entityStateManager.updateSetupProfile({ components });\n}\n\n// ---------------------------------------------------------------------------\n// Interactive wizard\n// ---------------------------------------------------------------------------\n\n// Preset bundles surfaced in the wizard\nconst PRESETS = [\n {\n value: 'personal',\n label: '🧠 Personal AI pod',\n hint: 'Synap + Traefik',\n ids: ['traefik', 'synap'],\n },\n {\n value: 'full',\n label: '🚀 Full stack',\n hint: 'Synap + Ollama + OpenClaw + Traefik',\n ids: ['traefik', 'synap', 'ollama', 'openclaw'],\n },\n {\n value: 'chat',\n label: '💬 AI chat server',\n hint: 'Synap + Open WebUI + Traefik',\n ids: ['traefik', 'synap', 'openwebui'],\n },\n {\n value: 'builder',\n label: '🏗️ Builder server',\n hint: 'Synap + Hermes + OpenClaw + Traefik',\n ids: ['traefik', 'synap', 'openclaw', 'hermes'],\n },\n {\n value: 'minimal',\n label: '⚡ Minimal',\n hint: 'Traefik only — add components later',\n ids: ['traefik'],\n },\n {\n value: 'custom',\n label: '🔧 Custom',\n hint: 'Pick each component individually',\n ids: [],\n },\n] as const;\n\nasync function interactiveComponentSelect(): Promise<Record<string, boolean>> {\n intro(colors.primary.bold('Eve — Composable Installer'));\n\n // Step 1: pick a preset\n const preset = await select({\n message: 'What do you want to set up?',\n options: PRESETS as unknown as { value: string; label: string; hint: string }[],\n initialValue: 'full',\n });\n\n if (isCancel(preset)) return {};\n\n // Step 2: for custom or to adjust preset, show multiselect\n const selectableComponents = COMPONENTS.filter(c => !c.alwaysInstall);\n let presetIds: string[] = preset === 'custom'\n ? selectableComponents.filter(c => c.category !== 'add-on').map(c => c.id)\n : (PRESETS.find(p => p.value === preset)?.ids.filter(id => id !== 'traefik') ?? []);\n\n // Minimal preset skips the multiselect — just Traefik, no further selection needed.\n // All other presets offer a multiselect to confirm or adjust the component set.\n let finalIds: string[] | symbol = [];\n if (preset !== 'minimal') {\n finalIds = await multiselect({\n message: preset === 'custom' ? 'Select components:' : 'Adjust selection (space to toggle):',\n options: selectableComponents.map(c => ({\n value: c.id,\n label: `${c.emoji} ${c.label}`,\n hint: c.description.split('.')[0],\n })),\n initialValues: presetIds,\n required: false,\n });\n }\n\n if (isCancel(finalIds)) return {};\n\n // Build result — traefik always on\n const result: Record<string, boolean> = { traefik: true };\n for (const id of (finalIds as string[])) {\n result[id] = true;\n }\n\n // Validate requires\n const missing: string[] = [];\n for (const id of Object.keys(result)) {\n const comp = COMPONENTS.find(c => c.id === id);\n for (const req of comp?.requires ?? []) {\n if (!result[req]) missing.push(`${comp!.label} requires ${req}`);\n }\n }\n if (missing.length) {\n note(missing.join('\\n'), 'Dependency note — adding missing requirements');\n for (const id of Object.keys(result)) {\n const comp = COMPONENTS.find(c => c.id === id);\n for (const req of comp?.requires ?? []) result[req] = true;\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Legacy profile inference\n// ---------------------------------------------------------------------------\n\nfunction inferLegacyProfile(components: string[]): SetupProfileKind {\n const set = new Set(components);\n const hasSynap = set.has('synap');\n const hasOllama = set.has('ollama');\n const hasBuilder = ['hermes', 'openclaw'].some(c => set.has(c));\n\n if (!hasSynap && hasOllama) return 'inference_only';\n if (hasSynap && hasOllama && hasBuilder) return 'full';\n if (hasSynap) return 'data_pod';\n return 'data_pod';\n}\n\n// ---------------------------------------------------------------------------\n// Command\n// ---------------------------------------------------------------------------\n\nexport function installCommand(program: Command): void {\n program\n .command('install')\n .alias('i')\n .description('Composable component installer — pick what you need')\n .option(\n '--components <list>',\n 'Comma-separated component IDs (traefik,synap,ollama,openclaw,hermes,rsshub,openwebui,dokploy,opencode,openclaude)',\n )\n .option('--domain <host>', 'Public hostname (default: localhost)', 'localhost')\n .option('--email <email>', \"Let's Encrypt email for TLS\")\n .option('--model <model>', 'Ollama model', 'llama3.1:8b')\n .option('--admin-email <email>', 'Admin bootstrap email for Synap')\n .option('--admin-password <secret>', 'Admin password for preseed bootstrap')\n .option('--admin-bootstrap-mode <mode>', 'Token | preseed (default: token)')\n .option('--tunnel <provider>', 'Tunnel provider: pangolin | cloudflare')\n .option('--tunnel-domain <host>', 'Tunnel hostname')\n .option('--ai-mode <m>', 'AI inference mode: local | provider | hybrid')\n .option('--ai-provider <p>', 'Default AI provider: openrouter | anthropic | openai | ollama')\n .option('--fallback-provider <p>', 'Fallback AI provider')\n .option('--synap-repo <path>', 'Path to synap-backend checkout')\n .option('--with-openclaw', 'Enable OpenClaw (legacy flag)')\n .option('--with-rsshub', 'Enable RSSHub (legacy flag)')\n .option('--from-image', 'Install Synap from prebuilt image')\n .option('--from-source', 'Install Synap from source')\n .option('--dry-run', 'Print planned steps without executing')\n .option('--skip-hardware', 'Skip hardware summary')\n .addHelpText(\n 'after',\n `\\nComponents\\n` +\n ` ${colors.muted('Infrastructure')} traefik (always)\\n` +\n ` ${colors.muted('Data')} synap, ollama\\n` +\n ` ${colors.muted('Agent')} openclaw\\n` +\n ` ${colors.muted('Builder')} hermes, dokploy, opencode, openclaude\\n` +\n ` ${colors.muted('Perception')} rsshub\\n\\n` +\n `Run \"eve add <component>\" to add components later.\\n` +\n `Run \"eve status\" to see current state.\\n`,\n )\n .action(async (rawOpts: {\n components?: string;\n domain?: string;\n email?: string;\n model?: string;\n adminEmail?: string;\n adminPassword?: string;\n adminBootstrapMode?: 'preseed' | 'token';\n tunnel?: string;\n tunnelDomain?: string;\n aiMode?: string;\n aiProvider?: string;\n fallbackProvider?: string;\n synapRepo?: string;\n withOpenclaw?: boolean;\n withRsshub?: boolean;\n fromImage?: boolean;\n fromSource?: boolean;\n dryRun?: boolean;\n skipHardware?: boolean;\n }) => {\n // Resolve environment\n if (rawOpts.synapRepo) {\n process.env.SYNAP_REPO_ROOT = rawOpts.synapRepo;\n }\n\n // Parse tunnel\n let tunnelProvider: 'pangolin' | 'cloudflare' | undefined;\n if (rawOpts.tunnel) {\n const t = rawOpts.tunnel.toLowerCase();\n if (t === 'pangolin') tunnelProvider = 'pangolin';\n else if (t === 'cloudflare' || t === 'cf') tunnelProvider = 'cloudflare';\n else {\n printError(`Unknown tunnel provider: ${rawOpts.tunnel} (use pangolin or cloudflare)`);\n process.exit(1);\n }\n }\n\n // Parse AI mode\n let aiMode: 'local' | 'provider' | 'hybrid' | undefined;\n if (rawOpts.aiMode) {\n const m = rawOpts.aiMode.toLowerCase();\n if (['local', 'provider', 'hybrid'].includes(m)) aiMode = m as any;\n }\n\n // Parse AI provider\n let aiProvider: 'ollama' | 'openrouter' | 'anthropic' | 'openai' | undefined;\n if (rawOpts.aiProvider) {\n const p = rawOpts.aiProvider.toLowerCase();\n if (['ollama', 'openrouter', 'anthropic', 'openai'].includes(p)) aiProvider = p as any;\n }\n\n let fallbackProvider: 'ollama' | 'openrouter' | 'anthropic' | 'openai' | undefined;\n if (rawOpts.fallbackProvider) {\n const p = rawOpts.fallbackProvider.toLowerCase();\n if (['ollama', 'openrouter', 'anthropic', 'openai'].includes(p)) fallbackProvider = p as any;\n }\n\n // Parse components\n let components: string[] | undefined;\n if (rawOpts.components) {\n components = rawOpts.components.split(',').map(s => s.trim()).filter(Boolean);\n }\n\n await runInstall({\n components,\n domain: rawOpts.domain,\n email: rawOpts.email,\n model: rawOpts.model,\n adminEmail: rawOpts.adminEmail,\n adminPassword: rawOpts.adminPassword,\n adminBootstrapMode: rawOpts.adminBootstrapMode,\n tunnel: tunnelProvider,\n tunnelDomain: rawOpts.tunnelDomain,\n aiMode,\n aiProvider,\n fallbackProvider,\n withOpenclaw: rawOpts.withOpenclaw,\n withRsshub: rawOpts.withRsshub,\n fromImage: rawOpts.fromImage,\n fromSource: rawOpts.fromSource,\n dryRun: rawOpts.dryRun,\n });\n });\n}\n\n// ---------------------------------------------------------------------------\n// Minimal execa re-export for use outside organ packages\n// ---------------------------------------------------------------------------\n\nfunction execa(cmd: string, args: string[], opts?: Record<string, unknown>): Promise<{ stdout: string }> {\n return import('execa').then(mod => mod.execa(cmd, args, { ...(opts || {}), shell: true }));\n}\n\nfunction spawnAsync(\n cmd: string,\n args: string[],\n opts?: { env?: Record<string, string>; cwd?: string },\n): Promise<void> {\n return import('execa').then(({ execa: execaFn }) =>\n execaFn(cmd, args, {\n env: { ...process.env, ...(opts?.env || {}) },\n cwd: opts?.cwd,\n stdio: 'inherit',\n }).then(() => undefined)\n );\n}\n","/**\n * `eve setup admin` — create the first human admin on a fresh Synap pod.\n *\n * Delegates to the canonical synap CLI's `synap setup admin` subcommand.\n * Three modes:\n * 1. --terminal (default if interactive): prompt for email + password,\n * then `synap setup admin --email e --password p` (preseed via\n * container exec).\n * 2. --magic-link: `synap setup admin --email e --magic-link` mints\n * a one-hour browser URL, eve polls `synap setup admin --status`\n * until the operator finishes in their browser.\n * 3. --password (fully scripted): `synap setup admin --email e --password p`.\n */\n\nimport * as readline from 'node:readline';\nimport { Command } from 'commander';\nimport { runSynapCli } from '@eve/brain';\nimport { readEveSecrets, resolveSynapUrlOnHost } from '@eve/dna';\nimport { resolveProvisioningToken } from '@eve/lifecycle';\nimport {\n colors,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n createSpinner,\n} from '../lib/ui.js';\n\n// ---------------------------------------------------------------------------\n// Prompt helpers\n// ---------------------------------------------------------------------------\n\nfunction prompt(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: true,\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\n/**\n * Prompt for a password. Input is hidden (no echo). Falls back to visible\n * input if the terminal doesn't support raw mode.\n */\nfunction promptPassword(question: string): Promise<string> {\n return new Promise((resolve) => {\n // Use readline with a muted output stream so keypresses aren't echoed.\n // The `*` masking trick requires raw mode which isn't always available\n // (e.g. piped stdin). We detect that and fall back gracefully.\n if (!process.stdin.isTTY) {\n // Non-interactive — read as plain text\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n });\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n return;\n }\n\n process.stdout.write(question);\n const chars: string[] = [];\n\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.setEncoding('utf-8');\n\n function onData(data: string) {\n const ch = data as string;\n if (ch === '\\r' || ch === '\\n') {\n process.stdin.setRawMode(false);\n process.stdin.pause();\n process.stdin.removeListener('data', onData);\n process.stdout.write('\\n');\n resolve(chars.join(''));\n } else if (ch === '\u0003') {\n // Ctrl-C\n process.stdin.setRawMode(false);\n process.stdin.pause();\n process.stdin.removeListener('data', onData);\n process.stdout.write('\\n');\n process.exit(1);\n } else if (ch === '' || ch === '\\b') {\n // Backspace\n if (chars.length > 0) {\n chars.pop();\n process.stdout.write('\\b \\b');\n }\n } else {\n chars.push(ch);\n process.stdout.write('*');\n }\n }\n\n process.stdin.on('data', onData);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Pod transport\n// ---------------------------------------------------------------------------\n//\n// Status probe and magic-link mint are HTTP calls — same path\n// `eve auth provision` uses. URL resolved via `resolveSynapUrlOnHost(secrets)`\n// (loopback :14000 first, public domain fallback). Auth token is the pod's\n// PROVISIONING_TOKEN — what the backend's `/api/hub/setup/magic-link` route\n// validates against. Preseed (`--password` mode) still delegates to the bash\n// CLI because it needs `docker compose exec` against the backend container.\n\ninterface PodTransport {\n podUrl: string;\n token?: string;\n}\n\nasync function resolvePodTransport(): Promise<PodTransport | { error: string }> {\n const cwd = process.env.EVE_HOME ?? process.cwd();\n const secrets = await readEveSecrets(cwd);\n const podUrl = (await resolveSynapUrlOnHost(secrets)).trim();\n if (!podUrl) {\n return {\n error: secrets\n ? 'synap pod URL unresolved — set domain.primary or synap.apiUrl in ~/.eve/secrets.json'\n : '~/.eve/secrets.json not found — run `eve install synap` first',\n };\n }\n const token = (await resolveProvisioningToken())?.trim() || undefined;\n return { podUrl, token };\n}\n\n/**\n * GET `${podUrl}/api/hub/setup/status` → `{ needsSetup: boolean }`.\n * Returns 'unknown' for any network error or unparseable response.\n */\nexport async function probeAdminStatus(): Promise<'needed' | 'ready' | 'unknown'> {\n const t = await resolvePodTransport();\n if ('error' in t) return 'unknown';\n try {\n const headers: Record<string, string> = { Accept: 'application/json' };\n if (t.token) headers.Authorization = `Bearer ${t.token}`;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), 6000);\n const res = await fetch(`${t.podUrl}/api/hub/setup/status`, { headers, signal: ctrl.signal });\n clearTimeout(timer);\n if (!res.ok) return 'unknown';\n const body = await res.json() as { needsSetup?: boolean };\n if (body.needsSetup === true) return 'needed';\n if (body.needsSetup === false) return 'ready';\n return 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\nasync function runPreseed(email: string, password: string): Promise<boolean> {\n // Preseed runs `docker compose exec backend node setup-admin.js …`. Stays\n // inside the bash CLI because it needs container access, not HTTP.\n const result = runSynapCli('setup', ['admin', '--email', email, '--password', password]);\n return result.ok;\n}\n\nasync function runMagicLinkMint(): Promise<string | null> {\n const t = await resolvePodTransport();\n if ('error' in t) {\n printWarning(t.error);\n return null;\n }\n if (!t.token) {\n printWarning('PROVISIONING_TOKEN not found — check synap deploy/.env or run `eve install synap`.');\n return null;\n }\n try {\n const res = await fetch(`${t.podUrl}/api/hub/setup/magic-link`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${t.token}`,\n },\n });\n if (res.status === 409) {\n printWarning('Pod already has an admin (409).');\n return null;\n }\n if (!res.ok) {\n const detail = await res.text().catch(() => '');\n printWarning(`Pod returned ${res.status} — ${detail.slice(0, 200)}`);\n return null;\n }\n const body = await res.json() as { url?: string };\n return body.url?.trim() || null;\n } catch (err) {\n printWarning(`Failed to reach pod: ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n}\n\nasync function pollUntilReady(timeoutMs = 5 * 60 * 1000, intervalMs = 3000): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n await new Promise(r => setTimeout(r, intervalMs));\n const status = await probeAdminStatus();\n if (status === 'ready') return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Core flow\n// ---------------------------------------------------------------------------\n\ninterface SetupAdminOptions {\n email?: string;\n password?: string;\n magicLink?: boolean;\n terminal?: boolean;\n}\n\n\nasync function runSetupAdmin(opts: SetupAdminOptions): Promise<void> {\n console.log();\n printHeader('Synap — First Admin Setup');\n console.log();\n\n // Single source of truth for \"is admin needed\" — the synap CLI probe.\n const spinner = createSpinner('Checking pod status…');\n spinner.start();\n const status = await probeAdminStatus();\n if (status === 'unknown') {\n spinner.fail('Could not reach the synap pod. Is it installed and running?');\n printInfo(' Try: eve status, eve doctor, or eve install synap.');\n process.exitCode = 1;\n return;\n }\n if (status === 'ready') {\n spinner.succeed('Pod already has an admin account.');\n printInfo(' Nothing to do — log in at your pod URL.');\n return;\n }\n spinner.succeed('Pod has no admin yet — proceeding.');\n console.log();\n\n // Resolve mode from flags. Precedence: --magic-link > --password > --terminal\n // > interactive picker (TTY) > magic-link (non-TTY default).\n let mode: 'terminal' | 'magic-link';\n if (opts.magicLink) {\n mode = 'magic-link';\n } else if (opts.password || opts.terminal) {\n mode = 'terminal';\n } else if (!process.stdin.isTTY) {\n mode = 'magic-link';\n } else {\n console.log(\n `${colors.muted('How would you like to create the first admin account?')}\\n` +\n ` ${colors.primary('1')} Enter credentials here (email + password) — terminal\\n` +\n ` ${colors.primary('2')} Open magic link in browser\\n`,\n );\n const choice = await prompt('Choice [1]: ');\n mode = choice === '2' ? 'magic-link' : 'terminal';\n }\n\n if (mode === 'terminal') {\n // Preseed needs both email + password baked in.\n const email = opts.email?.trim() || (await prompt('Email: '));\n if (!email) {\n printError('Email is required.');\n process.exitCode = 1;\n return;\n }\n const password = opts.password?.trim() ?? await promptPassword('Password: ');\n if (!password) {\n printError('Password is required.');\n process.exitCode = 1;\n return;\n }\n if (!opts.password) {\n const confirm = await promptPassword('Confirm password: ');\n if (password !== confirm) {\n printError('Passwords do not match.');\n process.exitCode = 1;\n return;\n }\n }\n console.log();\n const s = createSpinner('Creating admin via synap CLI…');\n s.start();\n const ok = await runPreseed(email, password);\n if (!ok) {\n s.fail('synap setup admin failed — see preceding output.');\n process.exitCode = 1;\n return;\n }\n s.succeed('Admin account created.');\n console.log();\n printSuccess(`Admin created: ${email}`);\n return;\n }\n\n // magic-link mode — the URL is purpose-only (\"first_admin_setup\"), email\n // and password are entered in the browser at /setup?token=...\n console.log();\n printInfo('Minting one-hour setup URL…');\n const url = await runMagicLinkMint();\n if (!url) {\n printError('Could not mint magic link.');\n process.exitCode = 1;\n return;\n }\n console.log(`\\n Open this link in your browser to complete setup:\\n ${url}\\n Link expires in 1 hour.\\n`);\n const pollSpinner = createSpinner('Waiting for you to complete setup in browser…');\n pollSpinner.start();\n const ok = await pollUntilReady();\n if (!ok) {\n pollSpinner.fail('Setup timed out (5 min) or failed.');\n printWarning('Generate a new link by running `eve setup admin --magic-link` again.');\n process.exitCode = 1;\n return;\n }\n pollSpinner.succeed('Admin account created via browser setup.');\n console.log();\n printSuccess('Pod is now ready. Run `eve auth provision` to mint agent keys.');\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Command registration\n// ---------------------------------------------------------------------------\n\nexport function setupAdminCommand(setupParent: Command): void {\n setupParent\n .command('admin')\n .description('Create the first admin account on a fresh Synap pod')\n .option('--email <email>', 'Admin email (skips the interactive prompt)')\n .option('--password <secret>', 'Admin password (fully scripted — implies --terminal)')\n .option('--terminal', 'Force terminal-mode entry (default in interactive sessions)')\n .option('--magic-link', 'Generate a browser setup link instead of entering credentials here')\n .action(async (opts: SetupAdminOptions) => {\n try {\n await runSetupAdmin(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from 'commander';\nimport { setupAdminCommand } from './setup-admin.js';\nimport { select, confirm, isCancel, text } from '@clack/prompts';\nimport { homedir, tmpdir } from 'node:os';\nimport { existsSync } from 'node:fs';\nimport { readdir, rm } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n readSetupProfile,\n writeSetupProfile,\n getSetupProfilePath,\n readUsbSetupManifest,\n probeHardware,\n formatHardwareReport,\n readEveSecrets,\n writeEveSecrets,\n ensureSecretValue,\n defaultSkillsDir,\n ensureEveSkillsLayout,\n type SetupProfileKind,\n type EveSecrets,\n} from '@eve/dna';\nimport { runBrainInit, runInferenceInit } from '@eve/brain';\nimport { runLegsProxySetup } from '@eve/legs';\nimport {\n gatherInstallConfig,\n defaultPrompts,\n InstallConfigError,\n migrateSetupProfileToSecrets,\n} from '@eve/lifecycle';\nimport { getGlobalCliFlags, outputJson } from '@eve/cli-kit';\nimport { colors, emojis } from '../lib/ui.js';\nimport { cloneOrFetchTarball, ensureGitHttpFloor } from '../lib/git.js';\n\nexport interface SetupCliOptions {\n profile?: string;\n dryRun?: boolean;\n synapRepo?: string;\n domain?: string;\n email?: string;\n model?: string;\n withOpenclaw?: boolean;\n withRsshub?: boolean;\n adminEmail?: string;\n adminPassword?: string;\n adminBootstrapMode?: 'preseed' | 'token';\n fromImage?: boolean;\n fromSource?: boolean;\n skipHardware?: boolean;\n nvidiaSmi?: boolean;\n /** local | provider | hybrid */\n aiMode?: string;\n /** default provider for Eve provider routing (openrouter|anthropic|openai|ollama) */\n aiProvider?: string;\n /** optional fallback provider */\n fallbackProvider?: string;\n /** pangolin | cloudflare — Data Pod / full only */\n tunnel?: string;\n tunnelDomain?: string;\n}\n\nfunction parseProfile(s: string | undefined): SetupProfileKind | null {\n if (!s) return null;\n const v = s.trim().toLowerCase().replace(/-/g, '_');\n if (v === 'inference_only' || v === 'inferenceonly') return 'inference_only';\n if (v === 'data_pod' || v === 'datapod') return 'data_pod';\n if (v === 'full') return 'full';\n return null;\n}\n\nfunction parseTunnel(s: string | undefined): 'pangolin' | 'cloudflare' | undefined {\n if (!s) return undefined;\n const v = s.trim().toLowerCase();\n if (v === 'pangolin') return 'pangolin';\n if (v === 'cloudflare' || v === 'cf') return 'cloudflare';\n return undefined;\n}\n\nfunction parseCodeEngine(\n s: string | undefined,\n): 'opencode' | 'openclaude' | 'claudecode' | undefined {\n if (!s) return undefined;\n const v = s.trim().toLowerCase();\n if (v === 'opencode') return 'opencode';\n if (v === 'openclaude') return 'openclaude';\n if (v === 'claudecode' || v === 'claude_code' || v === 'claude-code') return 'claudecode';\n return undefined;\n}\n\nfunction parseAiMode(s: string | undefined): 'local' | 'provider' | 'hybrid' | undefined {\n if (!s) return undefined;\n const v = s.trim().toLowerCase();\n if (v === 'local' || v === 'provider' || v === 'hybrid') return v;\n return undefined;\n}\n\nfunction parseAiProvider(\n s: string | undefined,\n): 'ollama' | 'openrouter' | 'anthropic' | 'openai' | undefined {\n if (!s) return undefined;\n const v = s.trim().toLowerCase();\n if (v === 'ollama' || v === 'openrouter' || v === 'anthropic' || v === 'openai') return v;\n return undefined;\n}\n\nfunction prevAiModeFromUsb(\n usb: { target_profile: SetupProfileKind } | null,\n): 'local' | 'provider' | 'hybrid' | undefined {\n if (!usb) return undefined;\n if (usb.target_profile === 'inference_only') return 'local';\n return undefined;\n}\n\nconst SYNAP_BACKEND_REPO_URL = 'https://github.com/synap-core/backend.git';\nconst SYNAP_BACKEND_TARBALL_URL =\n 'https://codeload.github.com/synap-core/backend/tar.gz/refs/heads/main';\n\nfunction looksLikeSynapRepo(repoRoot: string): boolean {\n return (\n existsSync(join(repoRoot, 'synap')) &&\n existsSync(join(repoRoot, 'deploy', 'docker-compose.yml'))\n );\n}\n\nfunction findLocalSynapRepo(startDir: string): string | null {\n const candidates = new Set<string>();\n const resolvedStart = resolve(startDir);\n let cursor = resolvedStart;\n for (let i = 0; i < 8; i += 1) {\n candidates.add(cursor);\n candidates.add(join(cursor, 'synap-backend'));\n const parent = dirname(cursor);\n if (parent === cursor) break;\n cursor = parent;\n }\n\n const home = homedir();\n for (const p of [\n '/opt/synap-backend',\n '/srv/synap-backend',\n join(home, 'synap-backend'),\n join(home, 'synap', 'synap-backend'),\n ]) {\n candidates.add(p);\n }\n\n for (const candidate of candidates) {\n if (looksLikeSynapRepo(candidate)) return candidate;\n }\n return null;\n}\n\nasync function isDirectoryEmpty(path: string): Promise<boolean> {\n try {\n const entries = await readdir(path);\n return entries.length === 0;\n } catch {\n return false;\n }\n}\n\nasync function ensureSynapRepoForProfile(\n requestedPath: string | undefined,\n cwd: string,\n nonInteractive: boolean,\n jsonMode: boolean,\n): Promise<string> {\n // Provisioning floor: Debian 12 hosts patched to libcurl 7.88.1-10+deb12u15\n // (unattended-upgrades, 2026-07-12) get a spurious 401 on every git-over-HTTP/2\n // fetch, which git reports as \"could not read Username\" — breaking clone AND\n // every later update, on public repos included. Pin HTTP/1.1 once, here, so a\n // freshly-imaged pod is never born with a broken update path. No-op elsewhere.\n const floor = await ensureGitHttpFloor();\n if (floor.changed && !jsonMode) {\n console.log(\n `${emojis.info} Pinned git http.version=HTTP/1.1 (this host's libcurl breaks git over HTTP/2).`,\n );\n }\n\n const explicit = requestedPath?.trim() || process.env.SYNAP_REPO_ROOT?.trim();\n if (explicit) {\n const resolved = resolve(explicit);\n if (!looksLikeSynapRepo(resolved)) {\n throw new Error(\n `Invalid synap repo at ${resolved}. Expected ${resolved}/synap and ${resolved}/deploy/docker-compose.yml`,\n );\n }\n return resolved;\n }\n\n const detected = findLocalSynapRepo(cwd);\n if (detected) return detected;\n\n const defaultCloneDir = '/opt/synap-backend';\n let targetDir = defaultCloneDir;\n\n if (!nonInteractive && !jsonMode) {\n const shouldClone = await confirm({\n message: `No synap-backend checkout detected. Clone it automatically to ${defaultCloneDir}?`,\n initialValue: true,\n });\n if (isCancel(shouldClone) || !shouldClone) {\n throw new Error(\n 'data_pod/full requires a synap-backend checkout. Pass --synap-repo or set SYNAP_REPO_ROOT.',\n );\n }\n\n const maybePath = await text({\n message: 'Where should synap-backend be cloned?',\n placeholder: defaultCloneDir,\n defaultValue: defaultCloneDir,\n });\n if (isCancel(maybePath)) {\n throw new Error('Cancelled.');\n }\n const trimmed = maybePath.trim();\n targetDir = resolve(trimmed.length ? trimmed : defaultCloneDir);\n }\n\n if (existsSync(targetDir) && !looksLikeSynapRepo(targetDir)) {\n const empty = await isDirectoryEmpty(targetDir);\n if (empty) {\n await rm(targetDir, { recursive: true, force: true });\n } else if (!nonInteractive && !jsonMode) {\n const cleanup = await confirm({\n message: `${targetDir} exists but is not a valid synap-backend checkout. Remove it and retry download?`,\n initialValue: true,\n });\n if (isCancel(cleanup) || !cleanup) {\n throw new Error(\n `Cannot continue with invalid checkout at ${targetDir}. Pass --synap-repo to a valid checkout or remove that folder.`,\n );\n }\n await rm(targetDir, { recursive: true, force: true });\n } else {\n throw new Error(\n `Cannot auto-clone: target exists but is not a valid synap-backend checkout (${targetDir}). Remove it first or pass --synap-repo.`,\n );\n }\n }\n\n if (!existsSync(targetDir)) {\n if (!jsonMode) {\n console.log(`${emojis.info} Cloning synap-backend to ${colors.info(targetDir)} …`);\n }\n try {\n const res = await cloneOrFetchTarball({\n repoUrl: SYNAP_BACKEND_REPO_URL,\n tarballUrl: SYNAP_BACKEND_TARBALL_URL,\n targetDir,\n tmpDir: tmpdir(),\n log: (msg) => {\n if (!jsonMode) console.log(`${emojis.info} ${msg}`);\n },\n });\n // A tarball extraction leaves no remote unless we wire one. Without it\n // the checkout is permanently un-updatable — `eve synap deploy` would\n // have nothing to pull from, which is exactly how /opt/synap/* ended\n // up with 11 checkouts and zero remotes on synap-personal.\n if (res.via === 'tarball' && !res.gitUsable && !jsonMode) {\n console.log(\n `${emojis.warning} ${targetDir} has no git remote — future updates will need a manual re-download.`,\n );\n }\n } catch {\n throw new Error(\n `Failed to fetch public synap-backend source into ${targetDir}.\\n` +\n `Ensure outbound HTTPS to github.com/codeload.github.com is allowed and no proxy blocks downloads.\\n` +\n `You can also pass --synap-repo <path> (or set SYNAP_REPO_ROOT) to an existing checkout.`,\n );\n }\n }\n\n if (!looksLikeSynapRepo(targetDir)) {\n throw new Error(`Cloned repo at ${targetDir}, but synap CLI layout was not found.`);\n }\n\n return targetDir;\n}\n\nexport function setupCommand(program: Command): void {\n const setupCmd = program\n .command('setup')\n .description('Three-path guided setup: Ollama+gateway, Synap Data Pod, or both (logical prompts)')\n .option('--profile <p>', 'inference_only | data_pod | full')\n .option('--dry-run', 'Resolve profile and print plan; do not write state or install')\n .option('--synap-repo <path>', 'data_pod / full: path to synap-backend checkout')\n .option('--domain <host>', 'data_pod / full: synap install --domain (default: localhost, or from saved setup profile)')\n .option('--email <email>', 'data_pod / full: required if domain is not localhost')\n .option('--model <m>', 'inference_only / full: default Ollama model (default: llama3.1:8b)')\n .option('--with-openclaw', 'data_pod / full: synap install --with-openclaw')\n .option('--with-rsshub', 'data_pod / full: synap install --with-rsshub')\n .option('--admin-email <email>', 'data_pod / full: synap install --admin-email')\n .option('--admin-password <secret>', 'data_pod / full: synap install --admin-password (preseed mode)')\n .option('--admin-bootstrap-mode <mode>', 'data_pod / full: preseed | token (default token)')\n .option('--from-image', 'synap install --from-image')\n .option('--from-source', 'synap install --from-source')\n .option('--skip-hardware', 'Skip optional hardware summary')\n .option('--nvidia-smi', 'With hardware summary in non-interactive mode, run nvidia-smi')\n .option('--ai-mode <m>', 'local | provider | hybrid (AI foundation first); default after merge: hybrid')\n .option(\n '--ai-provider <p>',\n 'Default provider for Eve provider routing: openrouter | anthropic | openai | ollama',\n )\n .option('--fallback-provider <p>', 'Fallback provider for Eve provider routing')\n .option('--tunnel <provider>', 'data_pod | full: pangolin or cloudflare (runs eve legs setup after install)')\n .option('--tunnel-domain <host>', 'Hostname for tunnel / ingress (optional)')\n .addHelpText(\n 'after',\n '\\nWhy three paths\\n' +\n ' inference_only — Local Ollama + Traefik gateway (Basic auth on :11435). Synap is not installed.\\n' +\n ' data_pod — Official Synap stack via synap CLI (Caddy on 80/443). Use Eve for extra Docker apps.\\n' +\n ' full — data_pod first, then Ollama on Docker network only + same gateway (no host :11434).\\n\\n' +\n 'State & manifests\\n' +\n ' Writes .eve/setup-profile.json in the current working directory.\\n' +\n ' Pre-filled profile if ~/.eve/usb-profile.json, /opt/eve/profile.json, or EVE_SETUP_MANIFEST exists.\\n\\n' +\n 'Docs: hestia-cli/docs/EVE_SETUP_PROFILES.md, hestia-cli/docs/AI_ROUTING_CONSOLIDATION_ADR.md, and hestia-cli/README.md\\n',\n )\n .action(async (opts: SetupCliOptions) => {\n const flags = getGlobalCliFlags();\n const cwd = process.cwd();\n const existing = await readSetupProfile(cwd);\n let loadedExistingPrefs = false;\n\n if (\n !existing &&\n existsSync(getSetupProfilePath(cwd)) &&\n !flags.nonInteractive &&\n !flags.json &&\n !opts.dryRun\n ) {\n console.log(\n colors.warning(\n `${emojis.warning} ${getSetupProfilePath(cwd)} is present but invalid or unreadable. Fix or remove it to enable \"load saved preferences\".`,\n ),\n );\n }\n\n if (existing && !flags.nonInteractive && !opts.dryRun && !flags.json) {\n const load = await confirm({\n message: `Load latest saved setup preferences from .eve/setup-profile.json (${existing.profile})?`,\n initialValue: true,\n });\n if (isCancel(load)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n loadedExistingPrefs = Boolean(load);\n }\n\n let profile = parseProfile(opts.profile);\n const usb = await readUsbSetupManifest();\n if (!profile && usb) {\n profile = usb.target_profile;\n if (!flags.json) {\n console.log(\n `${emojis.info} Found USB/setup manifest → suggested profile: ${colors.info(profile)}`,\n );\n }\n }\n if (!profile && loadedExistingPrefs && existing?.profile) {\n profile = existing.profile;\n }\n\n if (!profile && !flags.nonInteractive) {\n const choice = await select({\n message: 'Choose setup profile',\n options: [\n {\n value: 'inference_only' as const,\n label: 'Ollama + gateway',\n hint: 'Local models + Traefik Basic auth on :11435 (Synap not installed)',\n },\n {\n value: 'data_pod' as const,\n label: 'Eve only',\n hint: 'Official synap install (Caddy on 80/443); Eve for extra Docker apps',\n },\n {\n value: 'full' as const,\n label: 'All',\n hint: 'Synap first, then Ollama on eve-network + gateway :11435',\n },\n ],\n initialValue: profile ?? 'data_pod',\n });\n if (isCancel(choice)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n profile = choice as SetupProfileKind;\n }\n\n if (!profile) {\n console.error('Profile required: use --profile inference_only|data_pod|full or run interactively.');\n process.exit(1);\n }\n\n // AI foundation first (local/provider/hybrid) before Synap and side systems\n let aiMode =\n parseAiMode(opts.aiMode) ??\n prevAiModeFromUsb(usb) ??\n (loadedExistingPrefs ? existing?.aiMode : undefined);\n let defaultProvider =\n parseAiProvider(opts.aiProvider) ??\n (loadedExistingPrefs ? existing?.aiDefaultProvider : undefined);\n let fallbackProvider =\n parseAiProvider(opts.fallbackProvider) ??\n (loadedExistingPrefs ? existing?.aiFallbackProvider : undefined);\n\n if (!opts.dryRun && !flags.nonInteractive && !flags.json) {\n if (!aiMode) {\n const m = await select({\n message: 'AI foundation: where should inference run?',\n options: [\n { value: 'local' as const, label: 'Local only', hint: 'Ollama on this server' },\n { value: 'provider' as const, label: 'Provider only', hint: 'OpenRouter/Anthropic/OpenAI' },\n { value: 'hybrid' as const, label: 'Hybrid (recommended)', hint: 'Local + provider fallback' },\n ],\n initialValue: 'hybrid',\n });\n if (isCancel(m)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n aiMode = parseAiMode(String(m));\n }\n\n if (!defaultProvider && aiMode !== 'local') {\n const p = await select({\n message: 'Choose default cloud provider',\n options: [\n { value: 'openrouter' as const, label: 'OpenRouter', hint: 'Multi-provider gateway' },\n { value: 'anthropic' as const, label: 'Anthropic' },\n { value: 'openai' as const, label: 'OpenAI' },\n ],\n initialValue: 'openrouter',\n });\n if (isCancel(p)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n defaultProvider = parseAiProvider(String(p));\n }\n\n // Always propose fallback for resilience\n const askFallback = await confirm({\n message: 'Add a fallback provider?',\n initialValue: true,\n });\n if (isCancel(askFallback)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n if (askFallback && !fallbackProvider) {\n const fp = await select({\n message: 'Fallback provider',\n options: [\n { value: 'openrouter' as const, label: 'OpenRouter' },\n { value: 'anthropic' as const, label: 'Anthropic' },\n { value: 'openai' as const, label: 'OpenAI' },\n { value: 'ollama' as const, label: 'Ollama local' },\n { value: 'none' as const, label: 'Skip fallback' },\n ],\n initialValue: aiMode === 'local' ? 'none' : 'ollama',\n });\n if (isCancel(fp)) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n fallbackProvider =\n fp === 'none' ? undefined : parseAiProvider(String(fp));\n }\n }\n\n if (!aiMode) aiMode = 'hybrid';\n if (!defaultProvider && aiMode !== 'local') defaultProvider = 'openrouter';\n\n // ---------------------------------------------------------------\n // One-shot: copy domain/email from .eve/setup-profile.json into\n // ~/.eve/secrets.json. Idempotent — only writes when secrets are\n // missing the field. Runs before gatherInstallConfig so the\n // resolver sees the back-filled values via the secrets source.\n // ---------------------------------------------------------------\n if (!opts.dryRun) {\n await migrateSetupProfileToSecrets(cwd).catch(() => {\n // Migration is best-effort. If it fails, the resolver still\n // reads the saved profile directly via its 'saved-profile'\n // source — operator just doesn't get the canonicalisation.\n });\n }\n\n // ---------------------------------------------------------------\n // Resolve install configuration via the shared funnel.\n //\n // The wizard owns AI-foundation (above) and the 3-path profile\n // selector; everything else (domain/SSL/email/admin/tunnel/install\n // mode) flows through gatherInstallConfig so eve install / eve setup\n // / eve init all share one resolution chain. Saved-profile loading\n // is on for setup so re-runs auto-resume.\n // ---------------------------------------------------------------\n const usbTunnelDomain = usb?.tunnel_domain?.trim() || undefined;\n let installDomain: string;\n let installEmail: string | undefined;\n let installMode: 'auto' | 'from_image' | 'from_source';\n let installWithOpenclaw: boolean;\n let installWithRsshub: boolean;\n let adminBootstrapMode: 'preseed' | 'token';\n let adminEmail: string | undefined;\n let adminPassword: string | undefined;\n let exposureMode: 'local' | 'public';\n let tunnelProvider: 'pangolin' | 'cloudflare' | undefined;\n let tunnelDomain: string | undefined;\n let legsHostStrategy: 'same_as_synap' | 'custom' | undefined;\n let resolvedSsl = false;\n\n if (profile === 'inference_only') {\n // No Synap install — only AI defaults matter. Skip the funnel.\n installDomain = 'localhost';\n installEmail = opts.email?.trim() || process.env.LETSENCRYPT_EMAIL?.trim();\n installMode = opts.fromImage ? 'from_image' : opts.fromSource ? 'from_source' : 'auto';\n installWithOpenclaw = Boolean(opts.withOpenclaw);\n installWithRsshub = Boolean(opts.withRsshub);\n adminBootstrapMode =\n opts.adminBootstrapMode === 'preseed' || opts.adminBootstrapMode === 'token'\n ? opts.adminBootstrapMode\n : 'token';\n adminEmail = opts.adminEmail?.trim() || process.env.ADMIN_EMAIL?.trim();\n adminPassword = opts.adminPassword?.trim() || process.env.ADMIN_PASSWORD?.trim();\n exposureMode = 'local';\n tunnelProvider = parseTunnel(opts.tunnel) ?? usb?.tunnel_provider;\n tunnelDomain = opts.tunnelDomain?.trim() || usbTunnelDomain;\n } else {\n const seedComponents = profile === 'data_pod'\n ? ['traefik', 'synap']\n : ['traefik', 'synap', 'ollama'];\n try {\n const cfg = await gatherInstallConfig({\n cwd,\n flags: {\n components: seedComponents,\n domain: opts.domain?.trim() || usb?.domain_hint || undefined,\n email: opts.email?.trim() || undefined,\n adminEmail: opts.adminEmail?.trim() || undefined,\n adminPassword: opts.adminPassword?.trim() || undefined,\n adminBootstrapMode: opts.adminBootstrapMode,\n fromImage: opts.fromImage,\n fromSource: opts.fromSource,\n withOpenclaw: opts.withOpenclaw,\n withRsshub: opts.withRsshub,\n tunnel: parseTunnel(opts.tunnel) ?? usb?.tunnel_provider,\n tunnelDomain: opts.tunnelDomain?.trim() || usbTunnelDomain,\n },\n interactive: !opts.dryRun && !flags.nonInteractive && !flags.json,\n loadSavedProfile: true,\n seed: {\n ai: { mode: aiMode, defaultProvider, fallbackProvider },\n },\n prompts: defaultPrompts,\n });\n installDomain = cfg.domain;\n installEmail = cfg.email;\n installMode = cfg.installMode;\n installWithOpenclaw = cfg.withOpenclaw;\n installWithRsshub = cfg.withRsshub;\n adminBootstrapMode = cfg.adminBootstrapMode;\n adminEmail = cfg.adminEmail;\n adminPassword = cfg.adminPassword;\n exposureMode = cfg.exposure;\n tunnelProvider = cfg.tunnel?.provider;\n tunnelDomain = cfg.tunnel?.domain;\n legsHostStrategy = cfg.tunnel?.hostStrategy;\n resolvedSsl = cfg.ssl;\n } catch (err) {\n if (err instanceof InstallConfigError) {\n console.error(err.message);\n process.exit(1);\n }\n throw err;\n }\n }\n\n // Interactive domain/email/SSL/admin/tunnel prompts have moved to\n // gatherInstallConfig (above) — single funnel shared with `eve install`.\n\n if (flags.nonInteractive && opts.tunnel && !tunnelProvider) {\n console.error('Invalid --tunnel (use pangolin or cloudflare).');\n process.exit(1);\n }\n if (flags.nonInteractive && opts.aiMode && !parseAiMode(opts.aiMode)) {\n console.error('Invalid --ai-mode (use local|provider|hybrid).');\n process.exit(1);\n }\n if (flags.nonInteractive && opts.aiProvider && !parseAiProvider(opts.aiProvider)) {\n console.error('Invalid --ai-provider (use openrouter|anthropic|openai|ollama).');\n process.exit(1);\n }\n if (\n flags.nonInteractive &&\n opts.adminBootstrapMode &&\n opts.adminBootstrapMode !== 'token' &&\n opts.adminBootstrapMode !== 'preseed'\n ) {\n console.error('Invalid --admin-bootstrap-mode (use token|preseed).');\n process.exit(1);\n }\n // Domain/email/admin presence is now validated by gatherInstallConfig\n // (above) — it throws InstallConfigError with a structured missing[]\n // list before reaching here.\n\n const synapInstallWithOpenclaw =\n installWithOpenclaw && adminBootstrapMode === 'preseed';\n if (installWithOpenclaw && adminBootstrapMode === 'token' && !opts.dryRun) {\n if (!flags.json) {\n console.log(\n colors.info(\n 'OpenClaw: token bootstrap has no workspace at install time, so `synap install` runs without --with-openclaw. After you finish /admin/bootstrap, use the admin dashboard prompt or run `./synap services add openclaw` on the server.',\n ),\n );\n }\n }\n\n if (!flags.json) {\n const synapReachability =\n installDomain === 'localhost'\n ? 'local only (localhost/private network)'\n : `public via https://${installDomain}`;\n const legsReachability = tunnelProvider\n ? `enabled (${tunnelProvider}${tunnelDomain ? `, hostname: ${tunnelDomain}` : ''})`\n : 'disabled (no tunnel/public Legs route configured)';\n console.log(\n colors.info(\n '\\nNetwork exposure plan:\\n' +\n ` - Synap Data Pod (API/auth): ${synapReachability}\\n` +\n ` - Eve side services (Legs routes): ${legsReachability}\\n`,\n ),\n );\n }\n\n if (existing && !flags.nonInteractive && !opts.dryRun && !loadedExistingPrefs) {\n const ok = await confirm({\n message: `Existing setup profile (${existing.profile}). Overwrite and continue?`,\n initialValue: false,\n });\n if (isCancel(ok) || !ok) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n }\n\n if (opts.dryRun) {\n const plan = {\n profile,\n existing: existing?.profile ?? null,\n usbManifest: usb ? { target_profile: usb.target_profile } : null,\n ai: {\n mode: aiMode ?? null,\n defaultProvider: defaultProvider ?? null,\n fallbackProvider: fallbackProvider ?? null,\n },\n tunnel: tunnelProvider ?? null,\n tunnelDomain: tunnelDomain ?? null,\n legsHostStrategy: legsHostStrategy ?? null,\n synap: {\n domain: installDomain,\n email: installEmail ?? null,\n mode: installMode,\n withOpenclaw: installWithOpenclaw,\n synapInstallWithOpenclaw,\n withRsshub: installWithRsshub,\n adminBootstrapMode,\n adminEmail: adminEmail ?? null,\n },\n };\n if (flags.json) outputJson(plan);\n else console.log(JSON.stringify(plan, null, 2));\n return;\n }\n\n if (!opts.skipHardware && !flags.json) {\n if (flags.nonInteractive) {\n if (opts.nvidiaSmi) {\n const facts = await probeHardware(true);\n console.log(`\\n${colors.primary('Hardware')}\\n${formatHardwareReport(facts)}\\n`);\n }\n } else {\n const showHw = await confirm({\n message: 'Show optional hardware summary (CPU, RAM, OS)?',\n initialValue: false,\n });\n if (!isCancel(showHw) && showHw) {\n const gpu = await confirm({\n message: 'Also run nvidia-smi (may fail if no NVIDIA GPU)?',\n initialValue: false,\n });\n const facts = await probeHardware(!isCancel(gpu) && Boolean(gpu));\n console.log(`\\n${colors.primary('Hardware')}\\n${formatHardwareReport(facts)}\\n`);\n }\n }\n }\n\n await writeSetupProfile(\n {\n profile,\n source: usb ? 'usb_manifest' : flags.nonInteractive ? 'cli' : 'wizard',\n domainHint: installDomain,\n hearthName: usb?.hearth_name,\n tunnelProvider,\n tunnelDomain,\n aiMode,\n aiDefaultProvider: defaultProvider,\n aiFallbackProvider: fallbackProvider,\n network: {\n exposureMode,\n synapHost: installDomain,\n legs: tunnelProvider\n ? {\n tunnelProvider,\n hostStrategy: legsHostStrategy ?? (tunnelDomain ? 'custom' : undefined),\n host: tunnelDomain,\n }\n : undefined,\n },\n synapInstall: {\n mode: installMode,\n tlsEmail: installEmail,\n withOpenclaw: installWithOpenclaw,\n withRsshub: installWithRsshub,\n adminBootstrapMode,\n adminEmail,\n },\n },\n cwd,\n );\n\n const prevSecrets = await readEveSecrets(cwd);\n type SecretsMerge = Omit<EveSecrets, 'version' | 'updatedAt'>;\n const skillsDir =\n prevSecrets?.builder?.skillsDir?.trim() ||\n process.env.EVE_SKILLS_DIR?.trim() ||\n defaultSkillsDir();\n\n const merge: SecretsMerge = {\n ai: {\n mode: aiMode,\n defaultProvider,\n fallbackProvider,\n syncToSynap: true,\n providers: [\n { id: 'ollama', enabled: aiMode !== 'provider', baseUrl: prevSecrets?.inference?.ollamaUrl ?? 'http://127.0.0.1:11434' },\n {\n id: 'openrouter',\n enabled: defaultProvider === 'openrouter' || fallbackProvider === 'openrouter',\n apiKey: prevSecrets?.ai?.providers?.find((p) => p.id === 'openrouter')?.apiKey ?? process.env.OPENROUTER_API_KEY,\n baseUrl: 'https://openrouter.ai/api/v1',\n defaultModel: prevSecrets?.ai?.providers?.find((p) => p.id === 'openrouter')?.defaultModel ?? process.env.OPENROUTER_MODEL,\n },\n {\n id: 'anthropic',\n enabled: defaultProvider === 'anthropic' || fallbackProvider === 'anthropic',\n apiKey: prevSecrets?.ai?.providers?.find((p) => p.id === 'anthropic')?.apiKey ?? process.env.ANTHROPIC_API_KEY,\n defaultModel: prevSecrets?.ai?.providers?.find((p) => p.id === 'anthropic')?.defaultModel ?? process.env.ANTHROPIC_MODEL,\n },\n {\n id: 'openai',\n enabled: defaultProvider === 'openai' || fallbackProvider === 'openai',\n apiKey: prevSecrets?.ai?.providers?.find((p) => p.id === 'openai')?.apiKey ?? process.env.OPENAI_API_KEY,\n defaultModel: prevSecrets?.ai?.providers?.find((p) => p.id === 'openai')?.defaultModel ?? process.env.OPENAI_MODEL,\n },\n ],\n },\n builder: {\n codeEngine:\n parseCodeEngine(process.env.BUILDER_CODE_ENGINE) ?? prevSecrets?.builder?.codeEngine,\n openclaudeUrl:\n profile === 'data_pod'\n ? prevSecrets?.builder?.openclaudeUrl ??\n (process.env.OPENCLAUDE_BRAIN_URL || undefined)\n : prevSecrets?.builder?.openclaudeUrl ??\n prevSecrets?.inference?.gatewayUrl ??\n 'http://127.0.0.1:11435',\n dokployApiUrl: prevSecrets?.builder?.dokployApiUrl ?? process.env.DOKPLOY_API_URL ?? 'http://127.0.0.1:3000',\n dokployApiKey: ensureSecretValue(prevSecrets?.builder?.dokployApiKey ?? process.env.DOKPLOY_API_KEY),\n dokployWebhookUrl:\n prevSecrets?.builder?.dokployWebhookUrl ?? process.env.DOKPLOY_WEBHOOK_URL ?? undefined,\n workspaceDir: prevSecrets?.builder?.workspaceDir ?? join(homedir(), '.eve', 'workspace'),\n skillsDir,\n },\n };\n\n if (profile !== 'inference_only') {\n const podKey = ensureSecretValue(\n prevSecrets?.synap?.apiKey ?? process.env.SYNAP_API_KEY ?? process.env.OPENCLAW_SYNAP_API_KEY,\n );\n // We deliberately do NOT write `apiUrl` here. The pod URL is\n // derived at read time from `domain.primary` via\n // `resolveSynapUrl(secrets)` (see @eve/dna/components.ts). Storing\n // it would re-introduce the drift bug that wasted hours of\n // debugging: change domain → stored apiUrl goes stale → every\n // CLI call hits the wrong URL. Pure derivation can't drift.\n //\n // Existing `apiUrl` from previous installs is preserved by\n // writeEveSecrets' merge — that's intentional, since some users\n // explicitly point Eve at a remote pod (different from their\n // domain.primary). The resolver honors that override.\n merge.synap = {\n apiKey: podKey,\n hubBaseUrl: prevSecrets?.synap?.hubBaseUrl ?? process.env.SYNAP_HUB_BASE_URL ?? undefined,\n };\n merge.arms = {\n openclaw: { synapApiKey: podKey },\n };\n } else {\n merge.arms = {\n openclaw: {\n synapApiKey: ensureSecretValue(\n prevSecrets?.arms?.openclaw?.synapApiKey ?? process.env.OPENCLAW_SYNAP_API_KEY,\n ),\n },\n };\n }\n if (profile !== 'data_pod') {\n merge.inference = {\n ollamaUrl:\n prevSecrets?.inference?.ollamaUrl ??\n (profile === 'full' ? 'http://eve-brain-ollama:11434' : 'http://127.0.0.1:11434'),\n gatewayUrl: prevSecrets?.inference?.gatewayUrl ?? 'http://127.0.0.1:11435',\n gatewayUser: prevSecrets?.inference?.gatewayUser,\n gatewayPass: prevSecrets?.inference?.gatewayPass,\n };\n }\n // Persist resolved domain → secrets.json (single source of truth for\n // domain/ssl/email; consumed by preflight, runBrainInit, eve domain).\n if (installDomain && installDomain !== 'localhost') {\n merge.domain = {\n primary: installDomain,\n ssl: resolvedSsl,\n email: installEmail,\n };\n }\n await writeEveSecrets(merge, cwd);\n ensureEveSkillsLayout(skillsDir);\n\n if (flags.json) {\n outputJson({ ok: true, profile, persisted: true });\n }\n\n try {\n if (profile === 'inference_only') {\n await runInferenceInit({\n model: opts.model ?? 'llama3.1:8b',\n withGateway: true,\n internalOllamaOnly: false,\n });\n } else if (profile === 'data_pod') {\n const repo = await ensureSynapRepoForProfile(\n opts.synapRepo,\n cwd,\n Boolean(flags.nonInteractive),\n Boolean(flags.json),\n );\n await runBrainInit({\n synapRepo: repo,\n domain: installDomain,\n email: installEmail,\n withOpenclaw: synapInstallWithOpenclaw,\n withRsshub: installWithRsshub,\n fromImage: installMode === 'from_image',\n fromSource: installMode === 'from_source',\n adminBootstrapMode,\n adminEmail,\n adminPassword,\n withAi: false,\n });\n if (tunnelProvider) {\n const legsDomain =\n installDomain !== 'localhost' ? installDomain : tunnelDomain ?? undefined;\n await runLegsProxySetup({\n domain: legsDomain,\n tunnel: tunnelProvider,\n tunnelDomain,\n ssl: false,\n standalone: false,\n });\n }\n } else {\n const repo = await ensureSynapRepoForProfile(\n opts.synapRepo,\n cwd,\n Boolean(flags.nonInteractive),\n Boolean(flags.json),\n );\n if (!flags.json) {\n console.log(colors.info('\\nFull profile: (1) Data Pod (2) Ollama internal + gateway\\n'));\n }\n await runBrainInit({\n synapRepo: repo,\n domain: installDomain,\n email: installEmail,\n withOpenclaw: synapInstallWithOpenclaw,\n withRsshub: installWithRsshub,\n fromImage: installMode === 'from_image',\n fromSource: installMode === 'from_source',\n adminBootstrapMode,\n adminEmail,\n adminPassword,\n withAi: false,\n });\n await runInferenceInit({\n model: opts.model ?? 'llama3.1:8b',\n withGateway: true,\n internalOllamaOnly: true,\n });\n if (tunnelProvider) {\n const legsDomain =\n installDomain !== 'localhost' ? installDomain : tunnelDomain ?? undefined;\n await runLegsProxySetup({\n domain: legsDomain,\n tunnel: tunnelProvider,\n tunnelDomain,\n ssl: false,\n standalone: false,\n });\n }\n }\n\n if (!flags.json) {\n console.log(\n `\\n${emojis.check} Setup complete. Profile: ${colors.success(profile)} (.eve/setup-profile.json)`,\n );\n console.log(\n colors.muted(\n 'Ports: Synap Caddy 80/443; inference gateway 127.0.0.1:11435; Ollama direct 127.0.0.1:11434 when published. See hestia-cli/docs/EVE_SETUP_PROFILES.md',\n ),\n );\n }\n } catch (e) {\n console.error(e instanceof Error ? e.message : e);\n process.exit(1);\n }\n });\n\n // Sub-command: `eve setup admin`\n setupAdminCommand(setupCmd);\n}\n","/**\n * `eve remove <component>` — remove a component from an existing entity.\n *\n * Reads current state, validates the component exists, stops/removes Docker\n * resources, updates state.json and setup-profile.json.\n */\n\nimport type { Command } from 'commander';\nimport { execa } from 'execa';\nimport { join } from 'node:path';\nimport { confirm, isCancel } from '@clack/prompts';\nimport { getGlobalCliFlags, } from '@eve/cli-kit';\nimport {\n entityStateManager,\n} from '@eve/dna';\nimport { uninstallDashboardContainer } from '@eve/legs';\nimport { materializeTargets } from '@eve/lifecycle';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n createSpinner,\n} from '../lib/ui.js';\nimport {\n COMPONENTS,\n resolveComponent,\n} from '../lib/components.js';\n\n// ---------------------------------------------------------------------------\n// Component-specific remove implementations\n// ---------------------------------------------------------------------------\n\nasync function removeTraefik(): Promise<void> {\n const spinner = createSpinner('Stopping Traefik...');\n spinner.start();\n try {\n // Try docker compose down for the legs project\n await execa('docker', ['compose', 'down', '--volumes'], {\n cwd: join(process.cwd(), '.eve', 'traefik'),\n stdio: 'inherit',\n });\n } catch {\n // Fallback: try docker ps filtering by name\n try {\n const { stdout } = await execa('docker', ['ps', '-q', '-f', 'name=eve-traefik']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n } catch {\n // Non-fatal: traefik might be managed externally\n }\n }\n spinner.succeed('Traefik stopped');\n}\n\nasync function removeSynap(): Promise<void> {\n const spinner = createSpinner('Stopping Synap Data Pod...');\n spinner.start();\n try {\n const deployDir = process.env.SYNAP_DEPLOY_DIR;\n if (deployDir) {\n const composePath = join(deployDir, 'docker-compose.yml');\n // Use array args — no shell string interpolation\n await execa('docker', ['compose', '-f', composePath, 'down', '--volumes'], {\n env: { ...process.env, SYNAP_ASSUME_YES: '1' },\n stdio: 'inherit',\n });\n } else {\n const { stdout } = await execa('docker', ['ps', '-q', '-f', 'name=eve-synap']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n }\n } catch {\n printWarning('Synap removal failed — check manually.');\n }\n spinner.succeed('Synap stopped');\n}\n\nasync function removeOllama(): Promise<void> {\n const spinner = createSpinner('Stopping Ollama...');\n spinner.start();\n try {\n const { stdout } = await execa('docker', ['ps', '-q', '-f', 'name=ollama']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n } catch {\n // Non-fatal\n }\n spinner.succeed('Ollama stopped');\n}\n\nasync function removeOpenclaw(): Promise<void> {\n const spinner = createSpinner('Removing OpenClaw...');\n spinner.start();\n try {\n const synapScript = process.env.SYNAP_SETUP_SCRIPT;\n if (synapScript && process.platform !== 'win32') {\n await execa('bash', [synapScript, 'services', 'remove', 'openclaw'], {\n env: { ...process.env, SYNAP_DEPLOY_DIR: process.env.SYNAP_DEPLOY_DIR || '', SYNAP_ASSUME_YES: '1' },\n stdio: 'inherit',\n });\n } else {\n const { stdout } = await execa('docker', ['ps', '-q', '-f', 'name=openclaw']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n }\n } catch {\n printWarning('OpenClaw removal failed — check manually.');\n }\n spinner.succeed('OpenClaw removed');\n}\n\nasync function removeNango(): Promise<void> {\n const spinner = createSpinner('Stopping Nango...');\n spinner.start();\n try {\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileAsync = promisify(execFile);\n await execFileAsync('docker', ['rm', '-f', 'eve-arms-nango'], { timeout: 10_000 });\n } catch {\n // Container already gone — fine\n }\n spinner.succeed('Nango stopped and removed');\n}\n\nasync function removeRsshub(): Promise<void> {\n const spinner = createSpinner('Removing RSSHub...');\n spinner.start();\n try {\n const { stdout } = await execa('docker', ['ps', '-q', '-f', 'name=rsshub']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n // Also remove RSSHubService managed container\n const { RSSHubService } = await import('@eve/eyes');\n const rsshub = new RSSHubService();\n await rsshub.stop();\n } catch {\n printWarning('RSSHub removal failed — check manually.');\n }\n spinner.succeed('RSSHub removed');\n}\n\nasync function removeOpenwebuiPipelines(): Promise<void> {\n const spinner = createSpinner('Stopping Open WebUI Pipelines sidecar...');\n spinner.start();\n try {\n const { existsSync } = await import('node:fs');\n const deployDir = '/opt/openwebui-pipelines';\n const composePath = join(deployDir, 'docker-compose.yml');\n\n if (existsSync(composePath)) {\n await execa('docker', ['compose', 'down', '--volumes'], {\n cwd: deployDir,\n stdio: 'inherit',\n });\n } else {\n const { stdout } = await execa('docker', ['ps', '-aq', '-f', 'name=eve-openwebui-pipelines']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n }\n\n // Best-effort: strip the pipelines wiring block from openwebui's .env so\n // it stops trying to call us on next restart.\n const owEnv = '/opt/openwebui/.env';\n if (existsSync(owEnv)) {\n const { readFileSync, writeFileSync } = await import('node:fs');\n const cur = readFileSync(owEnv, 'utf-8');\n const marker = '# Pipelines wiring — managed by eve add openwebui-pipelines';\n if (cur.includes(marker)) {\n const stripped = cur.split(marker)[0].trimEnd();\n writeFileSync(owEnv, stripped + '\\n', { mode: 0o600 });\n }\n }\n } catch {\n printWarning('Pipelines removal failed — check manually.');\n }\n spinner.succeed('Open WebUI Pipelines removed');\n}\n\nasync function removeDashboard(): Promise<void> {\n const spinner = createSpinner('Stopping Eve Dashboard...');\n spinner.start();\n try {\n uninstallDashboardContainer();\n } catch {\n printWarning('Eve Dashboard removal failed — check `docker ps -a` manually.');\n }\n spinner.succeed('Eve Dashboard removed');\n}\n\nasync function removeOpenwebui(): Promise<void> {\n const spinner = createSpinner('Stopping Open WebUI...');\n spinner.start();\n try {\n const { existsSync } = await import('node:fs');\n const deployDir = '/opt/openwebui';\n const composePath = join(deployDir, 'docker-compose.yml');\n\n if (existsSync(composePath)) {\n // Tear down via the same compose project we used to bring it up\n await execa('docker', ['compose', 'down', '--volumes'], {\n cwd: deployDir,\n stdio: 'inherit',\n });\n } else {\n // Fallback: remove by container name\n const { stdout } = await execa('docker', ['ps', '-aq', '-f', 'name=hestia-openwebui']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n }\n } catch {\n printWarning('Open WebUI removal failed — check manually.');\n }\n spinner.succeed('Open WebUI removed');\n}\n\n/**\n * Remove FreeLLMAPI.\n *\n * Two deliberate departures from the other remove paths:\n *\n * 1. The named volume is KEPT (`down` WITHOUT `--volumes`). It holds every\n * upstream free-tier key the user added, encrypted at rest. Those keys were\n * collected by hand across dozens of provider signups, and a `remove` that\n * silently destroys them is not recoverable by reinstalling. The command\n * prints how to purge it deliberately.\n * 2. The pod's provider row is DISABLED first. Leaving it enabled points the\n * Intelligence Service's cascade at a container that no longer exists —\n * which surfaces later as slow, confusing failover rather than as\n * \"the thing you removed is gone\".\n */\nasync function removeFreellmapi(): Promise<void> {\n const spinner = createSpinner('Stopping FreeLLMAPI...');\n spinner.start();\n let podNotice: string | null = null;\n\n // Disable on the pod BEFORE tearing the container down.\n try {\n const { readEveSecrets, resolveSynapUrl, readAgentKeyOrLegacy, setPodProviderEnabled, describePodProviderResult } =\n await import('@eve/dna');\n const secrets = await readEveSecrets(process.cwd());\n const podUrl = resolveSynapUrl(secrets);\n const apiKey = await readAgentKeyOrLegacy('eve', process.cwd());\n if (podUrl && apiKey) {\n const result = await setPodProviderEnabled(podUrl, apiKey, 'freellmapi', false);\n // The spinner has no stop(); report the outcome after it finishes below.\n podNotice = describePodProviderResult(result);\n }\n } catch {\n // Non-fatal: the container teardown below is the point of this command.\n printWarning('Could not disable the freellmapi provider on the pod — do it manually.');\n }\n\n try {\n const { existsSync } = await import('node:fs');\n const deployDir = '/opt/freellmapi';\n const composePath = join(deployDir, 'docker-compose.yml');\n\n if (existsSync(composePath)) {\n // NOTE: no `--volumes` — see the docblock.\n await execa('docker', ['compose', 'down'], { cwd: deployDir, stdio: 'inherit' });\n } else {\n const { stdout } = await execa('docker', ['ps', '-aq', '-f', 'name=eve-brain-freellmapi']);\n if (stdout.trim()) {\n const containers = stdout.trim().split('\\n').filter(Boolean);\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'inherit' });\n }\n }\n } catch {\n printWarning('FreeLLMAPI removal failed — check manually.');\n }\n spinner.succeed('FreeLLMAPI removed (provider keys kept)');\n if (podNotice) console.log(' ' + podNotice);\n printInfo(' Its stored provider keys were KEPT in the `freellmapi-data` volume.');\n printInfo(' To destroy them too: docker volume rm freellmapi_freellmapi-data');\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Remove a component from the current entity.\n */\nexport async function runRemove(componentId: string): Promise<void> {\n // Traefik is always-installed infrastructure — refuse removal\n if (componentId === 'traefik') {\n printError('Traefik is always-installed infrastructure and cannot be removed.');\n printInfo(' To stop it temporarily: docker stop eve-legs-traefik');\n process.exit(1);\n }\n // Eve dashboard is the UI itself — refuse removal\n if (componentId === 'eve-dashboard') {\n printError('Eve Dashboard is always-installed infrastructure and cannot be removed.');\n printInfo(' To stop it temporarily: docker stop eve-dashboard');\n process.exit(1);\n }\n\n const comp = resolveComponent(componentId);\n\n // Check if installed\n const installed = await entityStateManager.isComponentInstalled(componentId);\n if (!installed) {\n // Also check organ state — component may have been installed via old v1 path\n const organ = comp.organ;\n let organReady = false;\n if (organ) {\n const organState = await entityStateManager.getOrganState(organ as Parameters<typeof entityStateManager.getOrganState>[0]);\n organReady = organState.state === 'ready';\n }\n if (!organReady) {\n printWarning(`${comp.label} does not appear to be installed.`);\n printInfo(' Run \"eve status\" to see current state.');\n return;\n }\n }\n\n // Check if other components depend on this one\n const currentComponents = await entityStateManager.getInstalledComponents();\n const dependents = currentComponents.filter(dep => {\n const depInfo = COMPONENTS.find(c => c.id === dep);\n return depInfo?.requires?.includes(componentId) ?? false;\n });\n if (dependents.length > 0) {\n const depNames = dependents.map(d => {\n const info = COMPONENTS.find(c => c.id === d);\n return info ? info.label : d;\n });\n printWarning(`${comp.label} is a prerequisite for: ${depNames.join(', ')}`);\n printInfo(' Remove dependents first, or proceed with caution:');\n console.log();\n }\n\n printHeader(`Removing ${comp.label}`, comp.emoji);\n console.log();\n printInfo('This will stop and remove the Docker containers for this component.');\n console.log();\n\n // Confirm before destructive action (skip in non-interactive mode)\n const flags = getGlobalCliFlags();\n if (!flags.nonInteractive) {\n const ok = await confirm({ message: `Remove ${comp.label}? This cannot be undone.` });\n if (isCancel(ok) || !ok) {\n console.log(colors.muted('Cancelled.'));\n return;\n }\n }\n\n // Run the removal\n let removeFn: () => Promise<void>;\n try {\n removeFn = buildRemoveStep(comp.id);\n } catch (err) {\n printError(String(err));\n process.exit(1);\n }\n\n await removeFn();\n\n // Update state\n await updateStateAfterRemove(comp.id);\n\n // Auto-refresh Traefik routes so removed component's subdomain stops returning 502\n const [refresh] = await materializeTargets(null, ['traefik-routes']);\n if (refresh?.changed) {\n printInfo(refresh.summary);\n }\n\n console.log();\n printSuccess(`${comp.label} removed successfully!`);\n console.log();\n printInfo('Next steps:');\n printInfo(` - Run \"eve status\" to check entity state`);\n printInfo(` - Run \"eve add ${comp.id}\" to add it back later`);\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Step builder\n// ---------------------------------------------------------------------------\n\nfunction buildRemoveStep(componentId: string): () => Promise<void> {\n switch (componentId) {\n case 'traefik':\n return removeTraefik;\n case 'synap':\n return removeSynap;\n case 'ollama':\n return removeOllama;\n case 'openclaw':\n return removeOpenclaw;\n case 'nango':\n return removeNango;\n case 'rsshub':\n return removeRsshub;\n case 'openwebui':\n return removeOpenwebui;\n case 'freellmapi':\n return removeFreellmapi;\n case 'openwebui-pipelines':\n return removeOpenwebuiPipelines;\n case 'eve-dashboard':\n return removeDashboard;\n case 'hermes':\n case 'dokploy':\n case 'opencode':\n case 'openclaude':\n return async () => {\n const info = COMPONENTS.find(c => c.id === componentId);\n if (info) {\n printWarning(`${info.label} removal requires manual cleanup.`);\n printInfo(' Run \"eve builder stack\" to manage builder resources.');\n }\n };\n default:\n throw new Error(`No remove handler for component: ${componentId}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// State update\n// ---------------------------------------------------------------------------\n\nasync function updateStateAfterRemove(componentId: string): Promise<void> {\n const organMap: Record<string, 'brain' | 'arms' | 'builder' | 'eyes' | 'legs'> = {\n synap: 'brain',\n ollama: 'brain',\n openclaw: 'arms',\n hermes: 'arms',\n nango: 'arms',\n rsshub: 'eyes',\n traefik: 'legs',\n openwebui: 'eyes',\n 'openwebui-pipelines': 'eyes',\n dokploy: 'builder',\n opencode: 'builder',\n openclaude: 'builder',\n 'eve-dashboard': 'legs',\n };\n\n const organ = organMap[componentId];\n if (organ) {\n await entityStateManager.updateOrgan(organ, 'missing');\n }\n\n await entityStateManager.updateComponentEntry(componentId, {\n state: 'missing',\n });\n\n // Remove from setup profile v2 components list\n const current = await entityStateManager.getInstalledComponents();\n const updated = current.filter(id => id !== componentId);\n if (updated.length === 0) {\n // If no components left, reset to minimal\n await entityStateManager.updateSetupProfile({ components: ['traefik'] });\n await entityStateManager.updateComponentEntry('traefik', { state: 'ready' });\n await entityStateManager.updateOrgan('legs', 'ready', { version: '0.1.0' });\n } else {\n await entityStateManager.updateSetupProfile({ components: updated });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Command\n// ---------------------------------------------------------------------------\n\nexport function removeCommand(program: Command): void {\n program\n .command('remove')\n .alias('rm')\n .description('Remove a component from an existing entity')\n .argument('[component]', 'Component ID to remove (synap, ollama, openclaw, rsshub, traefik, openwebui)')\n .action(async (component: string | undefined) => {\n if (!component) {\n console.log();\n printHeader('Eve — Remove Component', emojis.entity);\n console.log();\n printInfo('Usage: eve remove <component>');\n console.log();\n printInfo('Available components:');\n for (const comp of COMPONENTS) {\n const installed = await entityStateManager.isComponentInstalled(comp.id);\n const tag = installed\n ? colors.success(' [installed]')\n : ((await entityStateManager.getOrganState(comp.organ! as Parameters<typeof entityStateManager.getOrganState>[0])).state === 'ready')\n ? colors.success(' [installed]')\n : colors.muted('[not installed]');\n console.log(` ${comp.emoji} ${colors.primary.bold(comp.label)}${tag}`);\n console.log(` ${comp.description.split('\\n')[0]}`);\n }\n console.log();\n printWarning('Warning: traefik cannot be removed (always installed).');\n printInfo('Examples:');\n printInfo(' eve remove ollama # Remove local AI inference');\n printInfo(' eve remove openclaw # Remove AI agent layer');\n printInfo(' eve remove rsshub # Remove data perception');\n console.log();\n return;\n }\n\n await runRemove(component);\n });\n}\n\n// ---------------------------------------------------------------------------\n// Import helper for dynamic imports\n// ---------------------------------------------------------------------------\n\n// no-op — import helper removed (not used at runtime)\n","import { Command } from 'commander';\nimport { execa } from 'execa';\nimport {\n printError,\n printInfo,\n} from '../../lib/ui.js';\n\nexport function logsCommand(program: Command): void {\n program\n .command('logs')\n .description('Docker Compose logs for Eve stack (set EVE_COMPOSE_FILE or run from compose directory)')\n .argument('[service]', 'Optional compose service name')\n .option('-f, --follow', 'Follow log output', false)\n .option('-n, --tail <lines>', 'Number of lines', '100')\n .option('--compose-file <path>', 'Path to docker-compose.yml')\n .action(async (service: string | undefined, opts: { follow?: boolean; tail?: string; composeFile?: string }) => {\n const composeFile = opts.composeFile || process.env.EVE_COMPOSE_FILE;\n const args = ['compose'];\n if (composeFile) {\n args.push('-f', composeFile);\n }\n args.push('logs', `--tail=${opts.tail ?? '100'}`);\n if (opts.follow) args.push('-f');\n if (service) args.push(service);\n\n try {\n printInfo(`docker ${args.join(' ')}`);\n await execa('docker', args, { stdio: 'inherit' });\n } catch (e) {\n printError(\n e instanceof Error\n ? e.message\n : 'docker compose failed. Set EVE_COMPOSE_FILE or use --compose-file.'\n );\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { execa } from 'execa';\nimport { entityStateManager, configManager } from '@eve/dna';\nimport { getGlobalCliFlags, outputJson } from '@eve/cli-kit';\nimport { colors, printInfo } from '../../lib/ui.js';\n\nexport function inspectCommand(program: Command): void {\n program\n .command('inspect')\n .description('Dump entity state, config path, and Eve-related containers (JSON)')\n .option('--containers-only', 'Only run docker ps filter')\n .action(async (opts: { containersOnly?: boolean }) => {\n try {\n let containers: Array<{ name: string; status: string; image: string }> = [];\n try {\n const { stdout } = await execa('docker', [\n 'ps',\n '-a',\n '--filter',\n 'name=eve-',\n '--format',\n '{{.Names}}\\t{{.Status}}\\t{{.Image}}',\n ]);\n containers = stdout\n .trim()\n .split('\\n')\n .filter(Boolean)\n .map((line) => {\n const [name, status, image] = line.split('\\t');\n return { name: name ?? '', status: status ?? '', image: image ?? '' };\n });\n } catch {\n containers = [];\n }\n\n if (opts.containersOnly) {\n const payload = { containers };\n if (getGlobalCliFlags().json) {\n outputJson(payload);\n } else {\n console.log(JSON.stringify(payload, null, 2));\n }\n return;\n }\n\n const state = await entityStateManager.getState();\n const cfgPath = configManager.getConfigPath();\n\n const payload = {\n entityState: state,\n configPath: cfgPath,\n containers,\n };\n\n if (getGlobalCliFlags().json) {\n outputJson(payload);\n } else {\n console.log(JSON.stringify(payload, null, 2));\n printInfo(`Config file: ${colors.muted(cfgPath)}`);\n }\n } catch (e) {\n console.error(e);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport {\n buildConfigDebugPayload,\n buildDiscoveryDebugPayload,\n buildEventsDebugPayload,\n buildMaterializedDebugPayload,\n} from '@eve/dna';\nimport { getGlobalCliFlags, outputJson } from '@eve/cli-kit';\n\ntype DebugTopic = 'config' | 'discovery' | 'materialized' | 'events';\n\nasync function buildPayload(topic: DebugTopic, opts: { limit?: string }) {\n switch (topic) {\n case 'config':\n return buildConfigDebugPayload();\n case 'discovery':\n return buildDiscoveryDebugPayload();\n case 'materialized':\n return buildMaterializedDebugPayload();\n case 'events': {\n const limit = opts.limit ? Number.parseInt(opts.limit, 10) : 100;\n return buildEventsDebugPayload(Number.isFinite(limit) ? limit : 100);\n }\n }\n}\n\nexport function debugCommand(program: Command): void {\n const debug = program\n .command('debug')\n .description('Inspect Eve operational config, discovery, materialized outputs, and events');\n\n for (const topic of ['config', 'discovery', 'materialized', 'events'] as const) {\n const command = debug\n .command(topic)\n .description(`Print ${topic} debug payload`)\n .action(async (opts: { limit?: string }) => {\n try {\n const payload = await buildPayload(topic, opts);\n if (getGlobalCliFlags().json) {\n outputJson(payload);\n } else {\n console.log(JSON.stringify(payload, null, 2));\n }\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n if (topic === 'events') {\n command.option('--limit <n>', 'Number of recent events', '100');\n }\n }\n}\n","import { Command } from 'commander';\nimport { readFile } from 'node:fs/promises';\nimport { configManager, readEveSecrets } from '@eve/dna';\nimport { getGlobalCliFlags, outputJson } from '@eve/cli-kit';\nimport { colors, printInfo, printError } from '../../lib/ui.js';\n\nconst CHANNEL_PLATFORMS = ['telegram', 'discord', 'whatsapp', 'signal', 'matrix', 'slack'] as const;\n\nexport function configCommands(program: Command): void {\n const cfg = program.command('config').description('Eve YAML config (~/.config/eve/config.yaml)');\n\n cfg\n .command('path')\n .description('Print path to config file')\n .action(() => {\n console.log(configManager.getConfigPath());\n });\n\n cfg\n .command('show')\n .description('Load and print config (JSON)')\n .action(async () => {\n try {\n const c = await configManager.loadConfig();\n const plain = {\n ...c,\n createdAt: c.createdAt instanceof Date ? c.createdAt.toISOString() : c.createdAt,\n updatedAt: c.updatedAt instanceof Date ? c.updatedAt.toISOString() : c.updatedAt,\n };\n\n // Augment with effective channel routing from secrets so the default\n // (\"hermes\" for any unconfigured platform) is visible without reading\n // secrets.json directly.\n const secrets = await readEveSecrets().catch(() => null);\n const routing = secrets?.channelRouting ?? {};\n const effectiveChannelRouting = Object.fromEntries(\n CHANNEL_PLATFORMS.map(p => [\n p,\n routing[p] ? routing[p] : `hermes (default)`,\n ]),\n );\n\n const output = { ...plain, effectiveChannelRouting };\n if (getGlobalCliFlags().json) {\n outputJson(output);\n } else {\n console.log(JSON.stringify(output, null, 2));\n }\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n cfg\n .command('dump')\n .description('Print raw YAML file contents')\n .action(async () => {\n try {\n const p = configManager.getConfigPath();\n const raw = await readFile(p, 'utf-8');\n console.log(raw);\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n cfg\n .command('set-entity-name')\n .description('Set entity display name in config')\n .argument('<name>', 'New entity name')\n .action(async (name: string) => {\n try {\n await configManager.updateConfig({ name });\n printInfo(`Updated entity name to ${colors.primary(name)}`);\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { execa } from 'execa';\nimport { execSync, spawnSync } from 'node:child_process';\nimport { createInterface } from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { getGlobalCliFlags } from '@eve/cli-kit';\nimport {\n runActionToCompletion,\n runBackendPreflight,\n provisionAllAgents,\n} from '@eve/lifecycle';\nimport { findPodDeployDir, entityStateManager, readEveSecrets } from '@eve/dna';\nimport { runSynapCli } from '@eve/brain';\nimport { installDashboardContainer, dashboardIsRunning } from '@eve/legs';\nimport { probeAdminStatus } from '../setup-admin.js';\nimport { randomBytes } from 'node:crypto';\nimport {\n printInfo,\n printSuccess,\n printWarning,\n printError,\n colors,\n createSpinner,\n} from '../../lib/ui.js';\n\n// ── helpers ───────────────────────────────────────────────────────────────────\n\nconst execFileAsync = promisify(execFile);\n\n/** Create initial Nango admin account — idempotent, retries until container is ready. */\nasync function nangoAutoSignup(secretKey: string, ownerEmail?: string): Promise<void> {\n const email = ownerEmail ?? 'admin@eve.local';\n const pw = `Nango_${secretKey.slice(0, 12)}`;\n const node = `\n const attempt = (n) => fetch('http://localhost:3003/api/v1/account/signup', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: 'Admin', email: ${JSON.stringify(email)}, password: ${JSON.stringify(pw)} }),\n }).then(r => r.json()).then(d => {\n if (d?.data?.uuid || d?.error === 'account_already_exists') process.exit(0);\n if (n > 0) setTimeout(() => attempt(n - 1), 2000); else process.exit(1);\n }).catch(() => { if (n > 0) setTimeout(() => attempt(n - 1), 2000); else process.exit(1); });\n attempt(15);\n `;\n await execFileAsync('docker', ['exec', 'eve-arms-nango', 'node', '-e', node], { timeout: 40_000 }).catch(() => {/* non-fatal */});\n}\n\nfunction getSynapBackendContainer(): string | null {\n try {\n const out = execSync(\n 'docker ps --filter \"label=com.docker.compose.project=synap-backend\" --filter \"label=com.docker.compose.service=backend\" --format \"{{.Names}}\"',\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim();\n return out.split('\\n')[0]?.trim() || null;\n } catch {\n return null;\n }\n}\n\nfunction connectToEveNetwork(name: string): void {\n try {\n execSync(`docker network connect eve-network ${name}`, { stdio: ['pipe', 'pipe', 'ignore'] });\n } catch { /* already connected */ }\n}\n\ninterface UpdateTarget {\n id: string;\n label: string;\n image?: string;\n container?: string;\n /** Returns optional sub-lines to render under the spinner success row. */\n update: () => Promise<{ subLines?: string[] } | void>;\n}\n\n/**\n * Pod Admin is shipped, migrated, and restarted by the canonical Synap CLI.\n * Keep it as a convenience update alias rather than inventing a second owner\n * with a partial service lifecycle.\n */\nexport function normalizeSynapManagedUpdateTargets(targets: Set<string> | null): boolean {\n if (!targets?.has('pod-admin')) return false;\n targets.delete('pod-admin');\n targets.add('synap');\n return true;\n}\n\n/**\n * Wrap `runActionToCompletion(id, \"update\")` so each top-level update\n * target is a thin shim that delegates to `@eve/lifecycle`. Single source\n * of truth: the lifecycle's UPDATE_PLAN handles compose/imagePull strategy,\n * recreate-vs-restart for env-bound components, missing-container drift,\n * and the obsolete-`version:` sanitization.\n */\nfunction lifecycleUpdate(id: string, label: string): UpdateTarget {\n return {\n id,\n label,\n update: async () => {\n const result = await runActionToCompletion(id, 'update');\n if (!result.ok) {\n // Always include the last few log lines from the lifecycle\n // stream — without them the user sees only the headline (e.g.\n // \"compose up exited 1\") and has no way to tell whether it was\n // a missing network, port conflict, or pull failure. The outer\n // catch in `eve update` prints the full multi-line message.\n const tail = result.logs.slice(-6).join('\\n');\n const headline = result.error ?? 'update failed';\n throw new Error(tail ? `${headline}\\n${tail}` : headline);\n }\n // Surface post-update reconciliation log lines under the spinner.\n // OpenClaw gets a filtered headline; everything else gets all log lines\n // so operators can see what actually happened (env rewired, API called, etc.)\n if (id === 'openclaw') return { subLines: extractOpenclawSubLines(id, result.logs) };\n return { subLines: result.logs.filter(l => l.trim().length > 0) };\n },\n };\n}\n\n/**\n * Pick the headline reconciliation note out of the lifecycle log stream.\n *\n * The post-update hook prefixes each note with `OpenClaw:`; we surface\n * exactly one of those — the most informative — under the spinner. Keep\n * everything else quiet so the success summary stays tight.\n */\nfunction extractOpenclawSubLines(id: string, logs: string[]): string[] {\n if (id !== 'openclaw') return [];\n const reconcileLogs = logs.filter(l => l.startsWith('OpenClaw:'));\n if (reconcileLogs.length === 0) return [];\n // Prefer the \"re-added\" line if present — that's the one the user wants\n // to see on the self-heal path. Otherwise fall back to whatever the\n // hook surfaced first (typically \"already in sync\").\n const reAdded = reconcileLogs.find(l => l.includes('re-added'));\n const headline = reAdded ?? reconcileLogs[0];\n // Strip the `OpenClaw: ` prefix — the spinner row already names the\n // component. Keep it short.\n return [headline.replace(/^OpenClaw:\\s*/, 'reconciled allowedOrigins: ')];\n}\n\n/**\n * Locate the self-update script shipped alongside the CLI binary.\n *\n * Two cases:\n * - Installed via bootstrap.sh → binary is /opt/eve/packages/eve-cli/dist/index.js\n * → script at /opt/eve/scripts/self-update.sh\n * - Dev mode (pnpm dev) → __dirname is packages/eve-cli/dist/\n * → script at ../../scripts/self-update.sh (i.e. hestia-cli root)\n */\nfunction findSelfUpdateScript(): string | null {\n const binDir = dirname(fileURLToPath(import.meta.url));\n // Walk up from the dist dir looking for scripts/self-update.sh\n let dir = binDir;\n for (let i = 0; i < 5; i++) {\n const candidate = join(dir, 'scripts', 'self-update.sh');\n if (existsSync(candidate)) return candidate;\n dir = dirname(dir);\n }\n return null;\n}\n\n/**\n * After a successful `eve update synap`, re-run agent provisioning so:\n * - New agents introduced in this release get their first key minted.\n * - Any first-install that previously failed auth gets a retry.\n *\n * skipIfPresent=true: keys that already exist are NOT re-minted — this\n * is an update, not a key rotation. Use `eve auth renew` for that.\n *\n * Never throws — this is a best-effort post-update hook. Returns sub-lines\n * for the spinner row so the user can see what happened without noise.\n */\nasync function tryPostUpdateProvision(_deployDir: string): Promise<{ subLines: string[] }> {\n const subLines: string[] = [];\n const eveCwd = process.cwd(); // Eve home — where secrets.json lives\n try {\n const preflight = await runBackendPreflight({ cwd: eveCwd });\n const adminStatus = await probeAdminStatus();\n if (adminStatus === 'needed') {\n subLines.push(`Admin setup required — run: eve setup admin`);\n return { subLines };\n }\n const installed = await entityStateManager.getInstalledComponents().catch(() => [] as string[]);\n const results = await provisionAllAgents({\n installedComponentIds: installed,\n deployDir: eveCwd,\n reason: 'post-update',\n synapUrl: preflight.synapUrl,\n provisioningToken: preflight.provisioningToken,\n skipIfPresent: true,\n });\n const ok = results.filter(r => r.provisioned).length;\n const failed = results.filter(r => !r.provisioned);\n if (failed.length > 0) {\n subLines.push(`${failed.length} agent key(s) failed — run: eve auth provision`);\n } else if (ok > 0) {\n subLines.push(`${ok} agent key${ok === 1 ? '' : 's'} verified`);\n }\n } catch {\n subLines.push('Agent provision skipped (backend not ready — run: eve auth provision)');\n }\n return { subLines };\n}\n\nasync function buildUpdateTargets(deployDir: string | undefined): Promise<UpdateTarget[]> {\n const targets: UpdateTarget[] = [];\n\n // Read installed component set once — guards all optional targets below.\n // Falls back to empty on any read error so a corrupt state file never\n // blocks updates of components the user explicitly names.\n const installed = await entityStateManager.getInstalledComponents().catch(() => [] as string[]);\n const has = (id: string) => installed.includes(id);\n\n // Eve CLI self-update — runs scripts/self-update.sh which does:\n // git pull + pnpm install + build + re-link /usr/local/bin/eve\n targets.push({\n id: 'eve',\n label: '🌿 Eve CLI',\n update: async () => {\n const script = findSelfUpdateScript();\n if (!script) {\n throw new Error(\n 'self-update.sh not found — Eve may have been installed outside of git. ' +\n 'To update manually: cd /opt/eve && git pull && pnpm install && pnpm --filter @eve/cli... run build',\n );\n }\n const result = spawnSync('bash', [script], { stdio: 'inherit' });\n if (result.status !== 0) {\n throw new Error(`self-update.sh exited ${result.status ?? 'unknown'}`);\n }\n },\n });\n\n // Synap delegates to the canonical synap-backend bash CLI, which owns the\n // canary-first update flow, kratos-migrate force-recreate, CREATE DATABASE\n // idempotency, and migration sequencing. Eve still handles the cross-project\n // plumbing (eve-network attach, agent provisioning) afterwards.\n // See: hestia-cli/.docs/synap-cli-as-source-of-truth.md\n if (deployDir) {\n targets.push({\n id: 'synap',\n label: '🧠 Synap Data Pod',\n update: async () => {\n // Resolve the bare root domain so the CLI heals an existing .env\n // whose DOMAIN= line was written before eve enforced the pod FQDN.\n const secrets = await readEveSecrets().catch(() => null);\n const bareDomain = secrets?.domain?.primary;\n const result = runSynapCli('update', ['--from-image'], {\n refreshGit: true,\n domain: bareDomain,\n });\n if (!result.ok) {\n throw new Error(\n `synap update exited ${result.exitCode}` +\n (result.stderr ? `: ${result.stderr}` : ''),\n );\n }\n const name = getSynapBackendContainer();\n if (name) connectToEveNetwork(name);\n\n // Post-update: mint agent keys for any new agents added in this\n // release, and verify existing ones are still valid. Best-effort\n // — a provision failure never blocks the update itself.\n return tryPostUpdateProvision(deployDir);\n },\n });\n }\n\n // Optional components — only added when they were part of the user's\n // setup. `has(id)` checks state.json's setupProfile.components[] so we\n // never attempt to update a service that was never installed.\n if (has('ollama')) targets.push(lifecycleUpdate('ollama', '🤖 Ollama'));\n if (has('openclaw')) targets.push(lifecycleUpdate('openclaw', '🦾 OpenClaw'));\n if (has('nango')) targets.push({\n id: 'nango',\n label: '🔗 Nango',\n update: async () => {\n const { readEveSecrets } = await import('@eve/dna');\n const { randomUUID } = await import('node:crypto');\n const { writeEveSecrets } = await import('@eve/dna');\n const secrets = await readEveSecrets(process.cwd()).catch(() => null);\n let secretKey = secrets?.connectors?.nango?.secretKey as string | undefined;\n if (!secretKey) throw new Error('No Nango secret key found in secrets.json — run: eve add nango');\n // Nango requires UUID v4 — regenerate if the stored key is a legacy hex string\n const uuidV4Re = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n if (!uuidV4Re.test(secretKey)) {\n secretKey = randomUUID();\n await writeEveSecrets({ connectors: { nango: { secretKey } } });\n }\n const domain = secrets?.domain?.primary as string | undefined;\n // Default to https for any public domain — Traefik always terminates SSL.\n const ssl = secrets?.domain?.ssl !== false;\n const nangoHost = domain ? `${ssl ? 'https' : 'http'}://nango.${domain}` : 'http://eve-arms-nango:3003';\n const podPublicUrl = domain ? `${ssl ? 'https' : 'http'}://${domain}` : '';\n // Read postgres credentials from deploy/.env\n let pgUser = 'synap';\n let pgPass = 'synap';\n const dDir0 = findPodDeployDir() ?? undefined;\n if (dDir0) {\n const { readFile: rf0 } = await import('node:fs/promises');\n const { join: pj0 } = await import('node:path');\n const e0 = await rf0(pj0(dDir0, '.env'), 'utf8').catch(() => '');\n const mu = e0.match(/^POSTGRES_USER=(.+)$/m); if (mu?.[1]) pgUser = mu[1].trim();\n const mp = e0.match(/^POSTGRES_PASSWORD=(.+)$/m); if (mp?.[1]) pgPass = mp[1].trim();\n }\n await execFileAsync('docker', ['pull', 'nangohq/nango-server:hosted'], { timeout: 120_000 });\n await execFileAsync('docker', ['rm', '-f', 'eve-arms-nango'], { timeout: 10_000 }).catch(() => {});\n // Find postgres by compose labels, create nango DB, and connect to eve-network\n const pgOut = await execFileAsync('docker', [\n 'ps', '--filter', 'label=com.docker.compose.project=synap-backend',\n '--filter', 'label=com.docker.compose.service=postgres', '--format', '{{.Names}}',\n ], { timeout: 4000 }).catch(() => ({ stdout: '' }));\n const pgContainer = pgOut.stdout.trim().split('\\n')[0]?.trim();\n if (pgContainer) {\n await execFileAsync('docker', ['exec', pgContainer, 'psql', '-U', pgUser, '-c', 'CREATE DATABASE nango;'], { timeout: 10_000 }).catch(() => {});\n await execFileAsync('docker', ['network', 'connect', '--alias', 'eve-brain-postgres', 'eve-network', pgContainer], { timeout: 10_000 }).catch(() => {});\n }\n const runArgs = [\n 'run', '-d', '--name', 'eve-arms-nango', '--network', 'eve-network', '--restart', 'unless-stopped',\n '-e', `NANGO_SECRET_KEY=${secretKey}`, '-e', 'SERVER_PORT=3003',\n '-e', `NANGO_DATABASE_URL=postgresql://${pgUser}:${pgPass}@eve-brain-postgres:5432/nango`,\n '-e', 'NODE_ENV=production',\n '-e', 'NANGO_EMAIL_ACCOUNT_VERIFICATION_REQUIRED=false',\n ...(nangoHost ? ['-e', `NANGO_SERVER_URL=${nangoHost}`] : []),\n ...(podPublicUrl ? ['-e', `NANGO_WEBHOOK_URL=${podPublicUrl}/api/connectors/nango-webhook`] : []),\n '-v', 'eve-arms-nango-data:/var/lib/nango',\n 'nangohq/nango-server:hosted',\n ];\n await execFileAsync('docker', runArgs, { timeout: 30_000 });\n const ownerEmail = secrets?.synap?.userSession?.email ?? (secrets?.builder?.openwebui as Record<string, unknown> | undefined)?.adminEmail as string | undefined;\n await nangoAutoSignup(secretKey, ownerEmail);\n // Write updated NANGO_HOST to deploy/.env (use top-level import, not re-import)\n const dDir = findPodDeployDir() ?? undefined;\n if (dDir) {\n const { readFile, writeFile } = await import('node:fs/promises');\n const { join: pj } = await import('node:path');\n const envPath = pj(dDir, '.env');\n let envContent = await readFile(envPath, 'utf8').catch(() => '');\n const setVar = (c: string, k: string, v: string) => {\n const re = new RegExp(`^${k}=.*$`, 'm');\n return re.test(c) ? c.replace(re, `${k}=${v}`) : `${c}\\n${k}=${v}`;\n };\n envContent = setVar(envContent, 'NANGO_HOST', nangoHost);\n envContent = setVar(envContent, 'NANGO_SECRET_KEY', secretKey);\n await writeFile(envPath, envContent.trimStart(), 'utf8');\n // Restart synap-backend to pick up any env changes\n const container = getSynapBackendContainer();\n if (container) {\n await execFileAsync('docker', ['restart', container], { timeout: 60_000 });\n connectToEveNetwork(container);\n }\n }\n return { subLines: [`image updated, container recreated with NANGO_DATABASE_URL`] };\n },\n });\n if (has('rsshub')) targets.push(lifecycleUpdate('rsshub', '👁️ RSSHub'));\n if (has('traefik')) targets.push(lifecycleUpdate('traefik', '🦿 Traefik'));\n if (has('openwebui')) targets.push(lifecycleUpdate('openwebui', '💬 Open WebUI'));\n if (has('openwebui-pipelines')) targets.push(lifecycleUpdate('openwebui-pipelines', '🪈 Pipelines'));\n if (has('hermes')) targets.push(lifecycleUpdate('hermes', '🧠 Hermes'));\n if (has('stalwart')) targets.push(lifecycleUpdate('stalwart', '📧 Stalwart Mail'));\n if (has('bulwark')) targets.push(lifecycleUpdate('bulwark', '✉️ Bulwark Webmail'));\n\n // Traefik can recreate its container on update; reconnect synap to\n // eve-network afterwards so cross-container DNS keeps working. (Done\n // here rather than in the lifecycle because eve-network reconnect is\n // a `eve update` orchestration concern, not a per-component one.)\n const traefikTarget = targets.find(t => t.id === 'traefik');\n if (traefikTarget) {\n const inner = traefikTarget.update;\n traefikTarget.update = async () => {\n await inner();\n const name = getSynapBackendContainer();\n if (name) connectToEveNetwork(name);\n };\n }\n\n // Eve Dashboard — rebuild the container image so UI changes from the\n // Eve CLI git pull land. Only added when the dashboard container is\n // currently running (i.e. it was installed with `eve add eve-dashboard`).\n if (dashboardIsRunning()) {\n targets.push({\n id: 'eve-dashboard',\n label: '📊 Eve Dashboard',\n update: async () => {\n const secrets = await readEveSecrets(process.cwd());\n const secret = secrets?.dashboard?.secret\n ?? randomBytes(24).toString('hex');\n installDashboardContainer({\n workspaceRoot: process.cwd(),\n secret,\n rebuild: true,\n });\n return { subLines: ['image rebuilt from updated source'] };\n },\n });\n }\n\n return targets;\n}\n\nasync function confirmDestructiveReset(): Promise<boolean> {\n const flags = getGlobalCliFlags();\n if (flags.nonInteractive) return true;\n\n const rl = createInterface({ input, output });\n try {\n const answer = await rl.question(\"Type 'recreate' to continue: \");\n return answer.trim() === 'recreate';\n } finally {\n rl.close();\n }\n}\n\nexport function backupUpdateCommands(program: Command): void {\n program\n .command('backup')\n .description('List Eve-related Docker volumes (full backup: stop stack + docker run volume export — see docs)')\n .action(async () => {\n try {\n const { stdout } = await execa('docker', ['volume', 'ls', '--format', '{{.Name}}']);\n const vols = stdout\n .split('\\n')\n .filter((n) => n.includes('eve') || n.includes('ollama') || n.includes('synap') || n.includes('openwebui'));\n if (vols.length === 0) {\n printInfo('No matching volumes found. Create the stack with eve brain init first.');\n return;\n }\n console.log(colors.primary.bold('Docker volumes (candidates for backup):\\n'));\n for (const v of vols) {\n console.log(` ${v}`);\n }\n printInfo('\\nTip: align volume backups with your synap-backend deploy backup process when on production.');\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n program\n .command('update')\n // `[components...]` accepts zero or more positional component IDs.\n // No args = update all. Args = scope to those components. This is the\n // most natural CLI shape and what the user expects from\n // `eve update openwebui`. `--only` is kept for backwards compat.\n .argument('[components...]', 'Component ids to update (omit to update all; `pod-admin` updates Synap)')\n .description('Update Eve components. Synap owns its bundled Pod Admin lifecycle, so `eve update pod-admin` updates the Data Pod safely.')\n .option('--only <organs>', 'Comma-separated organs to update (deprecated — use positional args)')\n .option('--skip <organs>', 'Comma-separated organs to skip, e.g. traefik')\n .action(async (components: string[] | undefined, opts: { only?: string; skip?: string }) => {\n // Use findPodDeployDir() — the canonical resolver used everywhere else\n // (preflight, doctor, lifecycle). It checks SYNAP_DEPLOY_DIR env var\n // first, then walks candidate paths including /opt/synap-backend/deploy\n // and /opt/synap-backend. The old hardcoded list missed the deploy/\n // subdirectory layout and couldn't be overridden without changing code.\n const deployDir = findPodDeployDir() ?? undefined;\n\n const targets = await buildUpdateTargets(deployDir);\n\n // Positional args take precedence over `--only`. If the user passes\n // both, positional wins (more specific intent).\n const positionalSet = components && components.length > 0\n ? new Set(components)\n : null;\n const only = positionalSet\n ?? (opts.only ? new Set(opts.only.split(',').map(s => s.trim())) : null);\n const podAdminRequested = normalizeSynapManagedUpdateTargets(only);\n if (podAdminRequested) {\n printInfo('Pod Admin is released with Synap; updating the Synap Data Pod.');\n }\n const skip = opts.skip ? new Set(opts.skip.split(',').map(s => s.trim())) : new Set<string>();\n if (normalizeSynapManagedUpdateTargets(skip)) {\n printInfo('Pod Admin cannot be updated separately; skipping it skips the Synap Data Pod.');\n }\n\n // Validate positional ids — fail fast on typos rather than silently\n // doing nothing when none of the args match a target.\n if (positionalSet) {\n const known = new Set(targets.map(t => t.id));\n const unknown = [...positionalSet].filter(id => !known.has(id));\n if (unknown.length > 0) {\n printError(`Unknown component(s): ${unknown.join(', ')}`);\n printInfo(` Available: ${[...known].join(', ')}`);\n process.exit(1);\n }\n }\n\n const toUpdate = targets.filter(t =>\n (!only || only.has(t.id)) && !skip.has(t.id),\n );\n\n if (toUpdate.length === 0) {\n printWarning('Nothing to update — filter excluded every target.');\n return;\n }\n\n console.log();\n console.log(colors.primary.bold('Eve Update'));\n console.log(colors.muted('─'.repeat(50)));\n\n const results: { label: string; ok: boolean; msg?: string }[] = [];\n\n for (const target of toUpdate) {\n const spinner = createSpinner(`Updating ${target.label}...`);\n spinner.start();\n try {\n const outcome = await target.update();\n spinner.succeed(`${target.label} updated`);\n // Render any post-update sub-lines (e.g. OpenClaw allowedOrigins\n // reconciliation) directly under the spinner row so the user\n // sees what self-heal happened. Quiet by default — only emits\n // when the lifecycle actually did something worth reporting.\n const subLines = outcome?.subLines ?? [];\n for (const line of subLines) {\n console.log(` ${colors.muted('↳')} ${colors.muted(line)}`);\n }\n results.push({ label: target.label, ok: true });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n // Warn with the headline; print the full multi-line context\n // (log tail from the lifecycle generator) directly afterwards\n // so the user can actually diagnose what went wrong rather\n // than seeing only \"compose up exited 1\".\n spinner.warn(`${target.label} — skipped (${msg.split('\\n')[0]})`);\n const remainder = msg.split('\\n').slice(1);\n if (remainder.length > 0) {\n for (const line of remainder) {\n console.log(` ${colors.muted('│')} ${line.trim()}`);\n }\n }\n results.push({ label: target.label, ok: false, msg });\n }\n }\n\n console.log();\n const failed = results.filter(r => !r.ok);\n if (failed.length === 0) {\n printSuccess('All organs updated.');\n } else {\n printWarning(`${results.filter(r => r.ok).length}/${results.length} updated. Skipped:`);\n for (const f of failed) {\n console.log(` ${colors.muted('→')} ${f.label}: ${colors.muted(f.msg?.split('\\n')[0] ?? '')}`);\n }\n }\n console.log();\n });\n\n program\n .command('recreate')\n .description('Full cleanup + full recreation (remove stale Docker data and rebuild stack)')\n .option('--no-prune', 'Skip docker system prune')\n .action(async (opts: { prune?: boolean }) => {\n try {\n console.log(colors.error.bold('\\n⚠️ Dangerous operation: full cleanup + recreation\\n'));\n console.log('This command will:');\n console.log(' - stop and remove all compose resources in the current directory');\n console.log(' - remove project volumes (data loss)');\n if (opts.prune !== false) {\n console.log(' - prune stale Docker containers/images/volumes/networks');\n }\n console.log('');\n\n const confirmed = await confirmDestructiveReset();\n if (!confirmed) {\n printInfo('Cancelled.');\n return;\n }\n\n printInfo('Stopping stack and removing compose resources...');\n await execa('docker', ['compose', 'down', '--volumes', '--remove-orphans'], { stdio: 'inherit' });\n\n if (opts.prune !== false) {\n printInfo('Pruning stale Docker resources...');\n await execa('docker', ['system', 'prune', '-a', '-f', '--volumes'], { stdio: 'inherit' });\n }\n\n printInfo('Recreating stack...');\n await execa('docker', ['compose', 'up', '-d'], { stdio: 'inherit' });\n printInfo('Done. Stack recreated from clean state.');\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n program\n .command('restart')\n .argument('[components...]', 'Component ids to restart (omit to restart all). E.g. `eve restart synap openwebui`')\n .description('Restart one or more Eve components without pulling new images.')\n .action(async (components: string[]) => {\n const knownIds = ['synap', 'ollama', 'openclaw', 'nango', 'rsshub', 'traefik', 'openwebui', 'openwebui-pipelines', 'hermes'];\n\n const toRestart = components.length > 0 ? components : knownIds;\n\n const unknown = toRestart.filter(id => !knownIds.includes(id));\n if (unknown.length > 0) {\n printError(`Unknown component(s): ${unknown.join(', ')}`);\n printInfo(` Available: ${knownIds.join(', ')}`);\n process.exit(1);\n }\n\n console.log();\n console.log(colors.primary.bold('Eve Restart'));\n console.log(colors.muted('─'.repeat(50)));\n\n for (const id of toRestart) {\n const spinner = createSpinner(`Restarting ${id}…`);\n spinner.start();\n try {\n const result = await runActionToCompletion(id, 'restart');\n if (result.ok) {\n spinner.succeed(`${id} restarted`);\n } else {\n spinner.warn(`${id} — ${result.error ?? 'not running or not installed'}`);\n }\n } catch (e) {\n spinner.warn(`${id} — ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n console.log();\n });\n}\n","/**\n * `eve purge` — wipe everything Eve manages so you can start from scratch.\n *\n * Removes in order:\n * 1. Eve-managed Docker containers (by name pattern)\n * 2. Synap backend Docker stack (compose down --volumes)\n * 3. Eve Docker volumes (matching eve/synap/ollama/openwebui/librechat patterns)\n * 4. Eve Docker networks (eve-network, hestia-network)\n * 5. Eve state files (~/.local/share/eve/, ~/.eve/)\n * 6. Deploy directories (/opt/synap-backend, /opt/openwebui, /opt/librechat)\n * 7. Optional: docker system prune -a (removes all unused images)\n *\n * The Eve CLI installation itself (/opt/eve) is NOT removed — use --self to include it.\n */\n\nimport type { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport { existsSync, rmSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\nimport { execa } from 'execa';\nimport { getGlobalCliFlags } from '@eve/cli-kit';\nimport {\n colors,\n printInfo,\n printSuccess,\n printWarning,\n printError,\n createSpinner,\n} from '../../lib/ui.js';\n\n// ---------------------------------------------------------------------------\n// Container / volume / network patterns\n// ---------------------------------------------------------------------------\n\n/** Name prefixes for Eve-managed containers */\nconst CONTAINER_PREFIXES = [\n 'eve-brain-',\n 'eve-arms-',\n 'eve-eyes-',\n 'eve-legs-',\n 'eve-builder-',\n 'hestia-',\n 'synap-backend-',\n];\n\n/** Volume name substrings to match */\nconst VOLUME_PATTERNS = ['eve', 'synap', 'ollama', 'openwebui', 'librechat'];\n\n/** Networks created by Eve */\nconst NETWORKS = ['eve-network', 'hestia-network'];\n\n/** Optional deploy directories to remove */\nconst DEPLOY_DIRS = [\n '/opt/synap-backend',\n '/opt/openwebui',\n '/opt/librechat',\n];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction listEveContainers(): string[] {\n try {\n const out = execSync('docker ps -a --format \"{{.Names}}\"', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n return out\n .split('\\n')\n .map(n => n.trim())\n .filter(n => n && CONTAINER_PREFIXES.some(prefix => n.startsWith(prefix)));\n } catch {\n return [];\n }\n}\n\nfunction listEveVolumes(): string[] {\n try {\n const out = execSync('docker volume ls --format \"{{.Name}}\"', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n return out\n .split('\\n')\n .map(n => n.trim())\n .filter(n => n && VOLUME_PATTERNS.some(p => n.includes(p)));\n } catch {\n return [];\n }\n}\n\nfunction listEveNetworks(): string[] {\n try {\n const out = execSync('docker network ls --format \"{{.Name}}\"', {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n return out\n .split('\\n')\n .map(n => n.trim())\n .filter(n => NETWORKS.includes(n));\n } catch {\n return [];\n }\n}\n\nasync function confirmPhrase(phrase: string): Promise<boolean> {\n const flags = getGlobalCliFlags();\n if (flags.nonInteractive) return true;\n const rl = createInterface({ input, output });\n try {\n const answer = await rl.question(` Type \"${phrase}\" to confirm: `);\n return answer.trim() === phrase;\n } finally {\n rl.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Purge implementation\n// ---------------------------------------------------------------------------\n\nexport interface PurgeOptions {\n /** Also run docker system prune -a to remove all unused images */\n images?: boolean;\n /** Also remove the Eve CLI installation directory (default: /opt/eve) */\n self?: boolean;\n /** Skip the confirmation prompt */\n yes?: boolean;\n /** Eve install dir (only used when --self) */\n eveDir?: string;\n}\n\nexport async function runPurge(opts: PurgeOptions = {}): Promise<void> {\n const flags = getGlobalCliFlags();\n const nonInteractive = Boolean(flags.nonInteractive) || Boolean(opts.yes);\n\n // -----------------------------------------------------------------\n // 1. Inventory\n // -----------------------------------------------------------------\n const containers = listEveContainers();\n const volumes = listEveVolumes();\n const networks = listEveNetworks();\n const stateDir = join(homedir(), '.local', 'share', 'eve');\n const skillsDir = join(homedir(), '.eve');\n const deployDirs = DEPLOY_DIRS.filter(d => existsSync(d));\n const eveDir = opts.eveDir ?? '/opt/eve';\n\n // -----------------------------------------------------------------\n // 2. Show what will be removed\n // -----------------------------------------------------------------\n console.log();\n console.log(colors.error.bold('⚠️ Eve Purge — complete wipe'));\n console.log(colors.muted('─'.repeat(50)));\n console.log();\n\n if (containers.length > 0) {\n console.log(colors.primary.bold(`Containers (${containers.length}):`));\n for (const c of containers) console.log(` ${colors.muted('•')} ${c}`);\n console.log();\n }\n\n if (volumes.length > 0) {\n console.log(colors.primary.bold(`Volumes (${volumes.length}):`));\n for (const v of volumes) console.log(` ${colors.muted('•')} ${v}`);\n console.log();\n }\n\n if (networks.length > 0) {\n console.log(colors.primary.bold(`Networks (${networks.length}):`));\n for (const n of networks) console.log(` ${colors.muted('•')} ${n}`);\n console.log();\n }\n\n const statePaths: string[] = [];\n if (existsSync(stateDir)) statePaths.push(stateDir);\n if (existsSync(skillsDir)) statePaths.push(skillsDir);\n if (statePaths.length > 0) {\n console.log(colors.primary.bold('State & config files:'));\n for (const p of statePaths) console.log(` ${colors.muted('•')} ${p}`);\n console.log();\n }\n\n if (deployDirs.length > 0) {\n console.log(colors.primary.bold('Deploy directories:'));\n for (const d of deployDirs) console.log(` ${colors.muted('•')} ${d}`);\n console.log();\n }\n\n if (opts.images) {\n console.log(colors.primary.bold('Docker images:'));\n console.log(` ${colors.muted('•')} All unused images (docker system prune -a)`);\n console.log();\n }\n\n if (opts.self && existsSync(eveDir)) {\n console.log(colors.primary.bold('Eve CLI installation:'));\n console.log(` ${colors.muted('•')} ${eveDir}`);\n console.log();\n }\n\n const nothingToDo =\n containers.length === 0 &&\n volumes.length === 0 &&\n networks.length === 0 &&\n statePaths.length === 0 &&\n deployDirs.length === 0 &&\n !opts.images &&\n !(opts.self && existsSync(eveDir));\n\n if (nothingToDo) {\n printInfo('Nothing to purge — environment looks clean.');\n return;\n }\n\n // -----------------------------------------------------------------\n // 3. Confirmation\n // -----------------------------------------------------------------\n if (!nonInteractive) {\n console.log(colors.warning('This operation is irreversible. All data in the listed volumes will be lost.'));\n console.log();\n const confirmed = await confirmPhrase('purge');\n if (!confirmed) {\n printInfo('Cancelled.');\n return;\n }\n console.log();\n }\n\n // -----------------------------------------------------------------\n // 4. Stop & remove containers\n // -----------------------------------------------------------------\n if (containers.length > 0) {\n const s = createSpinner(`Removing ${containers.length} container(s)...`);\n s.start();\n try {\n await execa('docker', ['rm', '-f', ...containers], { stdio: 'pipe' });\n s.succeed(`Removed ${containers.length} container(s)`);\n } catch (err) {\n s.warn(`Some containers could not be removed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`);\n }\n }\n\n // -----------------------------------------------------------------\n // 5. Tear down Synap backend compose stack (if deploy dir exists)\n // -----------------------------------------------------------------\n const synapDeployDir = ['/opt/synap-backend/deploy', process.env.SYNAP_DEPLOY_DIR]\n .filter(Boolean)\n .find(d => d && existsSync(join(d as string, 'docker-compose.yml')));\n\n if (synapDeployDir) {\n const s = createSpinner('Tearing down Synap backend compose stack...');\n s.start();\n try {\n await execa('docker', ['compose', 'down', '--volumes', '--remove-orphans'], {\n cwd: synapDeployDir,\n stdio: 'pipe',\n });\n s.succeed('Synap compose stack removed');\n } catch {\n s.warn('Synap compose down failed (stack may already be down)');\n }\n }\n\n // -----------------------------------------------------------------\n // 6. Remove volumes\n // -----------------------------------------------------------------\n const freshVolumes = listEveVolumes(); // re-query after compose down\n if (freshVolumes.length > 0) {\n const s = createSpinner(`Removing ${freshVolumes.length} volume(s)...`);\n s.start();\n const failed: string[] = [];\n for (const vol of freshVolumes) {\n try {\n await execa('docker', ['volume', 'rm', vol], { stdio: 'pipe' });\n } catch {\n failed.push(vol);\n }\n }\n if (failed.length === 0) {\n s.succeed(`Removed ${freshVolumes.length} volume(s)`);\n } else {\n s.warn(`Removed ${freshVolumes.length - failed.length}/${freshVolumes.length} volumes. In use: ${failed.join(', ')}`);\n }\n }\n\n // -----------------------------------------------------------------\n // 7. Remove networks\n // -----------------------------------------------------------------\n const freshNetworks = listEveNetworks();\n if (freshNetworks.length > 0) {\n const s = createSpinner('Removing Docker networks...');\n s.start();\n const failed: string[] = [];\n for (const net of freshNetworks) {\n try {\n await execa('docker', ['network', 'rm', net], { stdio: 'pipe' });\n } catch {\n failed.push(net);\n }\n }\n if (failed.length === 0) {\n s.succeed(`Removed networks: ${freshNetworks.join(', ')}`);\n } else {\n s.warn(`Could not remove: ${failed.join(', ')} (containers still attached?)`);\n }\n }\n\n // -----------------------------------------------------------------\n // 8. Remove state files\n // -----------------------------------------------------------------\n if (existsSync(stateDir)) {\n const s = createSpinner('Removing Eve state files...');\n s.start();\n try {\n rmSync(stateDir, { recursive: true, force: true });\n s.succeed(`Removed ${stateDir}`);\n } catch (err) {\n s.warn(`Could not remove ${stateDir}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n if (existsSync(skillsDir)) {\n const s = createSpinner('Removing Eve skills & config (~/.eve)...');\n s.start();\n try {\n rmSync(skillsDir, { recursive: true, force: true });\n s.succeed(`Removed ${skillsDir}`);\n } catch (err) {\n s.warn(`Could not remove ${skillsDir}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n // -----------------------------------------------------------------\n // 9. Remove deploy directories\n // -----------------------------------------------------------------\n for (const dir of deployDirs) {\n const s = createSpinner(`Removing ${dir}...`);\n s.start();\n try {\n rmSync(dir, { recursive: true, force: true });\n s.succeed(`Removed ${dir}`);\n } catch (err) {\n s.warn(`Could not remove ${dir}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n // -----------------------------------------------------------------\n // 10. Optional: docker system prune -a\n // -----------------------------------------------------------------\n if (opts.images) {\n const s = createSpinner('Pruning all unused Docker images...');\n s.start();\n try {\n await execa('docker', ['system', 'prune', '-a', '-f', '--volumes'], { stdio: 'pipe' });\n s.succeed('Docker system pruned (all unused images removed)');\n } catch (err) {\n s.warn(`docker system prune failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`);\n }\n }\n\n // -----------------------------------------------------------------\n // 11. Optional: remove Eve CLI itself\n // -----------------------------------------------------------------\n if (opts.self && existsSync(eveDir)) {\n const s = createSpinner(`Removing Eve CLI installation (${eveDir})...`);\n s.start();\n try {\n rmSync(eveDir, { recursive: true, force: true });\n s.succeed(`Removed ${eveDir}`);\n } catch (err) {\n s.warn(`Could not remove ${eveDir}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n // -----------------------------------------------------------------\n // Done\n // -----------------------------------------------------------------\n console.log();\n printSuccess('Purge complete. Your server is clean.');\n console.log();\n if (!opts.self) {\n printInfo('Eve CLI is still installed. To reinstall from scratch:');\n printInfo(' eve install');\n console.log();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Command registration\n// ---------------------------------------------------------------------------\n\nexport function purgeCommand(program: Command): void {\n program\n .command('purge')\n .description('Remove all Eve containers, volumes, networks, and state — clean slate for reinstall')\n .option('--images', 'Also remove all unused Docker images (docker system prune -a)')\n .option('--self', 'Also remove the Eve CLI installation directory (/opt/eve)')\n .option('--eve-dir <path>', 'Eve install directory (default: /opt/eve, only with --self)')\n .addHelpText('after', `\nExamples:\n eve purge # Remove containers, volumes, networks, state files\n eve purge --images # Also wipe all Docker image cache\n eve purge --self # Also remove /opt/eve (use when decommissioning the server)\n eve --yes purge # Non-interactive (skip confirmation prompt)\n\nWhat is NOT removed by default:\n /opt/eve # Eve CLI itself (use --self to include)\n Docker images # Pulled images stay cached (use --images to wipe)\n Other Docker resources # Only resources matching Eve naming patterns are removed\n`)\n .action(async (opts: { images?: boolean; self?: boolean; eveDir?: string }) => {\n try {\n await runPurge(opts);\n } catch (err) {\n printError(`Purge failed: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n });\n}\n","/**\n * `eve mode` — toggle stack-wide modes that touch more than one\n * component. Today: `multi-user`. Each mode flips a coordinated set of\n * env vars across two or more `.env` files and recreates the affected\n * containers via `@eve/lifecycle` so we don't reinvent `compose up`.\n *\n * Why this exists: synap-backend just shipped per-user sub-tokens\n * (HUB_PROTOCOL_SUB_TOKENS=true) and openwebui-pipelines started\n * honoring SYNAP_PER_USER_TOKENS=1 on the same release. The two flags\n * MUST move together — leaving one ON and one OFF gives a broken state\n * (pipeline mints sub-tokens that backend rejects, or backend issues\n * sub-tokens nobody uses). Editing two `.env` files by hand and\n * remembering to recreate two containers is a footgun, so we wrap it.\n *\n * Design notes:\n * - Idempotent: `on`/`off` skip the recreate step when both flags\n * already match the requested state. `eve mode multi-user on`\n * twice never spuriously bounces traffic.\n * - Atomic env writes via `@eve/lifecycle/writeEnvVar` so Ctrl-C\n * can't leave a half-written file.\n * - Container state-of-the-world reported by cross-checking the\n * `.env` file against `docker inspect` — drift means the file says\n * one thing but the running container has a different env (last\n * install was before the flag, or someone restarted instead of\n * `compose up -d` after editing). Status flags this loudly.\n * - Missing-component graceful: if openwebui-pipelines isn't\n * installed, flipping multi-user still updates the synap side and\n * warns. Symmetric for synap.\n * - We never call `docker` directly — recreate goes through\n * `runActionToCompletion(id, 'update')`, the same lifecycle path\n * `eve update` uses. Compose-based components run `compose up -d`,\n * which IS what re-reads the `.env` file. So the existing recreate\n * path already does the right thing for our env-file changes; no\n * new lifecycle hook needed.\n */\n\nimport { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n runActionToCompletion,\n readEnvVar,\n writeEnvVar,\n reconcileOpenclawConfig,\n} from '@eve/lifecycle';\nimport { entityStateManager, readEveSecrets } from '@eve/dna';\nimport {\n colors,\n printInfo,\n printSuccess,\n printWarning,\n printError,\n createSpinner,\n emojis,\n} from '../lib/ui.js';\n\n// ── multi-user mode definition ────────────────────────────────────────────────\n\ntype Strategy = 'first' | 'all' | 'none';\nconst STRATEGIES: readonly Strategy[] = ['first', 'all', 'none'] as const;\nconst DEFAULT_STRATEGY: Strategy = 'first';\n\ninterface ComponentSlot {\n /** Lifecycle component id (matches @eve/dna COMPONENTS). */\n id: string;\n /** User-facing label for printouts. */\n label: string;\n /** Resolved deploy dir holding the `.env` file. */\n resolveDeployDir: () => string | null;\n /** Container name to introspect for drift detection. */\n containerName: string;\n /** Env keys this slot owns for the multi-user flag. */\n flagKey: string;\n flagOn: string;\n flagOff: string;\n /** Optional secondary keys (e.g. strategy on synap). */\n extras?: ReadonlyArray<{ key: string; on: string; off: string | null }>;\n}\n\nfunction resolveSynapDeployDir(): string | null {\n const candidates = [process.env.SYNAP_DEPLOY_DIR, '/opt/synap-backend/deploy'];\n for (const d of candidates) {\n if (d && existsSync(join(d, 'docker-compose.yml'))) return d;\n }\n return null;\n}\n\nfunction resolvePipelinesDeployDir(): string | null {\n const dir = '/opt/openwebui-pipelines';\n return existsSync(join(dir, 'docker-compose.yml')) ? dir : null;\n}\n\n/**\n * Build the slot list for a given strategy. The strategy only affects\n * the synap-backend slot's `extras` (HUB_PROTOCOL_EXTERNAL_USER_WORKSPACE_STRATEGY).\n */\nfunction multiUserSlots(strategy: Strategy): ComponentSlot[] {\n return [\n {\n id: 'synap',\n label: '🧠 synap-backend',\n resolveDeployDir: resolveSynapDeployDir,\n containerName: 'synap-backend-backend-1',\n flagKey: 'HUB_PROTOCOL_SUB_TOKENS',\n flagOn: 'true',\n flagOff: 'false',\n extras: [\n {\n key: 'HUB_PROTOCOL_EXTERNAL_USER_WORKSPACE_STRATEGY',\n on: strategy,\n // When turning multi-user OFF we drop the strategy line so the\n // backend falls back to its compiled default and the file stays\n // tidy.\n off: null,\n },\n ],\n },\n {\n id: 'openwebui-pipelines',\n label: '🪈 openwebui-pipelines',\n resolveDeployDir: resolvePipelinesDeployDir,\n containerName: 'eve-openwebui-pipelines',\n flagKey: 'SYNAP_PER_USER_TOKENS',\n flagOn: '1',\n flagOff: '0',\n },\n ];\n}\n\ninterface SlotState {\n installed: boolean;\n deployDir: string | null;\n fileFlag: string | null;\n fileExtras: Record<string, string | null>;\n containerFlag: string | null;\n /** True if file says ON for the primary flag. */\n fileOn: boolean;\n /** True if container says ON for the primary flag (null = container missing). */\n containerOn: boolean | null;\n /** File and container disagree (drift). */\n drift: boolean;\n}\n\nasync function getInstalledIds(): Promise<Set<string>> {\n try {\n return new Set(await entityStateManager.getInstalledComponents());\n } catch {\n // state.json absent / unreadable — fall back to \"everything is\n // installed and let the deploy-dir check decide\". Better than\n // refusing to operate on a fresh server.\n return new Set(['synap', 'openwebui-pipelines']);\n }\n}\n\n/**\n * Read a single env var off a running container via `docker inspect`.\n * Returns null when the container isn't running, has no such env, or\n * docker isn't reachable. Quiet on failure — drift detection is a\n * nice-to-have.\n */\nfunction readContainerEnv(containerName: string, key: string): string | null {\n try {\n // Go template walks the env array and prints `KEY=VALUE` for our\n // match. Index format keeps it on one stdout line.\n const out = execSync(\n `docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' ${containerName}`,\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n );\n for (const line of out.split('\\n')) {\n const eq = line.indexOf('=');\n if (eq < 0) continue;\n if (line.slice(0, eq) === key) return line.slice(eq + 1);\n }\n return null;\n } catch {\n return null;\n }\n}\n\nasync function probeSlot(\n slot: ComponentSlot,\n installedIds: Set<string>,\n): Promise<SlotState> {\n const deployDir = slot.resolveDeployDir();\n // \"Installed\" here means \"the lifecycle thinks it's there OR the\n // deploy dir exists on disk\". State.json can lag; the deploy dir is\n // ground truth for whether `.env` writes will actually do anything.\n const installed = installedIds.has(slot.id) || !!deployDir;\n\n if (!installed || !deployDir) {\n return {\n installed: false,\n deployDir,\n fileFlag: null,\n fileExtras: {},\n containerFlag: null,\n fileOn: false,\n containerOn: null,\n drift: false,\n };\n }\n\n const fileFlag = readEnvVar(deployDir, slot.flagKey);\n const fileExtras: Record<string, string | null> = {};\n for (const e of slot.extras ?? []) {\n fileExtras[e.key] = readEnvVar(deployDir, e.key);\n }\n const containerFlag = readContainerEnv(slot.containerName, slot.flagKey);\n\n const fileOn = isTruthy(fileFlag);\n const containerOn = containerFlag === null ? null : isTruthy(containerFlag);\n const drift = containerOn !== null && containerOn !== fileOn;\n\n return {\n installed: true,\n deployDir,\n fileFlag,\n fileExtras,\n containerFlag,\n fileOn,\n containerOn,\n drift,\n };\n}\n\n/** Coerce a stringy env value to boolean. Mirrors backend + pipelines parse. */\nfunction isTruthy(value: string | null): boolean {\n if (value === null) return false;\n const v = value.trim().toLowerCase();\n return v === 'true' || v === '1' || v === 'yes' || v === 'on';\n}\n\nfunction fmtState(on: boolean | null): string {\n if (on === null) return colors.muted('—');\n return on ? colors.success('ON') : colors.muted('OFF');\n}\n\n// ── command actions ──────────────────────────────────────────────────────────\n\ninterface ActionOpts {\n strategy?: Strategy;\n}\n\nasync function modeStatus(strategy: Strategy): Promise<void> {\n const installed = await getInstalledIds();\n const slots = multiUserSlots(strategy);\n const states = await Promise.all(slots.map(s => probeSlot(s, installed)));\n\n console.log();\n console.log(colors.primary.bold('Eve Mode — multi-user'));\n console.log(colors.muted('─'.repeat(50)));\n\n for (let i = 0; i < slots.length; i++) {\n const slot = slots[i];\n const st = states[i];\n\n if (!st.installed) {\n console.log(` ${slot.label}: ${colors.muted('not installed')}`);\n continue;\n }\n\n const fileLine = `${slot.flagKey}=${st.fileFlag ?? colors.muted('(unset)')}`;\n const ctrLine = st.containerFlag === null\n ? colors.muted('(container not running)')\n : `${slot.flagKey}=${st.containerFlag}`;\n\n console.log(\n ` ${slot.label}: file=${fmtState(st.fileOn)} container=${fmtState(st.containerOn)}`,\n );\n console.log(` ${colors.muted('.env:')} ${fileLine}`);\n console.log(` ${colors.muted('inspect:')} ${ctrLine}`);\n\n for (const e of slot.extras ?? []) {\n const v = st.fileExtras[e.key];\n console.log(` ${colors.muted('.env:')} ${e.key}=${v ?? colors.muted('(unset)')}`);\n }\n\n if (st.drift) {\n printWarning(\n ` ${slot.label}: .env says ${st.fileOn ? 'ON' : 'OFF'} but the running container has it ${st.containerOn ? 'ON' : 'OFF'}. Run \\`eve mode multi-user ${st.fileOn ? 'on' : 'off'}\\` (or \\`eve update ${slot.id}\\`) to reconcile.`,\n );\n }\n }\n\n // Cross-component coherence check. Both must be ON or both OFF.\n const installedStates = states.filter(s => s.installed);\n if (installedStates.length === 2) {\n const [a, b] = installedStates;\n if (a.fileOn !== b.fileOn) {\n console.log();\n printWarning(\n 'Multi-user flags disagree: one component is ON and the other is OFF. ' +\n 'Sub-token issuance and consumption MUST move together. ' +\n 'Run `eve mode multi-user on` (or `off`) to bring them back in sync.',\n );\n }\n }\n\n console.log();\n}\n\ninterface SetResult {\n slotId: string;\n changed: boolean;\n /** True if we updated the file or extras (i.e. need a restart). */\n fileTouched: boolean;\n}\n\nfunction applyDesiredState(\n slot: ComponentSlot,\n state: SlotState,\n desired: boolean,\n): SetResult {\n if (!state.installed || !state.deployDir) {\n return { slotId: slot.id, changed: false, fileTouched: false };\n }\n\n let touched = false;\n let changed = false;\n\n const want = desired ? slot.flagOn : slot.flagOff;\n const r = writeEnvVar(state.deployDir, slot.flagKey, want);\n if (r.changed) {\n touched = true;\n changed = true;\n }\n\n for (const e of slot.extras ?? []) {\n const targetValue = desired ? e.on : e.off;\n const er = writeEnvVar(state.deployDir, e.key, targetValue);\n if (er.changed) touched = true;\n }\n\n // Drift forces a recreate even if the file matched. Without this,\n // `mode multi-user on` against a system whose container env is stale\n // would falsely report success.\n if (state.drift) touched = true;\n\n return { slotId: slot.id, changed, fileTouched: touched };\n}\n\nasync function modeSet(desired: boolean, opts: ActionOpts): Promise<void> {\n const strategy = opts.strategy ?? DEFAULT_STRATEGY;\n const installed = await getInstalledIds();\n const slots = multiUserSlots(strategy);\n const states = await Promise.all(slots.map(s => probeSlot(s, installed)));\n\n // Warn upfront if a component is missing — proceed anyway with the\n // ones that are installed.\n const installedSlots: { slot: ComponentSlot; state: SlotState }[] = [];\n for (let i = 0; i < slots.length; i++) {\n const slot = slots[i];\n const st = states[i];\n if (!st.installed) {\n printWarning(`${slot.label} is not installed — skipping (the other component will still be updated).`);\n } else {\n installedSlots.push({ slot, state: st });\n }\n }\n\n if (installedSlots.length === 0) {\n printError('Neither component is installed. Nothing to do.');\n process.exitCode = 1;\n return;\n }\n\n console.log();\n console.log(colors.primary.bold(`Eve Mode — multi-user ${desired ? 'on' : 'off'}`));\n console.log(colors.muted('─'.repeat(50)));\n\n // Step 1: update env files atomically.\n const writes: SetResult[] = [];\n for (const { slot, state } of installedSlots) {\n const r = applyDesiredState(slot, state, desired);\n writes.push(r);\n if (r.changed) {\n const verb = desired ? 'enabled' : 'disabled';\n printInfo(`${slot.label}: ${slot.flagKey} ${verb} (was ${state.fileFlag ?? 'unset'})`);\n } else if (r.fileTouched) {\n // Strategy changed but primary flag didn't — surface it so the\n // user understands why we still recreate.\n printInfo(`${slot.label}: extras updated, primary flag already ${desired ? 'ON' : 'OFF'}`);\n } else {\n printInfo(`${slot.label}: already ${desired ? 'ON' : 'OFF'} — no file change`);\n }\n }\n\n // Step 2: recreate containers whose env changed (or whose container\n // drifted from the file). Idempotent — no-op when nothing was touched.\n const toRecreate = writes.filter(w => w.fileTouched);\n if (toRecreate.length === 0) {\n console.log();\n printSuccess(`Already ${desired ? 'ON' : 'OFF'} — no containers needed to restart.`);\n console.log();\n return;\n }\n\n for (const w of toRecreate) {\n const slot = installedSlots.find(s => s.slot.id === w.slotId)!.slot;\n const spinner = createSpinner(`Recreating ${slot.label} to apply env changes...`);\n spinner.start();\n try {\n // `update` runs `compose up -d` for compose-based components, which\n // re-reads the .env file. Same path `eve update` uses — single\n // source of truth for the recreate orchestration.\n const result = await runActionToCompletion(slot.id, 'update');\n if (!result.ok) {\n const tail = result.logs.slice(-4).join('\\n');\n spinner.fail(`${slot.label} — recreate failed (${result.error ?? 'unknown'})`);\n if (tail) {\n for (const line of tail.split('\\n')) {\n console.log(` ${colors.muted('│')} ${line.trim()}`);\n }\n }\n process.exitCode = 1;\n } else {\n spinner.succeed(`${slot.label} restarted with new env`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n spinner.fail(`${slot.label} — recreate threw (${msg})`);\n process.exitCode = 1;\n }\n }\n\n // Step 3: re-probe and print a concise summary of effective state so\n // the user doesn't need to run `status` after every flip.\n console.log();\n const finalStates = await Promise.all(installedSlots.map(({ slot }) =>\n probeSlot(slot, installed),\n ));\n console.log(colors.primary.bold('Effective state'));\n for (let i = 0; i < installedSlots.length; i++) {\n const { slot } = installedSlots[i];\n const st = finalStates[i];\n console.log(\n ` ${slot.label}: file=${fmtState(st.fileOn)} container=${fmtState(st.containerOn)}`,\n );\n if (st.drift) {\n printWarning(` ${slot.label} still drifted — file and container disagree. Investigate.`);\n }\n }\n console.log();\n printSuccess(`Multi-user mode is now ${desired ? colors.success('ON') : colors.muted('OFF')}.`);\n console.log();\n}\n\nasync function modeStrategy(strategy: Strategy): Promise<void> {\n // Bare `--strategy` only makes sense for synap-backend (the routing\n // is backend-side). Pipelines doesn't have a strategy knob. So this\n // is a focused operation: write the strategy to synap's .env and\n // recreate ONLY when multi-user is currently ON (otherwise the value\n // sits dormant — perfectly fine, no restart).\n const installed = await getInstalledIds();\n const synapSlot = multiUserSlots(strategy)[0]; // index 0 = synap\n const state = await probeSlot(synapSlot, installed);\n\n if (!state.installed || !state.deployDir) {\n printError('synap-backend is not installed — cannot set strategy.');\n process.exitCode = 1;\n return;\n }\n\n const extras = synapSlot.extras ?? [];\n let touched = false;\n for (const e of extras) {\n const targetValue = state.fileOn ? e.on : e.off;\n const r = writeEnvVar(state.deployDir, e.key, targetValue);\n if (r.changed) {\n touched = true;\n printInfo(\n `${synapSlot.label}: ${e.key} = ${targetValue ?? '(removed)'} (was ${r.previous ?? 'unset'})`,\n );\n } else {\n printInfo(`${synapSlot.label}: ${e.key} already at desired value`);\n }\n }\n\n if (touched && state.fileOn) {\n const spinner = createSpinner(`Recreating ${synapSlot.label} to apply strategy change...`);\n spinner.start();\n try {\n const result = await runActionToCompletion(synapSlot.id, 'update');\n if (!result.ok) {\n spinner.fail(`${synapSlot.label} — recreate failed (${result.error ?? 'unknown'})`);\n process.exitCode = 1;\n } else {\n spinner.succeed(`${synapSlot.label} restarted with new strategy`);\n }\n } catch (err) {\n spinner.fail(`${synapSlot.label} — recreate threw (${err instanceof Error ? err.message : String(err)})`);\n process.exitCode = 1;\n }\n } else if (touched) {\n printInfo(\n 'Multi-user is currently OFF — strategy stored in .env but not applied to the container (no recreate). It will take effect next time you run `eve mode multi-user on`.',\n );\n } else {\n printInfo('No changes — strategy is already where you want it.');\n }\n}\n\n// ── reconcile-openclaw action ────────────────────────────────────────────────\n\ninterface ReconcileOpenclawOpts {\n /** Override the public domain. When undefined, falls back to secrets. */\n domain?: string;\n containerName?: string;\n configPath?: string;\n /** Restart the container if the file changed. Default true. */\n restart: boolean;\n}\n\n/**\n * One-shot reconciliation runner for `eve mode reconcile-openclaw`. The\n * heavy lifting lives in `@eve/lifecycle`'s `reconcileOpenclawConfig`; this\n * wrapper just resolves the domain from secrets when the user didn't pass\n * `--domain`, prints the structured result, and (optionally) restarts.\n *\n * Exits non-zero only on hard read/write failures inside the reconcile —\n * the no-op paths (container down, no domain configured) are reported as\n * INFO and exit clean. They're \"nothing to do\", not errors.\n */\nasync function runReconcileOpenclaw(opts: ReconcileOpenclawOpts): Promise<void> {\n // Resolve the domain. Explicit --domain wins; otherwise pull from secrets.\n // No domain at all is fine — the reconcile still merges localhost\n // origins and surfaces a note about the public side being skipped.\n let domain = opts.domain;\n if (!domain) {\n try {\n const secrets = await readEveSecrets();\n domain = secrets?.domain?.primary;\n } catch {\n // secrets.json missing/unreadable — proceed with no domain. The\n // reconcile fn already handles this path gracefully.\n }\n }\n\n console.log();\n console.log(colors.primary.bold('Eve Mode — reconcile-openclaw'));\n console.log(colors.muted('─'.repeat(50)));\n if (domain) {\n printInfo(`Public domain: ${domain} → https://openclaw.${stripScheme(domain)}`);\n } else {\n printInfo('No public domain configured — only localhost origins will be reconciled.');\n }\n\n const spinner = createSpinner('Reading OpenClaw config…');\n spinner.start();\n\n let result;\n try {\n result = await reconcileOpenclawConfig({\n domain,\n containerName: opts.containerName,\n configPath: opts.configPath,\n });\n } catch (err) {\n spinner.fail('reconcile threw');\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n return;\n }\n\n if (result.changed) {\n spinner.succeed('OpenClaw config updated');\n } else {\n spinner.succeed('OpenClaw config already in sync');\n }\n\n // Always print the notes — they describe the no-op cases (container\n // down, no domain) and the change description on the active path.\n for (const n of result.notes) {\n console.log(` ${colors.muted('↳')} ${n}`);\n }\n\n // Diff hint on the change path so the user can verify what landed.\n if (result.changed) {\n console.log();\n console.log(` ${colors.muted('before:')} ${formatOriginList(result.before.allowedOrigins)}`);\n console.log(` ${colors.muted('after: ')} ${formatOriginList(result.after.allowedOrigins)}`);\n }\n\n // Restart only when something actually changed AND the caller wants it.\n // The lifecycle's post-update hook does this automatically; this is the\n // explicit-CLI mirror.\n if (result.changed && opts.restart) {\n console.log();\n const rs = createSpinner(`Restarting ${opts.containerName ?? 'eve-arms-openclaw'} to apply…`);\n rs.start();\n try {\n execSync(`docker restart ${opts.containerName ?? 'eve-arms-openclaw'}`, {\n stdio: 'ignore',\n timeout: 15000,\n });\n rs.succeed('Container restarted');\n } catch (err) {\n rs.fail('docker restart failed');\n printWarning(err instanceof Error ? err.message : String(err));\n // Soft-fail: the file is correct, but the running process still has\n // the stale list. Tell the user the next step rather than throwing.\n printInfo(`Run \\`docker restart ${opts.containerName ?? 'eve-arms-openclaw'}\\` manually to apply.`);\n process.exitCode = 1;\n return;\n }\n } else if (result.changed && !opts.restart) {\n printInfo('--no-restart was set; the new origins will take effect on the next OpenClaw restart.');\n }\n\n console.log();\n if (result.changed) {\n printSuccess('Reconciliation complete.');\n } else {\n printSuccess('Nothing to do.');\n }\n console.log();\n}\n\nfunction stripScheme(host: string): string {\n return host\n .replace(/^https?:\\/\\//i, '')\n .replace(/\\/.*$/, '')\n .replace(/:\\d+$/, '');\n}\n\nfunction formatOriginList(origins: string[]): string {\n if (origins.length === 0) return colors.muted('(empty)');\n return origins.map(o => colors.primary(o)).join(', ');\n}\n\n// ── command registration ─────────────────────────────────────────────────────\n\nexport function modeCommands(program: Command): void {\n const mode = program.command('mode').description(`${emojis.sparkles} Toggle stack-wide modes (multi-user, reconcile-openclaw…)`);\n\n // ── reconcile-openclaw — one-shot config drift repair ─────────────────\n //\n // OpenClaw resets `gateway.controlUi.allowedOrigins` to localhost-only\n // every time it regenerates its auth token (e.g. after `eve update`,\n // image rebuild, or volume restore). The post-update lifecycle hook\n // already does this automatically, but we also expose it manually for:\n // - older installs that pre-date the self-heal hook\n // - drift after manual restarts that bypassed the lifecycle\n // - new public domains where the user wants to push the config without\n // redoing the full update cycle\n //\n // Idempotent — running it twice with no input changes leaves the file\n // alone the second time and reports `already in sync`.\n mode\n .command('reconcile-openclaw')\n .description('Re-add Eve\\'s expected entries to OpenClaw\\'s gateway.controlUi.allowedOrigins (idempotent).')\n .option('--domain <host>', 'Public domain to allow (default: secrets.domain.primary)')\n .option('--container <name>', 'OpenClaw container name', 'eve-arms-openclaw')\n .option('--config-path <path>', 'In-container path to openclaw.json', '/home/node/.openclaw/openclaw.json')\n .option('--no-restart', 'Skip the docker restart even when the file changed')\n .action(async (opts: {\n domain?: string;\n container?: string;\n configPath?: string;\n restart?: boolean;\n }) => {\n await runReconcileOpenclaw({\n domain: opts.domain,\n containerName: opts.container,\n configPath: opts.configPath,\n // Commander turns `--no-restart` into `restart: false`; default true.\n restart: opts.restart !== false,\n });\n });\n\n const mu = mode\n .command('multi-user')\n .description('Toggle per-user sub-tokens (HUB_PROTOCOL_SUB_TOKENS + SYNAP_PER_USER_TOKENS) across synap-backend and openwebui-pipelines.');\n\n mu.command('on')\n .description('Enable per-user sub-tokens on both components and recreate as needed.')\n .option('--strategy <strategy>', `Workspace assignment strategy (${STRATEGIES.join('|')})`, DEFAULT_STRATEGY)\n .action(async (opts: { strategy?: string }) => {\n const strategy = parseStrategy(opts.strategy);\n if (!strategy) return;\n await modeSet(true, { strategy });\n });\n\n mu.command('off')\n .description('Disable per-user sub-tokens on both components and recreate as needed.')\n .action(async () => {\n await modeSet(false, {});\n });\n\n mu.command('status')\n .description('Report multi-user mode state across components (file vs running container).')\n .action(async () => {\n // For status we only read; strategy default doesn't matter.\n await modeStatus(DEFAULT_STRATEGY);\n });\n\n // Allow `eve mode multi-user --strategy <s>` as a top-level form for\n // ergonomics — sets the synap strategy without flipping the mode.\n // Intentionally NOT mounted as a sub-command so the trio (on/off/status)\n // stays the primary surface in --help.\n mu.option('--strategy <strategy>', `Set HUB_PROTOCOL_EXTERNAL_USER_WORKSPACE_STRATEGY (${STRATEGIES.join('|')})`)\n .action(async (opts: { strategy?: string }) => {\n // Only fires when no sub-command (on/off/status) matched. Without\n // a flag, fall through to status to give the user something useful.\n if (!opts.strategy) {\n await modeStatus(DEFAULT_STRATEGY);\n return;\n }\n const s = parseStrategy(opts.strategy);\n if (!s) return;\n await modeStrategy(s);\n });\n}\n\nfunction parseStrategy(input: string | undefined): Strategy | null {\n if (!input) return DEFAULT_STRATEGY;\n if ((STRATEGIES as readonly string[]).includes(input)) return input as Strategy;\n printError(`Invalid strategy \"${input}\". Expected one of: ${STRATEGIES.join(', ')}`);\n process.exitCode = 1;\n return null;\n}\n","/**\n * `eve auth` — introspect, validate, and renew per-agent Synap keys.\n *\n * Synap mints a separate Hub Protocol key per `agentType` (eve, openclaw,\n * hermes, openwebui-pipelines, …). Each one has its own user, audit\n * trail, and scopes on the pod. Eve persists them under\n * `secrets.agents[agentType]`.\n *\n * Subcommands:\n * - `eve auth status [--agent <slug>]`\n * No flag → list every registered agent's status (one row per agent).\n * With flag → detailed view of that one agent (key prefix, user,\n * scopes, age, failure reason if any).\n * - `eve auth whoami [--agent <slug>]`\n * Tight one-liner. Defaults to the eve agent.\n * - `eve auth renew [--agent <slug>] [--all]`\n * Re-mint a key. `--all` walks the registry and renews each\n * provisioned agent. Default = eve.\n * - `eve auth provision`\n * Mint missing keys for every installed component's agent.\n * Useful after upgrading from a pre-per-agent install.\n *\n * Backwards compat: when no per-agent secrets exist yet but the legacy\n * `secrets.synap.apiKey` does, the default subject is the \"eve\" agent\n * — `writeAgentKey(\"eve\", …)` mirrors back into `synap.apiKey`, so the\n * single-key world stays seamless until first migration.\n */\n\nimport { Command } from 'commander';\nimport {\n ensurePodProvisioningToken,\n getAuthStatus,\n provisionAgent,\n provisionAllAgents,\n renewAgentKey,\n runActionToCompletion,\n runBackendPreflight,\n type AuthFailure,\n type AuthStatus,\n type ProvisionResult,\n} from '@eve/lifecycle';\nimport {\n AGENTS,\n entityStateManager,\n readAgentKey,\n readEveSecrets,\n resolveAgent,\n resolveSynapUrlOnHost,\n type AgentInfo,\n} from '@eve/dna';\nimport { runSynapCli } from '@eve/brain';\nimport { buildPodRunner } from '../lib/doctor-runners.js';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n createSpinner,\n} from '../lib/ui.js';\nimport { probeAdminStatus } from './setup-admin.js';\n\n// ---------------------------------------------------------------------------\n// Resolve pod URL + per-agent key\n// ---------------------------------------------------------------------------\n\ninterface ResolvedAgentConfig {\n agentType: string;\n agent: AgentInfo;\n synapUrl: string;\n apiKey: string;\n apiKeyPrefix: string;\n}\n\n/**\n * Poll the pod's /api/hub/setup/status endpoint until it returns a\n * parseable response — used as a Kratos-warmup signal in `runProvision`.\n *\n * The Hub Protocol's /setup/status handler internally calls\n * `checkKratosIdentity()` (an authenticated Kratos admin API call), so a\n * successful response confirms Kratos's admin listener is bound AND\n * reachable from the synap-backend container. That's the real \"ready\"\n * signal we need before probing admin status.\n *\n * Returns `true` on first valid response, `false` if the timeout fires\n * without one. Caller should warn-but-continue on `false` — the\n * downstream `probeAdminStatus()` will produce a clearer error.\n */\nasync function waitForKratosReady(podUrl: string, timeoutMs = 15_000): Promise<boolean> {\n const url = `${podUrl.replace(/\\/$/, '')}/api/hub/setup/status`;\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n try {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), 2000);\n const res = await fetch(url, { headers: { Accept: 'application/json' }, signal: ctrl.signal });\n clearTimeout(timer);\n if (res.ok) {\n const body = await res.json().catch(() => null) as { hasAdmin?: boolean; needsSetup?: boolean } | null;\n if (body && (typeof body.hasAdmin === 'boolean' || typeof body.needsSetup === 'boolean')) {\n return true;\n }\n }\n } catch {\n // transport error / abort — keep polling\n }\n await new Promise(r => setTimeout(r, 500));\n }\n return false;\n}\n\n/**\n * Resolve config for one agent. Returns `null` when the pod URL is\n * unconfigured or no key exists for this agent (and no legacy fallback\n * applies).\n */\nasync function resolveAgentConfig(\n agentType: string,\n): Promise<ResolvedAgentConfig | null> {\n const agent = resolveAgent(agentType);\n if (!agent) return null;\n\n const secrets = await readEveSecrets(process.cwd());\n // On-host: prefer the loopback published by Eve's compose override.\n // Off-host: this transparently falls back to the public URL.\n const synapUrl = await resolveSynapUrlOnHost(secrets);\n if (!synapUrl) return null;\n\n // Per-agent key first, then fall back to the legacy single-key field\n // ONLY for the eve agent (so older installs keep working until they\n // migrate). Other agents have no legacy fallback — they need their\n // own key minted via `eve auth provision`.\n const perAgent = await readAgentKey(agentType, process.cwd());\n let apiKey = perAgent?.hubApiKey?.trim() ?? '';\n if (!apiKey && agentType === 'eve') {\n apiKey = secrets?.synap?.apiKey?.trim() ?? '';\n }\n if (!apiKey) return null;\n\n return {\n agentType,\n agent,\n synapUrl,\n apiKey,\n apiKeyPrefix: apiKey.slice(0, 8),\n };\n}\n\n// Auth UI is concise — discard the transport note. `eve doctor` is the\n// place for verbose runner reporting.\nconst buildRunner = () => buildPodRunner();\n\n// ---------------------------------------------------------------------------\n// `eve auth status` — list-or-detail\n// ---------------------------------------------------------------------------\n\ninterface StatusOptions {\n agent?: string;\n}\n\nasync function runStatus(opts: StatusOptions): Promise<void> {\n console.log();\n printHeader(opts.agent ? `Synap auth status — ${opts.agent}` : 'Synap auth status');\n console.log();\n\n if (opts.agent) {\n const targeted = resolveAgent(opts.agent);\n if (!targeted) {\n printError(`Unknown agent: ${opts.agent}.`);\n printInfo(`Available: ${AGENTS.map((a) => a.agentType).join(', ')}`);\n process.exitCode = 1;\n return;\n }\n await renderAgentDetail(targeted);\n console.log();\n return;\n }\n\n // No `--agent` → table of every registered agent's status.\n const cwd = process.cwd();\n const secrets = await readEveSecrets(cwd);\n const synapUrl = await resolveSynapUrlOnHost(secrets);\n if (!synapUrl) {\n printWarning('skipped — synap not configured.');\n printInfo('Fix: re-run `eve install` or set domain.primary in secrets.json.');\n console.log();\n return;\n }\n printInfo(`Pod: ${colors.info(synapUrl)}`);\n console.log();\n\n const runner = buildRunner();\n for (const agent of AGENTS) {\n const cfg = await resolveAgentConfig(agent.agentType);\n if (!cfg) {\n console.log(\n ` ${colors.muted(emojis.warning)} ${agent.label.padEnd(22)} ${colors.muted('(no key — run `eve auth provision`)')}`,\n );\n continue;\n }\n const result = await getAuthStatus({\n synapUrl: cfg.synapUrl,\n apiKey: cfg.apiKey,\n runner,\n });\n if (result.ok) {\n const s = result.status;\n const userTag = s.userEmail ?? s.userId.slice(0, 8);\n console.log(\n ` ${colors.success(emojis.check)} ${agent.label.padEnd(22)} ${cfg.apiKeyPrefix}… ${colors.muted(`${userTag}, ${s.scopes.length} scope${s.scopes.length === 1 ? '' : 's'}, ${s.ageDays}d old`)}`,\n );\n } else {\n console.log(\n ` ${colors.error(emojis.cross)} ${agent.label.padEnd(22)} ${cfg.apiKeyPrefix}… ${colors.error(result.failure.reason)} — ${colors.muted(result.failure.message)}`,\n );\n }\n }\n console.log();\n printInfo(`Run \\`eve auth status --agent <slug>\\` for details, or \\`eve auth renew --agent <slug>\\` to fix.`);\n console.log();\n}\n\nasync function renderAgentDetail(agent: AgentInfo): Promise<void> {\n const cfg = await resolveAgentConfig(agent.agentType);\n if (!cfg) {\n printInfo(` Pod: ${colors.muted('(checked secrets.json)')}`);\n printInfo(` Key: ${colors.muted('(none registered for this agent)')}`);\n console.log();\n printWarning(`No key for agent \"${agent.agentType}\".`);\n printInfo('Fix: `eve auth provision` (mints any missing agent keys).');\n return;\n }\n\n const spinner = createSpinner(`Querying ${cfg.synapUrl}/api/hub/auth/status…`);\n spinner.start();\n const result = await getAuthStatus({\n synapUrl: cfg.synapUrl,\n apiKey: cfg.apiKey,\n runner: buildRunner(),\n });\n spinner.succeed('Auth check complete');\n\n console.log();\n console.log(` ${colors.muted('Pod:'.padEnd(11))} ${colors.info(cfg.synapUrl)} ${colors.muted('(resolved via domain config)')}`);\n console.log(` ${colors.muted('Agent:'.padEnd(11))} ${cfg.agentType} ${colors.muted(`(${agent.description})`)}`);\n console.log(` ${colors.muted('Key:'.padEnd(11))} ${cfg.apiKeyPrefix}… ${colors.muted('(prefix shown)')}`);\n\n if (result.ok) {\n renderActiveStatus(result.status);\n } else {\n renderFailure(result.failure, agent.agentType);\n }\n}\n\nfunction renderActiveStatus(s: AuthStatus): void {\n const userLine = s.userEmail ? `${s.userId.slice(0, 8)} (${s.userEmail})` : s.userId.slice(0, 8);\n console.log(` ${colors.muted('User:'.padEnd(11))} ${userLine}`);\n if (s.name) {\n console.log(` ${colors.muted('Name:'.padEnd(11))} ${s.name}`);\n }\n const scopes = s.scopes.length > 0 ? s.scopes.join(', ') : colors.muted('(none)');\n console.log(` ${colors.muted('Scopes:'.padEnd(11))} ${scopes}`);\n console.log(` ${colors.muted('Age:'.padEnd(11))} ${s.ageDays} day${s.ageDays === 1 ? '' : 's'}`);\n if (s.lastUsedAt) {\n console.log(` ${colors.muted('Last seen:'.padEnd(11))} ${s.lastUsedAt}`);\n }\n if (s.expiresAt) {\n console.log(` ${colors.muted('Expires:'.padEnd(11))} ${s.expiresAt}`);\n }\n console.log(` ${colors.muted('Status:'.padEnd(11))} ${colors.success(`${emojis.check} active`)}`);\n}\n\nfunction renderFailure(failure: AuthFailure, agentType: string): void {\n const { reason, message, missingScope } = failure;\n console.log(\n ` ${colors.muted('Status:'.padEnd(11))} ${colors.error(`${emojis.cross} ${reason}`)} — ${message}`,\n );\n\n // Per-reason fix hint (mirrors the diagnostics module so the hints stay\n // identical between `eve doctor` and `eve auth status`).\n let fix: string | null = null;\n switch (reason) {\n case 'key_revoked':\n case 'expired':\n fix = `eve auth renew --agent ${agentType}`;\n break;\n case 'invalid_format':\n fix = `Re-run \\`eve install\\` or \\`eve auth renew --agent ${agentType}\\``;\n break;\n case 'no_auth':\n fix = `eve auth provision`;\n break;\n case 'missing_scope':\n fix = missingScope\n ? `Re-mint with required scopes (eve auth renew --agent ${agentType})`\n : `Re-mint with required scopes (eve auth renew --agent ${agentType})`;\n break;\n case 'backend_unhealthy':\n fix = 'docker logs synap-backend-backend-1 --tail 50';\n break;\n case 'transport':\n fix = 'Check the Synap container is running (eve doctor)';\n break;\n default:\n fix = null;\n }\n if (fix) {\n console.log(` ${colors.muted('Fix:'.padEnd(11))} ${colors.info(fix)}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// `eve auth whoami`\n// ---------------------------------------------------------------------------\n\nasync function runWhoami(opts: { agent?: string }): Promise<void> {\n const agentType = opts.agent ?? 'eve';\n const cfg = await resolveAgentConfig(agentType);\n if (!cfg) {\n printError(\n `No key for agent \"${agentType}\". Run \\`eve auth provision\\` to mint missing keys.`,\n );\n process.exitCode = 1;\n return;\n }\n const result = await getAuthStatus({\n synapUrl: cfg.synapUrl,\n apiKey: cfg.apiKey,\n runner: buildRunner(),\n });\n if (!result.ok) {\n printError(`auth failed for ${agentType} (${result.failure.reason}): ${result.failure.message}`);\n process.exitCode = 1;\n return;\n }\n const s = result.status;\n const tag = s.userEmail ? `${s.userId.slice(0, 8)} <${s.userEmail}>` : s.userId.slice(0, 8);\n console.log(\n `${colors.success(emojis.check)} ${agentType} → ${tag} ${colors.muted(`(${s.scopes.length} scope${s.scopes.length === 1 ? '' : 's'}, key age ${s.ageDays}d, prefix ${cfg.apiKeyPrefix}…)`)}`,\n );\n}\n\n// ---------------------------------------------------------------------------\n// `eve auth renew` — re-mint one or all agent keys\n// ---------------------------------------------------------------------------\n\ninterface RenewOptions {\n agent?: string;\n all?: boolean;\n /** Skip the auto-restart of openwebui-pipelines after a successful eve renew. */\n skipPipelinesRestart?: boolean;\n}\n\nasync function runRenew(opts: RenewOptions): Promise<void> {\n console.log();\n printHeader('Synap auth renew');\n console.log();\n\n if (opts.all) {\n await runRenewAll();\n return;\n }\n\n const agentType = opts.agent ?? 'eve';\n const targeted = resolveAgent(agentType);\n if (!targeted) {\n printError(`Unknown agent: ${agentType}.`);\n printInfo(`Available: ${AGENTS.map((a) => a.agentType).join(', ')}`);\n process.exitCode = 1;\n return;\n }\n\n const cfg = await resolveAgentConfig(agentType);\n const previousPrefix = cfg?.apiKeyPrefix ?? '(none)';\n\n printInfo(`Agent: ${agentType} (${targeted.label})`);\n if (cfg) {\n printInfo(`Pod: ${cfg.synapUrl}`);\n printInfo(`Previous key: ${previousPrefix}…`);\n } else {\n printInfo(`Pod: ${colors.muted('(resolving from secrets…)')}`);\n }\n console.log();\n\n const spinner = createSpinner(`Calling POST /api/hub/setup/agent (agentType=${agentType})…`);\n spinner.start();\n const result = await renewAgentKey({\n deployDir: process.cwd(),\n agentType,\n reason: 'manual',\n runner: buildRunner(),\n });\n if (!result.renewed) {\n spinner.fail('Renew failed');\n printError(result.reason);\n console.log();\n printInfo(\n 'Common causes:\\n' +\n ' • PROVISIONING_TOKEN unavailable — set EVE_PROVISIONING_TOKEN=<token> and retry.\\n' +\n \" The token lives in your synap-backend's deploy/.env on the pod host.\\n\" +\n ' • Backend version too old — run `eve update synap`.\\n' +\n ' • Network: pod unreachable from this host (`eve doctor`).',\n );\n process.exitCode = 1;\n return;\n }\n spinner.succeed(`Renewed ${agentType} agent key — new prefix ${result.keyIdPrefix}…`);\n\n console.log();\n printSuccess(\n `Renewed ${agentType} agent key (was ${previousPrefix}…, now ${result.keyIdPrefix}…)`,\n );\n printInfo(' secrets.json updated atomically.');\n\n // Pipelines restart only matters when the eve agent was renewed —\n // its key mirrors back into the legacy `synap.apiKey` field that\n // older pipelines wiring reads. Renewing openclaw / hermes /\n // pipelines-the-agent doesn't change that field, so no restart needed.\n if (agentType === 'eve' && !opts.skipPipelinesRestart) {\n console.log();\n const rs = createSpinner('Restarting openwebui-pipelines to pick up the new key…');\n rs.start();\n try {\n const r = await runActionToCompletion('openwebui-pipelines', 'update');\n if (r.ok) {\n rs.succeed('openwebui-pipelines refreshed');\n } else {\n rs.warn('openwebui-pipelines not refreshed (component may not be installed)');\n if (r.error && !r.error.includes('No update path')) {\n printInfo(` ${colors.muted(r.error)}`);\n }\n }\n } catch (err) {\n rs.warn('openwebui-pipelines refresh threw — restart manually if needed');\n printInfo(` ${colors.muted(err instanceof Error ? err.message : String(err))}`);\n }\n } else if (agentType === 'eve' && opts.skipPipelinesRestart) {\n printInfo('Skipping pipelines restart (--no-pipelines-restart).');\n printInfo(' Run `eve update openwebui-pipelines` to apply the new key downstream.');\n }\n console.log();\n}\n\nasync function runRenewAll(): Promise<void> {\n printInfo('Renewing every provisioned agent key…');\n console.log();\n\n const installed = await entityStateManager\n .getInstalledComponents()\n .catch(() => [] as string[]);\n\n const spinner = createSpinner(`Walking ${AGENTS.length} agents in registry order…`);\n spinner.start();\n const results = await provisionAllAgents({\n installedComponentIds: installed,\n deployDir: process.cwd(),\n reason: 'renew-all',\n skipIfPresent: false,\n runner: buildRunner(),\n });\n spinner.succeed(`Walked ${results.length} agents`);\n\n console.log();\n renderProvisionResults(results);\n console.log();\n\n const failures = results.filter((r) => !r.provisioned);\n if (failures.length > 0) {\n process.exitCode = 1;\n }\n}\n\n// ---------------------------------------------------------------------------\n// `eve auth provision` — mint missing agent keys\n// ---------------------------------------------------------------------------\n\nasync function runProvision(opts: { agent?: string; email?: string; force?: boolean }): Promise<void> {\n console.log();\n printHeader('Synap auth provision');\n console.log();\n\n // ------------------------------------------------------------------\n // Preflight: auto-discover and configure every prerequisite so the\n // operator doesn't have to manually set up secrets.json, compose\n // overrides, or PROVISIONING_TOKEN before running this command.\n // ------------------------------------------------------------------\n const preflightSpinner = createSpinner('Checking prerequisites…');\n preflightSpinner.start();\n\n let synapUrl: string;\n let provisioningToken: string;\n try {\n const preflight = await runBackendPreflight({ cwd: process.cwd() });\n synapUrl = preflight.synapUrl;\n provisioningToken = preflight.provisioningToken;\n if (preflight.configured || preflight.notes.length > 0) {\n preflightSpinner.succeed('Prerequisites ready (auto-configured)');\n for (const note of preflight.notes) {\n printInfo(` ${note}`);\n }\n console.log();\n } else {\n preflightSpinner.succeed('Prerequisites ready');\n }\n } catch (err) {\n preflightSpinner.fail('Preflight failed');\n printError(err instanceof Error ? err.message : String(err));\n console.log();\n printInfo('Run `eve setup` to initialise Eve on this server from scratch.');\n process.exitCode = 1;\n return;\n }\n\n // ------------------------------------------------------------------\n // Ensure Kratos is running. The synap CLI's `start kratos` is idempotent —\n // brings up the kratos service if it isn't already, no-ops if it is. For\n // a stale schema or new image, the operator runs `eve update synap`.\n // ------------------------------------------------------------------\n printInfo('Ensuring Kratos is running…');\n const kratosStart = runSynapCli('start', ['kratos']);\n if (!kratosStart.ok) {\n printWarning(`Could not start Kratos via synap CLI (exit ${kratosStart.exitCode}). Run \\`eve update synap\\` to reconcile.`);\n } else {\n printSuccess('Kratos container started');\n }\n\n // Warmup wait: `synap CLI start kratos` returns when the docker compose\n // command finishes — i.e., \"container created/restarted\", NOT \"admin API\n // listening.\" If we call `probeAdminStatus()` immediately, Kratos's HTTP\n // listener hasn't bound yet, `checkKratosIdentity()` throws inside the\n // synap-backend, the try/catch returns false, and the probe wrongly says\n // \"no admin.\" Poll the pod's /api/hub/setup/status (which internally\n // exercises Kratos) until it returns a parseable response — that's our\n // end-to-end ready signal. Capped at 15s; on failure we continue anyway\n // so the downstream probe gets to surface its own clearer error.\n const kratosWaited = await waitForKratosReady(synapUrl, 15_000);\n if (kratosWaited) {\n printSuccess('Kratos admin API ready');\n } else {\n printWarning('Kratos admin API did not become ready within 15s — continuing; downstream checks may misreport admin status.');\n }\n\n // ------------------------------------------------------------------\n // Refuse to provision agents on a pod that has no admin yet.\n // Admin creation is its own command — `eve setup admin` — so each\n // step has a single clear responsibility.\n // ------------------------------------------------------------------\n const adminStatus = await probeAdminStatus();\n if (adminStatus === 'needed') {\n printError('No admin account on this pod yet.');\n printInfo(' Run: eve setup admin');\n printInfo(' Then re-run: eve auth provision');\n process.exitCode = 1;\n return;\n }\n if (adminStatus === 'unknown') {\n printWarning('Could not verify admin status (synap CLI returned no result).');\n printInfo(' Continuing anyway — provision will fail clearly if admin is actually missing.');\n }\n\n if (opts.agent) {\n const targeted = resolveAgent(opts.agent);\n if (!targeted) {\n printError(`Unknown agent: ${opts.agent}.`);\n printInfo(`Available: ${AGENTS.map((a) => a.agentType).join(', ')}`);\n process.exitCode = 1;\n return;\n }\n\n // Guard: if a key already exists for this agent, require --force to\n // re-mint (which revokes the old key). Without this, running\n // `eve auth provision --agent eve` silently rotates a perfectly good key.\n if (!opts.force) {\n const { readAgentKey } = await import('@eve/dna');\n const existing = await readAgentKey(opts.agent);\n if (existing?.hubApiKey) {\n printInfo(`${opts.agent} is already provisioned (key prefix ${(existing.keyId ?? existing.hubApiKey).slice(0, 8)}…).`);\n printInfo(`To re-mint and revoke the existing key, add --force.`);\n console.log();\n return;\n }\n }\n\n const spinner = createSpinner(`Provisioning ${opts.agent}…`);\n spinner.start();\n const result = await provisionAgent({\n agentType: opts.agent,\n deployDir: process.cwd(),\n reason: opts.force ? 'manual-provision-force' : 'manual-provision',\n runner: buildRunner(),\n synapUrl,\n provisioningToken,\n });\n if (result.provisioned) {\n spinner.succeed(`Provisioned ${opts.agent} (key prefix ${result.keyIdPrefix}…)`);\n } else {\n spinner.fail(`Provision failed: ${result.reason}`);\n process.exitCode = 1;\n }\n console.log();\n return;\n }\n\n const installed = await entityStateManager\n .getInstalledComponents()\n .catch(() => [] as string[]);\n\n const spinner = createSpinner('Provisioning every installed agent…');\n spinner.start();\n const results = await provisionAllAgents({\n installedComponentIds: installed,\n deployDir: process.cwd(),\n reason: 'manual-provision',\n skipIfPresent: true,\n runner: buildRunner(),\n synapUrl,\n provisioningToken,\n });\n spinner.succeed(`Walked ${results.length} agent${results.length === 1 ? '' : 's'}`);\n\n console.log();\n renderProvisionResults(results);\n console.log();\n\n const failures = results.filter((r) => !r.provisioned);\n if (failures.length > 0) {\n printWarning(\n `${failures.length} agent${failures.length === 1 ? '' : 's'} failed to provision — see reasons above.`,\n );\n // Surface the actionable hint that matches the actual failure pattern.\n const allOld = failures.every((r) => r.reason.includes('backend version too old'));\n const allToken = failures.every((r) =>\n r.reason.includes('PROVISIONING_TOKEN') || r.reason.includes('401') || r.reason.includes('403'),\n );\n if (allOld) {\n printInfo('Fix: run `eve update synap` to update the backend, then retry `eve auth provision`.');\n } else if (allToken) {\n printInfo('Fix: ensure PROVISIONING_TOKEN is set in /opt/synap-backend/.env, then retry.');\n } else {\n printInfo('Common causes:');\n printInfo(' • Backend outdated → `eve update synap`');\n printInfo(' • PROVISIONING_TOKEN missing → check /opt/synap-backend/.env');\n printInfo(' • Backend unreachable → `eve doctor`');\n }\n process.exitCode = 1;\n } else {\n printSuccess('All agents provisioned.');\n }\n}\n\nfunction renderProvisionResults(results: ProvisionResult[]): void {\n for (const r of results) {\n if (r.provisioned) {\n if (r.wasAlreadyPresent) {\n console.log(\n ` ${colors.muted('–')} ${r.agentType.padEnd(22)} ${colors.muted(`already provisioned (${r.keyIdPrefix}…)`)}`,\n );\n } else {\n console.log(\n ` ${colors.success(emojis.check)} ${r.agentType.padEnd(22)} ${r.keyIdPrefix}… ${colors.muted(`(user ${r.record.agentUserId.slice(0, 8)}, ws ${r.record.workspaceId?.slice(0, 8) ?? 'none'})`)}`,\n );\n }\n } else {\n console.log(\n ` ${colors.error(emojis.cross)} ${r.agentType.padEnd(22)} ${colors.error('failed')} ${colors.muted(r.reason)}`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Command registration\n// ---------------------------------------------------------------------------\n\nexport function authCommand(program: Command): void {\n const auth = program\n .command('auth')\n .description(`${emojis.sparkles} Inspect, validate, and renew per-agent Synap API keys`);\n\n auth\n .command('status')\n .description(\n 'Show current key state for every agent (or one with --agent). ' +\n 'Lists prefix, user, scopes, age, and any failure reason.',\n )\n .option(\n '--agent <slug>',\n 'Restrict to one agent (eve, openclaw, hermes, openwebui-pipelines, coder).',\n )\n .action(async (opts: StatusOptions) => {\n try {\n await runStatus(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n auth\n .command('whoami')\n .description('Tight one-liner — user, scopes count, key prefix.')\n .option('--agent <slug>', 'Which agent to introspect. Defaults to \"eve\".')\n .action(async (opts: { agent?: string }) => {\n try {\n await runWhoami(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n auth\n .command('renew')\n .description(\n 'Re-mint an agent API key via POST /api/hub/setup/agent and atomically update secrets.json.',\n )\n .option('--agent <slug>', 'Which agent to renew. Defaults to \"eve\".')\n .option('--all', 'Renew every registered agent key in registry order.')\n .option(\n '--no-pipelines-restart',\n 'Skip the auto-restart of openwebui-pipelines after a successful eve renew.',\n )\n .action(async (opts: { agent?: string; all?: boolean; pipelinesRestart?: boolean }) => {\n // Commander turns `--no-pipelines-restart` into `pipelinesRestart: false`.\n const skipPipelinesRestart = opts.pipelinesRestart === false;\n try {\n await runRenew({ agent: opts.agent, all: opts.all, skipPipelinesRestart });\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n auth\n .command('provision')\n .description(\n 'Mint missing agent keys for every installed component (and the always-on eve agent). ' +\n 'Idempotent — skips agents that already have a key. ' +\n 'If no admin account exists yet, runs first-admin setup automatically.',\n )\n .option('--agent <slug>', 'Provision a specific agent only.')\n .option(\n '--email <email>',\n 'Admin email for first-admin setup (prompt mode). Omit to use magic-link mode.',\n )\n .option(\n '--force',\n 'Re-mint even if a key already exists (revokes the old key). Only applies with --agent.',\n )\n .action(async (opts: { agent?: string; email?: string; force?: boolean }) => {\n try {\n await runProvision(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n auth\n .command('token')\n .description(\n 'Print the Eve dashboard admin key. Enter this in the dashboard onboarding ' +\n 'page (or Settings → Admin) to unlock admin features.',\n )\n .action(async () => {\n try {\n const secrets = await readEveSecrets(process.cwd());\n const adminToken = (secrets as { dashboard?: { adminToken?: string } } | null)\n ?.dashboard?.adminToken;\n if (!adminToken) {\n printWarning('No admin key found in secrets.json.');\n printInfo('The key is generated automatically on the first dashboard login.');\n printInfo('If you have not logged in yet, visit the dashboard and sign in first.');\n process.exitCode = 1;\n return;\n }\n console.log();\n printHeader('Eve dashboard admin key');\n console.log();\n console.log(` ${colors.info(adminToken)}`);\n console.log();\n printInfo('Paste this into the dashboard onboarding page or Settings → Admin.');\n console.log();\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n auth\n .command('bootstrap-token')\n .description(\n 'Ensure the pod has a working PROVISIONING_TOKEN. Generates one if ' +\n 'missing/empty, writes it to the pod\\'s deploy/.env, and restarts ' +\n 'the backend so it loads the new value. Idempotent — a no-op if a ' +\n 'real token already exists.',\n )\n .action(async () => {\n console.log();\n printHeader('Synap PROVISIONING_TOKEN bootstrap');\n console.log();\n const spinner = createSpinner('Resolving pod state…');\n spinner.start();\n try {\n const result = await ensurePodProvisioningToken();\n if (result.source === 'existing') {\n spinner.succeed('PROVISIONING_TOKEN already set — no change');\n printInfo(`Run \\`eve auth provision\\` to mint agent keys.`);\n } else {\n spinner.succeed(\n `Generated PROVISIONING_TOKEN and wrote it to ${result.writtenTo ?? '<pod>/.env'}`,\n );\n if (result.backendRestarted) {\n printInfo('Backend restarted — agent provisioning is now unblocked.');\n printInfo('Next: `eve auth provision`');\n } else {\n printWarning(\n 'Backend was not restarted (compose unavailable). The token is on disk; ' +\n 'restart synap-backend manually then run `eve auth provision`.',\n );\n }\n }\n } catch (err) {\n spinner.fail(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n console.log();\n });\n}\n","import { Command } from 'commander';\nimport { execa } from 'execa';\nimport { OllamaService, ModelService } from '@eve/brain';\nimport { getGlobalCliFlags, outputJson } from '@eve/cli-kit';\nimport {\n readEveSecrets,\n writeEveSecrets,\n entityStateManager,\n resolveHubBaseUrl,\n resolveSynapUrl,\n readAgentKeyOrLegacy,\n upsertPodProvider,\n describePodProviderResult,\n PodProviderError,\n AI_CONSUMERS_NEEDING_RECREATE,\n type WireAiResult,\n} from '@eve/dna';\nimport { materializeTargets, runActionToCompletion } from '@eve/lifecycle';\nimport { colors, printError, printInfo, printSuccess, printWarning } from '../lib/ui.js';\n\n/**\n * A provider id is a FREE STRING, matching the pod's `ai_providers.providerId`\n * (`z.string().min(1).max(64)`) and Eve's own `UnifiedProviderSchema`.\n *\n * It used to be a closed four-vendor union, enforced by `parseProviderId()`,\n * so `eve ai providers add` could not register a custom OpenAI-compatible\n * endpoint at all — while the secrets schema, the eve-dashboard route and the\n * pod's table were all open. The enum was the only thing in the chain that\n * disagreed, and it sat on the command an operator is most likely to type.\n */\ntype ProviderId = string;\n\n/** The four ids Eve ships opinionated defaults for. Defaults, never a gate. */\nconst PROVIDERS_WITH_DEFAULTS = ['ollama', 'openrouter', 'anthropic', 'openai'] as const;\ntype ProviderWithDefaults = (typeof PROVIDERS_WITH_DEFAULTS)[number];\n\nfunction buildNonSecretProviderRouting(\n secrets: Awaited<ReturnType<typeof readEveSecrets>>,\n): {\n mode?: 'local' | 'provider' | 'hybrid';\n defaultProvider?: string;\n fallbackProvider?: string;\n providers?: Array<{ id: string; enabled?: boolean; baseUrl?: string; defaultModel?: string; models?: string[] }>;\n} {\n const providers = (secrets?.ai?.providers ?? []).map((p) => ({\n id: p.id,\n enabled: p.enabled,\n baseUrl: p.baseUrl,\n defaultModel: p.defaultModel,\n models: p.models,\n }));\n return {\n mode: secrets?.ai?.mode,\n defaultProvider: secrets?.ai?.defaultProvider,\n fallbackProvider: secrets?.ai?.fallbackProvider,\n providers,\n };\n}\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map((v) => stableJson(v)).join(',')}]`;\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction parseProviderId(s: string): ProviderId {\n const v = s.trim().toLowerCase();\n if (!v) throw new Error('Provider id cannot be empty.');\n // Mirrors the pod's own constraint. Shape only — ANY id is allowed, because\n // registering an arbitrary OpenAI-compatible endpoint is the point.\n if (v.length > 64) throw new Error('Provider id must be 64 characters or fewer.');\n if (!/^[a-z0-9][a-z0-9._-]*$/.test(v)) {\n throw new Error(\n `Invalid provider id \"${s}\" — use lowercase letters, digits, dot, dash or underscore.`,\n );\n }\n return v;\n}\n\n/**\n * Re-wire every installed AI-consuming component from current secrets.\n * Used by `eve ai apply` and as a default after `eve ai providers add`.\n */\nasync function applyAiWiring(): Promise<WireAiResult[]> {\n const secrets = await readEveSecrets(process.cwd());\n let installed: string[] = [];\n try {\n installed = await entityStateManager.getInstalledComponents();\n } catch { /* state not initialized */ }\n\n if (installed.length === 0) {\n printWarning('No installed components — nothing to wire.');\n return [];\n }\n\n console.log();\n console.log(colors.primary.bold('Wiring AI provider into installed components:'));\n const [materialized] = await materializeTargets(secrets, ['ai-wiring'], { components: installed });\n const results = Array.isArray(materialized?.details?.results)\n ? materialized.details.results as WireAiResult[]\n : [];\n\n // For components whose env is set at `docker run` time (openclaw),\n // wire-only restart leaves the env stale. Recreate via lifecycle so\n // the new DEFAULT_MODEL etc. actually land. Mirrors the dashboard's\n // /api/ai/apply route — same single source of truth.\n //\n // Only recreate when wiring actually wrote a new env ('ok'). If wiring\n // was skipped (e.g. no agent key provisioned) or failed, the current\n // container is running with its last-good config — killing it here\n // would leave it down with no improvement to show for it.\n for (const id of AI_CONSUMERS_NEEDING_RECREATE) {\n if (!installed.includes(id)) continue;\n const wireOutcome = results.find(r => r.id === id)?.outcome;\n if (wireOutcome !== 'ok') continue;\n const r = await runActionToCompletion(id, 'recreate');\n const recreated: WireAiResult = {\n id,\n outcome: r.ok ? 'ok' : 'failed',\n summary: r.ok\n ? `${id} recreated · new env applied`\n : `${id} recreate failed: ${r.error ?? 'unknown'}`,\n };\n const idx = results.findIndex(x => x.id === id);\n if (idx >= 0) results[idx] = recreated;\n else results.push(recreated);\n }\n\n for (const r of results) {\n if (r.outcome === 'ok') {\n console.log(` ${colors.success('✓')} ${r.id.padEnd(12)} ${colors.muted(r.summary)}`);\n } else if (r.outcome === 'skipped') {\n console.log(` ${colors.muted('-')} ${r.id.padEnd(12)} ${colors.muted(r.summary)}`);\n } else {\n console.log(` ${colors.error('✗')} ${r.id.padEnd(12)} ${colors.error(r.summary)}`);\n if (r.detail) console.log(` ${colors.muted(r.detail)}`);\n }\n }\n return results;\n}\n\nexport function aiCommandGroup(program: Command): void {\n const ai = program.command('ai').description('AI foundation helpers (local Ollama + provider routing)');\n\n ai\n .command('status')\n .description('Show AI foundation mode, provider routing, and Ollama status')\n .action(async () => {\n const modelService = new ModelService();\n try {\n const secrets = await readEveSecrets(process.cwd());\n const providers = secrets?.ai?.providers ?? [];\n\n // Quick status for each component\n const ollamaRunning = await modelService.isOllamaRunning();\n const hermesRunning = await modelService.isHermesRunning();\n const ollamaModels = ollamaRunning ? await modelService.listOllamaModels() : [];\n const hermesModels = hermesRunning ? await modelService.listHermesModels() : [];\n\n const out = {\n ai: secrets?.ai ?? null,\n ollama: { running: ollamaRunning, modelsInstalled: ollamaModels },\n hermes: { running: hermesRunning, models: hermesModels },\n cloudProviders: providers.filter(p => p.apiKey).map(p => ({\n id: p.id,\n hasKey: true,\n models: p.models ?? [],\n })),\n };\n if (getGlobalCliFlags().json) {\n outputJson(out);\n return;\n }\n\n console.log(colors.primary.bold('AI Foundation'));\n console.log(` Mode: ${secrets?.ai?.mode ?? '(unset)'}`);\n console.log(` Default provider: ${secrets?.ai?.defaultProvider ?? '(unset)'}`);\n console.log(` Fallback provider: ${secrets?.ai?.fallbackProvider ?? '(unset)'}`);\n if (providers.length) {\n console.log(' Providers:');\n for (const p of providers) {\n console.log(` - ${p.id} enabled=${p.enabled ?? true} model=${p.defaultModel ?? '(unset)'}${p.models?.length ? ` models=${p.models.length} discovered` : ''}`);\n }\n }\n\n console.log();\n console.log(colors.primary.bold('Local Models'));\n console.log(` Ollama: ${ollamaRunning ? 'running' : 'stopped'}${ollamaModels.length ? ' · ' + ollamaModels.join(', ') : ''}`);\n console.log(` Hermes: ${hermesRunning ? 'running' : 'stopped'}${hermesModels.length ? ' · ' + hermesModels.join(', ') : ''}`);\n\n const cloudProviders = providers.filter(p => p.apiKey);\n if (cloudProviders.length) {\n console.log();\n console.log(colors.primary.bold('Cloud Providers'));\n for (const p of cloudProviders) {\n console.log(` - ${p.id} (${p.baseUrl ?? 'default url'})${p.models?.length ? ` · ${p.models.length} models cached` : ' · (run \\`eve ai models\\` to discover)'}`);\n }\n }\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n /**\n * Mirror a provider into the pod's canonical `ai_providers` table.\n *\n * Three outcomes, all reported honestly:\n * - no pod configured yet → local-only notice (bootstrap; NOT an error)\n * - pod wrote the row → applied\n * - pod filed a proposal → NOT active until approved (never \"saved\")\n */\n async function syncProviderToPod(\n pid: string,\n entry: { enabled?: boolean; apiKey?: string; baseUrl?: string },\n model?: string,\n ): Promise<void> {\n const secrets = await readEveSecrets(process.cwd());\n const podUrl = resolveSynapUrl(secrets);\n const apiKey = await readAgentKeyOrLegacy('eve', process.cwd());\n\n if (!podUrl || !apiKey) {\n printInfo('No pod configured yet — provider saved locally only.');\n printInfo(' Once the pod is up, run `eve ai apply` to register it there.');\n return;\n }\n if (!entry.baseUrl) {\n printInfo(`Provider \"${pid}\" has no base URL — not registered on the pod.`);\n return;\n }\n\n try {\n const result = await upsertPodProvider(podUrl, apiKey, {\n providerId: pid,\n name: pid,\n baseUrl: entry.baseUrl,\n apiKeyEnvVar: `${pid.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_API_KEY`,\n ...(entry.apiKey ? { apiKey: entry.apiKey } : {}),\n enabled: entry.enabled !== false,\n ...(model ? { models: [{ id: model }] } : {}),\n });\n console.log(describePodProviderResult(result));\n } catch (err) {\n // Loud, not fatal: the local write already succeeded, and failing the\n // whole command would leave the operator unsure what landed.\n if (err instanceof PodProviderError) {\n printWarning(`Provider saved locally, but the pod refused it:`);\n printWarning(` ${err.message}`);\n } else {\n printWarning(\n `Provider saved locally, but the pod could not be reached: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n }\n }\n\n const providers = ai.command('providers').description('Manage cloud/local provider entries in .eve/secrets/secrets.json');\n\n providers\n .command('list')\n .description('List configured providers')\n .action(async () => {\n const secrets = await readEveSecrets(process.cwd());\n const list = secrets?.ai?.providers ?? [];\n if (getGlobalCliFlags().json) {\n outputJson({ mode: secrets?.ai?.mode, defaultProvider: secrets?.ai?.defaultProvider, fallbackProvider: secrets?.ai?.fallbackProvider, providers: list });\n return;\n }\n if (!list.length) {\n console.log('No providers configured. Run `eve setup` or `eve ai providers add <id>`');\n return;\n }\n for (const p of list) {\n console.log(`${p.id}\\tenabled=${p.enabled ?? true}\\tmodel=${p.defaultModel ?? '(unset)'}`);\n }\n });\n\n // Sensible model defaults so flag-only `eve ai providers add anthropic --api-key X` still works.\n const DEFAULT_MODELS: Record<ProviderWithDefaults, string> = {\n anthropic: 'claude-sonnet-4-7',\n openai: 'gpt-5',\n openrouter: 'anthropic/claude-sonnet-4-7', // OpenRouter requires a model — this is just a starter\n ollama: 'llama3.1:8b',\n };\n\n providers\n .command('add <id>')\n .description('Add or update provider credentials/model — auto-wires every installed component')\n .option('--api-key <key>', 'Provider API key (required for cloud providers)')\n .option('--base-url <url>', 'Custom provider base URL')\n .option('--model <name>', 'Default model (required for openrouter; defaults to the latest for other providers)')\n .option('--disable', 'Set enabled=false')\n .option('--no-rewire', \"Don't auto-rewire installed components after save\")\n .action(async (id: string, opts: { apiKey?: string; baseUrl?: string; model?: string; disable?: boolean; rewire?: boolean }) => {\n try {\n const pid = parseProviderId(id);\n const secrets = await readEveSecrets(process.cwd());\n const list = [...(secrets?.ai?.providers ?? [])];\n const idx = list.findIndex((p) => p.id === pid);\n\n // Resolve final model: explicit --model wins, then existing, then sensible default\n const knownDefault = (PROVIDERS_WITH_DEFAULTS as readonly string[]).includes(pid)\n ? DEFAULT_MODELS[pid as ProviderWithDefaults]\n : undefined;\n const resolvedModel = opts.model ?? list[idx]?.defaultModel ?? knownDefault;\n\n // An unknown provider has no baseUrl Eve could guess. Refuse rather\n // than storing an entry that can never resolve.\n const resolvedBaseUrl = opts.baseUrl ?? list[idx]?.baseUrl;\n if (!knownDefault && !resolvedBaseUrl) {\n throw new Error(\n `--base-url is required for \"${pid}\" (Eve ships defaults only for ${PROVIDERS_WITH_DEFAULTS.join(', ')}).`,\n );\n }\n\n // OpenRouter without an explicit model is rarely what the user wants — warn\n if (pid === 'openrouter' && !opts.model && !list[idx]?.defaultModel) {\n printWarning(`OpenRouter has no useful default — using \"${resolvedModel}\" as a starter.`);\n printInfo(' Override with: --model <provider>/<model> (e.g. --model openai/gpt-5)');\n }\n\n const next = {\n id: pid,\n enabled: opts.disable ? false : true,\n apiKey: opts.apiKey ?? list[idx]?.apiKey,\n baseUrl: resolvedBaseUrl,\n defaultModel: resolvedModel,\n };\n if (idx >= 0) list[idx] = next;\n else list.push(next);\n await writeEveSecrets({ ai: { providers: list } }, process.cwd());\n printSuccess(`Provider ${pid} saved locally${resolvedModel ? ` (model: ${resolvedModel})` : ''}.`);\n\n // ── The pod is the source of truth ────────────────────────────────\n // `ai_providers` → pushProvidersToIS() is the canonical path by which\n // the Intelligence Service learns its providers. Writing ONLY local\n // secrets (what this command used to do) left the pod unaware, while\n // the `.env` wiring below raced the pod's own push into the same IS\n // registry — last writer wins, neither able to see the other.\n //\n // Best-effort ON PURPOSE, and never silent: `eve ai providers add` runs\n // during `eve setup`, BEFORE a pod necessarily exists. A hard failure\n // there would break bootstrap. So a missing pod is reported as\n // local-only rather than treated as an error — but a pod that IS\n // configured and REFUSES is surfaced loudly, because that is a real\n // misconfiguration (usually a key without `providers.write`).\n await syncProviderToPod(pid, next, resolvedModel);\n\n // Auto-rewire every installed component (default behavior)\n if (opts.rewire !== false) {\n await applyAiWiring();\n } else {\n printInfo('Run `eve ai apply` to push the new key to installed components.');\n }\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n providers\n .command('set-default <id>')\n .description('Set default provider (auto-applies to installed components)')\n .option('--no-rewire', 'Skip auto-applying to installed components')\n .action(async (id: string, opts: { rewire?: boolean }) => {\n try {\n const pid = parseProviderId(id);\n await writeEveSecrets({ ai: { defaultProvider: pid } }, process.cwd());\n printInfo(`Default provider set to ${pid}`);\n if (opts.rewire !== false) {\n await applyAiWiring();\n }\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n providers\n .command('set-fallback <id>')\n .description('Set fallback provider (auto-applies to installed components)')\n .option('--no-rewire', 'Skip auto-applying to installed components')\n .action(async (id: string, opts: { rewire?: boolean }) => {\n try {\n const pid = parseProviderId(id);\n await writeEveSecrets({ ai: { fallbackProvider: pid } }, process.cwd());\n printInfo(`Fallback provider set to ${pid}`);\n if (opts.rewire !== false) {\n await applyAiWiring();\n }\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n providers\n .command('set-service <componentId> <providerId>')\n .description('Override which provider a specific service uses (e.g. set-service openclaw anthropic). Pass \"default\" to clear.')\n .option('--no-rewire', 'Skip auto-applying to installed components')\n .action(async (componentId: string, providerId: string, opts: { rewire?: boolean }) => {\n try {\n const secrets = await readEveSecrets(process.cwd());\n const current = secrets?.ai?.serviceProviders ?? {};\n const next = { ...current };\n\n if (providerId === 'default' || providerId === 'clear') {\n delete next[componentId];\n printInfo(`Cleared service override for ${componentId} (now uses global default)`);\n } else {\n const pid = parseProviderId(providerId);\n next[componentId] = pid;\n printInfo(`${componentId} now routes via ${pid}`);\n }\n\n await writeEveSecrets(\n { ai: { serviceProviders: next } },\n process.cwd(),\n );\n if (opts.rewire !== false) {\n await applyAiWiring();\n }\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n ai\n .command('apply')\n .description('Re-wire every installed component to use the current AI provider config')\n .action(async () => {\n try {\n await applyAiWiring();\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n ai\n .command('sync')\n .description('Explicitly sync Eve provider routing policy to Synap workspace settings')\n .requiredOption('--workspace <id>', 'Workspace UUID to update')\n .option('--check', 'Only compare local policy vs workspace policy; do not write')\n .action(async (opts: { workspace: string; check?: boolean }) => {\n try {\n const secrets = await readEveSecrets(process.cwd());\n const hubBaseUrl = resolveHubBaseUrl(secrets ?? null);\n // `eve ai sync` writes workspace settings on the pod — admin-style\n // call. Use the eve agent's key (Doctor's identity) so the audit\n // trail attributes back to Eve, not to a specific consumer agent.\n const apiKey =\n secrets?.agents?.eve?.hubApiKey?.trim() ??\n secrets?.synap?.apiKey?.trim();\n if (!hubBaseUrl) {\n throw new Error('Cannot resolve Synap pod URL — set domain.primary or synap.apiUrl in .eve/secrets/secrets.json');\n }\n if (!apiKey) {\n throw new Error('Missing eve agent key — run `eve auth provision`');\n }\n\n const payload = buildNonSecretProviderRouting(secrets);\n if (opts.check) {\n const getRes = await fetch(\n `${hubBaseUrl}/workspaces/${encodeURIComponent(opts.workspace)}/eve-provider-routing`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n },\n );\n const getData = (await getRes.json().catch(() => ({}))) as Record<string, unknown>;\n if (!getRes.ok) {\n throw new Error(String(getData.error ?? `Check failed with HTTP ${getRes.status}`));\n }\n const remote = (getData.eveProviderRouting ?? null) as unknown;\n const same = stableJson(remote) === stableJson(payload);\n if (getGlobalCliFlags().json) {\n outputJson({ ok: true, workspaceId: opts.workspace, same, local: payload, remote });\n return;\n }\n if (same) {\n printInfo(`Provider routing already in sync for workspace ${opts.workspace}`);\n } else {\n printInfo(`Provider routing differs for workspace ${opts.workspace}`);\n }\n return;\n }\n\n const res = await fetch(\n `${hubBaseUrl}/workspaces/${encodeURIComponent(opts.workspace)}/eve-provider-routing`,\n {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n },\n );\n const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok) {\n throw new Error(String(data.error ?? `Sync failed with HTTP ${res.status}`));\n }\n if (getGlobalCliFlags().json) {\n outputJson({ ok: true, workspaceId: opts.workspace, synced: payload });\n return;\n }\n printInfo(`Provider routing synced to workspace ${opts.workspace}`);\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n ai\n .command('models')\n .description('List models from all providers (Ollama, Hermes, cloud)')\n .action(async () => {\n const modelService = new ModelService();\n const secrets = await readEveSecrets(process.cwd());\n const providers = secrets?.ai?.providers ?? [];\n const hermesApiKey = secrets?.builder?.hermes?.apiServerKey;\n const discovered = await modelService.discoverAll(\n providers.map(p => ({\n id: p.id,\n name: p.name,\n baseUrl: p.baseUrl,\n apiKey: p.apiKey,\n defaultModel: p.defaultModel,\n models: p.models,\n })),\n hermesApiKey,\n );\n\n if (getGlobalCliFlags().json) {\n outputJson({ providers: discovered });\n return;\n }\n\n if (discovered.length === 0) {\n printInfo('No models found. Run `eve brain init --with-ai` for local Ollama, or add a cloud provider with `eve ai providers add`.');\n return;\n }\n\n for (const group of discovered) {\n console.log();\n if (group.available) {\n console.log(colors.primary.bold(`── ${group.displayName} ──`));\n } else if (group.models.length > 0) {\n // Cached models from previous discovery (no current baseUrl/apiKey)\n console.log(colors.primary.bold(`── ${group.displayName} ──`));\n console.log(colors.muted(` (cached) ${group.models.length} model(s) from previous discovery`));\n for (const m of group.models) {\n const marker = m.isDefault ? colors.brain(' *') : '';\n console.log(` ${m.name}${marker}`);\n }\n continue;\n } else {\n console.log(colors.primary.bold(`── ${group.displayName} ──`));\n console.log(colors.muted(` (unreachable)`));\n console.log(` (no models discovered)`);\n }\n }\n\n console.log();\n console.log(colors.muted(' * = first model discovered (serves as default when no explicit default is set)'));\n });\n\n ai\n .command('pull')\n .description('Pull a model into Ollama')\n .argument('<model>', 'Model tag e.g. llama3.1:8b')\n .action(async (model: string) => {\n const ollama = new OllamaService();\n try {\n await ollama.pullModel(model);\n } catch (e) {\n printError(e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n });\n\n ai\n .command('chat')\n .description('Send a one-shot prompt to ollama run (requires container eve-brain-ollama)')\n .argument('<prompt>', 'Prompt text')\n .option('--model <m>', 'Model name', 'llama3.1:8b')\n .action(async (prompt: string, opts: { model?: string }) => {\n try {\n await execa(\n 'docker',\n ['exec', '-i', 'eve-brain-ollama', 'ollama', 'run', opts.model ?? 'llama3.1:8b', prompt],\n { stdio: 'inherit' }\n );\n } catch (e) {\n printError(\n e instanceof Error\n ? e.message\n : 'Failed. Ensure container eve-brain-ollama is running (eve brain init --with-ai).'\n );\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport {\n readEveSecrets,\n readAgentKeyOrLegacySync,\n buildOpenwebuiModelSources,\n buildOpenwebuiManagedConfig,\n registerOpenwebuiAdminApi,\n syncOpenwebuiExtras,\n formatExtrasSummary,\n} from '@eve/dna';\nimport { renewAgentKey } from '@eve/lifecycle';\nimport { createSpinner, printSuccess, printError, printWarning, colors } from '../lib/ui.js';\n\nexport function openwebuiCommand(program: Command): void {\n const owui = program\n .command('openwebui')\n .alias('owui')\n .description('OpenWebUI management commands');\n\n owui\n .command('sync')\n .description(\n 'Re-register all model sources in OpenWebUI via the admin API.\\n' +\n 'Use this to recover when `eve start` or `eve ai apply` succeeded\\n' +\n 'but models are missing from the OpenWebUI model picker.',\n )\n .option(\n '--max-retries <n>',\n 'Health check attempts before giving up (each attempt waits 5 s, default: 24 = 2 min)',\n '24',\n )\n .option('--skip-extras', 'Skip the extras sync (skills / knowledge / tools)')\n .action(async (opts: { maxRetries: string; skipExtras?: boolean }) => {\n const maxRetries = Math.max(1, parseInt(opts.maxRetries, 10) || 24);\n const secrets = await readEveSecrets(process.cwd());\n\n const synapApiKey = readAgentKeyOrLegacySync('eve', secrets);\n if (!synapApiKey) {\n printError('No Synap API key found for the eve agent — install Synap first (`eve add synap`)');\n process.exit(1);\n }\n\n const { modelSources } = buildOpenwebuiModelSources(secrets, '/opt/openwebui');\n\n // Apply correct keys (same logic as wireOpenwebui in wire-ai.ts)\n if (modelSources.length > 0) modelSources[0].apiKey = synapApiKey;\n const hermesApiServerKey = secrets?.builder?.hermes?.apiServerKey;\n const hermesIdx = modelSources.findIndex(m => m.displayName === 'Hermes Gateway');\n if (hermesIdx >= 0) modelSources[hermesIdx].apiKey = hermesApiServerKey ?? '';\n\n console.log(colors.muted(` ${modelSources.length} model source(s) to register`));\n console.log(colors.muted(` Health check budget: ${maxRetries} × 5 s = ${maxRetries * 5} s`));\n console.log();\n\n const spinner = createSpinner(`Waiting for OpenWebUI (up to ${maxRetries * 5} s)…`);\n spinner.start();\n\n const outcome = await registerOpenwebuiAdminApi(modelSources, {\n managedConfig: buildOpenwebuiManagedConfig(secrets),\n maxRetries,\n });\n\n if (!outcome.ok) {\n spinner.fail(`Registration failed at stage='${outcome.stage}'`);\n printError(outcome.reason);\n console.log();\n printWarning('Likely fix per stage:');\n console.log(colors.muted(\" health → docker ps --filter name=hestia-openwebui --format '{{.Ports}}'\"));\n console.log(colors.muted(' curl -sI http://127.0.0.1:3011/health'));\n console.log(colors.muted(\" secret-key → grep '^WEBUI_SECRET_KEY=' /opt/openwebui/.env\"));\n console.log(colors.muted(' admin-row → docker exec hestia-openwebui sqlite3 /app/backend/data/webui.db \"SELECT id,email,role FROM user\"'));\n console.log(colors.muted(' jwt-rejected → check OWUI version; admin JWT format may have changed'));\n console.log(colors.muted(' reconcile → docker logs hestia-openwebui --tail 30'));\n console.log();\n printWarning('After fixing, re-run: eve openwebui sync');\n process.exit(1);\n }\n\n spinner.succeed(`${modelSources.length} model source(s) registered in OpenWebUI`);\n\n if (!opts.skipExtras) {\n const extrasSpinner = createSpinner('Syncing extras (skills / knowledge / tools)…');\n extrasSpinner.start();\n try {\n let extras = await syncOpenwebuiExtras(process.cwd(), secrets);\n // Auto-recover from a stale eve hubApiKey. The skills + knowledge\n // pushes call Synap's Hub Protocol with `secrets.agents.eve.hubApiKey`;\n // if that key was revoked / expired, every push returns 401 and the\n // user is left with no Synap surfaces in OpenWebUI. Detect the 401\n // signature, mint a fresh key via /setup/agent, then retry once.\n const has401 = formatExtrasSummary(extras).match(/\\b401\\b|Unauthorized/i);\n if (has401) {\n extrasSpinner.warn('Detected 401 on Synap pushes — renewing eve agent key…');\n const renew = await renewAgentKey({ agentType: 'eve', reason: 'owui-sync-401-recover' });\n if (renew.renewed) {\n const retrySpinner = createSpinner('Retrying extras with fresh eve key…');\n retrySpinner.start();\n const refreshed = await readEveSecrets(process.cwd());\n extras = await syncOpenwebuiExtras(process.cwd(), refreshed);\n retrySpinner.succeed(formatExtrasSummary(extras));\n } else {\n printWarning(\n `Skills/knowledge returned 401 and renewal failed (${renew.reason}). ` +\n `Run \\`eve auth provision --agent eve\\` then retry.`,\n );\n printWarning(formatExtrasSummary(extras));\n }\n } else {\n extrasSpinner.succeed(formatExtrasSummary(extras));\n }\n } catch (err) {\n extrasSpinner.warn(`Extras sync failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n console.log();\n printSuccess('Sync complete. Models should now appear in the OpenWebUI model picker.');\n printSuccess('Run `eve doctor` to verify the full registration status.');\n });\n}\n","/**\n * `eve ui` — open the Eve Dashboard in a browser, with optional rebuild.\n *\n * The dashboard runs as a Docker service (`eve-dashboard`), installed via\n * `eve add eve-dashboard`. This command exists for the common case of\n * \"open the URL\" plus quick `--rebuild` and status helpers.\n */\n\nimport type { Command } from 'commander';\nimport { execa } from 'execa';\nimport { randomBytes } from 'node:crypto';\nimport { readEveSecrets, writeEveSecrets } from '@eve/dna';\nimport {\n installDashboardContainer,\n uninstallDashboardContainer,\n dashboardContainerName,\n dashboardIsRunning,\n} from '@eve/legs';\nimport { colors, emojis, printSuccess, printError, printInfo, printWarning } from '../lib/ui.js';\n\nasync function ensureDashboardSecret(port: number): Promise<string> {\n const existing = await readEveSecrets(process.cwd());\n if (existing?.dashboard?.secret) {\n return existing.dashboard.secret;\n }\n const secret = randomBytes(32).toString('hex');\n await writeEveSecrets({ dashboard: { secret, port } });\n console.log();\n console.log(colors.primary.bold('Dashboard key generated — save this somewhere safe:'));\n console.log(colors.muted('─'.repeat(66)));\n console.log(colors.primary.bold(secret));\n console.log(colors.muted('─'.repeat(66)));\n console.log(colors.muted('You will be prompted for this key when you open the dashboard.'));\n return secret;\n}\n\nfunction openBrowser(url: string): void {\n const opener =\n process.platform === 'darwin' ? 'open' :\n process.platform === 'win32' ? 'start' :\n 'xdg-open';\n execa(opener, [url]).catch(() => { /* headless box, no browser */ });\n}\n\nexport function uiCommand(program: Command): void {\n program\n .command('ui')\n .description('Open the Eve web dashboard')\n .option('--port <port>', 'Host port the dashboard is exposed on', '7979')\n .option('--no-open', 'Do not open the browser automatically')\n .option('--rebuild', 'Rebuild the dashboard image and restart the container')\n .option('--stop', 'Stop and remove the dashboard container')\n .option('--status', 'Show whether the dashboard container is running')\n .action(async (opts: {\n port: string;\n open: boolean;\n rebuild?: boolean;\n stop?: boolean;\n status?: boolean;\n }) => {\n const port = parseInt(opts.port, 10);\n\n if (opts.status) {\n if (dashboardIsRunning()) {\n printSuccess(`Eve Dashboard is running (container: ${dashboardContainerName()})`);\n printInfo(` Logs: docker logs -f ${dashboardContainerName()}`);\n } else {\n printWarning('Eve Dashboard is NOT running.');\n printInfo(' Install/start it with: eve add eve-dashboard');\n }\n return;\n }\n\n if (opts.stop) {\n try {\n uninstallDashboardContainer();\n printSuccess('Eve Dashboard stopped.');\n printInfo(' Restart it with: eve add eve-dashboard');\n } catch (err) {\n printError(`Stop failed: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n return;\n }\n\n if (opts.rebuild) {\n const secret = await ensureDashboardSecret(port);\n try {\n installDashboardContainer({\n workspaceRoot: process.cwd(),\n secret,\n rebuild: true,\n });\n printSuccess('Eve Dashboard rebuilt and restarted.');\n } catch (err) {\n printError(`Rebuild failed: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n // Fall through to open the URL.\n }\n\n // Default action: print key + URL, optionally open browser.\n const secrets = await readEveSecrets(process.cwd());\n const secret = secrets?.dashboard?.secret;\n\n if (!dashboardIsRunning()) {\n printWarning('Eve Dashboard is not running.');\n printInfo(' Start it with: eve add eve-dashboard');\n return;\n }\n\n const url = `http://localhost:${port}`;\n console.log();\n if (secret) {\n console.log(colors.muted('Your dashboard key:'));\n console.log(colors.primary.bold(secret));\n console.log();\n }\n console.log(`${emojis.entity} Eve Dashboard → ${colors.primary(url)}`);\n console.log();\n\n if (opts.open) openBrowser(url);\n });\n}\n","import type { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { writeEveSecrets, readEveSecrets, getAccessUrls, getServerIp, entityStateManager, validateBaseDomain } from '@eve/dna';\nimport { TraefikService } from '@eve/legs';\nimport { materializeTargets } from '@eve/lifecycle';\nimport { colors, printSuccess, printInfo, printWarning, printError } from '../lib/ui.js';\nimport { probeRoutes, probeSummary, probeVerdict, type RouteProbe } from '../lib/probe-routes.js';\n\nconst PLACEHOLDER_DOMAINS = new Set([\n 'localhost', '127.0.0.1', '::1', 'example.com',\n 'yourdomain.com', 'mydomain.com', 'your-domain.com',\n]);\n\nfunction isPlaceholderDomain(d: string): boolean {\n const lower = d.toLowerCase();\n return PLACEHOLDER_DOMAINS.has(lower) ||\n lower.startsWith('127.') ||\n lower.startsWith('192.168.') ||\n lower.startsWith('10.') ||\n !lower.includes('.');\n}\n\n/** Render a per-route probe summary as a small table (used by `set` + `check`). */\nfunction renderProbeTable(probes: RouteProbe[]): void {\n console.log(colors.muted(' ' + '─'.repeat(60)));\n for (const p of probes) {\n const dot = p.outcome === 'ok'\n ? colors.success('●')\n : p.outcome === 'upstream-down'\n ? colors.warning('●')\n : colors.error('●');\n const status = p.outcome === 'ok'\n ? colors.success(`${p.httpStatus} reachable`)\n : p.outcome === 'upstream-down'\n ? colors.warning(`${p.httpStatus} upstream down`)\n : p.outcome === 'not-routing'\n ? colors.error(`${p.httpStatus} no route match`)\n : p.outcome === 'dns-missing'\n ? colors.error('DNS missing')\n : p.outcome === 'dns-wrong'\n ? colors.warning(`DNS → ${p.dnsResolved}`)\n : colors.error('timeout');\n console.log(` ${dot} ${p.host.padEnd(34)} ${status}`);\n }\n}\n\n/** Render an actionable hint for a single failing probe. */\nfunction renderProbeHint(p: RouteProbe): void {\n switch (p.outcome) {\n case 'dns-missing':\n printInfo(` • ${p.host}: create A record pointing to your server IP`);\n break;\n case 'dns-wrong':\n printInfo(` • ${p.host}: DNS resolves to ${p.dnsResolved}; update A record to your server IP`);\n break;\n case 'upstream-down':\n printInfo(` • ${p.host}: route exists but upstream is down — check the container is running`);\n break;\n case 'not-routing':\n printInfo(` • ${p.host}: Traefik has no rule matching — try \\`eve domain repair\\``);\n break;\n case 'timeout':\n printInfo(` • ${p.host}: request timed out — check Traefik is running on port 80`);\n break;\n case 'ok':\n break;\n }\n}\n\nexport function domainCommand(program: Command): void {\n const domain = program\n .command('domain')\n .description('Configure domain access and Traefik routing');\n\n domain\n .command('set <domain>')\n .description('Set primary domain and configure Traefik subdomains')\n .option('--ssl', \"Enable SSL with Let's Encrypt\")\n .option('--email <email>', \"Email for Let's Encrypt notifications\")\n .action(async (domainName: string, opts: { ssl?: boolean; email?: string }) => {\n const domainError = validateBaseDomain(domainName);\n if (domainError) {\n printError(domainError);\n process.exit(1);\n }\n\n // Inherit ssl + behind-proxy + email from prior config when not\n // explicitly passed. Otherwise calling `eve domain set <new-domain>`\n // would silently flip an SSL or behind-proxy install back to plain.\n const prior = await readEveSecrets(process.cwd());\n const sslExplicit = opts.ssl === true;\n const ssl = sslExplicit || (!sslExplicit && !!prior?.domain?.ssl);\n const email = opts.email ?? prior?.domain?.email;\n\n if (ssl && !email) {\n printWarning(\"--ssl requires --email <address> for Let's Encrypt certificate provisioning.\");\n printWarning(\"Example: eve domain set \" + domainName + \" --ssl --email you@example.com\");\n process.exit(1);\n }\n\n await writeEveSecrets({ domain: { primary: domainName, ssl, email } });\n\n // Read installed components so we only wire routes for what's actually installed\n let installedComponents: string[] | undefined;\n try {\n installedComponents = await entityStateManager.getInstalledComponents();\n } catch {\n // First-time run or state not yet initialized — route everything\n }\n\n let writeOk = false;\n try {\n const results = await materializeTargets(null, ['backend-env', 'traefik-routes']);\n const routeResult = results.find(r => r.target === 'traefik-routes');\n if (!routeResult?.ok) throw new Error(routeResult?.error ?? routeResult?.summary ?? 'unknown Traefik error');\n writeOk = routeResult.changed;\n } catch (err) {\n printError(`Could not write Traefik config: ${err instanceof Error ? err.message : String(err)}`);\n printInfo('Run this command on your server (where Docker is available).');\n return;\n }\n\n const secrets = await readEveSecrets(process.cwd());\n const urls = getAccessUrls(secrets, installedComponents);\n\n // ─── DNS records the user needs to create ───────────────────────────\n const serverIp = getServerIp();\n const subdomainsNeeded = urls\n .filter(u => u.domainUrl)\n .map(u => u.domainUrl!.replace(/^https?:\\/\\//, '').split('/')[0].replace(`.${domainName}`, ''));\n\n console.log();\n console.log(colors.primary.bold('DNS records you must create:'));\n console.log(colors.muted('─'.repeat(60)));\n console.log(colors.muted(' Type Name Value'));\n for (const sub of subdomainsNeeded) {\n const name = `${sub}.${domainName}`.padEnd(32);\n const value = serverIp ?? colors.warning('<your-server-ip>');\n console.log(` ${colors.primary('A')} ${name}${value}`);\n }\n console.log(colors.muted('─'.repeat(60)));\n if (!serverIp) printInfo('Could not detect server IP — replace <your-server-ip> above.');\n\n // ─── Live probe — don't print ✅ unless routes actually work ────────\n if (writeOk) {\n console.log();\n console.log(colors.primary.bold('Verifying routes (probing each subdomain)...'));\n // Give Traefik a beat to reload after restart\n await new Promise(r => setTimeout(r, 1500));\n const probes = probeRoutes(urls);\n renderProbeTable(probes);\n\n const verdict = probeVerdict(probes);\n console.log();\n if (verdict === 'ok') {\n printSuccess(`Domain configured and all ${probes.length} routes are healthy.`);\n } else if (verdict === 'partial') {\n const broken = probes.filter(p => p.outcome !== 'ok');\n printWarning(`Domain configured, but ${broken.length}/${probes.length} routes need attention:`);\n for (const p of broken) renderProbeHint(p);\n } else {\n printError(`Domain configured but no routes are reachable yet.`);\n for (const p of probes) renderProbeHint(p);\n }\n if (opts.ssl) {\n console.log();\n printInfo('SSL certificates will provision automatically once DNS propagates (1–5 min).');\n }\n }\n console.log();\n });\n\n domain\n .command('show')\n .description('Show all access URLs (local, server IP, domain)')\n .action(async () => {\n const secrets = await readEveSecrets(process.cwd());\n let installedComponents: string[] | undefined;\n try { installedComponents = await entityStateManager.getInstalledComponents(); } catch { /* ignore */ }\n const urls = getAccessUrls(secrets, installedComponents);\n const domainSet = !!secrets?.domain?.primary;\n\n console.log();\n console.log(colors.primary.bold('Eve — Access URLs'));\n console.log(colors.muted('─'.repeat(70)));\n\n for (const svc of urls) {\n console.log();\n console.log(` ${svc.emoji} ${colors.primary.bold(svc.label)}`);\n console.log(` ${colors.muted('Local:')} ${svc.localUrl}`);\n if (svc.serverUrl) console.log(` ${colors.muted('Server:')} ${svc.serverUrl}`);\n if (svc.domainUrl) console.log(` ${colors.muted('Domain:')} ${colors.primary(svc.domainUrl)}`);\n }\n\n console.log();\n if (!domainSet) {\n console.log(colors.muted(\" Tip: run `eve domain set yourdomain.com --ssl` to configure domain access\"));\n }\n });\n\n domain\n .command('check')\n .description('Verify Traefik is running and routes are reachable')\n .action(async () => {\n const TRAEFIK_CONFIG = '/opt/traefik/traefik.yml';\n const TRAEFIK_DYNAMIC = '/opt/traefik/dynamic/eve-routes.yml';\n\n console.log();\n console.log(colors.primary.bold('Eve — Domain / Traefik diagnostic'));\n console.log(colors.muted('─'.repeat(60)));\n console.log();\n\n const tick = colors.success('✓');\n const cross = colors.error('✗');\n const warn = colors.warning('!');\n\n // ─── 1. Traefik container running? ─────────────────────────────────\n let traefikRunning = false;\n try {\n const out = execSync('docker ps --filter \"name=eve-legs-traefik\" --format \"{{.Names}}\"', {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n traefikRunning = out.length > 0;\n } catch { /* docker not available */ }\n\n console.log(traefikRunning\n ? ` ${tick} Traefik container: running (eve-legs-traefik)`\n : ` ${cross} Traefik container: NOT running — run: eve install --components=traefik`);\n\n // ─── 2. Config files present? ──────────────────────────────────────\n const staticOk = existsSync(TRAEFIK_CONFIG);\n const dynamicOk = existsSync(TRAEFIK_DYNAMIC);\n console.log(staticOk ? ` ${tick} Static config: ${TRAEFIK_CONFIG}` : ` ${cross} Static config: MISSING`);\n console.log(dynamicOk ? ` ${tick} Dynamic routes: ${TRAEFIK_DYNAMIC}` : ` ${cross} Dynamic routes: MISSING — run: eve domain set <yourdomain>`);\n\n if (!traefikRunning || !dynamicOk) {\n console.log();\n printError('Cannot continue diagnostic — Traefik or routes missing.');\n return;\n }\n\n // ─── 3. Read configured domain ─────────────────────────────────────\n const secrets = await readEveSecrets(process.cwd());\n const configuredDomain = secrets?.domain?.primary;\n console.log(configuredDomain\n ? ` ${tick} Configured domain: ${configuredDomain}`\n : ` ${warn} Configured domain: none — run: eve domain set <yourdomain>`);\n\n if (!configuredDomain) {\n console.log();\n printWarning('No domain set — nothing to verify.');\n return;\n }\n\n // ─── 4. Probe each route end-to-end (HTTP + DNS) ───────────────────\n console.log();\n console.log(colors.primary.bold(' Per-route probe (Host header → Traefik → upstream):'));\n\n let installedComponents: string[] | undefined;\n try { installedComponents = await entityStateManager.getInstalledComponents(); } catch { /* ignore */ }\n const urls = getAccessUrls(secrets, installedComponents);\n const probes = probeRoutes(urls);\n renderProbeTable(probes);\n\n // ─── 6. Traefik admin API — what routers are ACTUALLY loaded? ──────\n console.log();\n console.log(colors.primary.bold(' Routers loaded inside Traefik (via admin API :8080):'));\n console.log(colors.muted(' ' + '─'.repeat(58)));\n let loadedRouters: Array<{ name: string; rule: string; status: string }> = [];\n try {\n const apiOut = execSync('curl -s --max-time 3 http://localhost:8080/api/http/routers', {\n encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n if (apiOut) {\n const parsed = JSON.parse(apiOut) as Array<{ name: string; rule: string; status?: string }>;\n loadedRouters = parsed.map(r => ({ name: r.name, rule: r.rule, status: r.status ?? 'unknown' }));\n }\n } catch { /* admin API unreachable */ }\n\n if (loadedRouters.length === 0) {\n console.log(` ${cross} ${colors.error('NO ROUTERS LOADED!')} Traefik can't see your config file.`);\n console.log();\n console.log(colors.warning(' Likely causes:'));\n console.log(colors.warning(' 1. Volume mount broken — re-create container'));\n console.log(colors.warning(' 2. YAML syntax error — Traefik silently dropped the config'));\n console.log(colors.warning(' 3. Static config missing providers.file directive'));\n } else {\n for (const r of loadedRouters) {\n const enabled = r.status === 'enabled' ? colors.success('enabled') : colors.error(r.status);\n console.log(` ${r.name.padEnd(28)} ${enabled} ${colors.muted(r.rule)}`);\n }\n }\n\n // ─── 7. What the container actually sees ───────────────────────────\n console.log();\n console.log(colors.primary.bold(' What Traefik container sees (docker exec):'));\n console.log(colors.muted(' ' + '─'.repeat(58)));\n try {\n const containerStaticHead = execSync(\n 'docker exec eve-legs-traefik cat /etc/traefik/traefik.yml 2>&1 | head -8',\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim();\n console.log(colors.muted(' /etc/traefik/traefik.yml (first 8 lines):'));\n for (const line of containerStaticHead.split('\\n')) {\n console.log(` ${colors.muted(line)}`);\n }\n } catch {\n console.log(` ${cross} Could not read static config inside container`);\n }\n try {\n const containerLs = execSync(\n 'docker exec eve-legs-traefik ls -la /etc/traefik/dynamic/ 2>&1',\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim();\n console.log();\n console.log(colors.muted(' /etc/traefik/dynamic/ (container view):'));\n for (const line of containerLs.split('\\n')) {\n console.log(` ${colors.muted(line)}`);\n }\n } catch {\n console.log(` ${cross} Could not list dynamic dir inside container`);\n }\n\n // ─── 8. Recent Traefik logs (errors + provider events) ─────────────\n console.log();\n console.log(colors.muted(' Traefik errors / config events (last 30 relevant lines):'));\n try {\n const logs = execSync(\n 'docker logs eve-legs-traefik 2>&1 | grep -iE \"error|warn|provider|configuration|cannot|failed|unable|loaded|started\" | grep -v \"Peeking first byte\" | tail -30 || echo \"\"',\n { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'ignore'] },\n ).trim();\n if (!logs) {\n console.log(` ${colors.muted('(no relevant log entries)')}`);\n } else {\n for (const line of logs.split('\\n')) {\n const isError = /error|ERR|level=error|fail|unable|cannot/i.test(line);\n console.log(` ${isError ? colors.error(line) : colors.muted(line)}`);\n }\n }\n } catch {\n console.log(colors.muted(' (could not read logs)'));\n }\n\n // ─── 9. Targeted advice ────────────────────────────────────────────\n console.log();\n console.log(colors.primary.bold(' Hints:'));\n console.log(colors.muted(' ' + '─'.repeat(58)));\n if (loadedRouters.length === 0) {\n printError(' Traefik has NO routers loaded — your routes file is being ignored.');\n printInfo(' Try re-running: eve domain set <yourdomain>');\n printInfo(' If that doesn\\'t fix it, recreate the Traefik container:');\n printInfo(' docker rm -f eve-legs-traefik');\n printInfo(' eve install --components=traefik');\n printInfo(' eve domain set <yourdomain>');\n } else {\n printInfo(' • 404 with routers loaded = Host header mismatch. Test with:');\n printInfo(' curl -v -H \"Host: eve.<domain>\" http://localhost/');\n printInfo(' • 502 = route matched, upstream down. Check upstream containers.');\n printInfo(' • Eve dashboard runs on the HOST (port 7979), not in Docker.');\n printInfo(' Start it with: cd /opt/eve && npx eve ui');\n }\n console.log();\n });\n\n domain\n .command('repair')\n .description('Recreate Traefik with clean state — fixes stale routes & broken volume mounts')\n .action(async () => {\n const secrets = await readEveSecrets(process.cwd());\n const domainName = secrets?.domain?.primary;\n if (!domainName) {\n printError('No domain configured. Run: eve domain set <yourdomain> first.');\n process.exit(1);\n }\n\n // Fix C: Fail clearly if the stored domain is a placeholder\n if (isPlaceholderDomain(domainName)) {\n printError(`Stored domain \"${domainName}\" is a placeholder — secrets.json was corrupted by an earlier bug.`);\n printInfo('Fix: eve domain set <yourdomain> --ssl --email <you@example.com>');\n process.exit(1);\n }\n\n console.log();\n console.log(colors.primary.bold('Eve — Traefik repair'));\n console.log(colors.muted('─'.repeat(60)));\n console.log();\n\n // 1. Remove the running Traefik container (releases stale bind mounts)\n printInfo('Removing existing Traefik container...');\n try {\n execSync('docker rm -f eve-legs-traefik', { stdio: 'inherit' });\n } catch { /* container may not exist */ }\n\n // 2. Wipe stale dynamic config files using TraefikService (Fix E)\n const traefik = new TraefikService();\n printInfo('Cleaning stale config files...');\n traefik.cleanConfig();\n\n // 3. Reinstall Traefik (recreates container with proper bind mounts)\n printInfo('Reinstalling Traefik (fresh container)...');\n await traefik.install();\n\n // 4. Reapply domain routes + backend env (Fix D: pass behindProxy)\n printInfo('Applying domain routes...');\n const results = await materializeTargets(secrets, ['backend-env', 'traefik-routes']);\n const result = results.find(r => r.target === 'traefik-routes');\n if (!result?.ok) throw new Error(result?.error ?? result?.summary ?? 'unknown Traefik error');\n\n console.log();\n printSuccess('Repair complete. Run `eve domain check` to verify.');\n console.log();\n });\n\n domain\n .command('unset')\n .description('Remove domain configuration')\n .action(async () => {\n const secrets = await readEveSecrets(process.cwd());\n if (secrets?.domain?.primary) {\n await writeEveSecrets({ domain: { primary: undefined, ssl: undefined, email: undefined } });\n // Also rewrite the backend .env so PUBLIC_URL / DOMAIN are cleared\n await materializeTargets(null, ['backend-env']);\n printSuccess('Domain configuration removed');\n } else {\n printInfo('No domain configured');\n }\n });\n\n // ─── Add custom route ──────────────────────────────────────────────────────\n domain\n .command('add')\n .argument('<subdomain>', 'Subdomain to route (e.g., \"crm\" for crm.example.com)')\n .option('--port <port>', 'Target port on localhost', (v) => parseInt(v, 10))\n .option('--domain <domain>', 'Override domain (default: uses primary domain)')\n .description('Add a custom subdomain-to-port routing rule')\n .action(async (subdomain: string, opts: { port?: number; domain?: string }) => {\n const secrets = await readEveSecrets(process.cwd());\n if (!secrets?.domain?.primary) {\n printError('No primary domain configured. Run `eve domain set <domain>` first.');\n process.exit(1);\n }\n if (!opts.port) {\n printError('--port is required');\n process.exit(1);\n }\n\n const customRoutes = secrets.domain.customRoutes || [];\n const existing = customRoutes.find(r => r.subdomain === subdomain && (!r.domain || r.domain === (opts.domain || secrets.domain!.primary)));\n if (existing) {\n printWarning(`Route already exists: ${subdomain}.${opts.domain || secrets.domain!.primary} → port ${existing.port}`);\n printInfo(`To update, remove first: eve domain remove ${subdomain}`);\n return;\n }\n\n customRoutes.push({\n subdomain,\n port: opts.port,\n domain: opts.domain,\n });\n\n secrets.domain.customRoutes = customRoutes;\n await writeEveSecrets(secrets);\n\n printSuccess(`Added route: ${subdomain}.${opts.domain || secrets.domain!.primary} → localhost:${opts.port}`);\n printInfo('Run `eve domain apply` to update Traefik routes');\n });\n\n // ─── Remove custom route ───────────────────────────────────────────────────\n domain\n .command('remove')\n .alias('rm')\n .argument('<subdomain>', 'Subdomain to remove')\n .option('--domain <domain>', 'Domain override (if set during add)')\n .description('Remove a custom subdomain routing rule')\n .action(async (subdomain: string, opts: { domain?: string }) => {\n const secrets = await readEveSecrets(process.cwd());\n if (!secrets?.domain?.customRoutes?.length) {\n printInfo('No custom routes configured');\n return;\n }\n\n const targetDomain = opts.domain || secrets.domain.primary;\n const before = secrets.domain.customRoutes.length;\n secrets.domain.customRoutes = secrets.domain.customRoutes.filter(\n r => !(r.subdomain === subdomain && (!r.domain || r.domain === targetDomain))\n );\n\n if (secrets.domain.customRoutes.length === before) {\n printWarning(`No route found for ${subdomain}.${targetDomain}`);\n return;\n }\n\n await writeEveSecrets(secrets);\n printSuccess(`Removed route: ${subdomain}.${targetDomain}`);\n printInfo('Run `eve domain apply` to update Traefik routes');\n });\n\n // ─── List custom routes ────────────────────────────────────────────────────\n domain\n .command('list')\n .description('List all custom subdomain routes')\n .action(async () => {\n const secrets = await readEveSecrets(process.cwd());\n const routes = secrets?.domain?.customRoutes || [];\n const primary = secrets?.domain?.primary || 'not configured';\n\n console.log();\n console.log(colors.primary.bold('Custom Domain Routes'));\n console.log(colors.muted('─'.repeat(60)));\n console.log(`Primary domain: ${colors.primary(primary)}`);\n console.log();\n\n if (routes.length === 0) {\n printInfo('No custom routes configured. Add one with: eve domain add <subdomain> --port <number>');\n return;\n }\n\n console.log(colors.muted(' Subdomain'.padEnd(30) + 'Domain'.padEnd(35) + 'Port'));\n console.log(colors.muted(' ' + '─'.repeat(58)));\n for (const route of routes) {\n const domain = route.domain || primary;\n const fullDomain = `${route.subdomain}.${domain}`;\n console.log(` ${route.subdomain.padEnd(28)}${fullDomain.padEnd(35)}${route.port}`);\n }\n console.log();\n });\n\n // ─── Apply routes to Traefik ───────────────────────────────────────────────\n domain\n .command('apply')\n .description('Apply current domain configuration to Traefik')\n .action(async () => {\n const secrets = await readEveSecrets(process.cwd());\n const domainName = secrets?.domain?.primary;\n if (!domainName) {\n printError('No primary domain configured. Run `eve domain set <domain>` first.');\n process.exit(1);\n }\n\n printInfo(`Applying routes for domain: ${domainName}`);\n \n const traefik = new TraefikService();\n await traefik.configureSubdomains(\n domainName,\n secrets?.domain?.ssl !== false,\n secrets?.domain?.email,\n undefined, // installedComponents - will be resolved internally\n !!secrets?.domain?.behindProxy,\n secrets?.domain?.customRoutes,\n );\n\n printSuccess('Traefik routes updated successfully');\n });\n}\n","/**\n * `eve intent` — record and manage overnight intents.\n *\n * An \"intent\" is a row in `background_tasks` (Hub Protocol REST) that the\n * Hermes daemon polls and dispatches when due. The CLI wraps the Hub\n * Protocol surface so the user can work in plain natural language:\n *\n * eve intent add \"research synap kanban patterns\" --action coder.research\n * eve intent list\n * eve intent show <id>\n * eve intent pause <id>\n * eve intent resume <id>\n * eve intent remove <id>\n * eve intent run <id> # force-run on the next poll cycle\n *\n * Pre-flight: `--action` is validated locally against the mirrored\n * registry from @eve/dna so typos fail fast. The pod is the authoritative\n * validator — when a brand-new action ships server-side but Eve hasn't\n * been updated yet, this CLI surfaces a clear \"update Eve\" hint via the\n * 400 envelope's `validActions` field.\n */\n\nimport { Command } from 'commander';\nimport Table from 'cli-table3';\nimport {\n EVE_BACKGROUND_ACTIONS,\n isValidEveBackgroundAction,\n listEveBackgroundActions,\n type BackgroundTask,\n type BackgroundTaskStatus,\n type BackgroundTaskType,\n} from '@eve/dna';\nimport {\n BackgroundIntentError,\n getIntent,\n listIntents,\n pauseIntent,\n recordIntent,\n removeIntent,\n resumeIntent,\n updateIntent,\n} from '@eve/builder';\nimport {\n colors,\n emojis,\n printError,\n printHeader,\n printInfo,\n printSuccess,\n printWarning,\n} from '../lib/ui.js';\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\ninterface CommonOptions {\n /** Override pod URL — useful for tests / non-default deployments. */\n podUrl?: string;\n}\n\nfunction shortId(id: string): string {\n return id.length > 8 ? id.slice(0, 8) : id;\n}\n\nfunction formatNullable(v: string | null | undefined, fallback = '—'): string {\n if (!v) return fallback;\n return v;\n}\n\nfunction formatNextRun(row: BackgroundTask): string {\n if (!row.nextRunAt) return '—';\n const at = Date.parse(row.nextRunAt);\n if (Number.isNaN(at)) return row.nextRunAt;\n const delta = at - Date.now();\n if (delta <= 0) return colors.warning('due');\n if (delta < 60_000) return `<1m`;\n if (delta < 3_600_000) return `${Math.round(delta / 60_000)}m`;\n if (delta < 86_400_000) return `${Math.round(delta / 3_600_000)}h`;\n return `${Math.round(delta / 86_400_000)}d`;\n}\n\nfunction formatStatus(s: BackgroundTaskStatus): string {\n if (s === 'active') return colors.success(s);\n if (s === 'paused') return colors.muted(s);\n return colors.error(s);\n}\n\n/**\n * Map a free-text prompt into a stable `name`. Strip leading verbs,\n * truncate at 60 chars, never emit empty strings.\n */\nfunction deriveName(prompt: string): string {\n const cleaned = prompt.trim().replace(/\\s+/g, ' ');\n if (!cleaned) return 'untitled intent';\n const truncated = cleaned.length > 60 ? cleaned.slice(0, 57).trimEnd() + '…' : cleaned;\n return truncated;\n}\n\n/**\n * Centralised error renderer. Maps every BackgroundIntentError kind to a\n * concrete fix hint so the operator never has to grep this file to find\n * out what `unauthorized` means.\n */\nfunction renderIntentError(err: unknown, contextHint?: string): void {\n if (!(err instanceof BackgroundIntentError)) {\n printError(err instanceof Error ? err.message : String(err));\n return;\n }\n printError(err.message);\n switch (err.kind) {\n case 'no_auth':\n printInfo('Fix: run `eve install` (configures pod URL) or `eve auth provision --agent eve`.');\n break;\n case 'invalid_action': {\n printInfo('Use one of:');\n const valid = err.validActions ?? listEveBackgroundActions();\n for (const a of valid) {\n console.log(` ${colors.primary(a.id.padEnd(22))} ${colors.muted(a.description)}`);\n }\n break;\n }\n case 'unauthorized':\n printInfo('Fix: `eve auth status --agent eve` then `eve auth renew --agent eve`.');\n break;\n case 'transport':\n printInfo('Fix: pod unreachable — `eve doctor` to diagnose, or check network.');\n break;\n case 'not_found':\n printInfo('Fix: confirm the id with `eve intent list`. The row may have been deleted.');\n break;\n case 'proposed':\n printInfo(\n `A proposal was created (id=${err.proposalId ?? 'unknown'}); approve it on the pod first.`,\n );\n break;\n case 'validation':\n printInfo(`Fix: re-check the inputs. ${contextHint ?? ''}`.trim());\n break;\n default:\n printInfo('Run `eve doctor` if this keeps happening.');\n }\n}\n\n// ---------------------------------------------------------------------------\n// `eve intent add`\n// ---------------------------------------------------------------------------\n\ninterface AddOptions extends CommonOptions {\n action: string;\n schedule?: string;\n type?: BackgroundTaskType;\n workspace?: string;\n name?: string;\n}\n\nasync function runAdd(prompt: string, opts: AddOptions): Promise<void> {\n const trimmedPrompt = (prompt ?? '').trim();\n if (!trimmedPrompt) {\n printError('Prompt is required: `eve intent add \"<prompt>\" --action <id>`');\n process.exitCode = 1;\n return;\n }\n if (!opts.action) {\n printError('--action is required.');\n printInfo('Use one of:');\n for (const a of listEveBackgroundActions()) {\n console.log(` ${colors.primary(a.id.padEnd(22))} ${colors.muted(a.description)}`);\n }\n process.exitCode = 1;\n return;\n }\n if (!isValidEveBackgroundAction(opts.action)) {\n printError(`Unknown action \"${opts.action}\".`);\n printInfo('Use one of:');\n for (const a of listEveBackgroundActions()) {\n console.log(` ${colors.primary(a.id.padEnd(22))} ${colors.muted(a.description)}`);\n }\n process.exitCode = 1;\n return;\n }\n\n // Schedule resolution rules:\n // --type interval --schedule 1h → interval, run every 1h, next=now+1h\n // --type cron --schedule \"0 9 * * *\" → cron, next computed by daemon\n // no --schedule → one-shot interval, next=now+1m\n let type: BackgroundTaskType;\n let schedule: string | undefined;\n let nextRunHint: string | undefined;\n if (opts.schedule) {\n type = opts.type ?? guessTypeFromSchedule(opts.schedule);\n schedule = opts.schedule;\n } else {\n type = opts.type ?? 'interval';\n schedule = '1m';\n // Add a soft hint surfaced to the user but the daemon will compute\n // its own nextRunAt after the first run. We don't try to set\n // nextRunAt at create time — the backend service is responsible\n // for setting it on insert.\n nextRunHint = '~1m (one-shot)';\n }\n\n const definition = EVE_BACKGROUND_ACTIONS[opts.action];\n if (definition?.requiresWorkspace && !opts.workspace) {\n printError(`Action \"${opts.action}\" requires --workspace <id>.`);\n process.exitCode = 1;\n return;\n }\n\n const name = opts.name?.trim() || deriveName(trimmedPrompt);\n\n printHeader(`${emojis.sparkles} Recording intent`);\n console.log();\n printInfo(`Action: ${colors.primary(opts.action)}`);\n printInfo(`Name: ${name}`);\n printInfo(`Type: ${type}`);\n if (schedule) printInfo(`Schedule: ${schedule}`);\n if (nextRunHint) printInfo(`Next run: ${nextRunHint}`);\n if (opts.workspace) printInfo(`Workspace: ${opts.workspace}`);\n console.log();\n\n try {\n const created = await recordIntent({\n name,\n description: trimmedPrompt,\n type,\n schedule,\n action: opts.action,\n workspaceId: opts.workspace,\n context: {\n userPrompt: trimmedPrompt,\n },\n auth: opts.podUrl\n ? { podUrl: opts.podUrl, apiKey: '' }\n : undefined,\n });\n printSuccess(`Intent recorded — id ${shortId(created.id)} (${created.id})`);\n if (!opts.schedule) {\n // For one-shot intents, immediately bump nextRunAt to now so the\n // daemon picks it up on the next cycle without waiting for the\n // backend to compute it.\n try {\n await updateIntent({\n id: created.id,\n patch: { nextRunAt: new Date().toISOString() },\n });\n } catch (err) {\n printWarning(\n `Intent created but force-run scheduling failed (${err instanceof Error ? err.message : String(err)}); ` +\n `it will run on its normal cadence.`,\n );\n }\n }\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\nfunction guessTypeFromSchedule(schedule: string): BackgroundTaskType {\n // 5-field whitespace-separated → cron. Otherwise → interval.\n const parts = schedule.trim().split(/\\s+/);\n return parts.length === 5 ? 'cron' : 'interval';\n}\n\n// ---------------------------------------------------------------------------\n// `eve intent list`\n// ---------------------------------------------------------------------------\n\ninterface ListOptions extends CommonOptions {\n status?: BackgroundTaskStatus | 'all';\n type?: BackgroundTaskType;\n}\n\nasync function runList(opts: ListOptions): Promise<void> {\n try {\n const rows = await listIntents({\n status: opts.status,\n type: opts.type,\n });\n if (rows.length === 0) {\n printInfo('No intents recorded yet.');\n printInfo('Add one: `eve intent add \"<prompt>\" --action <id>`');\n return;\n }\n const table = new Table({\n head: ['ID', 'Name', 'Action', 'Type', 'Sched.', 'Next', 'Status', 'Runs'].map((h) =>\n colors.primary(h),\n ),\n style: { head: [], border: [] },\n wordWrap: true,\n });\n for (const r of rows) {\n table.push([\n colors.muted(shortId(r.id)),\n truncate(r.name, 30),\n r.action,\n r.type,\n truncate(formatNullable(r.schedule), 12),\n formatNextRun(r),\n formatStatus(r.status),\n `${r.executionCount}`,\n ]);\n }\n console.log(table.toString());\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\nfunction truncate(s: string, n: number): string {\n if (s.length <= n) return s;\n return s.slice(0, n - 1) + '…';\n}\n\n// ---------------------------------------------------------------------------\n// `eve intent show <id>`\n// ---------------------------------------------------------------------------\n\nasync function runShow(id: string, _opts: CommonOptions): Promise<void> {\n if (!id) {\n printError('id is required: `eve intent show <id>`');\n process.exitCode = 1;\n return;\n }\n try {\n const row = await getIntent({ id });\n printHeader(`${emojis.info} ${row.name}`);\n console.log();\n printKv('ID', row.id);\n printKv('Action', row.action);\n printKv('Type', row.type);\n if (row.schedule) printKv('Schedule', row.schedule);\n printKv('Status', row.status);\n if (row.workspaceId) printKv('Workspace', row.workspaceId);\n printKv('Created', row.createdAt);\n printKv('Updated', row.updatedAt);\n printKv('Last run', formatNullable(row.lastRunAt));\n printKv('Next run', formatNullable(row.nextRunAt));\n printKv('Runs', `${row.executionCount} (✓ ${row.successCount}, ✗ ${row.failureCount})`);\n if (row.errorMessage) {\n console.log();\n printError(`Last error: ${row.errorMessage}`);\n }\n if (row.description) {\n console.log();\n printInfo('Description:');\n console.log(` ${colors.muted(row.description)}`);\n }\n if (row.context && Object.keys(row.context).length > 0) {\n console.log();\n printInfo('Context:');\n console.log(colors.muted(JSON.stringify(row.context, null, 2)));\n }\n if (row.metadata && Object.keys(row.metadata).length > 0) {\n console.log();\n printInfo('Metadata:');\n console.log(colors.muted(JSON.stringify(row.metadata, null, 2)));\n }\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\nfunction printKv(key: string, value: string): void {\n console.log(` ${colors.muted(key.padEnd(11))} ${value}`);\n}\n\n// ---------------------------------------------------------------------------\n// `eve intent pause | resume | remove | run`\n// ---------------------------------------------------------------------------\n\nasync function runPause(id: string): Promise<void> {\n if (!id) {\n printError('id required.');\n process.exitCode = 1;\n return;\n }\n try {\n const row = await pauseIntent({ id });\n printSuccess(`Paused ${shortId(row.id)} — ${row.name}`);\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\nasync function runResume(id: string): Promise<void> {\n if (!id) {\n printError('id required.');\n process.exitCode = 1;\n return;\n }\n try {\n const row = await resumeIntent({ id });\n printSuccess(`Resumed ${shortId(row.id)} — ${row.name}`);\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\nasync function runRemove(id: string): Promise<void> {\n if (!id) {\n printError('id required.');\n process.exitCode = 1;\n return;\n }\n try {\n await removeIntent({ id });\n printSuccess(`Removed ${shortId(id)}.`);\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\nasync function runRun(id: string): Promise<void> {\n if (!id) {\n printError('id required.');\n process.exitCode = 1;\n return;\n }\n try {\n const row = await updateIntent({\n id,\n patch: { nextRunAt: new Date().toISOString() },\n });\n printSuccess(`Scheduled ${shortId(row.id)} for next poll cycle.`);\n } catch (err) {\n renderIntentError(err);\n process.exitCode = 1;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Command registration\n// ---------------------------------------------------------------------------\n\nexport function intentCommand(program: Command): void {\n const intent = program\n .command('intent')\n .description(`${emojis.sparkles} Record and manage overnight intents (background_tasks)`);\n\n intent\n .command('add <prompt>')\n .description('Record a new background intent.')\n .option('--action <id>', 'Action id from the registry (required).')\n .option('--schedule <schedule>', 'Cron expression (5 fields) or interval (e.g. 1h, 30m).')\n .option('--type <type>', 'cron | event | interval (auto-detected when omitted).')\n .option('--workspace <id>', 'Workspace id — required for action ids that need a workspace.')\n .option('--name <name>', 'Display name (auto-derived from the prompt when omitted).')\n .action(async (prompt: string, opts: AddOptions) => {\n try {\n await runAdd(prompt, opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n })\n .addHelpText(\n 'after',\n '\\nAvailable actions:\\n' +\n listEveBackgroundActions()\n .map((a) => ` ${a.id.padEnd(22)} ${a.description}`)\n .join('\\n'),\n );\n\n intent\n .command('list')\n .description('List recorded intents (one row per intent).')\n .option('--status <s>', 'active | paused | error | all (default: all)')\n .option('--type <t>', 'cron | event | interval')\n .action(async (opts: ListOptions) => {\n try {\n await runList(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n intent\n .command('show <id>')\n .description('Show full details for one intent.')\n .action(async (id: string, opts: CommonOptions) => {\n try {\n await runShow(id, opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n intent\n .command('pause <id>')\n .description('Pause an intent — the daemon will skip it until resumed.')\n .action(async (id: string) => {\n try {\n await runPause(id);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n intent\n .command('resume <id>')\n .description('Resume a paused (or errored) intent.')\n .action(async (id: string) => {\n try {\n await runResume(id);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n intent\n .command('remove <id>')\n .alias('rm')\n .description('Delete an intent permanently.')\n .action(async (id: string) => {\n try {\n await runRemove(id);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n intent\n .command('run <id>')\n .description('Force-run an intent on the next poll cycle (PATCHes nextRunAt = now).')\n .action(async (id: string) => {\n try {\n await runRun(id);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n}\n","/**\n * `eve deploy` — build, package, push via GHCR, then deploy to Coolify.\n *\n * Usage:\n * eve deploy # detect, build, push, deploy to staging\n * eve deploy --prod # deploy to production\n * eve deploy --docker # build + package only, skip push & deploy\n * eve deploy --app <name> # target a specific workspace app\n * eve deploy --clean # clean before build\n * eve deploy --yes # skip confirmation\n * eve deploy --env KEY=VAL # set env vars on deploy\n * eve deploy --tag mytag # custom image tag\n * eve deploy --rollback <image> # redeploy a previous image\n */\n\nimport { existsSync, readFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport * as clack from '@clack/prompts';\nimport {\n detectAppConfig,\n buildAndPackageImage,\n deployToCoolify,\n detectCoolifyTargets,\n type AppConfig,\n type DeployEnv,\n type DeployResult,\n} from '@eve/dna';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n createSpinner,\n printBox,\n} from '../lib/ui.js';\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\ninterface DeployOptions {\n docker?: boolean;\n app?: string;\n clean?: boolean;\n token?: string;\n tag?: string;\n prod?: boolean;\n env?: string[];\n yes?: boolean;\n rollback?: string;\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport function deployCommand(program: Command): void {\n const deploy = program\n .command('deploy')\n .description(`${emojis.arms} Build, package, and deploy an app via GHCR + Coolify`)\n .option(\n '--app <name>',\n 'Target a specific workspace app (for monorepo projects).',\n )\n .option(\n '--docker',\n 'Build and package only — skip pushing and deploying.',\n )\n .option(\n '--clean',\n 'Remove previous build output before building.',\n )\n .option(\n '--token <ghcr-token>',\n 'GitHub PAT for GHCR push (overrides stored credentials).',\n )\n .option(\n '--tag <tag>',\n 'Custom image tag (default: branch-sha).',\n )\n .option(\n '--prod',\n 'Deploy to production (CT 103) instead of staging.',\n )\n .option(\n '--env <key=value>',\n 'Custom environment variable (repeatable). e.g. --env DATABASE_URL=postgres://...',\n )\n .option(\n '-y, --yes',\n 'Skip confirmation step (non-interactive / CI mode).',\n )\n .option(\n '--rollback <image>',\n 'Re-deploy a previous image (e.g. ghcr.io/synap-core/app:branch-abc1234).',\n )\n .action(async (opts: DeployOptions) => {\n try {\n if (opts.rollback) {\n await runRollback(opts);\n } else {\n await runDeploy(opts);\n }\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nasync function runDeploy(opts: DeployOptions): Promise<void> {\n const t0 = Date.now();\n\n // Step 1: Determine working directory\n const baseDir = process.env.EVE_DEPLOY_DIR || process.cwd();\n\n // Step 2: Detect app\n console.log();\n printHeader('eve deploy');\n console.log();\n\n let appConfig: AppConfig | null = null;\n\n if (opts.app) {\n printInfo(`Targeting workspace app: ${colors.info(opts.app)}`);\n printInfo(`Base directory: ${colors.info(baseDir)}`);\n\n const candidateDirs = [\n join(baseDir, 'apps', opts.app),\n join(baseDir, 'packages', opts.app),\n join(baseDir, 'packages/@eve', opts.app),\n ];\n\n let targetDir: string | null = null;\n for (const d of candidateDirs) {\n const pkgPath = join(d, 'package.json');\n if (existsSync(pkgPath)) {\n targetDir = d;\n break;\n }\n }\n\n if (!targetDir) {\n printError(`Could not find workspace app \"${opts.app}\"`);\n printInfo(`Searched in: ${candidateDirs.join(', ')}`);\n process.exit(1);\n }\n\n appConfig = detectAppConfig(targetDir);\n appConfig.workspaceApp = opts.app;\n } else {\n appConfig = detectAppConfig(baseDir);\n }\n\n // Step 3: Display detected config\n console.log();\n printInfo(`App: ${colors.info(appConfig.name)}`);\n printInfo(`Framework: ${colors.info(appConfig.framework)}`);\n printInfo(`Build cmd: ${colors.muted(appConfig.buildCommand)}`);\n printInfo(`Output dir: ${colors.muted(appConfig.outputDir)}`);\n if (appConfig.branch) {\n printInfo(`Branch: ${colors.muted(appConfig.branch)}`);\n }\n printInfo(`Directory: ${colors.muted(appConfig.cwd)}`);\n\n // Step 4: (Optional) Clean build output\n if (opts.clean) {\n console.log();\n if (!opts.yes) {\n const confirmed = await clack.confirm({\n message: `Remove previous build output in ${appConfig.outputDir}?`,\n initialValue: false,\n });\n if (!confirmed) {\n clack.cancel('Build clean cancelled.');\n return;\n }\n }\n printInfo('Cleaning previous build...');\n const outPath = join(appConfig.cwd, appConfig.outputDir);\n if (existsSync(outPath)) {\n rmSync(outPath, { recursive: true, force: true });\n printSuccess('Cleaned');\n } else {\n printInfo('Nothing to clean');\n }\n }\n\n // Step 5: Parse env vars\n const envVars = parseEnvVars(opts.env);\n\n // Step 6: Build and package\n console.log();\n const spinner = createSpinner(opts.docker ? 'Building and packaging...' : 'Building, packaging, and deploying...');\n spinner.start();\n\n const ghcrToken = opts.token || process.env.GHCR_TOKEN || '';\n const buildResult = await buildAndPackageImage(\n appConfig,\n 'synap-core',\n ghcrToken || undefined,\n !!opts.docker,\n opts.tag,\n );\n\n let deployResult: DeployResult | undefined;\n\n if (opts.docker) {\n spinner.succeed('Done');\n printInfo('Build complete. Push and deploy with `eve deploy` (without --docker).');\n } else {\n // Step 7: Deploy to Coolify\n const targetEnv: DeployEnv = opts.prod ? 'production' : 'staging';\n const targets = detectCoolifyTargets();\n\n if (!targets[targetEnv]) {\n spinner.warn(`No ${targetEnv} Coolify target configured`);\n printWarning(`No ${targetEnv} Coolify target configured.`);\n printInfo(`Set env vars: COOLIFY_${targetEnv.toUpperCase()}_URL + COOLIFY_${targetEnv.toUpperCase()}_TOKEN`);\n printInfo(`Or run: eve login --coolify-${targetEnv} <token>`);\n console.log();\n return;\n }\n\n // Confirm before deploying to production\n if (targetEnv === 'production' && !opts.yes) {\n spinner.warn('Awaiting production confirmation');\n const confirmed = await clack.confirm({\n message: `Deploying to PRODUCTION. Continue?`,\n initialValue: false,\n });\n if (!confirmed) {\n clack.cancel('Deploy cancelled.');\n return;\n }\n }\n\n deployResult = await deployToCoolify({\n config: appConfig,\n dockerImage: buildResult.imageName,\n targetEnv,\n targets,\n envVars: Object.keys(envVars).length > 0 ? envVars : undefined,\n force: opts.clean,\n });\n\n spinner.succeed('Deployed');\n\n // Step 8: Post-deploy wait loop\n const url = deployResult.url || 'pending';\n console.log();\n printInfo(`Waiting for app to start...`);\n const readyUrl = await waitForDeploy(deployResult);\n if (readyUrl) {\n printSuccess(`App is live: ${readyUrl}`);\n }\n }\n\n // Step 9: Summary\n const elapsed = ((Date.now() - t0) / 1000).toFixed(1);\n const target = opts.prod ? 'production (CT 103)' : 'staging (CT 104)';\n console.log();\n printBox('Deployment summary', [\n `App: ${appConfig.name}`,\n `Framework: ${appConfig.framework}`,\n `Image: ${buildResult.imageName}`,\n `Target: ${target}`,\n `Build time: ${elapsed}s`,\n opts.docker ? 'Mode: Build-only (no push/deploy)' : 'Mode: Full build + push + deploy',\n ...(deployResult?.url ? [`URL: ${deployResult.url}`] : []),\n ]);\n}\n\nasync function runRollback(opts: DeployOptions): Promise<void> {\n const t0 = Date.now();\n const image = opts.rollback!;\n\n console.log();\n printHeader('eve deploy');\n console.log();\n printInfo(`Rolling back to image: ${colors.info(image)}`);\n\n // We need to detect the app config to know the name for Coolify\n const baseDir = process.env.EVE_DEPLOY_DIR || process.cwd();\n const appConfig = detectAppConfig(baseDir);\n\n const targetEnv: DeployEnv = opts.prod ? 'production' : 'staging';\n const targets = detectCoolifyTargets();\n\n if (!targets[targetEnv]) {\n printWarning(`No ${targetEnv} Coolify target configured.`);\n return;\n }\n\n if (!opts.yes) {\n const confirmed = await clack.confirm({\n message: `Rollback to ${image}?`,\n initialValue: false,\n });\n if (!confirmed) {\n clack.cancel('Rollback cancelled.');\n return;\n }\n }\n\n const spinner = createSpinner('Triggering rollback...');\n spinner.start();\n\n const deployResult = await deployToCoolify({\n config: appConfig,\n dockerImage: image,\n targetEnv,\n targets,\n force: true,\n });\n\n spinner.succeed('Rolled back');\n\n const elapsed = ((Date.now() - t0) / 1000).toFixed(1);\n console.log();\n printBox('Rollback summary', [\n `Image: ${image}`,\n `Target: ${targetEnv}`,\n `Time: ${elapsed}s`,\n ...(deployResult?.url ? [`URL: ${deployResult.url}`] : []),\n ]);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction parseEnvVars(raw?: string[]): Record<string, string> {\n if (!raw || raw.length === 0) return {};\n const result: Record<string, string> = {};\n for (const entry of raw) {\n const idx = entry.indexOf('=');\n if (idx === -1) {\n printWarning(`Skipping malformed env var (expected KEY=VAL): ${entry}`);\n continue;\n }\n const key = entry.slice(0, idx);\n const val = entry.slice(idx + 1);\n result[key] = val;\n }\n return result;\n}\n\n/**\n * Wait for a deployed app to become available by polling the URL.\n * Defaults to 90 retries (4.5 minutes at 5s intervals).\n * Returns the live URL or null on timeout.\n */\nasync function waitForDeploy(\n deployResult: { url?: string; appId?: string },\n retries = 90,\n intervalMs = 5000,\n): Promise<string | null> {\n const targetUrl = deployResult.url;\n if (!targetUrl) {\n return null;\n }\n\n // For Coolify, we poll the internal API for deployment status\n const urlPattern = /https?:\\/\\//;\n if (urlPattern.test(targetUrl)) {\n // Try to HTTP GET the app URL\n for (let i = 0; i < retries; i++) {\n try {\n const resp = await fetch(targetUrl, {\n signal: AbortSignal.timeout(5000),\n method: 'HEAD',\n });\n if (resp.ok || resp.status === 301 || resp.status === 302) {\n return targetUrl;\n }\n // Also try a GET on root\n const getResp = await fetch(targetUrl, {\n signal: AbortSignal.timeout(5000),\n });\n if (getResp.ok) {\n return targetUrl;\n }\n } catch {\n // App not ready yet, continue polling\n }\n const dots = '.'.repeat(Math.min(i + 1, 6));\n process.stdout.write(`\\r Waiting... ${dots}`);\n await sleep(intervalMs);\n }\n } else {\n // Coolify app ID — poll the API\n await sleep(10000);\n }\n\n return targetUrl; // Return whatever we have\n}\n\n","/**\n * `eve login` — store GHCR PAT and/or Coolify tokens locally.\n *\n * Usage:\n * eve login --ghcr <token> Store GitHub PAT for GHCR\n * eve login --coolify-staging Store Coolify staging token\n * eve login --coolify-prod Store Coolify production token\n * eve login (no args) Show stored status\n * eve login --clear Remove all stored credentials\n */\n\nimport { Command } from 'commander';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n} from '../lib/ui.js';\n\nimport {\n existsSync,\n mkdirSync,\n writeFileSync,\n readFileSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst CRED_DIR = join(homedir(), '.config', 'eve');\nconst CRED_FILE = join(CRED_DIR, 'deploy-creds.json');\n\ninterface DeployCreds {\n ghcr?: string | null;\n coolifyStaging?: string | null;\n coolifyProd?: string | null;\n}\n\nfunction loadCreds(): DeployCreds {\n if (existsSync(CRED_FILE)) {\n try {\n return JSON.parse(readFileSync(CRED_FILE, 'utf-8')) as DeployCreds;\n } catch {\n return {};\n }\n }\n return {};\n}\n\nfunction saveCreds(creds: DeployCreds): void {\n mkdirSync(CRED_DIR, { recursive: true });\n writeFileSync(CRED_FILE, JSON.stringify(creds, null, 2), { mode: 0o600 });\n}\n\nfunction maskToken(token: string): string {\n if (token.length <= 8) return '****';\n return token.slice(0, 4) + '…' + token.slice(-4);\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\nexport function loginCommand(program: Command): void {\n program\n .command('login')\n .description(`${emojis.arms} Store auth tokens for deploy/push operations`)\n .option('--ghcr <token>', 'GitHub PAT for GHCR push')\n .option('--coolify-staging <token>', 'Coolify staging API token')\n .option('--coolify-prod <token>', 'Coolify production API token')\n .option('--clear', 'Remove all stored credentials')\n .action(async (opts: {\n ghcr?: string;\n coolifyStaging?: string;\n coolifyProd?: string;\n clear?: boolean;\n }) => {\n try {\n await runLogin(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nasync function runLogin(opts: {\n ghcr?: string;\n coolifyStaging?: string;\n coolifyProd?: string;\n clear?: boolean;\n}): Promise<void> {\n console.log();\n printHeader('eve login');\n\n // --clear\n if (opts.clear) {\n saveCreds({});\n printSuccess('All stored credentials removed');\n return;\n }\n\n // No args — show status\n if (!opts.ghcr && !opts.coolifyStaging && !opts.coolifyProd) {\n const creds = loadCreds();\n const entries: string[] = [];\n if (creds.ghcr) {\n entries.push(`GHCR: ${colors.success('configured')} (${maskToken(creds.ghcr)})`);\n } else {\n entries.push('GHCR: ' + colors.warning('not configured'));\n }\n if (creds.coolifyStaging) {\n entries.push(`Coolify Stg: ${colors.success('configured')} (${maskToken(creds.coolifyStaging)})`);\n } else {\n const hasEnv = !!process.env.COOLIFY_STAGING_TOKEN;\n const label = hasEnv ? colors.info('env var only') : '—';\n entries.push(`Coolify Stg: ${label}`);\n }\n if (creds.coolifyProd) {\n entries.push(`Coolify Prod:${colors.success(' configured')} (${maskToken(creds.coolifyProd)})`);\n } else {\n const hasEnv = !!process.env.COOLIFY_PROD_TOKEN;\n const label = hasEnv ? colors.info('env var only') : '—';\n entries.push(`Coolify Prod:${label}`);\n }\n console.log();\n for (const line of entries) {\n console.log(` ${line}`);\n }\n console.log();\n printInfo('Run with flags to store: --ghcr <pat>, --coolify-staging <token>');\n return;\n }\n\n // Store values\n const creds = loadCreds();\n\n if (opts.ghcr) {\n creds.ghcr = opts.ghcr;\n printSuccess('GHCR token stored');\n }\n if (opts.coolifyStaging) {\n creds.coolifyStaging = opts.coolifyStaging;\n printSuccess('Coolify staging token stored');\n }\n if (opts.coolifyProd) {\n creds.coolifyProd = opts.coolifyProd;\n printSuccess('Coolify production token stored');\n }\n\n saveCreds(creds);\n}\n","/**\n * `eve ls` — list deployed apps across Coolify targets.\n *\n * Usage:\n * eve ls List staging + production apps\n * eve ls --staging Only staging\n * eve ls --production Only production\n * eve ls --json Machine-readable output\n */\n\nimport { Command } from 'commander';\nimport {\n colors,\n emojis,\n printHeader,\n printError,\n printInfo,\n} from '../lib/ui.js';\nimport {\n listCoolifyApps,\n getCoolifyTargetsFromEnv,\n type CoolifyTarget,\n type CoolifyApp,\n} from '@eve/dna';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveTargets(\n opts: { staging?: boolean; production?: boolean },\n): { env: string; label: string; target: CoolifyTarget }[] {\n const envVars = getCoolifyTargetsFromEnv();\n const results: { env: string; label: string; target: CoolifyTarget }[] = [];\n\n if (!opts.staging && envVars.staging) {\n results.push({ env: 'staging', label: 'Staging (CT 104)', target: envVars.staging });\n }\n if (!opts.production && envVars.staging && opts.staging) {\n results.push({ env: 'staging', label: 'Staging (CT 104)', target: envVars.staging });\n }\n if (!opts.staging && envVars.production) {\n results.push({ env: 'production', label: 'Production (CT 103)', target: envVars.production });\n }\n if (!opts.production && envVars.production && opts.production) {\n results.push({ env: 'production', label: 'Production (CT 103)', target: envVars.production });\n }\n\n return results;\n}\n\n// ---------------------------------------------------------------------------\n// Main\n// ---------------------------------------------------------------------------\n\ninterface LsOptions {\n staging?: boolean;\n production?: boolean;\n json?: boolean;\n}\n\ninterface LsApp {\n name: string;\n env: string;\n url: string;\n status: string;\n}\n\nexport function lsCommand(program: Command): void {\n program\n .command('ls')\n .description(`${emojis.info} List deployed apps in Coolify`)\n .option('--staging', 'Only show staging apps')\n .option('--production', 'Only show production apps')\n .option('--json', 'Output as JSON')\n .action(async (opts: LsOptions) => {\n try {\n await runLs(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nasync function runLs(opts: LsOptions): Promise<void> {\n console.log();\n\n const targets = resolveTargets(opts);\n\n const allApps: LsApp[] = [];\n\n if (targets.length === 0) {\n printHeader('eve ls');\n printInfo('No Coolify targets configured.');\n printInfo('Set env vars: COOLIFY_STAGING_URL + COOLIFY_STAGING_TOKEN, COOLIFY_PROD_URL + COOLIFY_PROD_TOKEN');\n return;\n }\n\n if (!opts.json) {\n printHeader('eve ls');\n }\n\n for (const target of targets) {\n try {\n const apps = await listCoolifyApps(target.target);\n\n if (opts.json) {\n for (const app of apps) {\n allApps.push({\n name: app.name || '<unnamed>',\n env: target.env,\n url: app.url || '',\n status: app.status || 'unknown',\n });\n }\n continue;\n }\n\n console.log(`\\n ${colors.primary.bold(target.label)} (${target.env}):`);\n\n if (apps.length === 0) {\n console.log(` ${colors.muted(' No apps deployed')}`);\n continue;\n }\n\n for (const app of apps) {\n const name = app.name || '<unnamed>';\n const url = app.url || '';\n const status = app.status || 'unknown';\n allApps.push({ name, env: target.env, url, status });\n console.log(` ${colors.info('•')} ${colors.muted(name.padEnd(30))} ${status}`);\n if (url) {\n console.log(` ${url}`);\n }\n }\n } catch {\n if (!opts.json) {\n console.log(`\\n ${colors.primary.bold(target.label)} (${target.env}):`);\n console.log(` ${colors.warning(' Failed to connect')}`);\n }\n }\n }\n\n if (opts.json) {\n console.log(JSON.stringify(allApps, null, 2));\n } else {\n console.log();\n }\n}\n","/**\n * `eve synap` — Manage Synap staging on CT101 (PM2 + Traefik).\n *\n * Usage:\n * eve synap deploy # sync + build all + PM2 start + routes\n * eve synap deploy --app crm # build + deploy single app\n * eve synap deploy --no-build # PM2 reload + routes only\n * eve synap status # PM2 + Docker + routes overview\n * eve synap logs <app> # tail PM2 logs\n * eve synap build # build all apps\n * eve synap build crm devplane # build specific apps\n */\n\nimport type { Command } from 'commander';\nimport { execSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { readEveSecrets } from '@eve/dna';\nimport { TraefikService } from '@eve/legs';\nimport { colors, printSuccess, printInfo, printWarning, printError, printHeader } from '../lib/ui.js';\nimport { syncRepo } from '../lib/git.js';\n\nconst SYNAP_DIR = '/opt/synap/synap-app';\nconst PM2_APPS = [\n { name: 'hub', port: 3120 },\n { name: 'canvas', port: 3124 },\n { name: 'base', port: 3126 },\n { name: 'web', port: 3128 },\n { name: 'studio', port: 3130 },\n { name: 'devplane', port: 3132 },\n { name: 'crm', port: 3134 },\n];\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction run(cmd: string, cwd?: string): string {\n try {\n return execSync(cmd, { cwd, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'inherit'] });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Command failed: ${cmd}\\n${msg}`);\n }\n}\n\nfunction runSilent(cmd: string, cwd?: string): string {\n return execSync(cmd, { cwd, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });\n}\n\nfunction pm2Cmd(args: string): string {\n return runSilent(`pm2 ${args}`).trim();\n}\n\nfunction appDir(name: string): string {\n return join(SYNAP_DIR, 'apps', name);\n}\n\nfunction hasPackageJson(dir: string): boolean {\n return existsSync(join(dir, 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Commands\n// ---------------------------------------------------------------------------\n\nexport function synapCommand(program: Command): void {\n const synap = program\n .command('synap')\n .description('Manage Synap staging on CT101 (PM2 + Traefik)');\n\n // ─── deploy ──────────────────────────────────────────────────────────────\n synap\n .command('deploy')\n .description('Build and deploy Synap apps to staging')\n .option('--app <name>', 'Deploy a single app')\n .option('--no-build', 'Skip build, only restart PM2 + apply routes')\n .option('--clean', 'Clean .next before build')\n .action(async (opts: { app?: string; build?: boolean; clean?: boolean }) => {\n printHeader('eve synap deploy');\n console.log();\n\n if (!existsSync(SYNAP_DIR)) {\n printError(`Synap app directory not found: ${SYNAP_DIR}`);\n printInfo('Run sync first: ./scripts/sync-to-ct101.sh');\n process.exit(1);\n }\n\n // Step 1: Sync code.\n //\n // FAIL CLOSED on anything that means the remote was not reached. The\n // previous version caught every error as \"may be uncommitted changes\"\n // and continued — so an auth or HTTP failure was reported to the\n // operator as a dirty tree, the build then ran against a STALE\n // checkout, and the deploy reported success. `syncRepo` distinguishes\n // the one benign case (local edits, remote reachable) from the rest;\n // only that one may continue. See lib/git.ts for the full history.\n printInfo('Syncing code...');\n const sync = await syncRepo(SYNAP_DIR);\n if (sync.kind === 'failed') {\n printError(`Cannot sync ${SYNAP_DIR} (${sync.reason}) — refusing to build stale code`);\n console.log(colors.muted(sync.message));\n printInfo(sync.fix);\n printInfo('Re-run with --no-build to deploy the current checkout as-is.');\n process.exit(1);\n }\n if (sync.note) printWarning(sync.note);\n if (sync.kind === 'dirty') {\n printWarning(\n `Remote reachable and up to date, but ${sync.files.length} tracked file(s) are modified locally — building the working tree as-is:`,\n );\n for (const f of sync.files.slice(0, 10)) console.log(colors.muted(` ${f}`));\n if (sync.files.length > 10) console.log(colors.muted(` … and ${sync.files.length - 10} more`));\n } else {\n printSuccess(\n sync.from === sync.to ? `Already current (${sync.to})` : `Code synced ${sync.from} → ${sync.to}`,\n );\n }\n\n // Step 2: Build\n if (opts.build !== false) {\n console.log();\n if (opts.app) {\n await buildApp(opts.app, opts.clean);\n } else {\n await buildAll(opts.clean);\n }\n }\n\n // Step 3: Start/restart PM2\n console.log();\n printInfo('Starting PM2 apps...');\n if (opts.app) {\n startPm2App(opts.app);\n } else {\n startAllPm2Apps();\n }\n\n // Step 4: Apply Traefik routes\n console.log();\n printInfo('Applying Traefik routes...');\n await applyRoutes();\n\n console.log();\n printSuccess('Deploy complete');\n printStagingUrls();\n });\n\n // ─── build ───────────────────────────────────────────────────────────────\n synap\n .command('build')\n .description('Build Synap apps')\n .argument('[apps...]', 'App names to build (default: all)')\n .option('--clean', 'Clean .next before build')\n .action(async (apps: string[], opts: { clean?: boolean }) => {\n printHeader('eve synap build');\n console.log();\n\n if (apps.length === 0) {\n await buildAll(opts.clean);\n } else {\n for (const app of apps) {\n await buildApp(app, opts.clean);\n }\n }\n\n console.log();\n printSuccess('Build complete');\n });\n\n // ─── status ──────────────────────────────────────────────────────────────\n synap\n .command('status')\n .alias('s')\n .description('Show Synap staging status')\n .action(async () => {\n printHeader('eve synap status');\n console.log();\n\n // PM2 status\n printInfo('PM2 Apps:');\n console.log(pm2Cmd('list'));\n\n // Docker services\n console.log();\n printInfo('Docker Services (synap-backend):');\n try {\n const out = runSilent('docker ps --filter \"name=synap-backend\" --format \"table {{.Names}}\\t{{.Status}}\"');\n console.log(out);\n } catch {\n printWarning('No synap-backend containers found');\n }\n\n // Traefik routes\n console.log();\n printInfo('Traefik Routes:');\n try {\n const routes = runSilent('curl -s http://localhost:8080/api/http/routers');\n const names = JSON.parse(routes)\n .filter((r: any) => r.name.includes('custom') || r.name.includes('synap') || r.name.includes('pod'))\n .map((r: any) => ` ${r.name.padEnd(30)} ${r.rule || ''}`);\n console.log(names.join('\\n'));\n } catch {\n printWarning('Could not fetch Traefik routes');\n }\n\n // Custom routes from Eve secrets\n console.log();\n printInfo('Custom Domain Routes:');\n try {\n const secrets = await readEveSecrets(process.cwd());\n const customRoutes = secrets?.domain?.customRoutes || [];\n if (customRoutes.length === 0) {\n printInfo(' No custom routes configured');\n } else {\n for (const route of customRoutes) {\n const domain = route.domain || secrets?.domain?.primary || 'unknown';\n console.log(` ${route.subdomain}.${domain} → port ${route.port}`);\n }\n }\n } catch {\n printWarning('Could not read Eve secrets');\n }\n\n console.log();\n });\n\n // ─── logs ────────────────────────────────────────────────────────────────\n synap\n .command('logs')\n .description('View PM2 app logs')\n .argument('<app>', 'App name')\n .option('--lines <n>', 'Number of lines', '50')\n .option('--errors', 'Show only error logs')\n .action((app: string, opts: { lines?: string; errors?: boolean }) => {\n const lines = opts.lines || '50';\n if (opts.errors) {\n run(`pm2 logs ${app} --err --lines ${lines} --nostream`, SYNAP_DIR);\n } else {\n run(`pm2 logs ${app} --lines ${lines} --nostream`, SYNAP_DIR);\n }\n });\n\n // ─── restart ─────────────────────────────────────────────────────────────\n synap\n .command('restart')\n .description('Restart PM2 apps')\n .argument('[apps...]', 'App names to restart (default: all)')\n .option('--update-env', 'Update environment variables')\n .action((apps: string[], opts: { updateEnv?: boolean }) => {\n printHeader('eve synap restart');\n console.log();\n\n const flag = opts.updateEnv ? ' --update-env' : '';\n if (apps.length === 0) {\n printInfo('Restarting all PM2 apps...');\n pm2Cmd(`reload all${flag}`);\n } else {\n for (const app of apps) {\n printInfo(`Restarting ${app}...`);\n pm2Cmd(`restart ${app}${flag}`);\n }\n }\n\n printSuccess('Restarted');\n });\n\n // ─── health ──────────────────────────────────────────────────────────────\n synap\n .command('health')\n .alias('h')\n .description('Quick health check — ports, PM2 status, HTTP response')\n .action(() => {\n printHeader('eve synap health');\n console.log();\n\n console.log(' APP PORT STATUS URL');\n console.log(' ---------- ------- --------- ----------------------------------------');\n\n for (const app of PM2_APPS) {\n const dir = appDir(app.name);\n if (!hasPackageJson(dir)) continue;\n\n // Check PM2 status\n let pm2Online = false;\n try {\n const list = pm2Cmd('jlist');\n const apps = JSON.parse(list);\n const existing = apps.find((a: any) => a.name === app.name);\n pm2Online = existing && existing.pm_uptime > 0;\n } catch { /* pm2 not ready */ }\n\n // Check HTTP response\n let httpCode = '000';\n try {\n httpCode = runSilent(`curl -s -o /dev/null -w '%{http_code}' http://localhost:${app.port} 2>/dev/null || echo '000'`).trim();\n } catch { /* curl failed */ }\n\n // Determine status display\n let status = 'stopped';\n if (pm2Online && httpCode === '200') {\n status = 'online';\n } else if (pm2Online) {\n status = `running (${httpCode})`;\n } else if (httpCode !== '000') {\n status = `responding (${httpCode})`;\n }\n\n const domain = getStagingDomain(app.name);\n console.log(` ${app.name.padEnd(12)}${String(app.port).padEnd(9)}${status.padEnd(12)}https://${domain}`);\n }\n\n console.log();\n });\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nasync function buildAll(clean?: boolean): Promise<void> {\n printInfo('Building all apps...');\n let success = 0;\n let failed = 0;\n\n for (const app of PM2_APPS) {\n const dir = appDir(app.name);\n if (!hasPackageJson(dir)) {\n printWarning(`Skipping ${app.name} — no package.json`);\n continue;\n }\n try {\n await buildApp(app.name, clean);\n success++;\n } catch {\n failed++;\n }\n }\n\n console.log();\n printInfo(`Build results: ${success} succeeded, ${failed} failed`);\n if (failed > 0) {\n printWarning('Some apps failed to build — check logs above');\n }\n}\n\nasync function buildApp(name: string, clean?: boolean): Promise<void> {\n const dir = appDir(name);\n if (!hasPackageJson(dir)) {\n printError(`App \"${name}\" not found at ${dir}`);\n throw new Error(`App \"${name}\" not found`);\n }\n\n printInfo(`Building ${name}...`);\n\n if (clean) {\n const nextDir = join(dir, '.next');\n if (existsSync(nextDir)) {\n run(`rm -rf ${nextDir}`);\n }\n }\n\n try {\n run(`pnpm --filter ${name} build`, SYNAP_DIR);\n printSuccess(`${name} built successfully`);\n } catch (err) {\n printError(`${name} build failed`);\n throw err;\n }\n}\n\nfunction startPm2App(name: string): void {\n const dir = appDir(name);\n const appConfig = PM2_APPS.find(a => a.name === name);\n const port = appConfig?.port || 3000;\n\n // Check if already running\n try {\n const list = pm2Cmd('jlist');\n const apps = JSON.parse(list);\n const existing = apps.find((a: any) => a.name === name);\n if (existing) {\n pm2Cmd(`reload ${name}`);\n printSuccess(`${name} reloaded`);\n return;\n }\n } catch { /* pm2 not ready */ }\n\n // Start new\n const cmd = `pm2 start node --name ${name} -- node_modules/next/dist/bin/next start -p ${port}`;\n try {\n pm2Cmd(`delete ${name}`);\n } catch { /* not running */ }\n run(cmd, dir);\n printSuccess(`${name} started on port ${port}`);\n}\n\nfunction startAllPm2Apps(): void {\n for (const app of PM2_APPS) {\n const dir = appDir(app.name);\n if (!hasPackageJson(dir)) continue;\n try {\n startPm2App(app.name);\n } catch {\n printWarning(`Failed to start ${app.name}`);\n }\n }\n pm2Cmd('save');\n}\n\nasync function applyRoutes(): Promise<void> {\n try {\n const traefik = new TraefikService();\n const secrets = await readEveSecrets(process.cwd());\n const domain = secrets?.domain?.primary;\n if (!domain) {\n printWarning('No primary domain configured — skipping Traefik route refresh');\n return;\n }\n\n await traefik.configureSubdomains(\n domain,\n secrets?.domain?.ssl !== false,\n secrets?.domain?.email,\n undefined,\n !!secrets?.domain?.behindProxy,\n secrets?.domain?.customRoutes,\n );\n printSuccess('Traefik routes updated');\n } catch (err) {\n printWarning(`Traefik route update failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction printStagingUrls(): void {\n console.log();\n printInfo('Staging URLs:');\n const secrets = readEveSecretsSync();\n const customRoutes = secrets?.domain?.customRoutes || [];\n const primaryDomain = secrets?.domain?.primary || 'perso.thearchitech.xyz';\n\n for (const route of customRoutes) {\n const domain = route.domain || primaryDomain;\n console.log(` https://${route.subdomain}.${domain}`);\n }\n\n if (customRoutes.length === 0) {\n printInfo(' No custom routes configured. Add with: eve domain add <subdomain> --port <n>');\n }\n}\n\nfunction readEveSecretsSync() {\n try {\n const path = join(process.env.EVE_HOME || process.cwd(), '.eve', 'secrets', 'secrets.json');\n if (existsSync(path)) {\n return JSON.parse(readFileSync(path, 'utf-8'));\n }\n } catch { /* ignore */ }\n return null;\n}\n\nfunction getStagingDomain(name: string): string {\n const domainMap: Record<string, string> = {\n hub: 'hub.staging.synap.live',\n canvas: 'canvas.staging.synap.live',\n base: 'base.staging.synap.live',\n web: 'web.staging.synap.live',\n studio: 'studio.staging.synap.live',\n devplane: 'devplane.staging.synap.live',\n crm: 'crm.staging.synap.live',\n };\n return domainMap[name] || `${name}.staging.synap.live`;\n}\n","/**\n * `eve connectors` — manage the Nango integration platform.\n *\n * Subcommands:\n * setup [provider] Register a real OAuth app (already built).\n * admin Show admin email + password (re-derived from secrets).\n * admin --reset-password Change the admin password via the Nango API.\n * dashboard Open the Nango dashboard in the browser.\n *\n * Why this exists: a fresh `eve add nango` brings up the server and creates an\n * admin account, but until a provider has real OAuth credentials `synap connect`\n * fails with \"Integration does not exist\". And once credentials scroll past,\n * the user has no way to recover them or change the password. This command\n * fills both gaps.\n */\n\nimport type { Command } from 'commander';\nimport { execFile, exec } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { text, password, select, isCancel, cancel } from '@clack/prompts';\nimport {\n readEveSecrets,\n writeEveSecrets,\n readAgentKeyOrLegacy,\n resolveSynapUrlOnHost,\n} from '@eve/dna';\nimport {\n colors,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n printWarning,\n} from '../lib/ui.js';\n\nconst execFileAsync = promisify(execFile);\nconst NANGO_CONTAINER = 'eve-arms-nango';\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\n/** Derive the admin password from the secret key (deterministic, recoverable). */\nfunction deriveAdminPassword(secretKey: string): string {\n return `Nango_${secretKey.slice(0, 12)}`;\n}\n\n/**\n * Read the actual Nango admin email from the `_nango_users` table.\n * Falls back to the legacy derivation from secrets if the DB is unreachable.\n */\nasync function readNangoAdminEmail(): Promise<string> {\n const pg = await findSynapPostgresContainer();\n if (pg) {\n try {\n const { stdout } = await execFileAsync('docker', [\n 'exec', pg, 'psql', '-U', 'synap', '-d', 'nango',\n '-t', '-c',\n \"SELECT email FROM nango._nango_users WHERE role = 'administrator' AND email NOT LIKE 'unknown@%' ORDER BY id LIMIT 1;\",\n ], { timeout: 10_000 });\n const email = stdout.trim();\n if (email && email.includes('@')) return email;\n } catch { /* DB query failed — fall through to fallback */ }\n }\n // Legacy fallback: derive from unrelated secrets (fragile, but better than nothing)\n const secrets = await readEveSecrets(process.cwd()).catch(() => null);\n return secrets?.synap?.userSession?.email\n ?? secrets?.builder?.openwebui?.adminEmail\n ?? 'admin@eve.local';\n}\n\n/** Read the Nango bearer secret the pod backend uses. */\nasync function readNangoSecretKey(): Promise<string | null> {\n const secrets = await readEveSecrets(process.cwd()).catch(() => null);\n return secrets?.connectors?.nango?.secretKey ?? null;\n}\n\n/** True if the Nango container is running on this host. */\nasync function isNangoRunning(): Promise<boolean> {\n try {\n const { stdout } = await execFileAsync(\n 'docker', ['ps', '--filter', `name=^${NANGO_CONTAINER}$`, '--format', '{{.Names}}'],\n { timeout: 4000 },\n );\n return stdout.trim() === NANGO_CONTAINER;\n } catch {\n return false;\n }\n}\n\n/** The Nango server URL the admin should open (NANGO_SERVER_URL from container). */\nasync function readNangoHost(): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(\n 'docker',\n ['inspect', NANGO_CONTAINER, '--format',\n '{{range .Config.Env}}{{println .}}{{end}}'],\n { timeout: 4000 },\n );\n const line = stdout.split('\\n').find((l) => l.startsWith('NANGO_SERVER_URL='));\n return line?.slice('NANGO_SERVER_URL='.length).trim() || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Check whether the given email's password hash matches the derived password.\n * Returns true if it's the default, false if it was changed, null on error.\n */\nasync function checkIsDefaultPassword(email: string, derivedPw: string, pgContainer: string): Promise<boolean | null> {\n try {\n const safeEmail = email.replace(/'/g, \"''\");\n const { stdout: dbOut } = await execFileAsync('docker', [\n 'exec', pgContainer, 'psql', '-U', 'synap', '-d', 'nango',\n '-t', '-c',\n `SELECT salt, hashed_password FROM nango._nango_users WHERE email = '${safeEmail}';`,\n ], { timeout: 10_000 });\n const parts = dbOut.trim().split('|').map(s => s.trim());\n if (parts.length < 2) return null;\n const [dbSalt, dbHash] = parts;\n\n const hashScript = `\n import crypto from 'node:crypto';\n import util from 'node:util';\n const pbkdf2Async = util.promisify(crypto.pbkdf2);\n const hash = (await pbkdf2Async(${JSON.stringify(derivedPw)}, ${JSON.stringify(dbSalt)}, 310000, 32, 'sha256')).toString('base64');\n process.stdout.write(hash);\n `;\n const { stdout: computedHash } = await execFileAsync(\n 'docker', ['exec', NANGO_CONTAINER, 'node', '--input-type=module', '-e', hashScript],\n { timeout: 10_000 },\n );\n return computedHash.trim() === dbHash;\n } catch {\n return null;\n }\n}\n\n/** Find the synap-backend postgres container for direct DB operations. */\nasync function findSynapPostgresContainer(): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(\n 'docker',\n ['ps', '--filter', 'label=com.docker.compose.project=synap-backend',\n '--filter', 'label=com.docker.compose.service=postgres',\n '--format', '{{.Names}}'],\n { timeout: 4000 },\n );\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/** Open a URL in the default browser (platform-aware). */\nfunction openBrowser(url: string): void {\n const platform = process.platform;\n let cmd: string;\n if (platform === 'darwin') cmd = `open \"${url}\"`;\n else if (platform === 'win32') cmd = `start \"\" \"${url}\"`;\n else cmd = `xdg-open \"${url}\"`;\n exec(cmd, () => {/* fire-and-forget */});\n}\n\n// ---------------------------------------------------------------------------\n// Provider catalog (for `setup`)\n// ---------------------------------------------------------------------------\n\n/**\n * Auth mechanism a connector uses. Generalized from the former `'OAUTH2'`\n * literal so the catalog can describe non-Nango connector types (api_key,\n * passkey, mcp, basic) alongside the existing OAuth-via-Nango entries.\n *\n * The two paths are complementary, not exclusive. The OAuth *connection* for an\n * `oauth2` connector is declared through the Nango integration path\n * (`eve connectors setup`). The tool *row* — including for an `oauth2` catalog\n * entry such as `nango-gmail` (whose `credentialRef` is `nango://gmail`) — is\n * seeded headlessly through the backend's `/api/hub/capabilities/apply` door\n * (`eve capabilities apply`), the same door the non-oauth (`api_key`, `passkey`,\n * `mcp`, `basic`) types use. So an `oauth2` entry typically needs BOTH: the\n * connection from `eve connectors setup` and the tool row from `capabilities apply`.\n */\nexport type ConnectorAuthMode = 'oauth2' | 'api_key' | 'passkey' | 'mcp' | 'basic';\n\ninterface ProviderSpec {\n key: string;\n label: string;\n uniqueKeys: string[];\n authMode: ConnectorAuthMode;\n consoleUrl: string;\n steps: string[];\n}\n\nconst PROVIDERS: ProviderSpec[] = [\n {\n key: 'google',\n label: 'Google (Calendar, Gmail, Drive, Contacts)',\n uniqueKeys: ['google-calendar', 'google-mail', 'google-drive', 'google-contacts'],\n authMode: 'oauth2',\n consoleUrl: 'https://console.cloud.google.com/apis/credentials',\n steps: [\n 'Create (or select) a project at https://console.cloud.google.com',\n 'APIs & Services → Enable APIs: Google Calendar, Gmail, Drive, People (Contacts)',\n 'APIs & Services → OAuth consent screen → External → add yourself as a Test user',\n 'APIs & Services → Credentials → Create credentials → OAuth client ID → Web application',\n 'Add the Authorized redirect URI shown below, then copy the Client ID + Secret',\n ],\n },\n {\n key: 'github',\n label: 'GitHub (repos, issues)',\n uniqueKeys: ['github'],\n authMode: 'oauth2',\n consoleUrl: 'https://github.com/settings/developers',\n steps: [\n 'Go to https://github.com/settings/developers → OAuth Apps → New OAuth App',\n 'Set the Authorization callback URL to the redirect URI shown below',\n 'Register, then copy the Client ID and generate a Client Secret',\n ],\n },\n {\n key: 'notion',\n label: 'Notion (pages, databases)',\n uniqueKeys: ['notion'],\n authMode: 'oauth2',\n consoleUrl: 'https://www.notion.so/my-integrations',\n steps: [\n 'Go to https://www.notion.so/my-integrations → New integration → type \"Public\"',\n 'Add the Redirect URI shown below under OAuth Domain & URIs',\n 'Copy the OAuth client ID and client secret',\n ],\n },\n {\n key: 'slack',\n label: 'Slack (messages, channels)',\n uniqueKeys: ['slack'],\n authMode: 'oauth2',\n consoleUrl: 'https://api.slack.com/apps',\n steps: [\n 'Go to https://api.slack.com/apps → Create New App → From scratch',\n 'OAuth & Permissions → Redirect URLs → add the redirect URI shown below',\n 'Copy the Client ID and Client Secret from Basic Information → App Credentials',\n ],\n },\n {\n key: 'linear',\n label: 'Linear (issues, projects)',\n uniqueKeys: ['linear'],\n authMode: 'oauth2',\n consoleUrl: 'https://linear.app/settings/api',\n steps: [\n 'Go to https://linear.app/settings/api → OAuth applications → Create new',\n 'Set the Callback URL to the redirect URI shown below',\n 'Copy the Client ID and Client Secret',\n ],\n },\n];\n\nasync function readNangoCallbackUrl(): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'docker',\n ['inspect', NANGO_CONTAINER, '--format',\n '{{range .Config.Env}}{{println .}}{{end}}'],\n { timeout: 4000 },\n );\n const line = stdout.split('\\n').find((l) => l.startsWith('NANGO_SERVER_URL='));\n const base = line?.slice('NANGO_SERVER_URL='.length).trim();\n if (base) return `${base.replace(/\\/$/, '')}/oauth/callback`;\n } catch { /* fall through */ }\n return 'https://nango.<your-domain>/oauth/callback';\n}\n\nasync function upsertIntegration(\n secretKey: string,\n uniqueKey: string,\n provider: string,\n authMode: string,\n clientId: string,\n clientSecret: string,\n): Promise<{ ok: true; action: 'created' | 'updated' } | { ok: false; error: string }> {\n // Nango's REST API expects the credential `type` in its own uppercase wire\n // form (e.g. \"OAUTH2\"). The catalog now carries lowercase ConnectorAuthMode\n // values, so normalise here at the Nango boundary.\n const nangoType = authMode.toUpperCase();\n const payload = JSON.stringify({\n provider,\n unique_key: uniqueKey,\n credentials: { type: nangoType, client_id: clientId, client_secret: clientSecret },\n });\n const patchPayload = JSON.stringify({\n credentials: { type: nangoType, client_id: clientId, client_secret: clientSecret },\n });\n\n const script = `\n const base = 'http://127.0.0.1:3003';\n const headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ${JSON.stringify(secretKey)} };\n const post = await fetch(base + '/integrations', { method: 'POST', headers, body: ${JSON.stringify(payload)} })\n .then(async r => ({ status: r.status, body: await r.text() })).catch(e => ({ status: 0, body: String(e) }));\n if (post.status >= 200 && post.status < 300) { process.stdout.write('created'); process.exit(0); }\n const patch = await fetch(base + '/integrations/' + encodeURIComponent(${JSON.stringify(uniqueKey)}), { method: 'PATCH', headers, body: ${JSON.stringify(patchPayload)} })\n .then(async r => ({ status: r.status, body: await r.text() })).catch(e => ({ status: 0, body: String(e) }));\n if (patch.status >= 200 && patch.status < 300) { process.stdout.write('updated'); process.exit(0); }\n process.stdout.write('ERR ' + post.status + ' ' + post.body + ' | PATCH ' + patch.status + ' ' + patch.body);\n process.exit(1);\n `;\n try {\n const { stdout } = await execFileAsync(\n 'docker', ['exec', NANGO_CONTAINER, 'node', '--input-type=module', '-e', script],\n { timeout: 20_000 },\n );\n const out = stdout.trim();\n if (out === 'created' || out === 'updated') return { ok: true, action: out as 'created' | 'updated' };\n return { ok: false, error: out || 'unknown error' };\n } catch (err) {\n const e = err as { stdout?: string; message?: string };\n return { ok: false, error: (e.stdout?.trim() || e.message || 'exec failed') };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Backend tool-row seeding (capability-substrate `tools` table)\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve eve's existing pod connection (loopback URL on the host + the `eve`\n * agent's Hub Protocol key). Reuses the same auth `eve capabilities` uses — no\n * new credentials are introduced.\n */\nasync function resolvePodToolsConnection(): Promise<{ synapUrl: string; apiKey: string } | null> {\n const secrets = await readEveSecrets(process.cwd()).catch(() => null);\n const synapUrl = await resolveSynapUrlOnHost(secrets).catch(() => null);\n if (!synapUrl) return null;\n const apiKey = (await readAgentKeyOrLegacy('eve', process.cwd()).catch(() => '')).trim();\n if (!apiKey) return null;\n return { synapUrl, apiKey };\n}\n\n/**\n * Seed a backend `tools` row for a Nango OAuth provider through the Hub door,\n * so the capability substrate sees the connector immediately after `setup`\n * (instead of waiting for the frontend's `syncToolRows`). Mirrors how the\n * `nango-gmail` capability template defines its provider tool:\n * { name, kind: 'provider', credentialRef: 'nango://<provider>',\n * config: { providerConfigKey: '<provider>' } }.\n *\n * Additive and fail-soft: a failure here NEVER fails the OAuth declare flow —\n * it only warns, since the frontend `syncToolRows` still backfills the row.\n */\nasync function seedToolRow(\n conn: { synapUrl: string; apiKey: string },\n provider: string,\n): Promise<{ ok: true } | { ok: false; error: string }> {\n const url = `${conn.synapUrl.replace(/\\/$/, '')}/api/hub/tools`;\n const body = JSON.stringify({\n name: provider,\n kind: 'provider',\n credentialRef: `nango://${provider}`,\n config: { providerConfigKey: provider },\n });\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${conn.apiKey}`,\n },\n body,\n });\n const rawText = await res.text();\n if (!res.ok) {\n let detail = rawText;\n try {\n const parsed = JSON.parse(rawText) as { error?: string };\n if (parsed.error) detail = parsed.error;\n } catch { /* keep raw text */ }\n return { ok: false, error: `HTTP ${res.status}: ${detail}`.slice(0, 200) };\n }\n return { ok: true };\n } catch (err) {\n return { ok: false, error: (err as Error).message || 'request failed' };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Subcommand: setup [provider]\n// ---------------------------------------------------------------------------\n\nasync function runConnectorsSetup(providerKey?: string): Promise<void> {\n console.log();\n printHeader('Eve — Connector Setup', '🔌');\n console.log();\n\n if (!await isNangoRunning()) {\n printError(`Nango container (${NANGO_CONTAINER}) is not running on this host.`);\n printInfo(' Install it first: eve add nango');\n printInfo(' Run this command on the pod host (where Docker runs).');\n process.exit(1);\n }\n\n const secretKey = await readNangoSecretKey();\n if (!secretKey) {\n printError('No Nango secret key found — run `eve add nango` first.');\n process.exit(1);\n }\n\n let spec = providerKey\n ? PROVIDERS.find((p) => p.key === providerKey.toLowerCase())\n : undefined;\n\n if (providerKey && !spec) {\n printError(`Unknown provider \"${providerKey}\".`);\n printInfo(` Available: ${PROVIDERS.map((p) => p.key).join(', ')}`);\n process.exit(1);\n }\n\n if (!spec) {\n const choice = await select({\n message: 'Which service do you want to connect?',\n options: PROVIDERS.map((p) => ({ value: p.key, label: p.label })),\n });\n if (isCancel(choice)) { cancel('Cancelled.'); process.exit(0); }\n spec = PROVIDERS.find((p) => p.key === choice)!;\n }\n\n const callbackUrl = await readNangoCallbackUrl();\n console.log();\n printInfo(colors.primary.bold(`Set up ${spec.label}`));\n console.log();\n printInfo(` Console: ${colors.info(spec.consoleUrl)}`);\n console.log();\n printInfo(' Steps:');\n for (const [i, step] of spec.steps.entries()) {\n printInfo(` ${i + 1}. ${step}`);\n }\n console.log();\n printInfo(' Authorized redirect URI (whitelist this exact value):');\n printInfo(` ${colors.info(callbackUrl)}`);\n if (callbackUrl.includes('<your-domain>')) {\n printWarning(' Could not read NANGO_SERVER_URL — set a domain and re-run `eve add nango`.');\n }\n console.log();\n\n const clientId = await text({\n message: `${spec.label} — OAuth Client ID`,\n validate: (v) => (v && v.trim().length > 0 ? undefined : 'Required'),\n });\n if (isCancel(clientId)) { cancel('Cancelled.'); process.exit(0); }\n\n const clientSecret = await password({\n message: `${spec.label} — OAuth Client Secret`,\n validate: (v) => (v && v.trim().length > 0 ? undefined : 'Required'),\n });\n if (isCancel(clientSecret)) { cancel('Cancelled.'); process.exit(0); }\n\n console.log();\n const results: Array<{ uniqueKey: string; ok: boolean; action?: string; error?: string }> = [];\n for (const uniqueKey of spec.uniqueKeys) {\n const res = await upsertIntegration(\n secretKey, uniqueKey, uniqueKey, spec.authMode,\n String(clientId).trim(), String(clientSecret).trim(),\n );\n if (res.ok) {\n printSuccess(` ${res.action === 'created' ? 'Created' : 'Updated'} integration: ${uniqueKey}`);\n results.push({ uniqueKey, ok: true, action: res.action });\n } else {\n printError(` Failed: ${uniqueKey} — ${res.error}`);\n results.push({ uniqueKey, ok: false, error: res.error });\n }\n }\n\n const okCount = results.filter((r) => r.ok).length;\n if (okCount === 0) {\n printError('No integrations were configured.');\n process.exit(1);\n }\n\n // Seed the backend `tools` row(s) headlessly so the capability substrate sees\n // each provider immediately — reusing eve's existing pod connection. Additive\n // and fail-soft: the frontend `syncToolRows` still backfills if this fails.\n const toolsConn = await resolvePodToolsConnection();\n if (toolsConn) {\n for (const r of results) {\n if (!r.ok) continue;\n const seed = await seedToolRow(toolsConn, r.uniqueKey);\n if (seed.ok) {\n printSuccess(` Seeded backend tool row: ${r.uniqueKey}`);\n } else {\n printWarning(` Could not seed tool row for ${r.uniqueKey} (${seed.error}) — the frontend will backfill it.`);\n }\n }\n } else {\n printWarning(' Skipped backend tool-row seeding (no pod connection) — the frontend will backfill it.');\n }\n\n const secrets = await readEveSecrets(process.cwd()).catch(() => null);\n const oauthApps = { ...(secrets?.connectors?.nango?.oauthApps ?? {}) };\n oauthApps[spec.key] = {\n clientId: String(clientId).trim(),\n configuredAt: new Date().toISOString(),\n };\n await writeEveSecrets({\n ...(secrets ?? {}),\n connectors: {\n ...(secrets?.connectors ?? {}),\n nango: {\n ...(secrets?.connectors?.nango ?? {}),\n secretKey,\n oauthApps,\n },\n },\n }, process.cwd());\n\n console.log();\n printSuccess(`${spec.label} configured (${okCount}/${spec.uniqueKeys.length} integrations).`);\n printInfo(' Connect your account now with:');\n for (const uniqueKey of spec.uniqueKeys) {\n printInfo(` synap connect ${uniqueKey}`);\n }\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Subcommand: admin\n// ---------------------------------------------------------------------------\n\nasync function runConnectorsAdmin(opts: { resetPassword?: boolean; setEmail?: string; force?: boolean }): Promise<void> {\n console.log();\n printHeader('Eve — Nango Admin', '👤');\n console.log();\n\n if (!await isNangoRunning()) {\n printError(`Nango container (${NANGO_CONTAINER}) is not running on this host.`);\n printInfo(' Run this command on the pod host (where Docker runs).');\n process.exit(1);\n }\n\n const secretKey = await readNangoSecretKey();\n if (!secretKey) {\n printError('No Nango secret key found — run `eve add nango` first.');\n process.exit(1);\n }\n\n const pgContainer = await findSynapPostgresContainer();\n if (!pgContainer) {\n printError('Could not find the synap-backend postgres container.');\n printInfo(' Make sure synap-backend is running on this host.');\n process.exit(1);\n }\n\n // ── --set-email ──────────────────────────────────────────────────────────\n if (opts.setEmail) {\n const newEmail = opts.setEmail.trim();\n if (!newEmail.includes('@')) {\n printError(`Invalid email: ${newEmail}`);\n process.exit(1);\n }\n\n // Verify there's an admin user to update\n const { stdout: current } = await execFileAsync('docker', [\n 'exec', pgContainer, 'psql', '-U', 'synap', '-d', 'nango',\n '-t', '-c',\n \"SELECT email FROM nango._nango_users WHERE role = 'administrator' AND email NOT LIKE 'unknown@%' ORDER BY id LIMIT 1;\",\n ], { timeout: 10_000 }).catch(() => ({ stdout: '' }));\n const currentEmail = current.trim();\n\n const safeNew = newEmail.replace(/'/g, \"''\");\n await execFileAsync('docker', [\n 'exec', pgContainer, 'psql', '-U', 'synap', '-d', 'nango',\n '-c', `UPDATE nango._nango_users SET email = '${safeNew}' WHERE email = '${currentEmail.replace(/'/g, \"''\")}';`,\n ], { timeout: 10_000 });\n\n console.log();\n printSuccess(`Admin email updated: ${currentEmail} → ${colors.primary.bold(newEmail)}`);\n printInfo(' Use this email to sign in at the Nango dashboard.');\n console.log();\n return;\n }\n\n // ── --reset-password ─────────────────────────────────────────────────────\n if (opts.resetPassword) {\n const currentEmail = await readNangoAdminEmail();\n const email = await text({\n message: 'Admin email',\n initialValue: currentEmail,\n validate: (v) => (v && v.includes('@') ? undefined : 'Enter a valid email'),\n });\n if (isCancel(email)) { cancel('Cancelled.'); process.exit(0); }\n\n let oldPassword = '';\n if (!opts.force) {\n oldPassword = await password({\n message: 'Current password',\n validate: (v) => (v && v.length > 0 ? undefined : 'Required'),\n }) as string;\n if (isCancel(oldPassword)) { cancel('Cancelled.'); process.exit(0); }\n }\n\n const newPassword = await password({\n message: 'New password (min 8 chars, 1 upper, 1 lower, 1 number, 1 special)',\n validate: (v) => {\n if (!v || v.length < 8) return 'At least 8 characters';\n if (!/[A-Z]/.test(v)) return 'Needs an uppercase letter';\n if (!/[a-z]/.test(v)) return 'Needs a lowercase letter';\n if (!/[0-9]/.test(v)) return 'Needs a number';\n if (!/[^A-Za-z0-9]/.test(v)) return 'Needs a special character';\n return undefined;\n },\n }) as string;\n if (isCancel(newPassword)) { cancel('Cancelled.'); process.exit(0); }\n\n const safeEmail = String(email).trim().replace(/'/g, \"''\");\n let newSalt: string, newHash: string;\n\n if (opts.force) {\n printInfo('Skipping old-password check (--force)...');\n const hashScript = `\n import crypto from 'node:crypto';\n import util from 'node:util';\n const pbkdf2Async = util.promisify(crypto.pbkdf2);\n const newPw = ${JSON.stringify(String(newPassword))};\n const newSalt = crypto.randomBytes(16).toString('base64');\n const newHash = (await pbkdf2Async(newPw, newSalt, 310000, 32, 'sha256')).toString('base64');\n process.stdout.write(newSalt + ':' + newHash);\n `;\n try {\n const { stdout } = await execFileAsync(\n 'docker', ['exec', NANGO_CONTAINER, 'node', '--input-type=module', '-e', hashScript],\n { timeout: 15_000 },\n );\n [newSalt, newHash] = stdout.trim().split(':');\n } catch (err) {\n printError(`Failed to compute password hash: ${(err as Error).message}`);\n process.exit(1);\n }\n } else {\n const verifyScript = `\n import crypto from 'node:crypto';\n import util from 'node:util';\n const pbkdf2Async = util.promisify(crypto.pbkdf2);\n const base = 'http://127.0.0.1:3003';\n const signin = await fetch(base + '/api/v1/account/signin', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email: ${JSON.stringify(String(email).trim())}, password: ${JSON.stringify(String(oldPassword))} }),\n });\n const body = await signin.json().catch(() => ({}));\n if (signin.status !== 200 || !body.user) {\n process.stdout.write('SIGNIN_FAIL ' + signin.status + ' ' + JSON.stringify(body).slice(0, 200));\n process.exit(1);\n }\n const newPw = ${JSON.stringify(String(newPassword))};\n const newSalt = crypto.randomBytes(16).toString('base64');\n const newHash = (await pbkdf2Async(newPw, newSalt, 310000, 32, 'sha256')).toString('base64');\n process.stdout.write(newSalt + ':' + newHash);\n `;\n\n printInfo('Verifying current password...');\n try {\n const { stdout } = await execFileAsync(\n 'docker', ['exec', NANGO_CONTAINER, 'node', '--input-type=module', '-e', verifyScript],\n { timeout: 20_000 },\n );\n const out = stdout.trim();\n if (out.startsWith('SIGNIN_FAIL')) {\n printError('Current password is incorrect.');\n printInfo(' The password shown by `eve connectors admin` is derived from the secret');\n printInfo(' key — if the account was set up manually, use the password you chose.');\n printInfo(' Or force-reset without knowing the old password:');\n printInfo(' eve connectors admin --reset-password --force');\n process.exit(1);\n }\n [newSalt, newHash] = out.split(':');\n } catch (err) {\n printError(`Could not verify password: ${(err as Error).message}`);\n printInfo(' Try with --force to skip verification:');\n printInfo(' eve connectors admin --reset-password --force');\n process.exit(1);\n }\n }\n\n await execFileAsync('docker', [\n 'exec', pgContainer, 'psql', '-U', 'synap', '-d', 'nango',\n '-c', `UPDATE nango._nango_users SET salt = '${newSalt}', hashed_password = '${newHash}' WHERE email = '${safeEmail}';`,\n ], { timeout: 10_000 });\n\n console.log();\n printSuccess('Password changed successfully.');\n console.log();\n return;\n }\n // ── Show credentials (default) ───────────────────────────────────────────\n const email = await readNangoAdminEmail();\n const adminPw = deriveAdminPassword(secretKey);\n const nangoHost = await readNangoHost();\n\n printInfo(` Admin email: ${colors.primary.bold(email)}`);\n\n // Check whether the password is still the default derived one.\n const pwStatus = await checkIsDefaultPassword(email, adminPw, pgContainer);\n if (pwStatus === true) {\n printInfo(` Admin password: ${colors.primary.bold(adminPw)} (default from secret key)`);\n } else if (pwStatus === false) {\n printInfo(` Admin password: ${colors.warning('(custom — was changed via --reset-password)')}`);\n } else {\n printInfo(` Admin password: ${colors.primary.bold(adminPw)} (derived — could not verify)`);\n }\n if (email === 'admin@eve.local') {\n printWarning(' Still using the stub email — update it:');\n printInfo(' eve connectors admin --set-email you@example.com');\n }\n console.log();\n if (nangoHost) {\n printInfo(` Dashboard: ${colors.info(nangoHost)}`);\n }\n console.log();\n printInfo(' Change email: eve connectors admin --set-email <email>');\n printInfo(' Change password: eve connectors admin --reset-password');\n printInfo(' Force-reset pw: eve connectors admin --reset-password --force');\n printInfo(' Set up providers: eve connectors setup <provider>');\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Subcommand: dashboard\n// ---------------------------------------------------------------------------\n\nasync function runDashboard(): Promise<void> {\n console.log();\n printHeader('Eve — Nango Dashboard', '🌐');\n console.log();\n\n if (!await isNangoRunning()) {\n printError(`Nango container (${NANGO_CONTAINER}) is not running on this host.`);\n printInfo(' Run this command on the pod host (where Docker runs).');\n process.exit(1);\n }\n\n const nangoHost = await readNangoHost();\n if (!nangoHost) {\n printError('Could not determine Nango dashboard URL.');\n printInfo(' Check that the container has NANGO_SERVER_URL set.');\n process.exit(1);\n }\n\n printInfo(` Opening ${colors.info(nangoHost)} ...`);\n openBrowser(nangoHost);\n console.log();\n printInfo(' If the browser didn\\'t open, paste this URL:');\n printInfo(` ${colors.info(nangoHost)}`);\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Command registration\n// ---------------------------------------------------------------------------\n\nexport function connectorsCommand(program: Command): void {\n const connectors = program\n .command('connectors')\n .description('Manage Nango — admin account, OAuth apps, dashboard');\n\n // `eve connectors setup [provider]`\n connectors\n .command('setup')\n .description('Register a real OAuth app for a provider (Google, GitHub, Notion, Slack, Linear)')\n .argument('[provider]', 'Provider key: google | github | notion | slack | linear')\n .action(async (provider: string | undefined) => {\n await runConnectorsSetup(provider);\n });\n\n // `eve connectors admin`\n connectors\n .command('admin')\n .description('Show Nango admin credentials (email + password)')\n .option('--reset-password', 'Change the admin password')\n .option('--force', 'Skip old-password verification (for --reset-password)')\n .option('--set-email <email>', 'Update the admin email')\n .action(async (opts: { resetPassword?: boolean; setEmail?: string; force?: boolean }) => {\n await runConnectorsAdmin({ resetPassword: opts.resetPassword, setEmail: opts.setEmail, force: opts.force });\n });\n\n // `eve connectors dashboard`\n connectors\n .command('dashboard')\n .description('Open the Nango dashboard in your browser')\n .action(async () => {\n await runDashboard();\n });\n\n // `eve connectors` with no subcommand → show help.\n connectors.action(() => {\n console.log();\n printHeader('Eve — Connectors', '🔌');\n console.log();\n printInfo('Usage: eve connectors <command>');\n console.log();\n printInfo(' setup [provider] Register a real OAuth app for a provider');\n printInfo(' admin Show admin email + password');\n printInfo(' admin --reset-password Change the admin password');\n printInfo(' dashboard Open the Nango dashboard in your browser');\n console.log();\n printInfo('Examples:');\n printInfo(' eve connectors setup google');\n printInfo(' eve connectors admin');\n printInfo(' eve connectors admin --reset-password');\n printInfo(' eve connectors dashboard');\n console.log();\n });\n}\n","/**\n * `eve capabilities` — apply CAPABILITY TEMPLATES headlessly through the\n * backend's Hub door (`POST /api/hub/capabilities/apply`).\n *\n * A capability template is \"a connector/workspace config, applied like a view\":\n * a config descriptor that instantiates a set of {vault secrets · tools · skills}\n * in ONE governed call. The backend interpolates `{{param}}` placeholders, then\n * creates the vault secrets → tools → skills through the GOVERNED routers\n * (proposal-gated) and returns what it created + the proposal ids.\n *\n * This is the generic, provider-agnostic seed path. OAuth-via-Nango connectors\n * keep their dedicated declare flow in `eve connectors setup`; THIS command is\n * for api_key / passkey / mcp / basic connector types (and any inline template).\n *\n * Subcommands:\n * eve capabilities list\n * List the known backend seed templates.\n *\n * eve capabilities apply <template>\n * <template> is EITHER a backend template key (e.g. \"generic-apikey\",\n * resolved server-side) OR a path to a local `*.json` CapabilityDefinition\n * file (sent inline as `definition`). Prompts for the template's declared\n * required params, then POSTs to /capabilities/apply.\n *\n * Flags:\n * --template <key> Force backend-resolved template-key mode.\n * --param k=v Provide a param non-interactively (repeatable).\n * --workspace <id> Scope the capability to a workspace (omit = pod-wide).\n * --agent <slug> Hub identity to act as (default: eve).\n */\n\nimport { Command } from 'commander';\nimport { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { resolve as resolvePath } from 'node:path';\nimport { text, isCancel, cancel } from '@clack/prompts';\nimport {\n readEveSecrets,\n readAgentKeyOrLegacy,\n resolveSynapUrlOnHost,\n} from '@eve/dna';\nimport {\n colors,\n emojis,\n printHeader,\n printSuccess,\n printError,\n printInfo,\n createSpinner,\n} from '../lib/ui.js';\nimport {\n CAPABILITY_TEMPLATES,\n findCapabilityTemplate,\n} from './capability-catalog.js';\nimport { CAPABILITY_DEFINITIONS } from './capability-definitions.js';\n\n// ---------------------------------------------------------------------------\n// Capability-definition shapes (mirror @synap/playbooks `CapabilityDefinition`)\n// Kept local so eve-cli has no backend/playbooks dependency — the field names\n// match the backend contract VERBATIM.\n// ---------------------------------------------------------------------------\n\nexport interface CapabilityParamSpec {\n name: string;\n label?: string;\n type?: 'text' | 'number' | 'entity' | 'choice' | 'boolean';\n required?: boolean;\n default?: unknown;\n description?: string;\n}\n\nexport interface CapabilityDefinition {\n key: string;\n name: string;\n description?: string;\n params?: CapabilityParamSpec[];\n vault?: unknown[];\n tools: unknown[];\n skills: unknown[];\n}\n\n/** Response shape from POST /api/hub/capabilities/apply. */\ninterface ApplyCapabilityResponse {\n capabilityKey: string;\n created: {\n vault: Record<string, unknown>[];\n tools: Record<string, unknown>[];\n skills: Record<string, unknown>[];\n };\n proposals: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Pod connection (reuses eve's existing pod-connection auth — no new auth)\n// ---------------------------------------------------------------------------\n\ninterface PodConnection {\n synapUrl: string;\n apiKey: string;\n}\n\n/**\n * Resolve the pod base URL + the agent's Hub API key from eve's existing\n * secrets. Mirrors the resolution `eve auth` uses: loopback-on-host URL +\n * per-agent Hub key (legacy `synap.apiKey` fallback for the eve agent).\n */\nasync function resolvePodConnection(agentType: string): Promise<PodConnection | null> {\n const secrets = await readEveSecrets(process.cwd());\n const synapUrl = await resolveSynapUrlOnHost(secrets);\n if (!synapUrl) return null;\n const apiKey = (await readAgentKeyOrLegacy(agentType, process.cwd())).trim();\n if (!apiKey) return null;\n return { synapUrl, apiKey };\n}\n\n// ---------------------------------------------------------------------------\n// Param parsing + prompting\n// ---------------------------------------------------------------------------\n\n/** Parse repeatable `--param k=v` flags into a record. */\nfunction parseParamFlags(raw: string[] | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const entry of raw ?? []) {\n const eq = entry.indexOf('=');\n if (eq <= 0) {\n throw new Error(`Invalid --param \"${entry}\" — expected key=value.`);\n }\n out[entry.slice(0, eq).trim()] = entry.slice(eq + 1);\n }\n return out;\n}\n\n/**\n * Prompt for any DECLARED params not already supplied via --param.\n * Required params with no value and no default must be answered; optional ones\n * may be skipped (Enter accepts the default / empty).\n */\nasync function collectParams(\n declared: CapabilityParamSpec[],\n provided: Record<string, string>,\n): Promise<Record<string, unknown>> {\n const params: Record<string, unknown> = { ...provided };\n\n for (const spec of declared) {\n if (spec.name in params) continue; // already provided via --param\n const label = spec.label ?? spec.name;\n const hint = spec.description ? ` ${colors.muted(`(${spec.description})`)}` : '';\n const defaultHint =\n spec.default !== undefined ? String(spec.default) : undefined;\n\n const answer = await text({\n message: `${label}${spec.required ? colors.error(' *') : ''}${hint}`,\n placeholder: defaultHint,\n initialValue: defaultHint,\n validate: (v) => {\n if (spec.required && (!v || v.trim().length === 0)) return 'Required';\n return undefined;\n },\n });\n if (isCancel(answer)) {\n cancel('Cancelled.');\n process.exit(0);\n }\n const value = String(answer).trim();\n // Only send non-empty values; the backend fills defaults from the template.\n if (value.length > 0) params[spec.name] = value;\n else if (spec.default !== undefined) params[spec.name] = spec.default;\n }\n\n return params;\n}\n\n// ---------------------------------------------------------------------------\n// Template resolution: backend key OR local file\n// ---------------------------------------------------------------------------\n\ninterface ResolvedTemplate {\n /** Pass-through backend template key (mode A). */\n templateKey?: string;\n /** Inline definition loaded from a local file (mode B). */\n definition?: CapabilityDefinition;\n /** The declared params to prompt for, from whichever source. */\n declaredParams: CapabilityParamSpec[];\n /** Display label. */\n label: string;\n}\n\n/**\n * Decide whether `<template>` is a local file path or a backend template key.\n *\n * - If `--template` is set, force backend-key mode.\n * - Else if `<template>` exists on disk (or ends in .json), load it as a\n * local CapabilityDefinition sent inline as `definition`.\n * - Else treat it as a backend template key passed straight through.\n */\nasync function resolveTemplate(\n arg: string | undefined,\n forcedTemplateKey: string | undefined,\n): Promise<ResolvedTemplate> {\n // Mode A — explicit backend template key.\n if (forcedTemplateKey) {\n const entry = findCapabilityTemplate(forcedTemplateKey);\n return {\n templateKey: forcedTemplateKey,\n declaredParams: [], // backend owns the params; we prompt only what we know\n label: entry?.label ?? forcedTemplateKey,\n };\n }\n\n if (!arg) {\n throw new Error('Provide a template key or a path to a *.json definition file.');\n }\n\n // Mode B — local definition file (path exists, or looks like a json file).\n const looksLikeFile = arg.endsWith('.json') || arg.includes('/') || existsSync(arg);\n if (looksLikeFile) {\n const path = resolvePath(process.cwd(), arg);\n if (!existsSync(path)) {\n throw new Error(`Definition file not found: ${path}`);\n }\n let definition: CapabilityDefinition;\n try {\n definition = JSON.parse(await readFile(path, 'utf-8')) as CapabilityDefinition;\n } catch (err) {\n throw new Error(\n `Could not parse ${path} as JSON: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (!definition.key || !Array.isArray(definition.tools) || !Array.isArray(definition.skills)) {\n throw new Error(\n `${path} is not a valid CapabilityDefinition (needs key, tools[], skills[]).`,\n );\n }\n return {\n definition,\n declaredParams: definition.params ?? [],\n label: definition.name ?? definition.key,\n };\n }\n\n // Mode A (implicit) — a known backend template key.\n const entry = findCapabilityTemplate(arg);\n return {\n templateKey: arg,\n declaredParams: [], // backend resolves + owns params for keyed templates\n label: entry?.label ?? arg,\n };\n}\n\n// ---------------------------------------------------------------------------\n// HTTP call\n// ---------------------------------------------------------------------------\n\n/**\n * Authed JSON POST to a Hub path. Shared by `apply` and `sync` (kills the\n * copy-paste fetch+error-unwrap). `label` names the operation in error messages.\n */\nasync function postJson<T>(\n conn: PodConnection,\n path: string,\n body: unknown,\n label: string,\n): Promise<T> {\n const url = `${conn.synapUrl.replace(/\\/$/, '')}${path}`;\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${conn.apiKey}`,\n },\n body: JSON.stringify(body),\n });\n const rawText = await res.text();\n if (!res.ok) {\n let detail = rawText;\n try {\n const parsed = JSON.parse(rawText) as { error?: string };\n if (parsed.error) detail = parsed.error;\n } catch {\n /* keep raw text */\n }\n throw new Error(`${label} failed (HTTP ${res.status}): ${detail}`);\n }\n return JSON.parse(rawText) as T;\n}\n\nasync function postApply(\n conn: PodConnection,\n body: {\n templateKey?: string;\n definition?: CapabilityDefinition;\n params: Record<string, unknown>;\n workspaceId?: string;\n },\n): Promise<ApplyCapabilityResponse> {\n return postJson<ApplyCapabilityResponse>(\n conn,\n '/api/hub/capabilities/apply',\n body,\n 'apply',\n );\n}\n\n// ---------------------------------------------------------------------------\n// `eve capabilities apply <template>`\n// ---------------------------------------------------------------------------\n\ninterface ApplyOptions {\n template?: string;\n param?: string[];\n workspace?: string;\n agent?: string;\n}\n\nasync function runApply(templateArg: string | undefined, opts: ApplyOptions): Promise<void> {\n console.log();\n printHeader('Eve — Apply Capability Template', '🧩');\n console.log();\n\n const agentType = opts.agent ?? 'eve';\n const conn = await resolvePodConnection(agentType);\n if (!conn) {\n printError('Could not resolve a pod URL + Hub API key.');\n printInfo(' Fix: run `eve auth provision` (mints the agent key), or set domain.primary in secrets.json.');\n process.exitCode = 1;\n return;\n }\n\n let resolved: ResolvedTemplate;\n let providedParams: Record<string, string>;\n try {\n resolved = await resolveTemplate(templateArg, opts.template);\n providedParams = parseParamFlags(opts.param);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n return;\n }\n\n printInfo(`Pod: ${colors.info(conn.synapUrl)}`);\n printInfo(`Template: ${colors.primary.bold(resolved.label)}`);\n printInfo(\n `Mode: ${resolved.definition ? 'inline definition (local file)' : 'backend template key'}`,\n );\n if (opts.workspace) printInfo(`Workspace: ${opts.workspace}`);\n console.log();\n\n // Prompt for declared params we know about (local-file mode) or any\n // --param-provided values (backend-key mode passes them straight through).\n const params = await collectParams(resolved.declaredParams, providedParams);\n\n const spinner = createSpinner('Calling POST /api/hub/capabilities/apply…');\n spinner.start();\n let result: ApplyCapabilityResponse;\n try {\n result = await postApply(conn, {\n templateKey: resolved.templateKey,\n definition: resolved.definition,\n params,\n workspaceId: opts.workspace,\n });\n } catch (err) {\n spinner.fail('Apply failed');\n printError(err instanceof Error ? err.message : String(err));\n console.log();\n printInfo('Common causes:');\n printInfo(' • Hub key lacks hub-protocol.write scope → `eve auth renew --agent ' + agentType + '`');\n printInfo(' • Unknown template key → `eve capabilities list`');\n printInfo(' • Backend unreachable → `eve doctor`');\n process.exitCode = 1;\n return;\n }\n spinner.succeed('Capability applied');\n\n // Summary.\n console.log();\n printSuccess(`Applied capability: ${colors.primary.bold(result.capabilityKey)}`);\n const v = result.created.vault.length;\n const t = result.created.tools.length;\n const s = result.created.skills.length;\n printInfo(` Created: ${v} vault secret${v === 1 ? '' : 's'}, ${t} tool${t === 1 ? '' : 's'}, ${s} skill${s === 1 ? '' : 's'}`);\n if (result.proposals.length > 0) {\n printInfo(` Proposals (pending review): ${result.proposals.length}`);\n for (const id of result.proposals) {\n printInfo(` ${colors.muted('•')} ${id}`);\n }\n console.log();\n printInfo('Review and approve them in Synap (proposals are reviewable + reversible).');\n } else {\n printInfo(' No proposals — resources were auto-approved.');\n }\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// `eve capabilities list`\n// ---------------------------------------------------------------------------\n\nfunction runList(): void {\n console.log();\n printHeader('Eve — Capability Templates', '🧩');\n console.log();\n printInfo('Backend seed templates (apply with `eve capabilities apply <key>`):');\n console.log();\n for (const t of CAPABILITY_TEMPLATES) {\n console.log(\n ` ${colors.primary.bold(t.key.padEnd(20))} ${colors.muted(`[${t.authMode}]`)} ${t.description}`,\n );\n }\n console.log();\n printInfo('Or apply a local file: eve capabilities apply ./my-connector.capability.json');\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// `eve capabilities sync` — push the vendored seed definitions into the pod DB\n// ---------------------------------------------------------------------------\n\n/** Response shape from POST /api/hub/capabilities/templates. */\ninterface UpsertTemplateResponse {\n id: string;\n key: string;\n version: number;\n status?: 'created' | 'updated';\n}\n\ninterface SyncOptions {\n workspace?: string;\n agent?: string;\n key?: string;\n}\n\nasync function runSync(opts: SyncOptions): Promise<void> {\n console.log();\n printHeader('Eve — Sync Capability Templates', '🧩');\n console.log();\n\n const agentType = opts.agent ?? 'eve';\n const conn = await resolvePodConnection(agentType);\n if (!conn) {\n printError('Could not resolve a pod URL + Hub API key.');\n printInfo(' Fix: run `eve auth provision` (mints the agent key), or set domain.primary in secrets.json.');\n process.exitCode = 1;\n return;\n }\n\n // Filter to a single key if --key was given.\n const entries = Object.entries(CAPABILITY_DEFINITIONS).filter(\n ([key]) => !opts.key || key === opts.key,\n );\n if (entries.length === 0) {\n printError(`No vendored definition matches --key \"${opts.key}\".`);\n printInfo(` Known keys: ${Object.keys(CAPABILITY_DEFINITIONS).join(', ')}`);\n process.exitCode = 1;\n return;\n }\n\n printInfo(`Pod: ${colors.info(conn.synapUrl)}`);\n if (opts.workspace) printInfo(`Workspace: ${opts.workspace}`);\n printInfo(`Templates: ${entries.length}`);\n console.log();\n\n let failed = 0;\n for (const [key, def] of entries) {\n const spinner = createSpinner(`Syncing ${colors.primary.bold(key)}…`);\n spinner.start();\n try {\n const result = await postJson<UpsertTemplateResponse>(\n conn,\n '/api/hub/capabilities/templates',\n {\n key,\n name: def.name,\n description: def.description,\n definition: def,\n workspaceId: opts.workspace,\n source: 'eve-sync',\n },\n 'sync',\n );\n const verb = result.status ?? 'synced';\n spinner.succeed(`${key} ${verb} (v${result.version})`);\n } catch (err) {\n failed += 1;\n spinner.fail(`${key} failed`);\n printError(err instanceof Error ? err.message : String(err));\n }\n }\n\n console.log();\n if (failed === 0) {\n printSuccess(`Synced ${entries.length} template${entries.length === 1 ? '' : 's'} to the pod DB.`);\n printInfo('Apply one with `eve capabilities apply <key>` — it now resolves DB-first.');\n } else {\n printError(`${failed} of ${entries.length} templates failed to sync.`);\n printInfo(' • Hub key lacks hub-protocol.write scope → `eve auth renew --agent ' + agentType + '`');\n printInfo(' • Backend unreachable → `eve doctor`');\n process.exitCode = 1;\n }\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// Command registration\n// ---------------------------------------------------------------------------\n\nexport function capabilitiesCommand(program: Command): void {\n const capabilities = program\n .command('capabilities')\n .description(`${emojis.sparkles} Apply capability templates (vault + tools + skills) through the Hub`);\n\n capabilities\n .command('apply')\n .description(\n 'Seed a connector/capability headlessly via POST /api/hub/capabilities/apply. ' +\n '<template> is a backend template key (e.g. generic-apikey) or a path to a ' +\n 'local *.json CapabilityDefinition.',\n )\n .argument('[template]', 'Backend template key or path to a *.json definition file')\n .option('--template <key>', 'Force backend-resolved template-key mode')\n .option('--param <key=value>', 'Provide a param non-interactively (repeatable)', (val: string, prev: string[]) => [...(prev ?? []), val], [] as string[])\n .option('--workspace <id>', 'Scope to a workspace (omit for pod-wide)')\n .option('--agent <slug>', 'Hub identity to act as. Defaults to \"eve\".')\n .action(async (template: string | undefined, opts: ApplyOptions) => {\n try {\n await runApply(template, opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n capabilities\n .command('list')\n .description('List the known backend capability seed templates.')\n .action(() => {\n try {\n runList();\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n capabilities\n .command('sync')\n .description(\n 'Push the vendored seed CapabilityDefinitions into the pod DB ' +\n '(POST /api/hub/capabilities/templates) so a `templateKey` apply resolves ' +\n 'DB-first on a deployed pod.',\n )\n .option('--workspace <id>', 'Scope the templates to a workspace (omit for pod-wide)')\n .option('--agent <slug>', 'Hub identity to act as. Defaults to \"eve\".')\n .option('--key <k>', 'Sync only this one template key')\n .action(async (opts: SyncOptions) => {\n try {\n await runSync(opts);\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n }\n });\n\n // Bare `eve capabilities` → help.\n capabilities.action(() => {\n console.log();\n printHeader('Eve — Capabilities', '🧩');\n console.log();\n printInfo('Usage: eve capabilities <command>');\n console.log();\n printInfo(' apply <template> Seed vault + tools + skills from a template (key or local file)');\n printInfo(' list List known backend seed templates');\n printInfo(' sync Push the vendored seed templates into the pod DB (templates-as-data)');\n console.log();\n printInfo('Examples:');\n printInfo(' eve capabilities apply generic-apikey --param apiKey=sk-… --param baseUrl=https://api.x.com/v1');\n printInfo(' eve capabilities apply ./my-connector.capability.json');\n printInfo(' eve capabilities sync');\n printInfo(' eve capabilities list');\n console.log();\n });\n}\n","/**\n * Shared connector / capability-template catalog.\n *\n * ONE typed source describing what kinds of connectors Eve can seed. It spans\n * BOTH paths:\n *\n * - `oauth2` entries → declared in Nango via `eve connectors setup` (the\n * existing OAuth-app flow). Listed here for discovery\n * and a uniform `eve capabilities list`; the actual\n * OAuth-app declaration stays in connectors.ts.\n * - everything else → seeded headlessly through the backend's\n * `/api/hub/capabilities/apply` door, either by a\n * backend-resolved `templateKey` or a local\n * definition file.\n *\n * This keeps the connector taxonomy from diverging across the CLI: the\n * `authMode` union lives with `ProviderSpec` in connectors.ts and is re-used\n * here, so adding a connector type is a single-place change.\n */\n\nimport type { ConnectorAuthMode } from './connectors.js';\n\n/**\n * A catalog entry an operator can pick from. `templateKey` points at a seed\n * template the BACKEND resolves (e.g. \"generic-apikey\" shipped in\n * synap-backend/templates/capabilities/). Entries without a `templateKey`\n * (today: the oauth2 ones) are informational — they route through the Nango\n * `setup` flow instead.\n */\nexport interface CapabilityCatalogEntry {\n /** Stable selector key, e.g. \"generic-apikey\". */\n key: string;\n /** Human label for prompts / listings. */\n label: string;\n /** How this connector authenticates. */\n authMode: ConnectorAuthMode;\n /** One-line description. */\n description: string;\n /**\n * Backend seed-template key to pass through to `/capabilities/apply`.\n * Present only for headlessly-seedable types (non-oauth2). When absent the\n * entry is OAuth-via-Nango and is handled by `eve connectors setup`.\n */\n templateKey?: string;\n}\n\n/**\n * The capability templates the backend can resolve by key today. Mirrors the\n * seeds in `synap-backend/templates/capabilities/`. Extend in lockstep with\n * that directory (or pass a local definition file for ad-hoc types).\n */\nexport const CAPABILITY_TEMPLATES: CapabilityCatalogEntry[] = [\n {\n key: 'generic-apikey',\n label: 'Generic API-key connector',\n authMode: 'api_key',\n description:\n 'Provider-neutral: stores one API key in the vault, registers one HTTP ' +\n 'API tool, and seeds a fetch-and-propose skill. Customize via params.',\n templateKey: 'generic-apikey',\n },\n {\n key: 'unipile-linkedin',\n label: 'Unipile — LinkedIn',\n authMode: 'api_key',\n description:\n 'LinkedIn outreach via Unipile (X-API-KEY in vault): a search-profiles ' +\n 'skill (proposes people) and a send-invitation skill, both proposal-gated.',\n templateKey: 'unipile-linkedin',\n },\n {\n key: 'nango-gmail',\n label: 'Nango — Gmail',\n authMode: 'oauth2',\n description:\n 'Send follow-up email via Gmail through Nango OAuth (no vault secret). ' +\n 'Seeds a proposal-gated gmail_send skill. Requires the gmail Nango integration.',\n templateKey: 'nango-gmail',\n },\n {\n key: 'discord-bot',\n label: 'Discord Bot',\n authMode: 'api_key',\n description:\n 'Post to a Discord channel via a bot (bot token in vault): a proposal-gated ' +\n 'discord_send_message skill that sends a channel message and notes the post.',\n templateKey: 'discord-bot',\n },\n];\n\n/** Look up a catalog entry by key (case-insensitive). */\nexport function findCapabilityTemplate(key: string): CapabilityCatalogEntry | undefined {\n const lower = key.toLowerCase();\n return CAPABILITY_TEMPLATES.find((t) => t.key.toLowerCase() === lower);\n}\n","/**\n * Vendored CapabilityDefinition seed payloads for `eve capabilities sync`.\n *\n * These are the source-of-truth seed templates from\n * `synap-backend/templates/capabilities/*.capability.json`, vendored INTO eve as\n * a TS literal so tsup bundles them (eve must not reach across repos at runtime).\n * `eve capabilities sync` POSTs each to /api/hub/capabilities/templates; the DB\n * is the source of truth POST-sync. To edit a template: edit the backend JSON,\n * re-vendor here, and re-run `eve capabilities sync`.\n *\n * Generated from the backend JSONs — keep field names VERBATIM with the backend\n * CapabilityDefinition contract.\n */\n\nimport type { CapabilityDefinition } from \"./capabilities.js\";\n\nexport const CAPABILITY_DEFINITIONS: Record<string, CapabilityDefinition> = {\n \"generic-apikey\": {\n \"key\": \"generic-apikey\",\n \"name\": \"Generic API-Key Connector\",\n \"description\": \"Provider-neutral demonstration of the capability-template shape: stores one API key in the vault, registers one HTTP API tool that authenticates with it, and seeds one code skill that fetches from the provider and proposes the results as entities. Customize via the {{baseUrl}}, {{apiKey}}, and {{entityProfile}} params — no provider is hardcoded.\",\n \"params\": [\n {\n \"name\": \"apiKey\",\n \"label\": \"API key\",\n \"type\": \"text\",\n \"required\": true,\n \"description\": \"The bearer API key for the provider. Stored server-encrypted in the vault; never persisted in the template.\"\n },\n {\n \"name\": \"baseUrl\",\n \"label\": \"Base URL\",\n \"type\": \"text\",\n \"required\": true,\n \"description\": \"The provider's API base URL, e.g. https://api.example.com/v1\"\n },\n {\n \"name\": \"entityProfile\",\n \"label\": \"Target entity profile\",\n \"type\": \"text\",\n \"required\": false,\n \"default\": \"note\",\n \"description\": \"The profileSlug the skill proposes fetched records as.\"\n }\n ],\n \"vault\": [\n {\n \"ref\": \"apiKeySecret\",\n \"name\": \"{{name}} API key\",\n \"value\": \"{{apiKey}}\",\n \"type\": \"api_key\",\n \"description\": \"API key for the generic-apikey connector.\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"generic_api\",\n \"kind\": \"api\",\n \"description\": \"Authenticated HTTP access to the provider API.\",\n \"credentialRef\": \"apiKeySecret\",\n \"executor\": \"is-agent\",\n \"config\": {\n \"baseUrl\": \"{{baseUrl}}\",\n \"auth\": {\n \"in\": \"header\",\n \"name\": \"Authorization\",\n \"prefix\": \"Bearer \"\n }\n }\n }\n ],\n \"skills\": [\n {\n \"name\": \"{{name}} fetch-and-propose\",\n \"kind\": \"code\",\n \"scope\": \"pod\",\n \"description\": \"Fetches records from the provider API and proposes each as an entity (proposal-gated). Calls the required tool by name via callProvider('generic_api', ...).\",\n \"requires\": [\n \"generic_api\"\n ],\n \"executionMode\": \"async\",\n \"timeoutSeconds\": 60,\n \"parameters\": {\n \"path\": \"string?\",\n \"entityProfile\": \"string?\"\n },\n \"code\": \"// Generic fetch -> propose loop. The skill body is a STATEMENT body (no `export\\n// default`); the executor wraps it as (async function(args, context){ <code> }).\\n// callProvider is POSITIONAL: callProvider(provider, method, path, body?) where\\n// `provider` is the required tool's NAME ('generic_api') — the dispatcher resolves\\n// it to the tool's credentialRef server-side and injects the vaulted API key. No\\n// providerRef arg needed. propose.entity REQUIRES `title` (not `name`) and routes\\n// the write through checkPermissionOrPropose.\\nconst path = args.path || '/records';\\nconst profileSlug = args.entityProfile || 'note';\\nconst res = await callProvider('generic_api', 'GET', path);\\nconst data = res && res.body !== undefined ? res.body : res;\\nconst records = Array.isArray(data)\\n ? data\\n : (data && Array.isArray(data.data) ? data.data : (data && data.records) || []);\\nlet proposed = 0;\\nfor (const record of records) {\\n await propose.entity({\\n profileSlug,\\n title: String((record && (record.name || record.title || record.id)) || 'record'),\\n properties: record,\\n });\\n proposed++;\\n}\\nreturn { proposed };\\n\"\n }\n ]\n },\n \"unipile-linkedin\": {\n \"key\": \"unipile-linkedin\",\n \"name\": \"Unipile — LinkedIn\",\n \"description\": \"LinkedIn outreach via Unipile (API-key connector). Stores the Unipile API key in the vault, registers one HTTP API tool that authenticates with Unipile's X-API-KEY header against the account's DSN, and seeds two proposal-gated code skills: search LinkedIn profiles (proposed as `person` entities) and send a connection invitation (the result noted as a `note`). Grounded in synap-backend's UnipileConnector (X-API-KEY auth, /api/v1 base) and the Unipile v1 LinkedIn API. PRECONDITION: a Unipile account with a connected LinkedIn account; pass that account_id as the skill `accountId` arg. The applier remaps the tool credentialRef to a runtime vault://<id>; the skills call the tool by NAME via callProvider('unipile_linkedin', ...), so the dispatcher resolves the credentialRef and injects the vaulted X-API-KEY server-side — no providerRef arg needed.\",\n \"params\": [\n {\n \"name\": \"unipileApiKey\",\n \"label\": \"Unipile API key\",\n \"type\": \"text\",\n \"required\": true,\n \"description\": \"The Unipile X-API-KEY. Stored server-encrypted in the vault; never persisted in the template.\"\n },\n {\n \"name\": \"unipileBaseUrl\",\n \"label\": \"Unipile DSN base URL\",\n \"type\": \"text\",\n \"required\": true,\n \"description\": \"Your Unipile DSN with the /api/v1 prefix, e.g. https://api6.unipile.com:13670/api/v1 — the same DSN UnipileConnector uses. Includes the host and port assigned to your Unipile account.\"\n },\n {\n \"name\": \"unipileAccountId\",\n \"label\": \"Unipile LinkedIn account id\",\n \"type\": \"text\",\n \"required\": true,\n \"description\": \"The Unipile account_id of the connected LinkedIn account that performs the search and sends invitations (from GET /api/v1/accounts). Used as the default skill accountId.\"\n },\n {\n \"name\": \"entityProfile\",\n \"label\": \"Target person profile\",\n \"type\": \"text\",\n \"required\": false,\n \"default\": \"person\",\n \"description\": \"The profileSlug found LinkedIn profiles are proposed as.\"\n }\n ],\n \"vault\": [\n {\n \"ref\": \"unipileApiKeySecret\",\n \"name\": \"{{name}} Unipile API key\",\n \"value\": \"{{unipileApiKey}}\",\n \"type\": \"api_key\",\n \"description\": \"Unipile X-API-KEY for the LinkedIn connector.\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"unipile_linkedin\",\n \"kind\": \"api\",\n \"description\": \"Authenticated HTTP access to the Unipile v1 API (LinkedIn). The applier injects the vaulted API key into the X-API-KEY header; its credentialRef is remapped to the runtime vault://<id> at apply time.\",\n \"credentialRef\": \"unipileApiKeySecret\",\n \"executor\": \"is-agent\",\n \"config\": {\n \"baseUrl\": \"{{unipileBaseUrl}}\",\n \"auth\": {\n \"in\": \"header\",\n \"name\": \"X-API-KEY\",\n \"prefix\": \"\"\n }\n }\n }\n ],\n \"skills\": [\n {\n \"name\": \"linkedin_search_profile\",\n \"kind\": \"code\",\n \"scope\": \"pod\",\n \"description\": \"Searches LinkedIn profiles via Unipile and proposes each match as a person entity (proposal-gated). Args: { keywords: string, accountId?: string, limit?: number }. Calls the tool by name via callProvider('unipile_linkedin', ...).\",\n \"requires\": [\n \"unipile_linkedin\"\n ],\n \"executionMode\": \"async\",\n \"timeoutSeconds\": 60,\n \"parameters\": {\n \"keywords\": \"string\",\n \"accountId\": \"string?\",\n \"limit\": \"number?\"\n },\n \"code\": \"// LinkedIn people search via Unipile, proposed as person entities.\\n// Executor wraps this body as (async function(args, context){ <code> }); use args\\n// directly and `return` the result. callProvider(provider, method, path, body?)\\n// runs the required tool through the dispatcher — pass the tool NAME\\n// ('unipile_linkedin') and the dispatcher resolves its credentialRef, injects the\\n// vaulted X-API-KEY, and uses the tool's config.baseUrl = DSN + /api/v1. No\\n// providerRef arg needed.\\nconst accountId = String(args?.accountId ?? '{{unipileAccountId}}');\\nconst keywords = String(args?.keywords ?? '').trim();\\nconst limit = Number(args?.limit ?? 10);\\nif (!keywords) throw new Error('linkedin_search_profile: keywords is required');\\n\\n// Unipile v1 LinkedIn search (category people).\\nconst qs = new URLSearchParams({ account_id: accountId, keywords, limit: String(limit) });\\nconst res = await callProvider('unipile_linkedin', 'GET', `/linkedin/search?${qs.toString()}`);\\nconst payload = res?.body ?? res;\\nconst items = Array.isArray(payload?.items) ? payload.items : (Array.isArray(payload) ? payload : []);\\n\\nconst profileSlug = '{{entityProfile}}' || 'person';\\nlet proposed = 0;\\nfor (const p of items.slice(0, limit)) {\\n const name = String(p?.name ?? [p?.first_name, p?.last_name].filter(Boolean).join(' ') ?? 'LinkedIn profile').trim() || 'LinkedIn profile';\\n await propose.entity({\\n profileSlug,\\n title: name,\\n properties: {\\n headline: p?.headline ?? null,\\n company: p?.current_company ?? p?.company ?? null,\\n location: p?.location ?? null,\\n linkedinProviderId: p?.provider_id ?? p?.id ?? null,\\n publicIdentifier: p?.public_identifier ?? p?.public_id ?? null,\\n profileUrl: p?.profile_url ?? null,\\n source: 'unipile-linkedin'\\n },\\n reasoning: `LinkedIn profile matched search \\\"${keywords}\\\" via Unipile.`\\n });\\n proposed += 1;\\n}\\nreturn { proposed, keywords };\\n\"\n },\n {\n \"name\": \"linkedin_send_invite\",\n \"kind\": \"code\",\n \"scope\": \"pod\",\n \"description\": \"Sends a LinkedIn connection invitation via Unipile, then notes the action as a note entity (proposal-gated). Args: { providerId: string (target LinkedIn provider_id), accountId?: string, message?: string }. Calls the tool by name via callProvider('unipile_linkedin', ...).\",\n \"requires\": [\n \"unipile_linkedin\"\n ],\n \"executionMode\": \"async\",\n \"timeoutSeconds\": 60,\n \"parameters\": {\n \"providerId\": \"string\",\n \"accountId\": \"string?\",\n \"message\": \"string?\"\n },\n \"code\": \"// Send a LinkedIn connection request via Unipile, then record a note.\\n// Executor wraps this body as (async function(args, context){ <code> }); use args\\n// directly and `return`. callProvider runs the unipile_linkedin tool through the\\n// dispatcher by NAME — the dispatcher resolves its credentialRef and injects the\\n// X-API-KEY server-side from the vault; propose.entity routes the write through\\n// governance. No providerRef arg needed.\\nconst accountId = String(args?.accountId ?? '{{unipileAccountId}}');\\nconst providerId = String(args?.providerId ?? '').trim();\\nconst message = typeof args?.message === 'string' ? args.message : undefined;\\nif (!providerId) throw new Error('linkedin_send_invite: providerId (the target LinkedIn provider_id) is required');\\n\\n// Unipile v1 connection-request endpoint.\\nconst body = { account_id: accountId, provider_id: providerId };\\nif (message) body.message = message;\\nconst res = await callProvider('unipile_linkedin', 'POST', '/users/invite', body);\\nconst ok = res?.status ? res.status >= 200 && res.status < 300 : true;\\n\\nawait propose.entity({\\n profileSlug: 'note',\\n title: `LinkedIn invitation ${ok ? 'sent' : 'attempted'} -> ${providerId}`,\\n properties: {\\n action: 'linkedin_send_invite',\\n providerId,\\n message: message ?? null,\\n status: res?.status ?? null,\\n success: ok,\\n source: 'unipile-linkedin'\\n },\\n reasoning: 'Recorded the outbound LinkedIn connection request for the activity timeline.'\\n});\\nreturn { success: ok, providerId, status: res?.status ?? null };\\n\"\n }\n ]\n },\n \"nango-gmail\": {\n \"key\": \"nango-gmail\",\n \"name\": \"Nango — Gmail\",\n \"description\": \"Send follow-up email via Gmail through Nango OAuth. Registers one provider tool whose credentialRef is the stable nango://gmail ref (Nango holds the OAuth credential — no vault secret), and seeds one proposal-gated code skill that sends an email via the Gmail API (users.messages.send) and notes the send as a `note`. Grounded in synap-backend's NangoConnector.proxyRequest (Connection-Id + Provider-Config-Key, host/proxy<path>) and external-dispatch's nango:// handler. PRECONDITION: a Nango integration with providerConfigKey 'gmail' must already exist and the acting user must have connected their Google account via Settings -> Connectors; the dispatcher resolves the user's most-recent gmail connection automatically.\",\n \"params\": [],\n \"vault\": [],\n \"tools\": [\n {\n \"name\": \"gmail\",\n \"kind\": \"provider\",\n \"description\": \"Gmail access through Nango. credentialRef nango://gmail resolves the user's Google connection (Connection-Id + Provider-Config-Key) and proxies the request to the Gmail API.\",\n \"credentialRef\": \"nango://gmail\",\n \"executor\": \"is-agent\",\n \"config\": {\n \"providerConfigKey\": \"gmail\"\n }\n }\n ],\n \"skills\": [\n {\n \"name\": \"gmail_send\",\n \"kind\": \"code\",\n \"scope\": \"pod\",\n \"description\": \"Sends an email via Gmail (Nango OAuth) and notes the send as a note entity (proposal-gated). Args: { to: string, subject: string, body: string }.\",\n \"requires\": [\n \"gmail\"\n ],\n \"executionMode\": \"async\",\n \"timeoutSeconds\": 60,\n \"parameters\": {\n \"to\": \"string\",\n \"subject\": \"string\",\n \"body\": \"string\"\n },\n \"code\": \"// Send a Gmail message via Nango OAuth, then record a note.\\n// Executor wraps this body as (async function(args, context){ <code> }); use args\\n// directly and `return`. callProvider('gmail', 'POST',\\n// '/gmail/v1/users/me/messages/send', { raw }) goes through the dispatcher by\\n// tool NAME ('gmail'): the dispatcher resolves the tool's credentialRef\\n// (nango://gmail), the nango:// handler resolves the user's Google connection and\\n// proxies to the Gmail API. (Passing the raw credentialRef 'nango://gmail' still\\n// works too — back-compat.)\\nconst to = String(args?.to ?? '').trim();\\nconst subject = String(args?.subject ?? '').trim();\\nconst bodyText = String(args?.body ?? '');\\nif (!to) throw new Error('gmail_send: to is required');\\nif (!subject) throw new Error('gmail_send: subject is required');\\n\\n// Build an RFC 2822 message and base64url-encode it (Gmail raw field).\\n// No Buffer/btoa in the isolate, so encode UTF-8 -> base64 manually.\\nconst mime = [\\n 'To: ' + to,\\n 'Subject: ' + subject,\\n 'MIME-Version: 1.0',\\n 'Content-Type: text/plain; charset=\\\"UTF-8\\\"',\\n '',\\n bodyText\\n].join('\\\\r\\\\n');\\n\\nconst B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\\nconst utf8Bytes = (str) => {\\n const out = [];\\n for (let i = 0; i < str.length; i++) {\\n let c = str.charCodeAt(i);\\n if (c < 0x80) out.push(c);\\n else if (c < 0x800) { out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f)); }\\n else if (c >= 0xd800 && c <= 0xdbff) {\\n const c2 = str.charCodeAt(++i);\\n c = 0x10000 + ((c & 0x3ff) << 10) + (c2 & 0x3ff);\\n out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));\\n } else { out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)); }\\n }\\n return out;\\n};\\nconst base64 = (bytes) => {\\n let s = '';\\n for (let i = 0; i < bytes.length; i += 3) {\\n const b0 = bytes[i], b1 = bytes[i + 1], b2 = bytes[i + 2];\\n s += B64[b0 >> 2];\\n s += B64[((b0 & 3) << 4) | ((b1 ?? 0) >> 4)];\\n s += b1 === undefined ? '=' : B64[((b1 & 15) << 2) | ((b2 ?? 0) >> 6)];\\n s += b2 === undefined ? '=' : B64[b2 & 63];\\n }\\n return s;\\n};\\nconst raw = base64(utf8Bytes(mime)).replace(/\\\\+/g, '-').replace(/\\\\//g, '_').replace(/=+$/, '');\\n\\nconst res = await callProvider('gmail', 'POST', '/gmail/v1/users/me/messages/send', { raw });\\nconst ok = res?.status ? res.status >= 200 && res.status < 300 : true;\\nconst messageId = res?.body?.id ?? null;\\n\\nawait propose.entity({\\n profileSlug: 'note',\\n title: 'Email ' + (ok ? 'sent' : 'attempted') + ' -> ' + to + ': ' + subject,\\n properties: {\\n action: 'gmail_send',\\n to,\\n subject,\\n gmailMessageId: messageId,\\n status: res?.status ?? null,\\n success: ok,\\n source: 'nango-gmail'\\n },\\n reasoning: 'Recorded the outbound follow-up email for the activity timeline.'\\n});\\nreturn { success: ok, to, subject, gmailMessageId: messageId, status: res?.status ?? null };\\n\"\n }\n ]\n },\n \"discord-bot\": {\n \"key\": \"discord-bot\",\n \"name\": \"Discord Bot\",\n \"description\": \"Post messages to a Discord channel via a Discord bot (API-key style auth). Stores the bot token in the vault, registers one HTTP API tool that authenticates with Discord's `Authorization: Bot <token>` header against the Discord v10 API, and seeds one proposal-gated code skill that sends a channel message and records it as a note. Rides on the shipped `vault://` executor: the applier remaps the tool's template-local vault ref to a runtime `vault://<id>`, and the dispatcher resolves the tool by NAME server-side and injects the vaulted token. PRECONDITION: a Discord application with a Bot user, the bot invited to the target server with the Send Messages permission and the Message Content intent enabled. Pass the bot token as `discordBotToken` and (optionally) a default `channelId`.\",\n \"params\": [\n {\n \"name\": \"discordBotToken\",\n \"label\": \"Discord bot token\",\n \"type\": \"text\",\n \"required\": true,\n \"description\": \"The Discord bot token (Developer Portal -> Bot -> Token). Stored server-encrypted in the vault; never persisted in the template.\"\n },\n {\n \"name\": \"channelId\",\n \"label\": \"Default Discord channel id\",\n \"type\": \"text\",\n \"required\": false,\n \"description\": \"Optional default channel id the bot posts to when a skill call omits channelId. The numeric snowflake id of the target channel.\"\n }\n ],\n \"vault\": [\n {\n \"ref\": \"discordBotTokenSecret\",\n \"name\": \"{{name}} Discord bot token\",\n \"value\": \"{{discordBotToken}}\",\n \"type\": \"api_key\",\n \"description\": \"Discord bot token for the discord_bot connector.\"\n }\n ],\n \"tools\": [\n {\n \"name\": \"discord_bot\",\n \"kind\": \"api\",\n \"description\": \"Authenticated HTTP access to the Discord v10 API. The applier injects the vaulted bot token into the Authorization header as `Bot <token>`; its credentialRef is remapped to the runtime vault://<id> at apply time.\",\n \"credentialRef\": \"discordBotTokenSecret\",\n \"executor\": \"is-agent\",\n \"config\": {\n \"baseUrl\": \"https://discord.com/api/v10\",\n \"auth\": {\n \"in\": \"header\",\n \"name\": \"Authorization\",\n \"prefix\": \"Bot \"\n }\n }\n }\n ],\n \"skills\": [\n {\n \"name\": \"discord_send_message\",\n \"kind\": \"code\",\n \"scope\": \"pod\",\n \"description\": \"Sends a message to a Discord channel via the bot, then records the post as a note entity (proposal-gated). Args: { content: string, channelId?: string }. The bot token is injected server-side from the vault; the dispatcher resolves the discord_bot tool by name.\",\n \"requires\": [\n \"discord_bot\"\n ],\n \"executionMode\": \"async\",\n \"timeoutSeconds\": 60,\n \"parameters\": {\n \"content\": \"string\",\n \"channelId\": \"string?\"\n },\n \"code\": \"// Post a message to a Discord channel via the bot, then record a note.\\n// Executor wraps this body as (async (args, context) => { <code> }); use args\\n// directly and `return` the result. callProvider(tool, method, path, body?)\\n// runs the required tool through the dispatcher (resolves the tool by NAME\\n// 'discord_bot', injects the vaulted bot token as Authorization: Bot <token>,\\n// uses the tool's config.baseUrl = https://discord.com/api/v10).\\nconst content = String(args?.content ?? '').trim();\\nif (!content) throw new Error('discord_send_message: content is required');\\nconst channelId = String(args?.channelId ?? '{{channelId}}').trim();\\nif (!channelId) throw new Error('discord_send_message: channelId is required (pass it or set a default in the template)');\\n\\n// Discord v10 create-message endpoint.\\nconst res = await callProvider('discord_bot', 'POST', '/channels/' + encodeURIComponent(channelId) + '/messages', { content });\\nconst ok = res?.status ? res.status >= 200 && res.status < 300 : true;\\nconst payload = res?.body ?? res;\\nconst messageId = payload?.id ?? null;\\n\\nawait propose.entity({\\n profileSlug: 'note',\\n title: 'Discord message ' + (ok ? 'sent' : 'attempted') + ' -> #' + channelId,\\n properties: {\\n action: 'discord_send_message',\\n channelId: channelId,\\n content: content,\\n messageId: messageId,\\n status: res?.status ?? null,\\n success: ok,\\n source: 'discord-bot'\\n },\\n reasoning: 'Recorded the outbound Discord message for the activity timeline.'\\n});\\nreturn { success: ok, channelId: channelId, messageId: messageId, status: res?.status ?? null };\\n\"\n }\n ]\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,eAAe,CAAC,cAAc,eAAe,WAAW;AAC9D,QAAM,UAAU,OAAO,SAAS;AAEhC,QAAI,QAAS,cAAa,KAAK,MAAM;AAErC,WAAO,UAAU;AAAA,MACf;AAAA,MACA,eAAe;AAAA,MACf,cAAc,OAAO,MAAM,CAAC;AAAA,MAC5B,MAAM;AAAA,MACN;AAAA,MACA,sBAAsB,uBAAO,wBAAwB;AAAA,MACrD,WAAW,uBAAO,WAAW;AAAA,MAC7B,aAAa,uBAAO,aAAa;AAAA,MACjC,YAAY,uBAAO,WAAW;AAAA,MAC9B,MAAM,MAAM;AAAA,MAAC;AAAA,IACf;AAAA;AAAA;;;AClBA;AAAA;AAAA;AAEA,QAAM,EAAE,aAAa,IAAI;AAEzB,QAAM,aAAa,OAAO,OAAO,OAAO;AAUxC,aAAS,OAAO,MAAM,aAAa;AACjC,UAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,UAAI,KAAK,WAAW,EAAG,QAAO,KAAK,CAAC;AAEpC,YAAM,SAAS,OAAO,YAAY,WAAW;AAC7C,UAAI,SAAS;AAEb,eAAS,IAAI,GA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AAgB,IAAI,CAAC;AAC5C,CAAC;AAGH,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAI,KAAK,SAAS,YAAY,KAAK,CAAC,KAAK,SAAS,QAAQ,KAAK,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,KAAK,SAAS,UAAU,GAAG;AACjH,UAAQ,OAAO,MAAM,gBAAgB,IAAI,CAAC;AAC1C,UAAQ,KAAK,CAAC;AAChB;AAEA,QAAQ,GAAG,sBAAsB,CAAC,WAAoB;AACpD,UAAQ,MAAM,cAAc,MAAM;AAClC,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,QAAQ,MAAM;AAEd,IAAI,CAAC,QAAQ,KAAK,MAAM,CAAC,EAAE,QAAQ;AACjC,UAAQ,WAAW;AACrB;","names":["output","PerMessageDeflate","data","PerMessageDeflate","Receiver","PerMessageDeflate","Sender","extension","randomBytes","URL","PerMessageDeflate","Receiver","Sender","WebSocket","key","WebSocket","createWebSocketStream","err","protocol","extension","PerMessageDeflate","subprotocol","WebSocket","WebSocketServer","existsSync","readFileSync","fileURLToPath","dirname","join","resolve","resolve","prompt","program","WebSocket","output","resolve","text","prompt","builder","builder2","writeFileSync9","execSync","execSync","program","execa","execSync","execSync","execSync","out","execSync","execSync","execSync","execSync","execa","existsSync","join","note","fetch","log","rm","program","execa","failed","note","execSync","existsSync","readFileSync","program","program","select","isCancel","existsSync","join","resolve","password","confirm","ok","isCancel","execa","existsSync","resolve","select","homedir","join","randomBytes","readEveSecrets","writeEveSecrets","installDashboardContainer","runAdd","execSync","mkdirSync","writeFileSync","program","select","confirm","isCancel","text","homedir","existsSync","join","existsSync","join","homedir","confirm","isCancel","text","program","select","execa","join","confirm","isCancel","execa","join","composePath","execFile","promisify","execFileAsync","RSSHubService","existsSync","readFileSync","writeFileSync","readEveSecrets","resolveSynapUrl","readAgentKeyOrLegacy","describePodProviderResult","confirm","isCancel","program","execa","program","execa","execa","program","execa","payload","program","program","output","execa","execSync","createInterface","existsSync","join","dirname","execSync","dirname","join","existsSync","readEveSecrets","writeEveSecrets","readFile","createInterface","program","execa","execSync","existsSync","homedir","join","createInterface","input","output","execa","execSync","createInterface","input","output","join","homedir","existsSync","execa","program","execSync","existsSync","join","existsSync","join","execSync","program","input","note","readAgentKey","spinner","program","execa","r","program","providers","prompt","execa","program","execa","randomBytes","randomBytes","execa","program","secret","execSync","existsSync","program","execSync","existsSync","domain","Table","prompt","runAdd","Table","runRemove","program","existsSync","rmSync","join","sleep","resolve","deployCommand","program","join","existsSync","rmSync","existsSync","mkdirSync","writeFileSync","readFileSync","join","homedir","program","creds","program","execSync","existsSync","readFileSync","join","execSync","join","existsSync","program","readFileSync","execFile","promisify","text","select","isCancel","cancel","execFileAsync","promisify","execFile","openBrowser","select","isCancel","cancel","text","email","program","readFile","existsSync","text","isCancel","cancel","text","isCancel","cancel","entry","existsSync","readFile","runList","program","fileURLToPath","dirname","readFileSync","join","resolve","existsSync","deployCommand"]}