{"version":3,"sources":["../node_modules/isexe/windows.js","../node_modules/isexe/mode.js","../node_modules/isexe/index.js","../node_modules/which/which.js","../node_modules/path-key/index.js","../node_modules/cross-spawn/lib/util/resolveCommand.js","../node_modules/cross-spawn/lib/util/escape.js","../node_modules/shebang-regex/index.js","../node_modules/shebang-command/index.js","../node_modules/cross-spawn/lib/util/readShebang.js","../node_modules/cross-spawn/lib/parse.js","../node_modules/cross-spawn/lib/enoent.js","../node_modules/cross-spawn/index.js","../src/hook-stop-collab.ts","../node_modules/@remixhq/core/dist/chunk-7XJGOKEO.js","../node_modules/is-plain-obj/index.js","../node_modules/execa/lib/arguments/file-url.js","../node_modules/execa/lib/methods/parameters.js","../node_modules/execa/lib/methods/template.js","../node_modules/execa/lib/utils/uint-array.js","../node_modules/execa/lib/methods/main-sync.js","../node_modules/execa/lib/arguments/specific.js","../node_modules/execa/lib/utils/standard-stream.js","../node_modules/execa/lib/verbose/values.js","../node_modules/execa/lib/verbose/log.js","../node_modules/execa/lib/arguments/escape.js","../node_modules/is-unicode-supported/index.js","../node_modules/figures/index.js","../node_modules/yoctocolors/base.js","../node_modules/execa/lib/verbose/default.js","../node_modules/execa/lib/verbose/custom.js","../node_modules/execa/lib/verbose/start.js","../node_modules/execa/lib/verbose/info.js","../node_modules/execa/lib/return/duration.js","../node_modules/execa/lib/arguments/command.js","../node_modules/execa/lib/arguments/options.js","../node_modules/npm-run-path/index.js","../node_modules/npm-run-path/node_modules/path-key/index.js","../node_modules/unicorn-magic/node.js","../node_modules/execa/lib/terminate/kill.js","../node_modules/execa/lib/return/final-error.js","../node_modules/execa/lib/terminate/signal.js","../node_modules/human-signals/build/src/main.js","../node_modules/human-signals/build/src/realtime.js","../node_modules/human-signals/build/src/signals.js","../node_modules/human-signals/build/src/core.js","../node_modules/execa/lib/utils/abort-signal.js","../node_modules/execa/lib/terminate/cancel.js","../node_modules/execa/lib/ipc/graceful.js","../node_modules/execa/lib/ipc/send.js","../node_modules/execa/lib/ipc/validation.js","../node_modules/execa/lib/utils/deferred.js","../node_modules/execa/lib/arguments/fd-options.js","../node_modules/execa/lib/ipc/strict.js","../node_modules/execa/lib/utils/max-listeners.js","../node_modules/execa/lib/ipc/forward.js","../node_modules/execa/lib/ipc/incoming.js","../node_modules/execa/lib/ipc/reference.js","../node_modules/execa/lib/ipc/outgoing.js","../node_modules/execa/lib/terminate/graceful.js","../node_modules/execa/lib/terminate/timeout.js","../node_modules/execa/lib/methods/node.js","../node_modules/execa/lib/ipc/ipc-input.js","../node_modules/execa/lib/arguments/encoding-option.js","../node_modules/execa/lib/arguments/cwd.js","../node_modules/execa/lib/arguments/shell.js","../node_modules/execa/lib/return/message.js","../node_modules/strip-final-newline/index.js","../node_modules/get-stream/source/index.js","../node_modules/is-stream/index.js","../node_modules/@sec-ant/readable-stream/dist/ponyfill/asyncIterator.js","../node_modules/get-stream/source/stream.js","../node_modules/get-stream/source/contents.js","../node_modules/get-stream/source/utils.js","../node_modules/get-stream/source/array.js","../node_modules/get-stream/source/array-buffer.js","../node_modules/get-stream/source/string.js","../node_modules/execa/lib/io/max-buffer.js","../node_modules/execa/lib/return/result.js","../node_modules/parse-ms/index.js","../node_modules/pretty-ms/index.js","../node_modules/execa/lib/verbose/error.js","../node_modules/execa/lib/verbose/complete.js","../node_modules/execa/lib/return/reject.js","../node_modules/execa/lib/stdio/handle-sync.js","../node_modules/execa/lib/stdio/type.js","../node_modules/execa/lib/transform/object-mode.js","../node_modules/execa/lib/transform/normalize.js","../node_modules/execa/lib/stdio/direction.js","../node_modules/execa/lib/ipc/array.js","../node_modules/execa/lib/stdio/stdio-option.js","../node_modules/execa/lib/stdio/native.js","../node_modules/execa/lib/stdio/input-option.js","../node_modules/execa/lib/stdio/duplicate.js","../node_modules/execa/lib/stdio/handle.js","../node_modules/execa/lib/io/strip-newline.js","../node_modules/execa/lib/transform/generator.js","../node_modules/execa/lib/transform/split.js","../node_modules/execa/lib/transform/validate.js","../node_modules/execa/lib/transform/encoding-transform.js","../node_modules/execa/lib/transform/run-async.js","../node_modules/execa/lib/transform/run-sync.js","../node_modules/execa/lib/io/input-sync.js","../node_modules/execa/lib/io/output-sync.js","../node_modules/execa/lib/verbose/output.js","../node_modules/execa/lib/resolve/all-sync.js","../node_modules/execa/lib/resolve/exit-async.js","../node_modules/execa/lib/resolve/exit-sync.js","../node_modules/execa/lib/methods/main-async.js","../node_modules/execa/lib/ipc/methods.js","../node_modules/execa/lib/ipc/get-one.js","../node_modules/execa/lib/ipc/get-each.js","../node_modules/execa/lib/return/early-error.js","../node_modules/execa/lib/stdio/handle-async.js","../node_modules/@sindresorhus/merge-streams/index.js","../node_modules/execa/lib/io/pipeline.js","../node_modules/execa/lib/io/output-async.js","../node_modules/execa/lib/terminate/cleanup.js","../node_modules/signal-exit/src/signals.ts","../node_modules/signal-exit/src/index.ts","../node_modules/execa/lib/pipe/pipe-arguments.js","../node_modules/execa/lib/pipe/throw.js","../node_modules/execa/lib/pipe/sequence.js","../node_modules/execa/lib/pipe/streaming.js","../node_modules/execa/lib/pipe/abort.js","../node_modules/execa/lib/pipe/setup.js","../node_modules/execa/lib/io/contents.js","../node_modules/execa/lib/io/iterate.js","../node_modules/execa/lib/resolve/wait-stream.js","../node_modules/execa/lib/resolve/stdio.js","../node_modules/execa/lib/resolve/all-async.js","../node_modules/execa/lib/resolve/wait-subprocess.js","../node_modules/execa/lib/verbose/ipc.js","../node_modules/execa/lib/ipc/buffer-messages.js","../node_modules/execa/lib/convert/concurrent.js","../node_modules/execa/lib/convert/readable.js","../node_modules/execa/lib/convert/shared.js","../node_modules/execa/lib/convert/writable.js","../node_modules/execa/lib/convert/duplex.js","../node_modules/execa/lib/convert/iterable.js","../node_modules/execa/lib/convert/add.js","../node_modules/execa/lib/methods/promise.js","../node_modules/execa/lib/methods/bind.js","../node_modules/execa/lib/methods/create.js","../node_modules/execa/lib/methods/command.js","../node_modules/execa/lib/methods/script.js","../node_modules/execa/index.js","../node_modules/@remixhq/core/dist/chunk-FA6PTZQI.js","../node_modules/@remixhq/core/dist/chunk-GNW6FA4J.js","../node_modules/zod/v3/external.js","../node_modules/zod/v3/helpers/util.js","../node_modules/zod/v3/ZodError.js","../node_modules/zod/v3/locales/en.js","../node_modules/zod/v3/errors.js","../node_modules/zod/v3/helpers/parseUtil.js","../node_modules/zod/v3/helpers/errorUtil.js","../node_modules/zod/v3/types.js","../node_modules/@remixhq/core/dist/collab.js","../src/auto-fix-dispatcher.ts","../src/finalize-failure-marker.ts","../src/collab-init-spawn-lock.ts","../src/runtime.ts","../src/hook-diagnostics.ts","../src/hook-state.ts","../src/source-conversation.ts","../package.json","../src/metadata.ts","../src/remix-cli-path.ts","../src/deferred-turn-queue.ts","../src/deferred-turn-drainer.ts","../node_modules/@remixhq/core/dist/chunk-COO3TIHW.js","../node_modules/@remixhq/core/dist/chunk-GVFTISVO.js","../node_modules/@remixhq/core/dist/chunk-62JBEMJH.js","../src/hook-auth.ts","../src/spawn-helpers.ts","../src/transient-failure.ts","../node_modules/@remixhq/core/dist/history.js","../src/usage/claudeCodeSession.ts","../src/hook-utils.ts"],"sourcesContent":["module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction checkPathExt (path, options) {\n  var pathext = options.pathExt !== undefined ?\n    options.pathExt : process.env.PATHEXT\n\n  if (!pathext) {\n    return true\n  }\n\n  pathext = pathext.split(';')\n  if (pathext.indexOf('') !== -1) {\n    return true\n  }\n  for (var i = 0; i < pathext.length; i++) {\n    var p = pathext[i].toLowerCase()\n    if (p && path.substr(-p.length).toLowerCase() === p) {\n      return true\n    }\n  }\n  return false\n}\n\nfunction checkStat (stat, path, options) {\n  if (!stat.isSymbolicLink() && !stat.isFile()) {\n    return false\n  }\n  return checkPathExt(path, options)\n}\n\nfunction isexe (path, options, cb) {\n  fs.stat(path, function (er, stat) {\n    cb(er, er ? false : checkStat(stat, path, options))\n  })\n}\n\nfunction sync (path, options) {\n  return checkStat(fs.statSync(path), path, options)\n}\n","module.exports = isexe\nisexe.sync = sync\n\nvar fs = require('fs')\n\nfunction isexe (path, options, cb) {\n  fs.stat(path, function (er, stat) {\n    cb(er, er ? false : checkStat(stat, options))\n  })\n}\n\nfunction sync (path, options) {\n  return checkStat(fs.statSync(path), options)\n}\n\nfunction checkStat (stat, options) {\n  return stat.isFile() && checkMode(stat, options)\n}\n\nfunction checkMode (stat, options) {\n  var mod = stat.mode\n  var uid = stat.uid\n  var gid = stat.gid\n\n  var myUid = options.uid !== undefined ?\n    options.uid : process.getuid && process.getuid()\n  var myGid = options.gid !== undefined ?\n    options.gid : process.getgid && process.getgid()\n\n  var u = parseInt('100', 8)\n  var g = parseInt('010', 8)\n  var o = parseInt('001', 8)\n  var ug = u | g\n\n  var ret = (mod & o) ||\n    (mod & g) && gid === myGid ||\n    (mod & u) && uid === myUid ||\n    (mod & ug) && myUid === 0\n\n  return ret\n}\n","var fs = require('fs')\nvar core\nif (process.platform === 'win32' || global.TESTING_WINDOWS) {\n  core = require('./windows.js')\n} else {\n  core = require('./mode.js')\n}\n\nmodule.exports = isexe\nisexe.sync = sync\n\nfunction isexe (path, options, cb) {\n  if (typeof options === 'function') {\n    cb = options\n    options = {}\n  }\n\n  if (!cb) {\n    if (typeof Promise !== 'function') {\n      throw new TypeError('callback not provided')\n    }\n\n    return new Promise(function (resolve, reject) {\n      isexe(path, options || {}, function (er, is) {\n        if (er) {\n          reject(er)\n        } else {\n          resolve(is)\n        }\n      })\n    })\n  }\n\n  core(path, options || {}, function (er, is) {\n    // ignore EACCES because that just means we aren't allowed to run it\n    if (er) {\n      if (er.code === 'EACCES' || options && options.ignoreErrors) {\n        er = null\n        is = false\n      }\n    }\n    cb(er, is)\n  })\n}\n\nfunction sync (path, options) {\n  // my kingdom for a filtered catch\n  try {\n    return core.sync(path, options || {})\n  } catch (er) {\n    if (options && options.ignoreErrors || er.code === 'EACCES') {\n      return false\n    } else {\n      throw er\n    }\n  }\n}\n","const isWindows = process.platform === 'win32' ||\n    process.env.OSTYPE === 'cygwin' ||\n    process.env.OSTYPE === 'msys'\n\nconst path = require('path')\nconst COLON = isWindows ? ';' : ':'\nconst isexe = require('isexe')\n\nconst getNotFoundError = (cmd) =>\n  Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })\n\nconst getPathInfo = (cmd, opt) => {\n  const colon = opt.colon || COLON\n\n  // If it has a slash, then we don't bother searching the pathenv.\n  // just check the file itself, and that's it.\n  const pathEnv = cmd.match(/\\//) || isWindows && cmd.match(/\\\\/) ? ['']\n    : (\n      [\n        // windows always checks the cwd first\n        ...(isWindows ? [process.cwd()] : []),\n        ...(opt.path || process.env.PATH ||\n          /* istanbul ignore next: very unusual */ '').split(colon),\n      ]\n    )\n  const pathExtExe = isWindows\n    ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'\n    : ''\n  const pathExt = isWindows ? pathExtExe.split(colon) : ['']\n\n  if (isWindows) {\n    if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')\n      pathExt.unshift('')\n  }\n\n  return {\n    pathEnv,\n    pathExt,\n    pathExtExe,\n  }\n}\n\nconst which = (cmd, opt, cb) => {\n  if (typeof opt === 'function') {\n    cb = opt\n    opt = {}\n  }\n  if (!opt)\n    opt = {}\n\n  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n  const found = []\n\n  const step = i => new Promise((resolve, reject) => {\n    if (i === pathEnv.length)\n      return opt.all && found.length ? resolve(found)\n        : reject(getNotFoundError(cmd))\n\n    const ppRaw = pathEnv[i]\n    const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n    const pCmd = path.join(pathPart, cmd)\n    const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n      : pCmd\n\n    resolve(subStep(p, i, 0))\n  })\n\n  const subStep = (p, i, ii) => new Promise((resolve, reject) => {\n    if (ii === pathExt.length)\n      return resolve(step(i + 1))\n    const ext = pathExt[ii]\n    isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {\n      if (!er && is) {\n        if (opt.all)\n          found.push(p + ext)\n        else\n          return resolve(p + ext)\n      }\n      return resolve(subStep(p, i, ii + 1))\n    })\n  })\n\n  return cb ? step(0).then(res => cb(null, res), cb) : step(0)\n}\n\nconst whichSync = (cmd, opt) => {\n  opt = opt || {}\n\n  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)\n  const found = []\n\n  for (let i = 0; i < pathEnv.length; i ++) {\n    const ppRaw = pathEnv[i]\n    const pathPart = /^\".*\"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw\n\n    const pCmd = path.join(pathPart, cmd)\n    const p = !pathPart && /^\\.[\\\\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd\n      : pCmd\n\n    for (let j = 0; j < pathExt.length; j ++) {\n      const cur = p + pathExt[j]\n      try {\n        const is = isexe.sync(cur, { pathExt: pathExtExe })\n        if (is) {\n          if (opt.all)\n            found.push(cur)\n          else\n            return cur\n        }\n      } catch (ex) {}\n    }\n  }\n\n  if (opt.all && found.length)\n    return found\n\n  if (opt.nothrow)\n    return null\n\n  throw getNotFoundError(cmd)\n}\n\nmodule.exports = which\nwhich.sync = whichSync\n","'use strict';\n\nconst pathKey = (options = {}) => {\n\tconst environment = options.env || process.env;\n\tconst platform = options.platform || process.platform;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n};\n\nmodule.exports = pathKey;\n// TODO: Remove this for the next major release\nmodule.exports.default = pathKey;\n","'use strict';\n\nconst path = require('path');\nconst which = require('which');\nconst getPathKey = require('path-key');\n\nfunction resolveCommandAttempt(parsed, withoutPathExt) {\n    const env = parsed.options.env || process.env;\n    const cwd = process.cwd();\n    const hasCustomCwd = parsed.options.cwd != null;\n    // Worker threads do not have process.chdir()\n    const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;\n\n    // If a custom `cwd` was specified, we need to change the process cwd\n    // because `which` will do stat calls but does not support a custom cwd\n    if (shouldSwitchCwd) {\n        try {\n            process.chdir(parsed.options.cwd);\n        } catch (err) {\n            /* Empty */\n        }\n    }\n\n    let resolved;\n\n    try {\n        resolved = which.sync(parsed.command, {\n            path: env[getPathKey({ env })],\n            pathExt: withoutPathExt ? path.delimiter : undefined,\n        });\n    } catch (e) {\n        /* Empty */\n    } finally {\n        if (shouldSwitchCwd) {\n            process.chdir(cwd);\n        }\n    }\n\n    // If we successfully resolved, ensure that an absolute path is returned\n    // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it\n    if (resolved) {\n        resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);\n    }\n\n    return resolved;\n}\n\nfunction resolveCommand(parsed) {\n    return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);\n}\n\nmodule.exports = resolveCommand;\n","'use strict';\n\n// See http://www.robvanderwoude.com/escapechars.php\nconst metaCharsRegExp = /([()\\][%!^\"`<>&|;, *?])/g;\n\nfunction escapeCommand(arg) {\n    // Escape meta chars\n    arg = arg.replace(metaCharsRegExp, '^$1');\n\n    return arg;\n}\n\nfunction escapeArgument(arg, doubleEscapeMetaChars) {\n    // Convert to string\n    arg = `${arg}`;\n\n    // Algorithm below is based on https://qntm.org/cmd\n    // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input\n    // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information\n\n    // Sequence of backslashes followed by a double quote:\n    // double up all the backslashes and escape the double quote\n    arg = arg.replace(/(?=(\\\\+?)?)\\1\"/g, '$1$1\\\\\"');\n\n    // Sequence of backslashes followed by the end of the string\n    // (which will become a double quote later):\n    // double up all the backslashes\n    arg = arg.replace(/(?=(\\\\+?)?)\\1$/, '$1$1');\n\n    // All other backslashes occur literally\n\n    // Quote the whole thing:\n    arg = `\"${arg}\"`;\n\n    // Escape meta chars\n    arg = arg.replace(metaCharsRegExp, '^$1');\n\n    // Double escape meta chars if necessary\n    if (doubleEscapeMetaChars) {\n        arg = arg.replace(metaCharsRegExp, '^$1');\n    }\n\n    return arg;\n}\n\nmodule.exports.command = escapeCommand;\nmodule.exports.argument = escapeArgument;\n","'use strict';\nmodule.exports = /^#!(.*)/;\n","'use strict';\nconst shebangRegex = require('shebang-regex');\n\nmodule.exports = (string = '') => {\n\tconst match = string.match(shebangRegex);\n\n\tif (!match) {\n\t\treturn null;\n\t}\n\n\tconst [path, argument] = match[0].replace(/#! ?/, '').split(' ');\n\tconst binary = path.split('/').pop();\n\n\tif (binary === 'env') {\n\t\treturn argument;\n\t}\n\n\treturn argument ? `${binary} ${argument}` : binary;\n};\n","'use strict';\n\nconst fs = require('fs');\nconst shebangCommand = require('shebang-command');\n\nfunction readShebang(command) {\n    // Read the first 150 bytes from the file\n    const size = 150;\n    const buffer = Buffer.alloc(size);\n\n    let fd;\n\n    try {\n        fd = fs.openSync(command, 'r');\n        fs.readSync(fd, buffer, 0, size, 0);\n        fs.closeSync(fd);\n    } catch (e) { /* Empty */ }\n\n    // Attempt to extract shebang (null is returned if not a shebang)\n    return shebangCommand(buffer.toString());\n}\n\nmodule.exports = readShebang;\n","'use strict';\n\nconst path = require('path');\nconst resolveCommand = require('./util/resolveCommand');\nconst escape = require('./util/escape');\nconst readShebang = require('./util/readShebang');\n\nconst isWin = process.platform === 'win32';\nconst isExecutableRegExp = /\\.(?:com|exe)$/i;\nconst isCmdShimRegExp = /node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;\n\nfunction detectShebang(parsed) {\n    parsed.file = resolveCommand(parsed);\n\n    const shebang = parsed.file && readShebang(parsed.file);\n\n    if (shebang) {\n        parsed.args.unshift(parsed.file);\n        parsed.command = shebang;\n\n        return resolveCommand(parsed);\n    }\n\n    return parsed.file;\n}\n\nfunction parseNonShell(parsed) {\n    if (!isWin) {\n        return parsed;\n    }\n\n    // Detect & add support for shebangs\n    const commandFile = detectShebang(parsed);\n\n    // We don't need a shell if the command filename is an executable\n    const needsShell = !isExecutableRegExp.test(commandFile);\n\n    // If a shell is required, use cmd.exe and take care of escaping everything correctly\n    // Note that `forceShell` is an hidden option used only in tests\n    if (parsed.options.forceShell || needsShell) {\n        // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`\n        // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument\n        // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,\n        // we need to double escape them\n        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);\n\n        // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\\bar)\n        // This is necessary otherwise it will always fail with ENOENT in those cases\n        parsed.command = path.normalize(parsed.command);\n\n        // Escape command & arguments\n        parsed.command = escape.command(parsed.command);\n        parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));\n\n        const shellCommand = [parsed.command].concat(parsed.args).join(' ');\n\n        parsed.args = ['/d', '/s', '/c', `\"${shellCommand}\"`];\n        parsed.command = process.env.comspec || 'cmd.exe';\n        parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped\n    }\n\n    return parsed;\n}\n\nfunction parse(command, args, options) {\n    // Normalize arguments, similar to nodejs\n    if (args && !Array.isArray(args)) {\n        options = args;\n        args = null;\n    }\n\n    args = args ? args.slice(0) : []; // Clone array to avoid changing the original\n    options = Object.assign({}, options); // Clone object to avoid changing the original\n\n    // Build our parsed object\n    const parsed = {\n        command,\n        args,\n        options,\n        file: undefined,\n        original: {\n            command,\n            args,\n        },\n    };\n\n    // Delegate further parsing to shell or non-shell\n    return options.shell ? parsed : parseNonShell(parsed);\n}\n\nmodule.exports = parse;\n","'use strict';\n\nconst isWin = process.platform === 'win32';\n\nfunction notFoundError(original, syscall) {\n    return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {\n        code: 'ENOENT',\n        errno: 'ENOENT',\n        syscall: `${syscall} ${original.command}`,\n        path: original.command,\n        spawnargs: original.args,\n    });\n}\n\nfunction hookChildProcess(cp, parsed) {\n    if (!isWin) {\n        return;\n    }\n\n    const originalEmit = cp.emit;\n\n    cp.emit = function (name, arg1) {\n        // If emitting \"exit\" event and exit code is 1, we need to check if\n        // the command exists and emit an \"error\" instead\n        // See https://github.com/IndigoUnited/node-cross-spawn/issues/16\n        if (name === 'exit') {\n            const err = verifyENOENT(arg1, parsed);\n\n            if (err) {\n                return originalEmit.call(cp, 'error', err);\n            }\n        }\n\n        return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params\n    };\n}\n\nfunction verifyENOENT(status, parsed) {\n    if (isWin && status === 1 && !parsed.file) {\n        return notFoundError(parsed.original, 'spawn');\n    }\n\n    return null;\n}\n\nfunction verifyENOENTSync(status, parsed) {\n    if (isWin && status === 1 && !parsed.file) {\n        return notFoundError(parsed.original, 'spawnSync');\n    }\n\n    return null;\n}\n\nmodule.exports = {\n    hookChildProcess,\n    verifyENOENT,\n    verifyENOENTSync,\n    notFoundError,\n};\n","'use strict';\n\nconst cp = require('child_process');\nconst parse = require('./lib/parse');\nconst enoent = require('./lib/enoent');\n\nfunction spawn(command, args, options) {\n    // Parse the arguments\n    const parsed = parse(command, args, options);\n\n    // Spawn the child process\n    const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);\n\n    // Hook into child process \"exit\" event to emit an error if the command\n    // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n    enoent.hookChildProcess(spawned, parsed);\n\n    return spawned;\n}\n\nfunction spawnSync(command, args, options) {\n    // Parse the arguments\n    const parsed = parse(command, args, options);\n\n    // Spawn the child process\n    const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);\n\n    // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16\n    result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);\n\n    return result;\n}\n\nmodule.exports = spawn;\nmodule.exports.spawn = spawn;\nmodule.exports.sync = spawnSync;\n\nmodule.exports._parse = parse;\nmodule.exports._enoent = enoent;\n","import { spawn } from \"node:child_process\";\nimport path from \"node:path\";\n\nimport * as coreCollab from \"@remixhq/core/collab\";\nimport {\n  isFinalizePreflightFailureCode,\n  type FinalizePreflightFailureCode,\n  type PendingFinalizeJob,\n  type TurnUsage,\n  type TurnUsagePayload,\n  type TurnUsagePreviousPatch,\n} from \"@remixhq/core/collab\";\nimport { readCollabBinding, readCollabBindingState } from \"@remixhq/core/binding\";\n\nimport { dispatchFinalizeFailure, isAutoFixableFinalizeFailureCode } from \"./auto-fix-dispatcher.js\";\nimport {\n  buildDeferredTurnRecord,\n  listDeferredTurnsForRepo,\n  pruneStaleDeferredTurns,\n  recordDeferredTurnFailedAttempt,\n  writeDeferredTurn,\n  deleteDeferredTurnFile,\n  type DeferredTurnEntry,\n} from \"./deferred-turn-queue.js\";\nimport { maybeRunDeferredTurnDrainerFromArgv } from \"./deferred-turn-drainer.js\";\nimport { clearFinalizeFailureMarker } from \"./finalize-failure-marker.js\";\nimport { spawnDeferredTurnDrainer } from \"./spawn-helpers.js\";\nimport { isTransientRecordingFailure } from \"./transient-failure.js\";\nimport { createHookCollabApiClient } from \"./hook-auth.js\";\nimport { appendHookDiagnosticsEvent, summarizeText } from \"./hook-diagnostics.js\";\nimport {\n  clearPendingTurnState,\n  listTouchedRepos,\n  loadLastFinalizedTurn,\n  loadPendingTurnState,\n  markLastFinalizedTurn,\n  markPendingTurnFailure,\n  markTouchedRepoRecordingFailure,\n  markTouchedRepoStopAttempted,\n  markTouchedRepoStopRecorded,\n  type RepoRecordMode,\n  type TouchedRepoState,\n  upsertTouchedRepo,\n} from \"./hook-state.js\";\nimport { pluginMetadata } from \"./metadata.js\";\nimport { harvestClaudeCodeUsage, readAndParseTranscript } from \"@remixhq/core/history\";\nimport { resolveClaudeCodeSession } from \"./usage/claudeCodeSession.js\";\nimport {\n  extractAssistantResponse,\n  extractBoolean,\n  extractString,\n  findBoundRepo,\n  readJsonStdin,\n  resolveBoundRepoSummary,\n} from \"./hook-utils.js\";\nimport {\n  getHookActor,\n  getPluginRuntime,\n  getRuntimeScopedTurnId,\n} from \"./runtime.js\";\nimport {\n  collabFinalizeTurn,\n  type ClaudeSourceConversation,\n} from \"./source-conversation.js\";\n\nconst HOOK_ACTOR = getHookActor(pluginMetadata.version);\n\nfunction getErrorDetails(error: unknown): {\n  message: string;\n  hint: string | null;\n  preflightCode: FinalizePreflightFailureCode | null;\n  // True when this failure looks like a transient blip (timeout, network\n  // error, 5xx) — caller uses this to defer the turn for silent retry\n  // instead of writing a user-visible failure marker.\n  isTransient: boolean;\n} {\n  if (error instanceof Error) {\n    const hint = typeof (error as { hint?: unknown }).hint === \"string\" ? String((error as { hint?: unknown }).hint) : null;\n    const codeRaw = (error as { code?: unknown }).code;\n    const preflightCode = isFinalizePreflightFailureCode(codeRaw) ? codeRaw : null;\n    return {\n      message: error.message || \"Fallback Remix turn recording failed.\",\n      hint,\n      preflightCode,\n      isTransient: isTransientRecordingFailure(error),\n    };\n  }\n  const message = typeof error === \"string\" && error.trim() ? error.trim() : \"Fallback Remix turn recording failed.\";\n  return { message, hint: null, preflightCode: null, isTransient: false };\n}\n\nfunction buildRepoIdempotencyKey(turnId: string, repo: TouchedRepoState): string {\n  const repoToken = repo.currentAppId?.trim() || repo.repoRoot;\n  return `${getRuntimeScopedTurnId(turnId)}:${repoToken}:finalize_turn`;\n}\n\nfunction isLegacyManualRecordingTool(toolName: string | null): boolean {\n  return /remix_collab_(add|add_change_step|record_turn|record_no_diff_turn)$/i.test(toolName ?? \"\");\n}\n\nfunction shouldSkipStopRecording(repo: TouchedRepoState): boolean {\n  if (repo.stopRecorded) {\n    return true;\n  }\n  if (!repo.manuallyRecorded) {\n    return false;\n  }\n  const alreadyRecordedByCompatibleFlow =\n    repo.manualRecordingScope === \"full_turn\" || isLegacyManualRecordingTool(repo.manuallyRecordedByTool);\n  if (!alreadyRecordedByCompatibleFlow) {\n    return false;\n  }\n  if (!repo.manuallyRecordedAt) {\n    return false;\n  }\n  if (!repo.lastObservedWriteAt) {\n    return true;\n  }\n  return new Date(repo.lastObservedWriteAt).getTime() <= new Date(repo.manuallyRecordedAt).getTime();\n}\n\nfunction createFallbackTouchedRepo(params: {\n  repoRoot: string;\n  projectId: string | null;\n  currentAppId: string | null;\n  upstreamAppId: string | null;\n}): TouchedRepoState {\n  const now = new Date().toISOString();\n  return {\n    repoRoot: params.repoRoot,\n    projectId: params.projectId,\n    currentAppId: params.currentAppId,\n    upstreamAppId: params.upstreamAppId,\n    firstTouchedAt: now,\n    lastTouchedAt: now,\n    lastObservedWriteAt: null,\n    touchedBy: [\"Stop:fallback-bound-repo\"],\n    hasObservedWrite: false,\n    manuallyRecorded: false,\n    manuallyRecordedAt: null,\n    manuallyRecordedByTool: null,\n    manualRecordingScope: null,\n    manualRemoteChangeRecordedAt: null,\n    stopAttempted: false,\n    stopRecorded: false,\n    stopRecordedAt: null,\n    stopRecordedMode: null,\n    recordingFailureMessage: null,\n    recordingFailureHint: null,\n    recordingFailedAt: null,\n  };\n}\n\n// Exponential-ish backoff intervals for the transcript-flush race. Claude Code\n// writes the assistant event to the JSONL transcript asynchronously — for\n// sub-second turns (\"say hi\" → \"hi\"), the Stop hook can fire before that write\n// lands on disk, and the first harvest sees no events for the current turn.\n// We retry by re-reading the transcript file on the failure path only;\n// successful first-tries add zero latency. Total worst-case wait is the sum of\n// the delays below (350 ms) before we give up and accept the miss.\nconst TRANSCRIPT_FLUSH_RETRY_DELAYS_MS: readonly number[] = [50, 100, 200];\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function harvestTurnUsage(params: {\n  hook: string;\n  sessionId: string;\n  state: { turnId: string; prompt: string; submittedAt: string };\n  payload: Record<string, unknown>;\n}): Promise<TurnUsagePayload | null> {\n  if (getPluginRuntime() === \"codex\") return null;\n  const { hook, sessionId, state, payload } = params;\n  const transcriptPath = extractString(payload, [\"transcript_path\"]);\n  if (!transcriptPath) return null;\n  const capturedAt = new Date().toISOString();\n\n  try {\n    const session = resolveClaudeCodeSession(payload);\n    const resolvedSessionId = session.agent.sessionId ?? sessionId;\n    let parsed = await readAndParseTranscript(transcriptPath);\n    if (!parsed.ok) {\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: state.turnId,\n        stage: \"usage_harvest_transcript_read\",\n        result: \"info\",\n        reason: parsed.reason,\n      });\n      return null;\n    }\n    let events = parsed.events;\n\n    const runCurrentHarvest = () =>\n      harvestClaudeCodeUsage({\n        events,\n        sessionId: resolvedSessionId,\n        promptText: state.prompt,\n        submittedAt: state.submittedAt,\n        agent: {\n          name: \"claude-code\",\n          version: null,\n          sessionId: resolvedSessionId,\n          turnId: state.turnId,\n          plan: session.agent.plan,\n        },\n        capturedAt,\n        extensions: session.extensions,\n      });\n\n    let currentResult = runCurrentHarvest();\n    let retriesUsed = 0;\n    let totalBackoffMs = 0;\n    // Re-read the transcript and re-harvest on the flush-race failure. Other\n    // failure reasons (e.g. session mismatch) are not transient — don't retry.\n    while (!currentResult.ok && currentResult.reason === \"no_messages_for_turn\") {\n      if (retriesUsed >= TRANSCRIPT_FLUSH_RETRY_DELAYS_MS.length) break;\n      const delayMs = TRANSCRIPT_FLUSH_RETRY_DELAYS_MS[retriesUsed]!;\n      await sleep(delayMs);\n      retriesUsed += 1;\n      totalBackoffMs += delayMs;\n      const reparsed = await readAndParseTranscript(transcriptPath);\n      if (!reparsed.ok) break;\n      events = reparsed.events;\n      currentResult = runCurrentHarvest();\n    }\n\n    let currentUsage: TurnUsage | null = null;\n    let currentBoundaryAt: string | null = null;\n    if (currentResult.ok) {\n      currentUsage = currentResult.usage;\n      currentBoundaryAt = currentResult.boundaryAt;\n      if (retriesUsed > 0) {\n        await appendHookDiagnosticsEvent({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          stage: \"usage_harvest_current\",\n          result: \"info\",\n          reason: \"recovered_after_flush_retry\",\n          fields: { retriesUsed, totalBackoffMs },\n        });\n      }\n    } else {\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: state.turnId,\n        stage: \"usage_harvest_current\",\n        result: \"info\",\n        reason: currentResult.reason,\n        fields: retriesUsed > 0 ? { retriesUsed, totalBackoffMs } : undefined,\n      });\n    }\n\n    let previousPatch: TurnUsagePreviousPatch | null = null;\n    const lastFinalized = await loadLastFinalizedTurn(sessionId);\n    if (lastFinalized && lastFinalized.sessionId && lastFinalized.turnId && lastFinalized.prompt) {\n      const prevResult = harvestClaudeCodeUsage({\n        events,\n        sessionId: lastFinalized.sessionId,\n        promptText: lastFinalized.prompt,\n        submittedAt: lastFinalized.finalizedAt,\n        checkSubsequentEvent: true,\n        // Constrain the previous-turn harvest to events strictly before this\n        // turn's actual user-event timestamp in the JSONL. Using the hook's\n        // submittedAt is too loose: Claude Code records the user event\n        // ~100–200 ms before the hook fires, so the current turn's own user\n        // message slips under that bound and findBoundary locks onto it.\n        // Prefer the timestamp returned by the current-turn harvest; fall\n        // back to submittedAt only if the current harvest failed.\n        nextBoundaryAt: currentBoundaryAt ?? state.submittedAt,\n        agent: {\n          name: \"claude-code\",\n          version: null,\n          sessionId: lastFinalized.sessionId,\n          turnId: lastFinalized.turnId,\n          plan: session.agent.plan,\n        },\n        capturedAt,\n        extensions: session.extensions,\n      });\n      if (prevResult.ok) {\n        previousPatch = {\n          previousAgentTurnId: lastFinalized.turnId,\n          previousSessionId: lastFinalized.sessionId,\n          usage: prevResult.usage,\n        };\n      } else {\n        await appendHookDiagnosticsEvent({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          stage: \"usage_harvest_previous\",\n          result: \"info\",\n          reason: prevResult.reason,\n        });\n      }\n    }\n\n    if (!currentUsage && !previousPatch) return null;\n    return { schemaVersion: 1, currentTurn: currentUsage, previousTurn: previousPatch };\n  } catch (err) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId: state.turnId,\n      stage: \"usage_harvest_threw\",\n      result: \"error\",\n      message: err instanceof Error ? err.message : String(err),\n    });\n    return null;\n  }\n}\n\n// Mixed-version safeguard: bind freshly-harvested usage onto pending-finalize\n// jobs that an older MCP server's manual finalize tool enqueued for the same\n// repo. That legacy path delayed the job so the Stop hook could attach usage;\n// we clear the deadline here so the detached drainer can claim it.\nasync function attachUsageToPendingMcpJobs(params: {\n  hook: string;\n  sessionId: string;\n  turnId: string;\n  repo: TouchedRepoState;\n  turnUsage: TurnUsagePayload | null;\n}): Promise<void> {\n  const { hook, sessionId, turnId, repo, turnUsage } = params;\n  const listPendingFinalizeJobs = (\n    coreCollab as { listPendingFinalizeJobs?: () => Promise<PendingFinalizeJob[]> }\n  ).listPendingFinalizeJobs;\n  const updatePendingFinalizeJob = (\n    coreCollab as {\n      updatePendingFinalizeJob?: (\n        jobId: string,\n        update: Partial<{ metadata: Record<string, unknown>; nextRetryAt: string | null }>,\n      ) => Promise<PendingFinalizeJob | null>;\n    }\n  ).updatePendingFinalizeJob;\n  if (typeof listPendingFinalizeJobs !== \"function\" || typeof updatePendingFinalizeJob !== \"function\") {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"usage_attach_skipped\",\n      result: \"info\",\n      reason: \"queue_helpers_unavailable\",\n      repoRoot: repo.repoRoot,\n    });\n    return;\n  }\n\n  let pending: PendingFinalizeJob[];\n  try {\n    pending = await listPendingFinalizeJobs();\n  } catch (err) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"usage_attach_list_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot: repo.repoRoot,\n      message: err instanceof Error ? err.message : String(err),\n    });\n    return;\n  }\n\n  const now = Date.now();\n  // Identify MCP-path \"awaiting usage\" jobs: `nextRetryAt > now` is shared by both\n  // the awaiting-usage deadline AND retry-backoff after a failure. Disambiguate the\n  // same way summarizePendingFinalizeJobs does: a fresh first-attempt job with no\n  // prior error and retryCount === 0 is the awaiting-usage marker; anything with a\n  // retry count or an error is a backoff retry that we MUST NOT touch (otherwise we\n  // would corrupt unrelated turns' usage data and prematurely re-fire failed jobs).\n  const matches = pending.filter(\n    (job) =>\n      job.status === \"queued\" &&\n      job.repoRoot === repo.repoRoot &&\n      job.retryCount === 0 &&\n      !job.error &&\n      job.nextRetryAt !== null &&\n      Number.isFinite(Date.parse(job.nextRetryAt)) &&\n      Date.parse(job.nextRetryAt) > now,\n  );\n\n  if (matches.length === 0) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"usage_attach_no_match\",\n      result: \"info\",\n      reason: turnUsage ? \"no_pending_mcp_job\" : \"no_pending_mcp_job_no_usage\",\n      repoRoot: repo.repoRoot,\n    });\n    return;\n  }\n\n  let updated = 0;\n  let skipped = 0;\n  let failed = 0;\n  for (const job of matches) {\n    try {\n      const next = await updatePendingFinalizeJob(job.id, {\n        metadata: turnUsage ? { turnUsage } : {},\n        nextRetryAt: null,\n      });\n      if (next) {\n        updated += 1;\n      } else {\n        // Job was completed/removed between list and update — expected race, not an error.\n        skipped += 1;\n      }\n    } catch (err) {\n      failed += 1;\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId,\n        stage: \"usage_attach_update_failed\",\n        result: \"error\",\n        reason: \"exception\",\n        repoRoot: repo.repoRoot,\n        message: err instanceof Error ? err.message : String(err),\n        fields: { jobId: job.id },\n      });\n    }\n  }\n\n  await appendHookDiagnosticsEvent({\n    hook,\n    sessionId,\n    turnId,\n    stage: \"usage_attach_completed\",\n    result: failed > 0 ? \"error\" : \"success\",\n    repoRoot: repo.repoRoot,\n    fields: {\n      matchedJobCount: matches.length,\n      updatedJobCount: updated,\n      skippedJobCount: skipped,\n      failedJobCount: failed,\n      hasUsage: Boolean(turnUsage),\n    },\n  });\n}\n\ntype RecordTouchedRepoResult = {\n  recorded: boolean;\n  queued: boolean;\n  // Populated when recording threw. Lets the caller dispatch on a\n  // structured failure code instead of pattern-matching messages.\n  failure: {\n    repoRoot: string;\n    message: string;\n    hint: string | null;\n    preflightCode: FinalizePreflightFailureCode | null;\n    // True when the recording call failed with a transient error\n    // (timeout, network blip, 5xx). The Stop hook's failure-loop\n    // routes transient failures to the deferred-turn queue (silent\n    // retry on the next prompt) and skips the user-facing failure\n    // marker dispatch so a flaky network doesn't spam the advisory.\n    isTransient: boolean;\n  } | null;\n};\n\nasync function recordTouchedRepo(params: {\n  hook: string;\n  sessionId: string;\n  turnId: string;\n  sourceConversation: ClaudeSourceConversation | null;\n  repo: TouchedRepoState;\n  prompt: string;\n  assistantResponse: string;\n  api: Awaited<ReturnType<typeof createHookCollabApiClient>>;\n  turnUsage: TurnUsagePayload | null;\n  /**\n   * ISO-8601 of when the user actually submitted this prompt, sourced from\n   * `PendingTurnState.submittedAt` at the call site. Forwarded to\n   * `collabFinalizeTurn` as `promptedAt` so the dashboard timeline orders\n   * this turn by its true submission time instead of by Stop-hook\n   * ingestion time. Optional for back-compat with any caller that lacks\n   * the field — when missing the dashboard falls back to `created_at`.\n   */\n  promptedAt?: string | null;\n}): Promise<RecordTouchedRepoResult> {\n  const { hook, sessionId, turnId, sourceConversation, repo, prompt, assistantResponse, api, turnUsage, promptedAt } = params;\n  await markTouchedRepoStopAttempted(sessionId, repo.repoRoot);\n  await appendHookDiagnosticsEvent({\n    hook,\n    sessionId,\n    turnId,\n    stage: \"recording_started\",\n    result: \"info\",\n    repoRoot: repo.repoRoot,\n    fields: {\n      hasObservedWrite: repo.hasObservedWrite,\n      manuallyRecorded: repo.manuallyRecorded,\n      stopAttempted: true,\n    },\n  });\n\n  try {\n    const binding = await readCollabBinding(repo.repoRoot).catch(() => null);\n    if (!binding) {\n      const failure = {\n        repoRoot: repo.repoRoot,\n        message: \"Fallback Remix turn recording failed because the repository is no longer bound to Remix.\",\n        hint: `Repo root: ${repo.repoRoot}`,\n        // Equivalent to the not_bound preflight code — the binding\n        // disappeared between touch-time and finalize-time. Reusing the\n        // code lets the dispatcher route this through the same recovery.\n        preflightCode: \"not_bound\" as const,\n        // Missing-binding is a permanent state mismatch (the user\n        // unbinded mid-flight); not transient. Spell it out so the\n        // upstream loop routes via dispatchFinalizeFailure instead of\n        // silent defer.\n        isTransient: false,\n      };\n      await markTouchedRepoRecordingFailure(sessionId, repo.repoRoot, {\n        message: failure.message,\n        hint: failure.hint,\n      });\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId,\n        stage: \"binding_lookup\",\n        result: \"error\",\n        reason: \"repo_not_bound\",\n        repoRoot: repo.repoRoot,\n      });\n      return { recorded: false, queued: false, failure };\n    }\n\n    const result = await collabFinalizeTurn({\n      api,\n      cwd: repo.repoRoot,\n      prompt,\n      assistantResponse,\n      idempotencyKey: buildRepoIdempotencyKey(turnId, repo),\n      actor: HOOK_ACTOR,\n      sourceConversation: sourceConversation ?? undefined,\n      turnUsage,\n      promptedAt: promptedAt ?? null,\n    });\n    await markTouchedRepoStopRecorded(sessionId, repo.repoRoot, { mode: result.mode as RepoRecordMode });\n    // Recording succeeded — clear any stale failure marker for this repo.\n    // The marker is the source of truth for \"previous turn left things\n    // broken\"; if we're here, things aren't broken anymore.\n    await clearFinalizeFailureMarker(repo.repoRoot).catch(() => undefined);\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"recording_completed\",\n      result: \"success\",\n      reason: result.mode,\n      repoRoot: repo.repoRoot,\n    });\n    return {\n      recorded: true,\n      queued: (result as { queued?: boolean }).queued === true,\n      failure: null,\n    };\n  } catch (error) {\n    const details = getErrorDetails(error);\n    await markTouchedRepoRecordingFailure(sessionId, repo.repoRoot, {\n      message: details.message,\n      hint: details.hint,\n    });\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"recording_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot: repo.repoRoot,\n      message: details.message,\n      fields: {\n        hint: details.hint,\n        preflightCode: details.preflightCode,\n        // Logged so a hung backend or DNS hiccup is greppable in the\n        // diagnostics file alongside the Cursor mirror — the next\n        // prompt's drain log will pair with this for the recovery.\n        isTransient: details.isTransient,\n      },\n    });\n    return {\n      recorded: false,\n      queued: false,\n      failure: {\n        repoRoot: repo.repoRoot,\n        message: details.message,\n        hint: details.hint,\n        preflightCode: details.preflightCode,\n        isTransient: details.isTransient,\n      },\n    };\n  }\n}\n\nfunction spawnFinalizeQueueDrainer(): void {\n  const entrypoint = process.argv[1];\n  if (!entrypoint) return;\n  const child = spawn(process.execPath, [...process.execArgv, entrypoint, \"--drain-finalize-queue\"], {\n    detached: true,\n    stdio: \"ignore\",\n    env: process.env,\n  });\n  child.unref();\n}\n\n// ---------------------------------------------------------------------------\n// Deferred-turn drain.\n//\n// Called BEFORE recording the current turn (Fix 2a in cursor's design):\n// any turns we previously deferred because their branch wasn't bound at\n// finalize time get a chance to flush, in chronological order, before\n// the new turn lands. That preserves submission order on the dashboard\n// timeline, and it lets the drain run even if the current turn fails.\n//\n// Safety rules:\n//   - Only drains turns whose `repoRoot` matches exactly.\n//   - Only records when the *current* branch on disk equals the\n//     `branchAtDefer` captured when we deferred. If the user has\n//     since switched branches we leave the record in place; recording\n//     under the wrong branch would be worse than waiting for them\n//     to switch back (and the TTL sweep will clean it up if they\n//     never do).\n//   - Each deferred turn carries its original turnId, so the\n//     idempotency key matches anything the same session already\n//     queued — duplicate-write attempts are a no-op server-side.\n//   - Failures don't propagate. The drain is a best-effort recovery\n//     channel; if it can't record now (network, etc.) we leave the\n//     file and try again next turn.\n// ---------------------------------------------------------------------------\n\nconst DEFERRED_TURN_PRUNE_LOG_LIMIT = 5;\n\nasync function drainDeferredTurnsForRepo(params: {\n  // Constrained to the dispatcher's accepted set so we can forward the\n  // value into `dispatchFinalizeFailure` (which only knows about the\n  // two real Claude hook entrypoints) without an unsafe cast on the\n  // promotion path.\n  hook: \"UserPromptSubmit\" | \"Stop\";\n  sessionId: string;\n  triggerTurnId: string;\n  repoRoot: string;\n  api: Awaited<ReturnType<typeof createHookCollabApiClient>>;\n}): Promise<void> {\n  const { hook, sessionId, triggerTurnId, repoRoot, api } = params;\n  let entries: DeferredTurnEntry[] = [];\n  try {\n    entries = await listDeferredTurnsForRepo(repoRoot);\n  } catch (listErr) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId: triggerTurnId,\n      stage: \"deferred_turn_list_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot,\n      message: listErr instanceof Error ? listErr.message : String(listErr),\n    });\n    return;\n  }\n  if (entries.length === 0) return;\n\n  const bindingState = await readCollabBindingState(repoRoot).catch(() => null);\n  const currentBranch = bindingState?.currentBranch ?? null;\n  const isCurrentBranchBound = bindingState?.binding != null;\n  const currentAppId = bindingState?.binding?.currentAppId ?? null;\n  const currentProjectId = bindingState?.binding?.projectId ?? bindingState?.projectId ?? null;\n\n  await appendHookDiagnosticsEvent({\n    hook,\n    sessionId,\n    turnId: triggerTurnId,\n    stage: \"deferred_turn_drain_started\",\n    result: \"info\",\n    repoRoot,\n    fields: {\n      candidateCount: entries.length,\n      currentBranch,\n      currentBranchBound: isCurrentBranchBound,\n      currentAppId,\n      currentProjectId,\n    },\n  });\n\n  let recordedCount = 0;\n  let skippedCount = 0;\n  let failedCount = 0;\n  let droppedCount = 0;\n\n  for (const entry of entries) {\n    const { record, filePath } = entry;\n    // Drop deferred turns whose binding identity at defer-time no\n    // longer matches the repo's current binding. This is the\n    // post-`force-new` (and post-fork) path: the user explicitly\n    // minted a brand-new app/project for the same `repoRoot`, so any\n    // turn captured against the *old* identity belongs to the *old*\n    // app's history and must not be silently re-attributed to the\n    // new app. Records written by older plugin versions have\n    // `appIdAtDefer === null`, in which case we fall back to the\n    // legacy branch-only check (preserves the existing branch-init\n    // race recovery for in-flight users).\n    const appIdMismatch =\n      record.appIdAtDefer != null && currentAppId != null && record.appIdAtDefer !== currentAppId;\n    const projectIdMismatch =\n      record.projectIdAtDefer != null &&\n      currentProjectId != null &&\n      record.projectIdAtDefer !== currentProjectId;\n    if (appIdMismatch || projectIdMismatch) {\n      droppedCount += 1;\n      await deleteDeferredTurnFile(filePath);\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: triggerTurnId,\n        stage: \"deferred_turn_dropped\",\n        result: \"info\",\n        reason: appIdMismatch ? \"app_id_mismatch\" : \"project_id_mismatch\",\n        repoRoot,\n        fields: {\n          deferredTurnId: record.turnId,\n          deferredSessionId: record.sessionId,\n          appIdAtDefer: record.appIdAtDefer,\n          projectIdAtDefer: record.projectIdAtDefer,\n          currentAppId,\n          currentProjectId,\n        },\n      });\n      continue;\n    }\n    if (!isCurrentBranchBound || (record.branchAtDefer && record.branchAtDefer !== currentBranch)) {\n      skippedCount += 1;\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: triggerTurnId,\n        stage: \"deferred_turn_skipped\",\n        result: \"info\",\n        reason: \"branch_mismatch\",\n        repoRoot,\n        fields: {\n          deferredTurnId: record.turnId,\n          deferredSessionId: record.sessionId,\n          branchAtDefer: record.branchAtDefer,\n          currentBranch,\n        },\n      });\n      continue;\n    }\n    try {\n      const idempotencyKey = `${getRuntimeScopedTurnId(record.turnId)}:${repoRoot}:finalize_turn`;\n      await collabFinalizeTurn({\n        api,\n        cwd: repoRoot,\n        prompt: record.prompt,\n        assistantResponse: record.assistantResponse,\n        idempotencyKey,\n        actor: HOOK_ACTOR,\n        sourceConversation: record.sourceConversation ?? undefined,\n        turnUsage: null,\n        promptedAt: record.submittedAt,\n      });\n      await deleteDeferredTurnFile(filePath);\n      recordedCount += 1;\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: triggerTurnId,\n        stage: \"deferred_turn_recorded\",\n        result: \"success\",\n        repoRoot,\n        fields: {\n          deferredTurnId: record.turnId,\n          deferredSessionId: record.sessionId,\n          deferredAt: record.deferredAt,\n          submittedAt: record.submittedAt,\n          recordingDelayMs: Math.max(0, Date.now() - Date.parse(record.deferredAt)),\n        },\n      });\n    } catch (recordErr) {\n      failedCount += 1;\n      // Bump the per-record attempt counter so a stuck record doesn't\n      // retry forever. When the cap is reached we delete the queue\n      // file and surface a user-visible failure marker via\n      // `dispatchFinalizeFailure` so the next prompt's advisory tells\n      // the user something went wrong (otherwise the lost turn would\n      // be silent — worse than the noisy advisory).\n      const outcome = await recordDeferredTurnFailedAttempt(filePath).catch(() => null);\n      const promoted = outcome?.promoted === true;\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: triggerTurnId,\n        stage: \"deferred_turn_record_failed\",\n        result: \"error\",\n        reason: \"exception\",\n        repoRoot,\n        message: recordErr instanceof Error ? recordErr.message : String(recordErr),\n        fields: {\n          deferredTurnId: record.turnId,\n          deferredSessionId: record.sessionId,\n          attemptCount: outcome?.promoted === false\n            ? outcome.newAttemptCount\n            : outcome?.promoted === true\n            ? outcome.finalAttemptCount\n            : null,\n          promoted,\n        },\n      });\n      if (promoted) {\n        // Emit a marker the user will see on the next prompt. Best-effort\n        // — never throws — so a flaky filesystem doesn't take down the\n        // drain loop. Reuses the existing dispatcher to keep the\n        // marker shape and hint copy consistent with other failure\n        // paths.\n        const errorDetails = getErrorDetails(recordErr);\n        await dispatchFinalizeFailure({\n          hook,\n          sessionId,\n          turnId: triggerTurnId,\n          repoRoot,\n          preflightCode: errorDetails.preflightCode,\n          message: `Deferred turn could not be recorded after ${outcome?.finalAttemptCount ?? \"max\"} attempts: ${errorDetails.message}`,\n          hint: errorDetails.hint,\n        }).catch(async (dispatchErr) => {\n          await appendHookDiagnosticsEvent({\n            hook,\n            sessionId,\n            turnId: triggerTurnId,\n            stage: \"deferred_turn_promotion_dispatch_failed\",\n            result: \"error\",\n            reason: \"exception\",\n            repoRoot,\n            message: dispatchErr instanceof Error ? dispatchErr.message : String(dispatchErr),\n            fields: {\n              deferredTurnId: record.turnId,\n              deferredSessionId: record.sessionId,\n            },\n          });\n        });\n      }\n    }\n  }\n\n  try {\n    const pruned = await pruneStaleDeferredTurns();\n    for (const prunedPath of pruned.slice(0, DEFERRED_TURN_PRUNE_LOG_LIMIT)) {\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: triggerTurnId,\n        stage: \"deferred_turn_pruned\",\n        result: \"info\",\n        reason: \"stale\",\n        repoRoot,\n        fields: { prunedFilePath: prunedPath },\n      });\n    }\n    if (pruned.length > DEFERRED_TURN_PRUNE_LOG_LIMIT) {\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: triggerTurnId,\n        stage: \"deferred_turn_pruned\",\n        result: \"info\",\n        reason: \"stale_truncated\",\n        repoRoot,\n        fields: {\n          totalPruned: pruned.length,\n          loggedPruned: DEFERRED_TURN_PRUNE_LOG_LIMIT,\n        },\n      });\n    }\n  } catch {\n    // Non-fatal; prune just retries next turn.\n  }\n\n  await appendHookDiagnosticsEvent({\n    hook,\n    sessionId,\n    turnId: triggerTurnId,\n    stage: \"deferred_turn_drain_completed\",\n    result: \"info\",\n    repoRoot,\n    fields: {\n      recordedCount,\n      skippedCount,\n      failedCount,\n      droppedCount,\n    },\n  });\n}\n\n// Defer this turn for silent retry on the next Stop hook because the\n// recording call failed with a transient error (timeout, network blip,\n// 5xx). Distinct from `deferTurnForRecoveryInProgress` in two important\n// ways:\n//\n//   1. We do NOT spawn the standalone deferred-turn drainer. Spawning\n//      it here would just keep retrying the same failing call every\n//      few seconds and waste both client and backend resources during\n//      the very window when one or both are unhealthy. Instead the\n//      next prompt's `drainDeferredTurnsForRepo` (run inline at the\n//      start of the next Stop hook, after the network has had time to\n//      recover) replays the turn.\n//\n//   2. We do NOT call `dispatchFinalizeFailure` — that helper writes a\n//      user-visible failure marker. For transient blips, surfacing an\n//      advisory on every flaky-network turn would create more noise\n//      than signal. The marker is only written if/when the deferred\n//      turn exhausts `DEFERRED_TURN_MAX_ATTEMPTS` (see the drainer's\n//      `recordDeferredTurnFailedAttempt` promotion path).\nasync function deferTurnForTransientFailure(params: {\n  hook: string;\n  sessionId: string;\n  turnId: string;\n  repoRoot: string;\n  prompt: string;\n  assistantResponse: string;\n  submittedAt: string;\n  sourceConversation: ClaudeSourceConversation | null;\n  failureMessage: string;\n}): Promise<string | null> {\n  const { hook, sessionId, turnId, repoRoot, prompt, assistantResponse, submittedAt, sourceConversation, failureMessage } = params;\n  const bindingState = await readCollabBindingState(repoRoot).catch(() => null);\n  const branchAtDefer = bindingState?.currentBranch ?? null;\n  const appIdAtDefer = bindingState?.binding?.currentAppId ?? null;\n  const projectIdAtDefer = bindingState?.binding?.projectId ?? bindingState?.projectId ?? null;\n\n  try {\n    const deferredFilePath = await writeDeferredTurn(\n      buildDeferredTurnRecord({\n        sessionId,\n        turnId,\n        sourceConversation,\n        repoRoot,\n        prompt,\n        assistantResponse,\n        submittedAt,\n        branchAtDefer,\n        appIdAtDefer,\n        projectIdAtDefer,\n        reason: \"transient_recording_failure\",\n      }),\n    );\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"turn_deferred\",\n      result: \"success\",\n      reason: \"transient_recording_failure\",\n      repoRoot,\n      fields: {\n        deferredFilePath,\n        promptLength: prompt.length,\n        assistantResponseLength: assistantResponse.length,\n        branchAtDefer,\n        // Forwarded so the diagnostics timeline pairs the defer with\n        // the originating recording_failed event without needing a\n        // join across stages.\n        failureMessage,\n      },\n    });\n    return deferredFilePath;\n  } catch (deferErr) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"deferred_turn_write_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot,\n      message: deferErr instanceof Error ? deferErr.message : String(deferErr),\n      fields: {\n        triggeredBy: \"transient_recording_failure\",\n      },\n    });\n    return null;\n  }\n}\n\nasync function deferTurnForRecoveryInProgress(params: {\n  hook: string;\n  sessionId: string;\n  turnId: string;\n  repoRoot: string;\n  prompt: string;\n  assistantResponse: string;\n  submittedAt: string;\n  sourceConversation: ClaudeSourceConversation | null;\n  preflightCode: FinalizePreflightFailureCode;\n}): Promise<string | null> {\n  const { hook, sessionId, turnId, repoRoot, prompt, assistantResponse, submittedAt, sourceConversation, preflightCode } = params;\n  const bindingState = await readCollabBindingState(repoRoot).catch(() => null);\n  const branchAtDefer = bindingState?.currentBranch ?? null;\n  // Stamp the binding identity active at defer-time so the drainer\n  // can drop this record if the user later runs `remix collab init\n  // --force-new` (which mints a fresh app/project for the same\n  // `repoRoot`). Without this, the recovered turn would silently\n  // land on the wrong app's timeline.\n  const appIdAtDefer = bindingState?.binding?.currentAppId ?? null;\n  const projectIdAtDefer = bindingState?.binding?.projectId ?? bindingState?.projectId ?? null;\n\n  try {\n    const deferredFilePath = await writeDeferredTurn(\n      buildDeferredTurnRecord({\n        sessionId,\n        turnId,\n        sourceConversation,\n        repoRoot,\n        prompt,\n        assistantResponse,\n        submittedAt,\n        branchAtDefer,\n        appIdAtDefer,\n        projectIdAtDefer,\n        reason: \"recovery_in_progress\",\n      }),\n    );\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"turn_deferred\",\n      result: \"success\",\n      reason: \"recovery_in_progress\",\n      repoRoot,\n      fields: {\n        deferredFilePath,\n        promptLength: prompt.length,\n        assistantResponseLength: assistantResponse.length,\n        branchAtDefer,\n        preflightCode,\n      },\n    });\n    spawnDeferredTurnDrainer(repoRoot);\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"deferred_turn_drainer_spawned\",\n      result: \"info\",\n      repoRoot,\n      fields: {\n        triggeredBy: \"recovery_in_progress\",\n        preflightCode,\n      },\n    });\n    return deferredFilePath;\n  } catch (deferErr) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId,\n      stage: \"deferred_turn_write_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot,\n      message: deferErr instanceof Error ? deferErr.message : String(deferErr),\n      fields: {\n        preflightCode,\n      },\n    });\n    return null;\n  }\n}\n\n// REMOVED: per-turn auto-spawn of `remix history import` from the Stop hook.\n//\n// Earlier versions of this hook self-healed a missing history import by\n// spawning `remix history import` whenever a successful turn recording\n// found no history-import marker. That\n// turned out to do more harm than good:\n//\n//   * It fired on EVERY repo any session ever recorded into, including\n//     branches and forks the user never explicitly asked to import.\n//   * It re-uploaded transcripts captured AFTER the live `finalize_turn`\n//     for the same prompt had already landed, so the dashboard ended up\n//     with `historical_repo_turn` rows interleaved with — and duplicating —\n//     the live `collab_turn` rows.\n//   * It ran from a per-turn hook with no way to gate by `bindingMode`,\n//     so branch lanes auto-spawned full transcript walks even though the\n//     main app's auto-spawn already covered the same on-disk transcripts.\n//\n// The history importer is now spawned in exactly ONE place: the\n// `remix collab init` flow (CLI + MCP), gated by `bindingMode ===\n// \"explicit_root\"` AND the absence of the marker file, with a hard\n// `--before <init-time>` cutoff so live data can never be re-uploaded\n// as historical. See remix-cli/src/services/historyImport/autoSpawn.ts\n// for the policy. Users who want to re-import can `rm` the marker and\n// run `remix history import` manually — that path still works.\n//\n// The Cursor plugin never had an analogous Stop-hook fallback, so\n// removing this keeps the two plugins behaviorally identical.\n\nexport async function runHookStopCollab(payload: Record<string, unknown>): Promise<void> {\n  const hook = \"Stop\";\n  if (extractBoolean(payload, [\"stop_hook_active\"])) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      stage: \"reentrancy_guard\",\n      result: \"skip\",\n      reason: \"stop_hook_active\",\n    });\n    return;\n  }\n\n  const sessionId = extractString(payload, [\"session_id\"]);\n  await appendHookDiagnosticsEvent({\n    hook,\n    sessionId,\n    stage: \"payload_received\",\n    result: \"start\",\n    fields: {\n      hasSessionId: Boolean(sessionId),\n      hasStopHookActive: Boolean(extractBoolean(payload, [\"stop_hook_active\"])),\n      hasAssistantResponse: summarizeText(extractAssistantResponse(payload)).present,\n    },\n  });\n  if (!sessionId) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      stage: \"payload_validation\",\n      result: \"skip\",\n      reason: \"missing_session_id\",\n    });\n    return;\n  }\n\n  const state = await loadPendingTurnState(sessionId);\n  if (!state) {\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      stage: \"state_lookup\",\n      result: \"skip\",\n      reason: \"pending_state_not_found\",\n    });\n    return;\n  }\n\n  await appendHookDiagnosticsEvent({\n    hook,\n    sessionId,\n    turnId: state.turnId,\n    stage: \"state_loaded\",\n    result: \"info\",\n    fields: {\n      consultedMemory: state.consultedMemory,\n      touchedRepoCount: Object.keys(state.touchedRepos).length,\n      hasTurnFailure: Boolean(state.turnFailureMessage),\n    },\n  });\n\n  try {\n    let touchedRepos = await listTouchedRepos(sessionId);\n    if (touchedRepos.length === 0) {\n      const fallbackRepo = await resolveBoundRepoSummary(state.initialCwd);\n      if (!fallbackRepo) {\n        // Disambiguate two structurally-identical-looking failures:\n        //   (a) `no_bound_repo_for_fallback`: no `.remix/config.json` anywhere\n        //       up the tree from initialCwd. Repo is genuinely not a Remix\n        //       repo. Silent skip is correct.\n        //   (b) `current_branch_unbound`: `.remix/config.json` exists but the\n        //       current git branch has no entry in `branchBindings`. Stop\n        //       can't record this turn, but the user almost certainly wants\n        //       turn-tracking — they just need to run `remix collab init` on\n        //       this branch. Without this disambiguation, this case used to\n        //       log as `no_bound_repo_for_fallback` with `repoRoot: null`,\n        //       which made it indistinguishable from case (a) in diagnostics.\n        let skipReason: \"no_bound_repo_for_fallback\" | \"current_branch_unbound\" = \"no_bound_repo_for_fallback\";\n        let unboundBranchRepoRoot: string | null = null;\n        let unboundBranchName: string | null = null;\n        let unboundBranchKnownCount = 0;\n        // The current branch is unbound by definition, so there's no\n        // per-lane appId to stamp. We can still capture the *repo's*\n        // projectId as a coarse identity anchor — `force-new` rotates\n        // both the project id and per-lane app ids in lockstep, so\n        // the drainer's project-mismatch check will still drop a\n        // stale record minted for the previous project. Lane-level\n        // mismatch is only resolvable once init lands and the new\n        // lane gets an app id, but by that point the project id has\n        // already moved.\n        let unboundProjectIdAtDefer: string | null = null;\n        const candidateRepoRoot = await findBoundRepo(state.initialCwd).catch(() => null);\n        if (candidateRepoRoot) {\n          const bindingState = await readCollabBindingState(candidateRepoRoot).catch(() => null);\n          const knownBoundBranches = bindingState ? Object.keys(bindingState.branchBindings) : [];\n          if (bindingState && !bindingState.binding && knownBoundBranches.length > 0) {\n            skipReason = \"current_branch_unbound\";\n            unboundBranchRepoRoot = candidateRepoRoot;\n            unboundBranchName = bindingState.currentBranch;\n            unboundBranchKnownCount = knownBoundBranches.length;\n            unboundProjectIdAtDefer = bindingState.projectId ?? null;\n          }\n        }\n        // Special-case the \"branch is being initialized\" race. The\n        // user sent a prompt while `remix collab init` (auto-spawned\n        // by UserPromptSubmit) was still resolving the new branch's\n        // lane. We have a complete prompt + assistant response on\n        // hand; instead of dropping them, persist to the deferred-\n        // turn queue. The next successful finalize for this same\n        // repoRoot will drain the queue and record this turn.\n        const promptTextForDefer = state.prompt.trim();\n        const assistantResponseForDefer = (extractAssistantResponse(payload) || \"\").trim();\n        let deferredFilePath: string | null = null;\n        if (\n          skipReason === \"current_branch_unbound\" &&\n          unboundBranchRepoRoot &&\n          promptTextForDefer &&\n          assistantResponseForDefer\n        ) {\n          try {\n            deferredFilePath = await writeDeferredTurn(\n              buildDeferredTurnRecord({\n                sessionId,\n                turnId: state.turnId,\n                sourceConversation: state.sourceConversation,\n                repoRoot: unboundBranchRepoRoot,\n                prompt: promptTextForDefer,\n                assistantResponse: assistantResponseForDefer,\n                submittedAt: state.submittedAt,\n                branchAtDefer: unboundBranchName,\n                // No appId for an unbound lane (the binding is null\n                // by construction); project id still anchors against\n                // `force-new`-style identity rotations.\n                appIdAtDefer: null,\n                projectIdAtDefer: unboundProjectIdAtDefer,\n              }),\n            );\n          } catch (deferErr) {\n            // Best-effort. If we can't write the defer file (disk\n            // full, perms) we still fall through to the original\n            // drop behavior — better to lose one turn than to crash\n            // the hook and break recording for the rest of the\n            // session. Logged so it's not silent.\n            await appendHookDiagnosticsEvent({\n              hook,\n              sessionId,\n              turnId: state.turnId,\n              stage: \"deferred_turn_write_failed\",\n              result: \"error\",\n              reason: \"exception\",\n              repoRoot: unboundBranchRepoRoot,\n              message: deferErr instanceof Error ? deferErr.message : String(deferErr),\n            });\n          }\n        }\n        await clearPendingTurnState(sessionId);\n        await appendHookDiagnosticsEvent({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          stage: \"fallback_repo_lookup\",\n          result: \"skip\",\n          reason: skipReason,\n          repoRoot: unboundBranchRepoRoot,\n          fields:\n            skipReason === \"current_branch_unbound\"\n              ? {\n                  currentBranch: unboundBranchName,\n                  knownBoundBranchCount: unboundBranchKnownCount,\n                  deferredForRetry: deferredFilePath !== null,\n                }\n              : {},\n        });\n        if (deferredFilePath && unboundBranchRepoRoot) {\n          await appendHookDiagnosticsEvent({\n            hook,\n            sessionId,\n            turnId: state.turnId,\n            stage: \"turn_deferred\",\n            result: \"success\",\n            reason: \"current_branch_unbound\",\n            repoRoot: unboundBranchRepoRoot,\n            fields: {\n              deferredFilePath,\n              promptLength: promptTextForDefer.length,\n              assistantResponseLength: assistantResponseForDefer.length,\n              branchAtDefer: unboundBranchName,\n            },\n          });\n          // Spawn an autonomous drainer so the recovery path doesn't\n          // depend on the user sending another prompt that happens to\n          // land on the now-bound branch. The drainer polls for binding\n          // and finalizes the deferred turn the moment `remix collab\n          // init` lands the new branch, even if the conversation goes\n          // idle.\n          spawnDeferredTurnDrainer(unboundBranchRepoRoot);\n          await appendHookDiagnosticsEvent({\n            hook,\n            sessionId,\n            turnId: state.turnId,\n            stage: \"deferred_turn_drainer_spawned\",\n            result: \"info\",\n            repoRoot: unboundBranchRepoRoot,\n            fields: { triggeredBy: \"defer\" },\n          });\n        }\n        await appendHookDiagnosticsEvent({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          stage: \"state_cleanup\",\n          result: \"success\",\n          reason: deferredFilePath ? \"cleared_after_defer\" : \"cleared_without_bound_repo\",\n        });\n        return;\n      }\n      await upsertTouchedRepo(sessionId, {\n        repoRoot: fallbackRepo.repoRoot,\n        projectId: fallbackRepo.projectId,\n        currentAppId: fallbackRepo.currentAppId,\n        upstreamAppId: fallbackRepo.upstreamAppId,\n        touchedBy: \"Stop:fallback-bound-repo\",\n        hasObservedWrite: false,\n      });\n      touchedRepos = await listTouchedRepos(sessionId);\n      if (touchedRepos.length === 0) {\n        touchedRepos = [createFallbackTouchedRepo(fallbackRepo)];\n      }\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: state.turnId,\n        stage: \"fallback_repo_lookup\",\n        result: \"info\",\n        repoRoot: fallbackRepo.repoRoot,\n        fields: {\n          touchedRepoCount: touchedRepos.length,\n        },\n      });\n    }\n\n    const prompt = state.prompt.trim();\n    const assistantResponse = (extractAssistantResponse(payload) || \"\").trim();\n    const promptSummary = summarizeText(prompt);\n    const assistantResponseSummary = summarizeText(assistantResponse);\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId: state.turnId,\n      stage: \"response_summary\",\n      result: \"info\",\n      fields: {\n        promptLength: promptSummary.length,\n        promptHash: promptSummary.sha256Prefix,\n        assistantResponseLength: assistantResponseSummary.length,\n        assistantResponseHash: assistantResponseSummary.sha256Prefix,\n      },\n    });\n    if (!prompt || !assistantResponse) {\n      await markPendingTurnFailure(sessionId, {\n        message: \"Fallback Remix turn recording failed because the prompt or assistant response was missing.\",\n      });\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: state.turnId,\n        stage: \"response_validation\",\n        result: \"error\",\n        reason: !prompt ? \"missing_prompt\" : \"missing_assistant_response\",\n      });\n      return;\n    }\n\n    const api = await createHookCollabApiClient();\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId: state.turnId,\n      stage: \"api_client_created\",\n      result: \"success\",\n      fields: {\n        touchedRepoCount: touchedRepos.length,\n      },\n    });\n\n    const turnUsage = await harvestTurnUsage({\n      hook,\n      sessionId,\n      state: { turnId: state.turnId, prompt, submittedAt: state.submittedAt },\n      payload,\n    });\n\n    // Drain any deferred turns for these repos BEFORE we record the\n    // current turn. Two reasons:\n    //   1. Ordering. If we drained after the current turn finished, a\n    //      deferred (older) prompt would land with a server-side\n    //      `createdAt` AFTER the newer prompt and the timeline would\n    //      render backwards. Draining first preserves submission order.\n    //   2. Failure isolation. If the current turn's recording fails\n    //      (preflight reconcile etc), the user otherwise also loses\n    //      the chance to drain. Now the drain happens regardless.\n    //\n    // Drain is best-effort: empty queue → fast no-op; transient failures\n    // stay queued and retry on the next finalize / via the standalone\n    // drainer.\n    for (const repo of touchedRepos) {\n      await drainDeferredTurnsForRepo({\n        hook,\n        sessionId,\n        triggerTurnId: state.turnId,\n        repoRoot: repo.repoRoot,\n        api,\n      }).catch(() => undefined);\n    }\n\n    let hadFailure = false;\n    let queuedFinalizeWork = false;\n    let anyRecorded = false;\n    let anyTurnExists = false;\n    const failures: NonNullable<RecordTouchedRepoResult[\"failure\"]>[] = [];\n\n    for (const repo of touchedRepos) {\n      if (shouldSkipStopRecording(repo)) {\n        const legacyMcpFinalizeQueued =\n          repo.manuallyRecordedByTool === \"remix_collab_finalize_turn\" && repo.manualRecordingScope === \"full_turn\";\n        queuedFinalizeWork = queuedFinalizeWork || legacyMcpFinalizeQueued;\n        await appendHookDiagnosticsEvent({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          stage: \"recording_skipped\",\n          result: \"info\",\n          reason: \"skip_stop_recording\",\n          repoRoot: repo.repoRoot,\n          fields: {\n            manuallyRecorded: repo.manuallyRecorded,\n            stopRecorded: repo.stopRecorded,\n            legacyMcpFinalizeQueued,\n            willAttachUsage: Boolean(turnUsage),\n          },\n        });\n        anyTurnExists = true;\n        // Bind harvested usage onto the MCP-enqueued pending job(s) and clear\n        // their `nextRetryAt` deadline so the detached drainer can claim them.\n        // Always run, even when usage is null, so the deadline gets cleared.\n        if (legacyMcpFinalizeQueued) {\n          await attachUsageToPendingMcpJobs({\n            hook,\n            sessionId,\n            turnId: state.turnId,\n            repo,\n            turnUsage,\n          });\n        }\n        continue;\n      }\n      const recording = await recordTouchedRepo({\n        hook,\n        sessionId,\n        turnId: state.turnId,\n        sourceConversation: state.sourceConversation,\n        repo,\n        prompt,\n        assistantResponse,\n        api,\n        turnUsage,\n        promptedAt: state.submittedAt,\n      });\n      queuedFinalizeWork = queuedFinalizeWork || recording.queued;\n      if (recording.recorded) {\n        anyRecorded = true;\n        anyTurnExists = true;\n        // NOTE: previous versions auto-spawned `remix history import`\n        // here when the repo's marker file was missing. That fallback\n        // was removed (see comment block above). The history importer\n        // now runs in exactly one place: the `remix collab init` flow,\n        // gated by `bindingMode === \"explicit_root\"` and the marker\n        // file. This keeps the Claude and Cursor plugins behaviorally\n        // identical and prevents per-turn auto-imports from re-uploading\n        // live transcripts as bogus \"historical\" rows.\n      } else {\n        hadFailure = true;\n        if (recording.failure) {\n          failures.push(recording.failure);\n        }\n      }\n    }\n\n    if (anyRecorded || anyTurnExists) {\n      await markLastFinalizedTurn(sessionId, state.turnId, prompt);\n    }\n\n    if (queuedFinalizeWork) {\n      spawnFinalizeQueueDrainer();\n    }\n\n    // Route each failure based on its kind:\n    //\n    //   - Transient (timeout, network blip, 5xx): defer the full turn\n    //     payload to the deferred-turn queue and skip\n    //     `dispatchFinalizeFailure` entirely. The next Stop hook's\n    //     pre-loop drain replays the turn silently. No user-visible\n    //     marker is written on the first transient defer — we only\n    //     promote to a permanent marker after `DEFERRED_TURN_MAX_ATTEMPTS`\n    //     drain attempts have all failed (see the drainer for the\n    //     promotion path).\n    //\n    //   - Auto-fixable preflight (`not_bound`, `branch_binding_missing`,\n    //     etc.): the dispatcher writes the marker AND spawns the\n    //     appropriate `remix collab` recovery command detached. We\n    //     *also* defer the turn so the recovery command's eventual\n    //     completion drains the turn instead of dropping it.\n    //\n    //   - Other permanent failures (validation errors, unknown 4xx,\n    //     etc.): the dispatcher writes the marker. No deferral — the\n    //     turn is genuinely lost and the user has to act.\n    let deferredFailureCount = 0;\n    let dispatchFailureCount = 0;\n    for (const failure of failures) {\n      if (failure.isTransient) {\n        const deferredFilePath = await deferTurnForTransientFailure({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          repoRoot: failure.repoRoot,\n          prompt,\n          assistantResponse,\n          submittedAt: state.submittedAt,\n          sourceConversation: state.sourceConversation,\n          failureMessage: failure.message,\n        });\n        if (deferredFilePath) {\n          deferredFailureCount += 1;\n        }\n        continue;\n      }\n      const outcome = await dispatchFinalizeFailure({\n        hook: \"Stop\",\n        sessionId,\n        turnId: state.turnId,\n        repoRoot: failure.repoRoot,\n        preflightCode: failure.preflightCode,\n        message: failure.message,\n        hint: failure.hint,\n      }).catch((dispatchErr) => {\n        dispatchFailureCount += 1;\n        return appendHookDiagnosticsEvent({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          stage: \"auto_fix_dispatch_failed\",\n          result: \"error\",\n          reason: \"exception\",\n          repoRoot: failure.repoRoot,\n          message: dispatchErr instanceof Error ? dispatchErr.message : String(dispatchErr),\n        }).then(() => null);\n      });\n      if (\n        outcome &&\n        isAutoFixableFinalizeFailureCode(failure.preflightCode) &&\n        (outcome.kind === \"spawned\" || outcome.kind === \"spawn_throttled\")\n      ) {\n        const deferredFilePath = await deferTurnForRecoveryInProgress({\n          hook,\n          sessionId,\n          turnId: state.turnId,\n          repoRoot: failure.repoRoot,\n          prompt,\n          assistantResponse,\n          submittedAt: state.submittedAt,\n          sourceConversation: state.sourceConversation,\n          preflightCode: failure.preflightCode,\n        });\n        if (deferredFilePath) {\n          deferredFailureCount += 1;\n        }\n      }\n    }\n\n    const allFailuresDeferred =\n      failures.length > 0 && deferredFailureCount === failures.length && dispatchFailureCount === 0;\n\n    if (!hadFailure || allFailuresDeferred) {\n      await clearPendingTurnState(sessionId);\n      await appendHookDiagnosticsEvent({\n        hook,\n        sessionId,\n        turnId: state.turnId,\n        stage: \"state_cleanup\",\n        result: \"success\",\n        reason: allFailuresDeferred ? \"cleared_after_recovery_defer\" : \"cleared_after_success\",\n        fields: allFailuresDeferred\n          ? {\n              deferredFailureCount,\n            }\n          : undefined,\n      });\n      return;\n    }\n\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId: state.turnId,\n      stage: \"state_cleanup\",\n      result: \"info\",\n      reason: \"retained_after_failure\",\n    });\n  } catch (error) {\n    const details = getErrorDetails(error);\n    await markPendingTurnFailure(sessionId, { message: details.message, hint: details.hint });\n    await appendHookDiagnosticsEvent({\n      hook,\n      sessionId,\n      turnId: state.turnId,\n      stage: \"turn_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      message: details.message,\n      fields: {\n        hint: details.hint,\n        preflightCode: details.preflightCode,\n      },\n    });\n  }\n}\n\nasync function main(): Promise<void> {\n  // Detached drainer entrypoint. `spawnDeferredTurnDrainer` re-invokes\n  // whatever process.argv[1] was; the Stop hook may be called as\n  // `... --drain-deferred-turns <repoRoot>`. Recognising the flag here\n  // prevents `readJsonStdin` from hanging indefinitely.\n  if (await maybeRunDeferredTurnDrainerFromArgv()) {\n    return;\n  }\n  if (process.argv.includes(\"--drain-finalize-queue\")) {\n    const api = await createHookCollabApiClient();\n    const drainPendingFinalizeQueue = (coreCollab as { drainPendingFinalizeQueue?: (params: { api: unknown }) => Promise<unknown> })\n      .drainPendingFinalizeQueue;\n    if (typeof drainPendingFinalizeQueue === \"function\") {\n      await drainPendingFinalizeQueue({ api });\n    }\n    return;\n  }\n  const payload = await readJsonStdin();\n  await runHookStopCollab(payload);\n}\n\nmain().catch((error) => {\n  const message = error instanceof Error ? error.message : String(error);\n  void appendHookDiagnosticsEvent({\n    hook: \"Stop\",\n    stage: \"unhandled_error\",\n    result: \"error\",\n    reason: \"exception\",\n    message,\n  });\n  process.stderr.write(`${message}\\n`);\n  process.exitCode = 0;\n});\n","// src/errors/cliError.ts\nvar RemixError = class extends Error {\n  code;\n  exitCode;\n  hint;\n  // HTTP status code when this error originates from an API response.\n  // null for non-HTTP errors (validation, local IO, programming bugs).\n  // Callers use this to distinguish transient (5xx) from permanent (4xx)\n  // API failures without resorting to error-message string matching.\n  statusCode;\n  constructor(message, opts) {\n    super(message);\n    this.name = \"RemixError\";\n    this.code = opts?.code ?? null;\n    this.exitCode = opts?.exitCode ?? 1;\n    this.hint = opts?.hint ?? null;\n    this.statusCode = opts?.statusCode ?? null;\n  }\n};\n\nexport {\n  RemixError\n};\n","export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n","import {fileURLToPath} from 'node:url';\n\n// Allow some arguments/options to be either a file path string or a file URL\nexport const safeNormalizeFileUrl = (file, name) => {\n\tconst fileString = normalizeFileUrl(normalizeDenoExecPath(file));\n\n\tif (typeof fileString !== 'string') {\n\t\tthrow new TypeError(`${name} must be a string or a file URL: ${fileString}.`);\n\t}\n\n\treturn fileString;\n};\n\n// In Deno node:process execPath is a special object, not just a string:\n// https://github.com/denoland/deno/blob/f460188e583f00144000aa0d8ade08218d47c3c1/ext/node/polyfills/process.ts#L344\nconst normalizeDenoExecPath = file => isDenoExecPath(file)\n\t? file.toString()\n\t: file;\n\nexport const isDenoExecPath = file => typeof file !== 'string'\n\t&& file\n\t&& Object.getPrototypeOf(file) === String.prototype;\n\n// Same but also allows other values, e.g. `boolean` for the `shell` option\nexport const normalizeFileUrl = file => file instanceof URL ? fileURLToPath(file) : file;\n","import isPlainObject from 'is-plain-obj';\nimport {safeNormalizeFileUrl} from '../arguments/file-url.js';\n\n// The command `arguments` and `options` are both optional.\n// This also does basic validation on them and on the command file.\nexport const normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {\n\tconst filePath = safeNormalizeFileUrl(rawFile, 'First argument');\n\tconst [commandArguments, options] = isPlainObject(rawArguments)\n\t\t? [[], rawArguments]\n\t\t: [rawArguments, rawOptions];\n\n\tif (!Array.isArray(commandArguments)) {\n\t\tthrow new TypeError(`Second argument must be either an array of arguments or an options object: ${commandArguments}`);\n\t}\n\n\tif (commandArguments.some(commandArgument => typeof commandArgument === 'object' && commandArgument !== null)) {\n\t\tthrow new TypeError(`Second argument must be an array of strings: ${commandArguments}`);\n\t}\n\n\tconst normalizedArguments = commandArguments.map(String);\n\tconst nullByteArgument = normalizedArguments.find(normalizedArgument => normalizedArgument.includes('\\0'));\n\tif (nullByteArgument !== undefined) {\n\t\tthrow new TypeError(`Arguments cannot contain null bytes (\"\\\\0\"): ${nullByteArgument}`);\n\t}\n\n\tif (!isPlainObject(options)) {\n\t\tthrow new TypeError(`Last argument must be an options object: ${options}`);\n\t}\n\n\treturn [filePath, normalizedArguments, options];\n};\n","import {ChildProcess} from 'node:child_process';\nimport isPlainObject from 'is-plain-obj';\nimport {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';\n\n// Check whether the template string syntax is being used\nexport const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);\n\n// Convert execa`file ...commandArguments` to execa(file, commandArguments)\nexport const parseTemplates = (templates, expressions) => {\n\tlet tokens = [];\n\n\tfor (const [index, template] of templates.entries()) {\n\t\ttokens = parseTemplate({\n\t\t\ttemplates,\n\t\t\texpressions,\n\t\t\ttokens,\n\t\t\tindex,\n\t\t\ttemplate,\n\t\t});\n\t}\n\n\tif (tokens.length === 0) {\n\t\tthrow new TypeError('Template script must not be empty');\n\t}\n\n\tconst [file, ...commandArguments] = tokens;\n\treturn [file, commandArguments, {}];\n};\n\nconst parseTemplate = ({templates, expressions, tokens, index, template}) => {\n\tif (template === undefined) {\n\t\tthrow new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);\n\t}\n\n\tconst {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);\n\tconst newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);\n\n\tif (index === expressions.length) {\n\t\treturn newTokens;\n\t}\n\n\tconst expression = expressions[index];\n\tconst expressionTokens = Array.isArray(expression)\n\t\t? expression.map(expression => parseExpression(expression))\n\t\t: [parseExpression(expression)];\n\treturn concatTokens(newTokens, expressionTokens, trailingWhitespaces);\n};\n\n// Like `string.split(/[ \\t\\r\\n]+/)` except newlines and tabs are:\n//  - ignored when input as a backslash sequence like: `echo foo\\n bar`\n//  - not ignored when input directly\n// The only way to distinguish those in JavaScript is to use a tagged template and compare:\n//  - the first array argument, which does not escape backslash sequences\n//  - its `raw` property, which escapes them\nconst splitByWhitespaces = (template, rawTemplate) => {\n\tif (rawTemplate.length === 0) {\n\t\treturn {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};\n\t}\n\n\tconst nextTokens = [];\n\tlet templateStart = 0;\n\tconst leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);\n\n\tfor (\n\t\tlet templateIndex = 0, rawIndex = 0;\n\t\ttemplateIndex < template.length;\n\t\ttemplateIndex += 1, rawIndex += 1\n\t) {\n\t\tconst rawCharacter = rawTemplate[rawIndex];\n\t\tif (DELIMITERS.has(rawCharacter)) {\n\t\t\tif (templateStart !== templateIndex) {\n\t\t\t\tnextTokens.push(template.slice(templateStart, templateIndex));\n\t\t\t}\n\n\t\t\ttemplateStart = templateIndex + 1;\n\t\t} else if (rawCharacter === '\\\\') {\n\t\t\tconst nextRawCharacter = rawTemplate[rawIndex + 1];\n\t\t\tif (nextRawCharacter === '\\n') {\n\t\t\t\t// Handles escaped newlines in templates\n\t\t\t\ttemplateIndex -= 1;\n\t\t\t\trawIndex += 1;\n\t\t\t} else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {\n\t\t\t\trawIndex = rawTemplate.indexOf('}', rawIndex + 3);\n\t\t\t} else {\n\t\t\t\trawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst trailingWhitespaces = templateStart === template.length;\n\tif (!trailingWhitespaces) {\n\t\tnextTokens.push(template.slice(templateStart));\n\t}\n\n\treturn {nextTokens, leadingWhitespaces, trailingWhitespaces};\n};\n\nconst DELIMITERS = new Set([' ', '\\t', '\\r', '\\n']);\n\n// Number of characters in backslash escape sequences: \\0 \\xXX or \\uXXXX\n// \\cX is allowed in RegExps but not in strings\n// Octal sequences are not allowed in strict mode\nconst ESCAPE_LENGTH = {x: 3, u: 5};\n\nconst concatTokens = (tokens, nextTokens, isSeparated) => isSeparated\n\t|| tokens.length === 0\n\t|| nextTokens.length === 0\n\t? [...tokens, ...nextTokens]\n\t: [\n\t\t...tokens.slice(0, -1),\n\t\t`${tokens.at(-1)}${nextTokens[0]}`,\n\t\t...nextTokens.slice(1),\n\t];\n\n// Handle `${expression}` inside the template string syntax\nconst parseExpression = expression => {\n\tconst typeOfExpression = typeof expression;\n\n\tif (typeOfExpression === 'string') {\n\t\treturn expression;\n\t}\n\n\tif (typeOfExpression === 'number') {\n\t\treturn String(expression);\n\t}\n\n\tif (isPlainObject(expression) && ('stdout' in expression || 'isMaxBuffer' in expression)) {\n\t\treturn getSubprocessResult(expression);\n\t}\n\n\tif (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {\n\t\t// eslint-disable-next-line no-template-curly-in-string\n\t\tthrow new TypeError('Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.');\n\t}\n\n\tthrow new TypeError(`Unexpected \"${typeOfExpression}\" in template expression`);\n};\n\nconst getSubprocessResult = ({stdout}) => {\n\tif (typeof stdout === 'string') {\n\t\treturn stdout;\n\t}\n\n\tif (isUint8Array(stdout)) {\n\t\treturn uint8ArrayToString(stdout);\n\t}\n\n\tif (stdout === undefined) {\n\t\tthrow new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\\' \"stdout\" option.');\n\t}\n\n\tthrow new TypeError(`Unexpected \"${typeof stdout}\" stdout in template expression`);\n};\n","import {StringDecoder} from 'node:string_decoder';\n\nconst {toString: objectToString} = Object.prototype;\n\nexport const isArrayBuffer = value => objectToString.call(value) === '[object ArrayBuffer]';\n\n// Is either Uint8Array or Buffer\nexport const isUint8Array = value => objectToString.call(value) === '[object Uint8Array]';\n\nexport const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n\nconst textEncoder = new TextEncoder();\nconst stringToUint8Array = string => textEncoder.encode(string);\n\nconst textDecoder = new TextDecoder();\nexport const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);\n\nexport const joinToString = (uint8ArraysOrStrings, encoding) => {\n\tconst strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);\n\treturn strings.join('');\n};\n\nconst uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {\n\tif (encoding === 'utf8' && uint8ArraysOrStrings.every(uint8ArrayOrString => typeof uint8ArrayOrString === 'string')) {\n\t\treturn uint8ArraysOrStrings;\n\t}\n\n\tconst decoder = new StringDecoder(encoding);\n\tconst strings = uint8ArraysOrStrings\n\t\t.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'\n\t\t\t? stringToUint8Array(uint8ArrayOrString)\n\t\t\t: uint8ArrayOrString)\n\t\t.map(uint8Array => decoder.write(uint8Array));\n\tconst finalString = decoder.end();\n\treturn finalString === '' ? strings : [...strings, finalString];\n};\n\nexport const joinToUint8Array = uint8ArraysOrStrings => {\n\tif (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {\n\t\treturn uint8ArraysOrStrings[0];\n\t}\n\n\treturn concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));\n};\n\nconst stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'\n\t? stringToUint8Array(uint8ArrayOrString)\n\t: uint8ArrayOrString);\n\nexport const concatUint8Arrays = uint8Arrays => {\n\tconst result = new Uint8Array(getJoinLength(uint8Arrays));\n\n\tlet index = 0;\n\tfor (const uint8Array of uint8Arrays) {\n\t\tresult.set(uint8Array, index);\n\t\tindex += uint8Array.length;\n\t}\n\n\treturn result;\n};\n\nconst getJoinLength = uint8Arrays => {\n\tlet joinLength = 0;\n\tfor (const uint8Array of uint8Arrays) {\n\t\tjoinLength += uint8Array.length;\n\t}\n\n\treturn joinLength;\n};\n","import {spawnSync} from 'node:child_process';\nimport {handleCommand} from '../arguments/command.js';\nimport {normalizeOptions} from '../arguments/options.js';\nimport {concatenateShell} from '../arguments/shell.js';\nimport {makeError, makeEarlyError, makeSuccessResult} from '../return/result.js';\nimport {handleResult} from '../return/reject.js';\nimport {handleStdioSync} from '../stdio/handle-sync.js';\nimport {stripNewline} from '../io/strip-newline.js';\nimport {addInputOptionsSync} from '../io/input-sync.js';\nimport {transformOutputSync} from '../io/output-sync.js';\nimport {getMaxBufferSync} from '../io/max-buffer.js';\nimport {getAllSync} from '../resolve/all-sync.js';\nimport {getExitResultSync} from '../resolve/exit-sync.js';\n\n// Main shared logic for all sync methods: `execaSync()`, `$.sync()`\nexport const execaCoreSync = (rawFile, rawArguments, rawOptions) => {\n\tconst {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArguments, rawOptions);\n\tconst result = spawnSubprocessSync({\n\t\tfile,\n\t\tcommandArguments,\n\t\toptions,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tverboseInfo,\n\t\tfileDescriptors,\n\t\tstartTime,\n\t});\n\treturn handleResult(result, verboseInfo, options);\n};\n\n// Compute arguments to pass to `child_process.spawnSync()`\nconst handleSyncArguments = (rawFile, rawArguments, rawOptions) => {\n\tconst {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);\n\tconst syncOptions = normalizeSyncOptions(rawOptions);\n\tconst {file, commandArguments, options} = normalizeOptions(rawFile, rawArguments, syncOptions);\n\tvalidateSyncOptions(options);\n\tconst fileDescriptors = handleStdioSync(options, verboseInfo);\n\treturn {\n\t\tfile,\n\t\tcommandArguments,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstartTime,\n\t\tverboseInfo,\n\t\toptions,\n\t\tfileDescriptors,\n\t};\n};\n\n// Options normalization logic specific to sync methods\nconst normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;\n\n// Options validation logic specific to sync methods\nconst validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal}) => {\n\tif (ipcInput) {\n\t\tthrowInvalidSyncOption('ipcInput');\n\t}\n\n\tif (ipc) {\n\t\tthrowInvalidSyncOption('ipc: true');\n\t}\n\n\tif (detached) {\n\t\tthrowInvalidSyncOption('detached: true');\n\t}\n\n\tif (cancelSignal) {\n\t\tthrowInvalidSyncOption('cancelSignal');\n\t}\n};\n\nconst throwInvalidSyncOption = value => {\n\tthrow new TypeError(`The \"${value}\" option cannot be used with synchronous methods.`);\n};\n\nconst spawnSubprocessSync = ({file, commandArguments, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime}) => {\n\tconst syncResult = runSubprocessSync({\n\t\tfile,\n\t\tcommandArguments,\n\t\toptions,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tfileDescriptors,\n\t\tstartTime,\n\t});\n\tif (syncResult.failed) {\n\t\treturn syncResult;\n\t}\n\n\tconst {resultError, exitCode, signal, timedOut, isMaxBuffer} = getExitResultSync(syncResult, options);\n\tconst {output, error = resultError} = transformOutputSync({\n\t\tfileDescriptors,\n\t\tsyncResult,\n\t\toptions,\n\t\tisMaxBuffer,\n\t\tverboseInfo,\n\t});\n\tconst stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));\n\tconst all = stripNewline(getAllSync(output, options), options, 'all');\n\treturn getSyncResult({\n\t\terror,\n\t\texitCode,\n\t\tsignal,\n\t\ttimedOut,\n\t\tisMaxBuffer,\n\t\tstdio,\n\t\tall,\n\t\toptions,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstartTime,\n\t});\n};\n\nconst runSubprocessSync = ({file, commandArguments, options, command, escapedCommand, fileDescriptors, startTime}) => {\n\ttry {\n\t\taddInputOptionsSync(fileDescriptors, options);\n\t\tconst normalizedOptions = normalizeSpawnSyncOptions(options);\n\t\treturn spawnSync(...concatenateShell(file, commandArguments, normalizedOptions));\n\t} catch (error) {\n\t\treturn makeEarlyError({\n\t\t\terror,\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tfileDescriptors,\n\t\t\toptions,\n\t\t\tstartTime,\n\t\t\tisSync: true,\n\t\t});\n\t}\n};\n\n// The `encoding` option is handled by Execa, not by `child_process.spawnSync()`\nconst normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});\n\nconst getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined\n\t? makeSuccessResult({\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstdio,\n\t\tall,\n\t\tipcOutput: [],\n\t\toptions,\n\t\tstartTime,\n\t})\n\t: makeError({\n\t\terror,\n\t\tcommand,\n\t\tescapedCommand,\n\t\ttimedOut,\n\t\tisCanceled: false,\n\t\tisGracefullyCanceled: false,\n\t\tisMaxBuffer,\n\t\tisForcefullyTerminated: false,\n\t\texitCode,\n\t\tsignal,\n\t\tstdio,\n\t\tall,\n\t\tipcOutput: [],\n\t\toptions,\n\t\tstartTime,\n\t\tisSync: true,\n\t});\n","import {debuglog} from 'node:util';\nimport isPlainObject from 'is-plain-obj';\nimport {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';\n\n// Some options can have different values for `stdout`/`stderr`/`fd3`.\n// This normalizes those to array of values.\n// For example, `{verbose: {stdout: 'none', stderr: 'full'}}` becomes `{verbose: ['none', 'none', 'full']}`\nexport const normalizeFdSpecificOptions = options => {\n\tconst optionsCopy = {...options};\n\n\tfor (const optionName of FD_SPECIFIC_OPTIONS) {\n\t\toptionsCopy[optionName] = normalizeFdSpecificOption(options, optionName);\n\t}\n\n\treturn optionsCopy;\n};\n\nexport const normalizeFdSpecificOption = (options, optionName) => {\n\tconst optionBaseArray = Array.from({length: getStdioLength(options) + 1});\n\tconst optionArray = normalizeFdSpecificValue(options[optionName], optionBaseArray, optionName);\n\treturn addDefaultValue(optionArray, optionName);\n};\n\nconst getStdioLength = ({stdio}) => Array.isArray(stdio)\n\t? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length)\n\t: STANDARD_STREAMS_ALIASES.length;\n\nconst normalizeFdSpecificValue = (optionValue, optionArray, optionName) => isPlainObject(optionValue)\n\t? normalizeOptionObject(optionValue, optionArray, optionName)\n\t: optionArray.fill(optionValue);\n\nconst normalizeOptionObject = (optionValue, optionArray, optionName) => {\n\tfor (const fdName of Object.keys(optionValue).sort(compareFdName)) {\n\t\tfor (const fdNumber of parseFdName(fdName, optionName, optionArray)) {\n\t\t\toptionArray[fdNumber] = optionValue[fdName];\n\t\t}\n\t}\n\n\treturn optionArray;\n};\n\n// Ensure priority order when setting both `stdout`/`stderr`, `fd1`/`fd2`, and `all`\nconst compareFdName = (fdNameA, fdNameB) => getFdNameOrder(fdNameA) < getFdNameOrder(fdNameB) ? 1 : -1;\n\nconst getFdNameOrder = fdName => {\n\tif (fdName === 'stdout' || fdName === 'stderr') {\n\t\treturn 0;\n\t}\n\n\treturn fdName === 'all' ? 2 : 1;\n};\n\nconst parseFdName = (fdName, optionName, optionArray) => {\n\tif (fdName === 'ipc') {\n\t\treturn [optionArray.length - 1];\n\t}\n\n\tconst fdNumber = parseFd(fdName);\n\tif (fdNumber === undefined || fdNumber === 0) {\n\t\tthrow new TypeError(`\"${optionName}.${fdName}\" is invalid.\nIt must be \"${optionName}.stdout\", \"${optionName}.stderr\", \"${optionName}.all\", \"${optionName}.ipc\", or \"${optionName}.fd3\", \"${optionName}.fd4\" (and so on).`);\n\t}\n\n\tif (fdNumber >= optionArray.length) {\n\t\tthrow new TypeError(`\"${optionName}.${fdName}\" is invalid: that file descriptor does not exist.\nPlease set the \"stdio\" option to ensure that file descriptor exists.`);\n\t}\n\n\treturn fdNumber === 'all' ? [1, 2] : [fdNumber];\n};\n\n// Use the same syntax for fd-specific options and the `from`/`to` options\nexport const parseFd = fdName => {\n\tif (fdName === 'all') {\n\t\treturn fdName;\n\t}\n\n\tif (STANDARD_STREAMS_ALIASES.includes(fdName)) {\n\t\treturn STANDARD_STREAMS_ALIASES.indexOf(fdName);\n\t}\n\n\tconst regexpResult = FD_REGEXP.exec(fdName);\n\tif (regexpResult !== null) {\n\t\treturn Number(regexpResult[1]);\n\t}\n};\n\nconst FD_REGEXP = /^fd(\\d+)$/;\n\nconst addDefaultValue = (optionArray, optionName) => optionArray.map(optionValue => optionValue === undefined\n\t? DEFAULT_OPTIONS[optionName]\n\t: optionValue);\n\n// Default value for the `verbose` option\nconst verboseDefault = debuglog('execa').enabled ? 'full' : 'none';\n\nconst DEFAULT_OPTIONS = {\n\tlines: false,\n\tbuffer: true,\n\tmaxBuffer: 1000 * 1000 * 100,\n\tverbose: verboseDefault,\n\tstripFinalNewline: true,\n};\n\n// List of options which can have different values for `stdout`/`stderr`\nexport const FD_SPECIFIC_OPTIONS = ['lines', 'buffer', 'maxBuffer', 'verbose', 'stripFinalNewline'];\n\n// Retrieve fd-specific option\nexport const getFdSpecificValue = (optionArray, fdNumber) => fdNumber === 'ipc'\n\t? optionArray.at(-1)\n\t: optionArray[fdNumber];\n","import process from 'node:process';\n\nexport const isStandardStream = stream => STANDARD_STREAMS.includes(stream);\nexport const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];\nexport const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];\nexport const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;\n","import {getFdSpecificValue} from '../arguments/specific.js';\n\n// The `verbose` option can have different values for `stdout`/`stderr`\nexport const isVerbose = ({verbose}, fdNumber) => getFdVerbose(verbose, fdNumber) !== 'none';\n\n// Whether IPC and output and logged\nexport const isFullVerbose = ({verbose}, fdNumber) => !['none', 'short'].includes(getFdVerbose(verbose, fdNumber));\n\n// The `verbose` option can be a function to customize logging\nexport const getVerboseFunction = ({verbose}, fdNumber) => {\n\tconst fdVerbose = getFdVerbose(verbose, fdNumber);\n\treturn isVerboseFunction(fdVerbose) ? fdVerbose : undefined;\n};\n\n// When using `verbose: {stdout, stderr, fd3, ipc}`:\n//  - `verbose.stdout|stderr|fd3` is used for 'output'\n//  - `verbose.ipc` is only used for 'ipc'\n//  - highest `verbose.*` value is used for 'command', 'error' and 'duration'\nconst getFdVerbose = (verbose, fdNumber) => fdNumber === undefined\n\t? getFdGenericVerbose(verbose)\n\t: getFdSpecificValue(verbose, fdNumber);\n\n// When using `verbose: {stdout, stderr, fd3, ipc}` and logging is not specific to a file descriptor.\n// We then use the highest `verbose.*` value, using the following order:\n//  - function > 'full' > 'short' > 'none'\n//  - if several functions are defined: stdout > stderr > fd3 > ipc\nconst getFdGenericVerbose = verbose => verbose.find(fdVerbose => isVerboseFunction(fdVerbose))\n\t?? VERBOSE_VALUES.findLast(fdVerbose => verbose.includes(fdVerbose));\n\n// Whether the `verbose` option is customized using a function\nexport const isVerboseFunction = fdVerbose => typeof fdVerbose === 'function';\n\nexport const VERBOSE_VALUES = ['none', 'short', 'full'];\n","import {inspect} from 'node:util';\nimport {escapeLines} from '../arguments/escape.js';\nimport {defaultVerboseFunction} from './default.js';\nimport {applyVerboseOnLines} from './custom.js';\n\n// This prints on stderr.\n// If the subprocess prints on stdout and is using `stdout: 'inherit'`,\n// there is a chance both writes will compete (introducing a race condition).\n// This means their respective order is not deterministic.\n// In particular, this means the verbose command lines might be after the start of the subprocess output.\n// Using synchronous I/O does not solve this problem.\n// However, this only seems to happen when the stdout/stderr target\n// (e.g. a terminal) is being written to by many subprocesses at once, which is unlikely in real scenarios.\nexport const verboseLog = ({type, verboseMessage, fdNumber, verboseInfo, result}) => {\n\tconst verboseObject = getVerboseObject({type, result, verboseInfo});\n\tconst printedLines = getPrintedLines(verboseMessage, verboseObject);\n\tconst finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber);\n\tif (finalLines !== '') {\n\t\tconsole.warn(finalLines.slice(0, -1));\n\t}\n};\n\nconst getVerboseObject = ({\n\ttype,\n\tresult,\n\tverboseInfo: {escapedCommand, commandId, rawOptions: {piped = false, ...options}},\n}) => ({\n\ttype,\n\tescapedCommand,\n\tcommandId: `${commandId}`,\n\ttimestamp: new Date(),\n\tpiped,\n\tresult,\n\toptions,\n});\n\nconst getPrintedLines = (verboseMessage, verboseObject) => verboseMessage\n\t.split('\\n')\n\t.map(message => getPrintedLine({...verboseObject, message}));\n\nconst getPrintedLine = verboseObject => {\n\tconst verboseLine = defaultVerboseFunction(verboseObject);\n\treturn {verboseLine, verboseObject};\n};\n\n// Serialize any type to a line string, for logging\nexport const serializeVerboseMessage = message => {\n\tconst messageString = typeof message === 'string' ? message : inspect(message);\n\tconst escapedMessage = escapeLines(messageString);\n\treturn escapedMessage.replaceAll('\\t', ' '.repeat(TAB_SIZE));\n};\n\n// Same as `util.inspect()`\nconst TAB_SIZE = 2;\n","import {platform} from 'node:process';\nimport {stripVTControlCharacters} from 'node:util';\n\n// Compute `result.command` and `result.escapedCommand`\nexport const joinCommand = (filePath, rawArguments) => {\n\tconst fileAndArguments = [filePath, ...rawArguments];\n\tconst command = fileAndArguments.join(' ');\n\tconst escapedCommand = fileAndArguments\n\t\t.map(fileAndArgument => quoteString(escapeControlCharacters(fileAndArgument)))\n\t\t.join(' ');\n\treturn {command, escapedCommand};\n};\n\n// Remove ANSI sequences and escape control characters and newlines\nexport const escapeLines = lines => stripVTControlCharacters(lines)\n\t.split('\\n')\n\t.map(line => escapeControlCharacters(line))\n\t.join('\\n');\n\nconst escapeControlCharacters = line => line.replaceAll(SPECIAL_CHAR_REGEXP, character => escapeControlCharacter(character));\n\nconst escapeControlCharacter = character => {\n\tconst commonEscape = COMMON_ESCAPES[character];\n\tif (commonEscape !== undefined) {\n\t\treturn commonEscape;\n\t}\n\n\tconst codepoint = character.codePointAt(0);\n\tconst codepointHex = codepoint.toString(16);\n\treturn codepoint <= ASTRAL_START\n\t\t? `\\\\u${codepointHex.padStart(4, '0')}`\n\t\t: `\\\\U${codepointHex}`;\n};\n\n// Characters that would create issues when printed are escaped using the \\u or \\U notation.\n// Those include control characters and newlines.\n// The \\u and \\U notation is Bash specific, but there is no way to do this in a shell-agnostic way.\n// Some shells do not even have a way to print those characters in an escaped fashion.\n// Therefore, we prioritize printing those safely, instead of allowing those to be copy-pasted.\n// List of Unicode character categories: https://www.fileformat.info/info/unicode/category/index.htm\nconst getSpecialCharRegExp = () => {\n\ttry {\n\t\t// This throws when using Node.js without ICU support.\n\t\t// When using a RegExp literal, this would throw at parsing-time, instead of runtime.\n\t\t// eslint-disable-next-line prefer-regex-literals\n\t\treturn new RegExp('\\\\p{Separator}|\\\\p{Other}', 'gu');\n\t} catch {\n\t\t// Similar to the above RegExp, but works even when Node.js has been built without ICU support.\n\t\t// Unlike the above RegExp, it only covers whitespaces and C0/C1 control characters.\n\t\t// It does not cover some edge cases, such as Unicode reserved characters.\n\t\t// See https://github.com/sindresorhus/execa/issues/1143\n\t\t// eslint-disable-next-line no-control-regex\n\t\treturn /[\\s\\u0000-\\u001F\\u007F-\\u009F\\u00AD]/g;\n\t}\n};\n\nconst SPECIAL_CHAR_REGEXP = getSpecialCharRegExp();\n\n// Accepted by $'...' in Bash.\n// Exclude \\a \\e \\v which are accepted in Bash but not in JavaScript (except \\v) and JSON.\nconst COMMON_ESCAPES = {\n\t' ': ' ',\n\t'\\b': '\\\\b',\n\t'\\f': '\\\\f',\n\t'\\n': '\\\\n',\n\t'\\r': '\\\\r',\n\t'\\t': '\\\\t',\n};\n\n// Up until that codepoint, \\u notation can be used instead of \\U\nconst ASTRAL_START = 65_535;\n\n// Some characters are shell-specific, i.e. need to be escaped when the command is copy-pasted then run.\n// Escaping is shell-specific. We cannot know which shell is used: `process.platform` detection is not enough.\n// For example, Windows users could be using `cmd.exe`, Powershell or Bash for Windows which all use different escaping.\n// We use '...' on Unix, which is POSIX shell compliant and escape all characters but ' so this is fairly safe.\n// On Windows, we assume cmd.exe is used and escape with \"...\", which also works with Powershell.\nconst quoteString = escapedArgument => {\n\tif (NO_ESCAPE_REGEXP.test(escapedArgument)) {\n\t\treturn escapedArgument;\n\t}\n\n\treturn platform === 'win32'\n\t\t? `\"${escapedArgument.replaceAll('\"', '\"\"')}\"`\n\t\t: `'${escapedArgument.replaceAll('\\'', '\\'\\\\\\'\\'')}'`;\n};\n\nconst NO_ESCAPE_REGEXP = /^[\\w./-]+$/;\n","import process from 'node:process';\n\nexport default function isUnicodeSupported() {\n\tconst {env} = process;\n\tconst {TERM, TERM_PROGRAM} = env;\n\n\tif (process.platform !== 'win32') {\n\t\treturn TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| TERM_PROGRAM === 'vscode'\n\t\t|| TERM === 'xterm-256color'\n\t\t|| TERM === 'alacritty'\n\t\t|| TERM === 'rxvt-unicode'\n\t\t|| TERM === 'rxvt-unicode-256color'\n\t\t|| env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n","import isUnicodeSupported from 'is-unicode-supported';\n\nconst common = {\n\tcircleQuestionMark: '(?)',\n\tquestionMarkPrefix: '(?)',\n\tsquare: '█',\n\tsquareDarkShade: '▓',\n\tsquareMediumShade: '▒',\n\tsquareLightShade: '░',\n\tsquareTop: '▀',\n\tsquareBottom: '▄',\n\tsquareLeft: '▌',\n\tsquareRight: '▐',\n\tsquareCenter: '■',\n\tbullet: '●',\n\tdot: '․',\n\tellipsis: '…',\n\tpointerSmall: '›',\n\ttriangleUp: '▲',\n\ttriangleUpSmall: '▴',\n\ttriangleDown: '▼',\n\ttriangleDownSmall: '▾',\n\ttriangleLeftSmall: '◂',\n\ttriangleRightSmall: '▸',\n\thome: '⌂',\n\theart: '♥',\n\tmusicNote: '♪',\n\tmusicNoteBeamed: '♫',\n\tarrowUp: '↑',\n\tarrowDown: '↓',\n\tarrowLeft: '←',\n\tarrowRight: '→',\n\tarrowLeftRight: '↔',\n\tarrowUpDown: '↕',\n\talmostEqual: '≈',\n\tnotEqual: '≠',\n\tlessOrEqual: '≤',\n\tgreaterOrEqual: '≥',\n\tidentical: '≡',\n\tinfinity: '∞',\n\tsubscriptZero: '₀',\n\tsubscriptOne: '₁',\n\tsubscriptTwo: '₂',\n\tsubscriptThree: '₃',\n\tsubscriptFour: '₄',\n\tsubscriptFive: '₅',\n\tsubscriptSix: '₆',\n\tsubscriptSeven: '₇',\n\tsubscriptEight: '₈',\n\tsubscriptNine: '₉',\n\toneHalf: '½',\n\toneThird: '⅓',\n\toneQuarter: '¼',\n\toneFifth: '⅕',\n\toneSixth: '⅙',\n\toneEighth: '⅛',\n\ttwoThirds: '⅔',\n\ttwoFifths: '⅖',\n\tthreeQuarters: '¾',\n\tthreeFifths: '⅗',\n\tthreeEighths: '⅜',\n\tfourFifths: '⅘',\n\tfiveSixths: '⅚',\n\tfiveEighths: '⅝',\n\tsevenEighths: '⅞',\n\tline: '─',\n\tlineBold: '━',\n\tlineDouble: '═',\n\tlineDashed0: '┄',\n\tlineDashed1: '┅',\n\tlineDashed2: '┈',\n\tlineDashed3: '┉',\n\tlineDashed4: '╌',\n\tlineDashed5: '╍',\n\tlineDashed6: '╴',\n\tlineDashed7: '╶',\n\tlineDashed8: '╸',\n\tlineDashed9: '╺',\n\tlineDashed10: '╼',\n\tlineDashed11: '╾',\n\tlineDashed12: '−',\n\tlineDashed13: '–',\n\tlineDashed14: '‐',\n\tlineDashed15: '⁃',\n\tlineVertical: '│',\n\tlineVerticalBold: '┃',\n\tlineVerticalDouble: '║',\n\tlineVerticalDashed0: '┆',\n\tlineVerticalDashed1: '┇',\n\tlineVerticalDashed2: '┊',\n\tlineVerticalDashed3: '┋',\n\tlineVerticalDashed4: '╎',\n\tlineVerticalDashed5: '╏',\n\tlineVerticalDashed6: '╵',\n\tlineVerticalDashed7: '╷',\n\tlineVerticalDashed8: '╹',\n\tlineVerticalDashed9: '╻',\n\tlineVerticalDashed10: '╽',\n\tlineVerticalDashed11: '╿',\n\tlineDownLeft: '┐',\n\tlineDownLeftArc: '╮',\n\tlineDownBoldLeftBold: '┓',\n\tlineDownBoldLeft: '┒',\n\tlineDownLeftBold: '┑',\n\tlineDownDoubleLeftDouble: '╗',\n\tlineDownDoubleLeft: '╖',\n\tlineDownLeftDouble: '╕',\n\tlineDownRight: '┌',\n\tlineDownRightArc: '╭',\n\tlineDownBoldRightBold: '┏',\n\tlineDownBoldRight: '┎',\n\tlineDownRightBold: '┍',\n\tlineDownDoubleRightDouble: '╔',\n\tlineDownDoubleRight: '╓',\n\tlineDownRightDouble: '╒',\n\tlineUpLeft: '┘',\n\tlineUpLeftArc: '╯',\n\tlineUpBoldLeftBold: '┛',\n\tlineUpBoldLeft: '┚',\n\tlineUpLeftBold: '┙',\n\tlineUpDoubleLeftDouble: '╝',\n\tlineUpDoubleLeft: '╜',\n\tlineUpLeftDouble: '╛',\n\tlineUpRight: '└',\n\tlineUpRightArc: '╰',\n\tlineUpBoldRightBold: '┗',\n\tlineUpBoldRight: '┖',\n\tlineUpRightBold: '┕',\n\tlineUpDoubleRightDouble: '╚',\n\tlineUpDoubleRight: '╙',\n\tlineUpRightDouble: '╘',\n\tlineUpDownLeft: '┤',\n\tlineUpBoldDownBoldLeftBold: '┫',\n\tlineUpBoldDownBoldLeft: '┨',\n\tlineUpDownLeftBold: '┥',\n\tlineUpBoldDownLeftBold: '┩',\n\tlineUpDownBoldLeftBold: '┪',\n\tlineUpDownBoldLeft: '┧',\n\tlineUpBoldDownLeft: '┦',\n\tlineUpDoubleDownDoubleLeftDouble: '╣',\n\tlineUpDoubleDownDoubleLeft: '╢',\n\tlineUpDownLeftDouble: '╡',\n\tlineUpDownRight: '├',\n\tlineUpBoldDownBoldRightBold: '┣',\n\tlineUpBoldDownBoldRight: '┠',\n\tlineUpDownRightBold: '┝',\n\tlineUpBoldDownRightBold: '┡',\n\tlineUpDownBoldRightBold: '┢',\n\tlineUpDownBoldRight: '┟',\n\tlineUpBoldDownRight: '┞',\n\tlineUpDoubleDownDoubleRightDouble: '╠',\n\tlineUpDoubleDownDoubleRight: '╟',\n\tlineUpDownRightDouble: '╞',\n\tlineDownLeftRight: '┬',\n\tlineDownBoldLeftBoldRightBold: '┳',\n\tlineDownLeftBoldRightBold: '┯',\n\tlineDownBoldLeftRight: '┰',\n\tlineDownBoldLeftBoldRight: '┱',\n\tlineDownBoldLeftRightBold: '┲',\n\tlineDownLeftRightBold: '┮',\n\tlineDownLeftBoldRight: '┭',\n\tlineDownDoubleLeftDoubleRightDouble: '╦',\n\tlineDownDoubleLeftRight: '╥',\n\tlineDownLeftDoubleRightDouble: '╤',\n\tlineUpLeftRight: '┴',\n\tlineUpBoldLeftBoldRightBold: '┻',\n\tlineUpLeftBoldRightBold: '┷',\n\tlineUpBoldLeftRight: '┸',\n\tlineUpBoldLeftBoldRight: '┹',\n\tlineUpBoldLeftRightBold: '┺',\n\tlineUpLeftRightBold: '┶',\n\tlineUpLeftBoldRight: '┵',\n\tlineUpDoubleLeftDoubleRightDouble: '╩',\n\tlineUpDoubleLeftRight: '╨',\n\tlineUpLeftDoubleRightDouble: '╧',\n\tlineUpDownLeftRight: '┼',\n\tlineUpBoldDownBoldLeftBoldRightBold: '╋',\n\tlineUpDownBoldLeftBoldRightBold: '╈',\n\tlineUpBoldDownLeftBoldRightBold: '╇',\n\tlineUpBoldDownBoldLeftRightBold: '╊',\n\tlineUpBoldDownBoldLeftBoldRight: '╉',\n\tlineUpBoldDownLeftRight: '╀',\n\tlineUpDownBoldLeftRight: '╁',\n\tlineUpDownLeftBoldRight: '┽',\n\tlineUpDownLeftRightBold: '┾',\n\tlineUpBoldDownBoldLeftRight: '╂',\n\tlineUpDownLeftBoldRightBold: '┿',\n\tlineUpBoldDownLeftBoldRight: '╃',\n\tlineUpBoldDownLeftRightBold: '╄',\n\tlineUpDownBoldLeftBoldRight: '╅',\n\tlineUpDownBoldLeftRightBold: '╆',\n\tlineUpDoubleDownDoubleLeftDoubleRightDouble: '╬',\n\tlineUpDoubleDownDoubleLeftRight: '╫',\n\tlineUpDownLeftDoubleRightDouble: '╪',\n\tlineCross: '╳',\n\tlineBackslash: '╲',\n\tlineSlash: '╱',\n};\n\nconst specialMainSymbols = {\n\ttick: '✔',\n\tinfo: 'ℹ',\n\twarning: '⚠',\n\tcross: '✘',\n\tsquareSmall: '◻',\n\tsquareSmallFilled: '◼',\n\tcircle: '◯',\n\tcircleFilled: '◉',\n\tcircleDotted: '◌',\n\tcircleDouble: '◎',\n\tcircleCircle: 'ⓞ',\n\tcircleCross: 'ⓧ',\n\tcirclePipe: 'Ⓘ',\n\tradioOn: '◉',\n\tradioOff: '◯',\n\tcheckboxOn: '☒',\n\tcheckboxOff: '☐',\n\tcheckboxCircleOn: 'ⓧ',\n\tcheckboxCircleOff: 'Ⓘ',\n\tpointer: '❯',\n\ttriangleUpOutline: '△',\n\ttriangleLeft: '◀',\n\ttriangleRight: '▶',\n\tlozenge: '◆',\n\tlozengeOutline: '◇',\n\thamburger: '☰',\n\tsmiley: '㋡',\n\tmustache: '෴',\n\tstar: '★',\n\tplay: '▶',\n\tnodejs: '⬢',\n\toneSeventh: '⅐',\n\toneNinth: '⅑',\n\toneTenth: '⅒',\n};\n\nconst specialFallbackSymbols = {\n\ttick: '√',\n\tinfo: 'i',\n\twarning: '‼',\n\tcross: '×',\n\tsquareSmall: '□',\n\tsquareSmallFilled: '■',\n\tcircle: '( )',\n\tcircleFilled: '(*)',\n\tcircleDotted: '( )',\n\tcircleDouble: '( )',\n\tcircleCircle: '(○)',\n\tcircleCross: '(×)',\n\tcirclePipe: '(│)',\n\tradioOn: '(*)',\n\tradioOff: '( )',\n\tcheckboxOn: '[×]',\n\tcheckboxOff: '[ ]',\n\tcheckboxCircleOn: '(×)',\n\tcheckboxCircleOff: '( )',\n\tpointer: '>',\n\ttriangleUpOutline: '∆',\n\ttriangleLeft: '◄',\n\ttriangleRight: '►',\n\tlozenge: '♦',\n\tlozengeOutline: '◊',\n\thamburger: '≡',\n\tsmiley: '☺',\n\tmustache: '┌─┐',\n\tstar: '✶',\n\tplay: '►',\n\tnodejs: '♦',\n\toneSeventh: '1/7',\n\toneNinth: '1/9',\n\toneTenth: '1/10',\n};\n\nexport const mainSymbols = {...common, ...specialMainSymbols};\nexport const fallbackSymbols = {...common, ...specialFallbackSymbols};\n\nconst shouldUseMain = isUnicodeSupported();\nconst figures = shouldUseMain ? mainSymbols : fallbackSymbols;\nexport default figures;\n\nconst replacements = Object.entries(specialMainSymbols);\n\n// On terminals which do not support Unicode symbols, substitute them to other symbols\nexport const replaceSymbols = (string, {useFallback = !shouldUseMain} = {}) => {\n\tif (useFallback) {\n\t\tfor (const [key, mainSymbol] of replacements) {\n\t\t\tstring = string.replaceAll(mainSymbol, fallbackSymbols[key]);\n\t\t}\n\t}\n\n\treturn string;\n};\n","import tty from 'node:tty';\n\n// eslint-disable-next-line no-warning-comments\n// TODO: Use a better method when it's added to Node.js (https://github.com/nodejs/node/pull/40240)\n// Lots of optionals here to support Deno.\nconst hasColors = tty?.WriteStream?.prototype?.hasColors?.() ?? false;\n\nconst format = (open, close) => {\n\tif (!hasColors) {\n\t\treturn input => input;\n\t}\n\n\tconst openCode = `\\u001B[${open}m`;\n\tconst closeCode = `\\u001B[${close}m`;\n\n\treturn input => {\n\t\tconst string = input + ''; // eslint-disable-line no-implicit-coercion -- This is faster.\n\t\tlet index = string.indexOf(closeCode);\n\n\t\tif (index === -1) {\n\t\t\t// Note: Intentionally not using string interpolation for performance reasons.\n\t\t\treturn openCode + string + closeCode;\n\t\t}\n\n\t\t// Handle nested colors.\n\n\t\t// We could have done this, but it's too slow (as of Node.js 22).\n\t\t// return openCode + string.replaceAll(closeCode, (close === 22 ? closeCode : '') + openCode) + closeCode;\n\n\t\tlet result = openCode;\n\t\tlet lastIndex = 0;\n\n\t\t// SGR 22 resets both bold (1) and dim (2). When we encounter a nested\n\t\t// close for styles that use 22, we need to re-open the outer style.\n\t\tconst reopenOnNestedClose = close === 22;\n\t\tconst replaceCode = (reopenOnNestedClose ? closeCode : '') + openCode;\n\n\t\twhile (index !== -1) {\n\t\t\tresult += string.slice(lastIndex, index) + replaceCode;\n\t\t\tlastIndex = index + closeCode.length;\n\t\t\tindex = string.indexOf(closeCode, lastIndex);\n\t\t}\n\n\t\tresult += string.slice(lastIndex) + closeCode;\n\n\t\treturn result;\n\t};\n};\n\nexport const reset = format(0, 0);\nexport const bold = format(1, 22);\nexport const dim = format(2, 22);\nexport const italic = format(3, 23);\nexport const underline = format(4, 24);\nexport const overline = format(53, 55);\nexport const inverse = format(7, 27);\nexport const hidden = format(8, 28);\nexport const strikethrough = format(9, 29);\n\nexport const black = format(30, 39);\nexport const red = format(31, 39);\nexport const green = format(32, 39);\nexport const yellow = format(33, 39);\nexport const blue = format(34, 39);\nexport const magenta = format(35, 39);\nexport const cyan = format(36, 39);\nexport const white = format(37, 39);\nexport const gray = format(90, 39);\n\nexport const bgBlack = format(40, 49);\nexport const bgRed = format(41, 49);\nexport const bgGreen = format(42, 49);\nexport const bgYellow = format(43, 49);\nexport const bgBlue = format(44, 49);\nexport const bgMagenta = format(45, 49);\nexport const bgCyan = format(46, 49);\nexport const bgWhite = format(47, 49);\nexport const bgGray = format(100, 49);\n\nexport const redBright = format(91, 39);\nexport const greenBright = format(92, 39);\nexport const yellowBright = format(93, 39);\nexport const blueBright = format(94, 39);\nexport const magentaBright = format(95, 39);\nexport const cyanBright = format(96, 39);\nexport const whiteBright = format(97, 39);\n\nexport const bgRedBright = format(101, 49);\nexport const bgGreenBright = format(102, 49);\nexport const bgYellowBright = format(103, 49);\nexport const bgBlueBright = format(104, 49);\nexport const bgMagentaBright = format(105, 49);\nexport const bgCyanBright = format(106, 49);\nexport const bgWhiteBright = format(107, 49);\n","import figures from 'figures';\nimport {\n\tgray,\n\tbold,\n\tredBright,\n\tyellowBright,\n} from 'yoctocolors';\n\n// Default when `verbose` is not a function\nexport const defaultVerboseFunction = ({\n\ttype,\n\tmessage,\n\ttimestamp,\n\tpiped,\n\tcommandId,\n\tresult: {failed = false} = {},\n\toptions: {reject = true},\n}) => {\n\tconst timestampString = serializeTimestamp(timestamp);\n\tconst icon = ICONS[type]({failed, reject, piped});\n\tconst color = COLORS[type]({reject});\n\treturn `${gray(`[${timestampString}]`)} ${gray(`[${commandId}]`)} ${color(icon)} ${color(message)}`;\n};\n\n// Prepending the timestamp allows debugging the slow paths of a subprocess\nconst serializeTimestamp = timestamp => `${padField(timestamp.getHours(), 2)}:${padField(timestamp.getMinutes(), 2)}:${padField(timestamp.getSeconds(), 2)}.${padField(timestamp.getMilliseconds(), 3)}`;\n\nconst padField = (field, padding) => String(field).padStart(padding, '0');\n\nconst getFinalIcon = ({failed, reject}) => {\n\tif (!failed) {\n\t\treturn figures.tick;\n\t}\n\n\treturn reject ? figures.cross : figures.warning;\n};\n\nconst ICONS = {\n\tcommand: ({piped}) => piped ? '|' : '$',\n\toutput: () => ' ',\n\tipc: () => '*',\n\terror: getFinalIcon,\n\tduration: getFinalIcon,\n};\n\nconst identity = string => string;\n\nconst COLORS = {\n\tcommand: () => bold,\n\toutput: () => identity,\n\tipc: () => identity,\n\terror: ({reject}) => reject ? redBright : yellowBright,\n\tduration: () => gray,\n};\n","import {getVerboseFunction} from './values.js';\n\n// Apply the `verbose` function on each line\nexport const applyVerboseOnLines = (printedLines, verboseInfo, fdNumber) => {\n\tconst verboseFunction = getVerboseFunction(verboseInfo, fdNumber);\n\treturn printedLines\n\t\t.map(({verboseLine, verboseObject}) => applyVerboseFunction(verboseLine, verboseObject, verboseFunction))\n\t\t.filter(printedLine => printedLine !== undefined)\n\t\t.map(printedLine => appendNewline(printedLine))\n\t\t.join('');\n};\n\nconst applyVerboseFunction = (verboseLine, verboseObject, verboseFunction) => {\n\tif (verboseFunction === undefined) {\n\t\treturn verboseLine;\n\t}\n\n\tconst printedLine = verboseFunction(verboseLine, verboseObject);\n\tif (typeof printedLine === 'string') {\n\t\treturn printedLine;\n\t}\n};\n\nconst appendNewline = printedLine => printedLine.endsWith('\\n')\n\t? printedLine\n\t: `${printedLine}\\n`;\n","import {isVerbose} from './values.js';\nimport {verboseLog} from './log.js';\n\n// When `verbose` is `short|full|custom`, print each command\nexport const logCommand = (escapedCommand, verboseInfo) => {\n\tif (!isVerbose(verboseInfo)) {\n\t\treturn;\n\t}\n\n\tverboseLog({\n\t\ttype: 'command',\n\t\tverboseMessage: escapedCommand,\n\t\tverboseInfo,\n\t});\n};\n","import {isVerbose, VERBOSE_VALUES, isVerboseFunction} from './values.js';\n\n// Information computed before spawning, used by the `verbose` option\nexport const getVerboseInfo = (verbose, escapedCommand, rawOptions) => {\n\tvalidateVerbose(verbose);\n\tconst commandId = getCommandId(verbose);\n\treturn {\n\t\tverbose,\n\t\tescapedCommand,\n\t\tcommandId,\n\t\trawOptions,\n\t};\n};\n\nconst getCommandId = verbose => isVerbose({verbose}) ? COMMAND_ID++ : undefined;\n\n// Prepending the `pid` is useful when multiple commands print their output at the same time.\n// However, we cannot use the real PID since this is not available with `child_process.spawnSync()`.\n// Also, we cannot use the real PID if we want to print it before `child_process.spawn()` is run.\n// As a pro, it is shorter than a normal PID and never re-uses the same id.\n// As a con, it cannot be used to send signals.\nlet COMMAND_ID = 0n;\n\nconst validateVerbose = verbose => {\n\tfor (const fdVerbose of verbose) {\n\t\tif (fdVerbose === false) {\n\t\t\tthrow new TypeError('The \"verbose: false\" option was renamed to \"verbose: \\'none\\'\".');\n\t\t}\n\n\t\tif (fdVerbose === true) {\n\t\t\tthrow new TypeError('The \"verbose: true\" option was renamed to \"verbose: \\'short\\'\".');\n\t\t}\n\n\t\tif (!VERBOSE_VALUES.includes(fdVerbose) && !isVerboseFunction(fdVerbose)) {\n\t\t\tconst allowedValues = VERBOSE_VALUES.map(allowedValue => `'${allowedValue}'`).join(', ');\n\t\t\tthrow new TypeError(`The \"verbose\" option must not be ${fdVerbose}. Allowed values are: ${allowedValues} or a function.`);\n\t\t}\n\t}\n};\n","import {hrtime} from 'node:process';\n\n// Start counting time before spawning the subprocess\nexport const getStartTime = () => hrtime.bigint();\n\n// Compute duration after the subprocess ended.\n// Printed by the `verbose` option.\nexport const getDurationMs = startTime => Number(hrtime.bigint() - startTime) / 1e6;\n","import {logCommand} from '../verbose/start.js';\nimport {getVerboseInfo} from '../verbose/info.js';\nimport {getStartTime} from '../return/duration.js';\nimport {joinCommand} from './escape.js';\nimport {normalizeFdSpecificOption} from './specific.js';\n\n// Compute `result.command`, `result.escapedCommand` and `verbose`-related information\nexport const handleCommand = (filePath, rawArguments, rawOptions) => {\n\tconst startTime = getStartTime();\n\tconst {command, escapedCommand} = joinCommand(filePath, rawArguments);\n\tconst verbose = normalizeFdSpecificOption(rawOptions, 'verbose');\n\tconst verboseInfo = getVerboseInfo(verbose, escapedCommand, {...rawOptions});\n\tlogCommand(escapedCommand, verboseInfo);\n\treturn {\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstartTime,\n\t\tverboseInfo,\n\t};\n};\n","import path from 'node:path';\nimport process from 'node:process';\nimport crossSpawn from 'cross-spawn';\nimport {npmRunPathEnv} from 'npm-run-path';\nimport {normalizeForceKillAfterDelay} from '../terminate/kill.js';\nimport {normalizeKillSignal} from '../terminate/signal.js';\nimport {validateCancelSignal} from '../terminate/cancel.js';\nimport {validateGracefulCancel} from '../terminate/graceful.js';\nimport {validateTimeout} from '../terminate/timeout.js';\nimport {handleNodeOption} from '../methods/node.js';\nimport {validateIpcInputOption} from '../ipc/ipc-input.js';\nimport {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';\nimport {normalizeCwd} from './cwd.js';\nimport {normalizeFileUrl} from './file-url.js';\nimport {normalizeFdSpecificOptions} from './specific.js';\n\n// Normalize the options object, and sometimes also the file paths and arguments.\n// Applies default values, validate allowed options, normalize them.\nexport const normalizeOptions = (filePath, rawArguments, rawOptions) => {\n\trawOptions.cwd = normalizeCwd(rawOptions.cwd);\n\tconst [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions);\n\n\tconst {command: file, args: commandArguments, options: initialOptions} = crossSpawn._parse(processedFile, processedArguments, processedOptions);\n\n\tconst fdOptions = normalizeFdSpecificOptions(initialOptions);\n\tconst options = addDefaultOptions(fdOptions);\n\tvalidateTimeout(options);\n\tvalidateEncoding(options);\n\tvalidateIpcInputOption(options);\n\tvalidateCancelSignal(options);\n\tvalidateGracefulCancel(options);\n\toptions.shell = normalizeFileUrl(options.shell);\n\toptions.env = getEnv(options);\n\toptions.killSignal = normalizeKillSignal(options.killSignal);\n\toptions.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);\n\toptions.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]);\n\n\tif (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {\n\t\t// #116\n\t\tcommandArguments.unshift('/q');\n\t}\n\n\treturn {file, commandArguments, options};\n};\n\nconst addDefaultOptions = ({\n\textendEnv = true,\n\tpreferLocal = false,\n\tcwd,\n\tlocalDir: localDirectory = cwd,\n\tencoding = 'utf8',\n\treject = true,\n\tcleanup = true,\n\tall = false,\n\twindowsHide = true,\n\tkillSignal = 'SIGTERM',\n\tforceKillAfterDelay = true,\n\tgracefulCancel = false,\n\tipcInput,\n\tipc = ipcInput !== undefined || gracefulCancel,\n\tserialization = 'advanced',\n\t...options\n}) => ({\n\t...options,\n\textendEnv,\n\tpreferLocal,\n\tcwd,\n\tlocalDirectory,\n\tencoding,\n\treject,\n\tcleanup,\n\tall,\n\twindowsHide,\n\tkillSignal,\n\tforceKillAfterDelay,\n\tgracefulCancel,\n\tipcInput,\n\tipc,\n\tserialization,\n});\n\nconst getEnv = ({env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath}) => {\n\tconst env = extendEnv ? {...process.env, ...envOption} : envOption;\n\n\tif (preferLocal || node) {\n\t\treturn npmRunPathEnv({\n\t\t\tenv,\n\t\t\tcwd: localDirectory,\n\t\t\texecPath: nodePath,\n\t\t\tpreferLocal,\n\t\t\taddExecPath: node,\n\t\t});\n\t}\n\n\treturn env;\n};\n","import process from 'node:process';\nimport path from 'node:path';\nimport pathKey from 'path-key';\nimport {toPath, traversePathUp} from 'unicorn-magic';\n\nexport const npmRunPath = ({\n\tcwd = process.cwd(),\n\tpath: pathOption = process.env[pathKey()],\n\tpreferLocal = true,\n\texecPath = process.execPath,\n\taddExecPath = true,\n} = {}) => {\n\tconst cwdPath = path.resolve(toPath(cwd));\n\tconst result = [];\n\tconst pathParts = pathOption.split(path.delimiter);\n\n\tif (preferLocal) {\n\t\tapplyPreferLocal(result, pathParts, cwdPath);\n\t}\n\n\tif (addExecPath) {\n\t\tapplyExecPath(result, pathParts, execPath, cwdPath);\n\t}\n\n\treturn pathOption === '' || pathOption === path.delimiter\n\t\t? `${result.join(path.delimiter)}${pathOption}`\n\t\t: [...result, pathOption].join(path.delimiter);\n};\n\nconst applyPreferLocal = (result, pathParts, cwdPath) => {\n\tfor (const directory of traversePathUp(cwdPath)) {\n\t\tconst pathPart = path.join(directory, 'node_modules/.bin');\n\t\tif (!pathParts.includes(pathPart)) {\n\t\t\tresult.push(pathPart);\n\t\t}\n\t}\n};\n\n// Ensure the running `node` binary is used\nconst applyExecPath = (result, pathParts, execPath, cwdPath) => {\n\tconst pathPart = path.resolve(cwdPath, toPath(execPath), '..');\n\tif (!pathParts.includes(pathPart)) {\n\t\tresult.push(pathPart);\n\t}\n};\n\nexport const npmRunPathEnv = ({env = process.env, ...options} = {}) => {\n\tenv = {...env};\n\n\tconst pathName = pathKey({env});\n\toptions.path = env[pathName];\n\tenv[pathName] = npmRunPath(options);\n\n\treturn env;\n};\n","export default function pathKey(options = {}) {\n\tconst {\n\t\tenv = process.env,\n\t\tplatform = process.platform\n\t} = options;\n\n\tif (platform !== 'win32') {\n\t\treturn 'PATH';\n\t}\n\n\treturn Object.keys(env).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';\n}\n","import {promisify} from 'node:util';\nimport {execFile as execFileCallback, execFileSync as execFileSyncOriginal} from 'node:child_process';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\n\nconst execFileOriginal = promisify(execFileCallback);\n\nexport function toPath(urlOrPath) {\n\treturn urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n}\n\nexport function rootDirectory(pathInput) {\n\treturn path.parse(toPath(pathInput)).root;\n}\n\nexport function traversePathUp(startPath) {\n\treturn {\n\t\t* [Symbol.iterator]() {\n\t\t\tlet currentPath = path.resolve(toPath(startPath));\n\t\t\tlet previousPath;\n\n\t\t\twhile (previousPath !== currentPath) {\n\t\t\t\tyield currentPath;\n\t\t\t\tpreviousPath = currentPath;\n\t\t\t\tcurrentPath = path.resolve(currentPath, '..');\n\t\t\t}\n\t\t},\n\t};\n}\n\nconst TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024;\n\nexport async function execFile(file, arguments_, options = {}) {\n\treturn execFileOriginal(file, arguments_, {\n\t\tmaxBuffer: TEN_MEGABYTES_IN_BYTES,\n\t\t...options,\n\t});\n}\n\nexport function execFileSync(file, arguments_ = [], options = {}) {\n\treturn execFileSyncOriginal(file, arguments_, {\n\t\tmaxBuffer: TEN_MEGABYTES_IN_BYTES,\n\t\tencoding: 'utf8',\n\t\tstdio: 'pipe',\n\t\t...options,\n\t});\n}\n\nexport * from './default.js';\n","import {setTimeout} from 'node:timers/promises';\nimport {isErrorInstance} from '../return/final-error.js';\nimport {normalizeSignalArgument} from './signal.js';\n\n// Normalize the `forceKillAfterDelay` option\nexport const normalizeForceKillAfterDelay = forceKillAfterDelay => {\n\tif (forceKillAfterDelay === false) {\n\t\treturn forceKillAfterDelay;\n\t}\n\n\tif (forceKillAfterDelay === true) {\n\t\treturn DEFAULT_FORCE_KILL_TIMEOUT;\n\t}\n\n\tif (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) {\n\t\tthrow new TypeError(`Expected the \\`forceKillAfterDelay\\` option to be a non-negative integer, got \\`${forceKillAfterDelay}\\` (${typeof forceKillAfterDelay})`);\n\t}\n\n\treturn forceKillAfterDelay;\n};\n\nconst DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;\n\n// Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`\nexport const subprocessKill = (\n\t{kill, options: {forceKillAfterDelay, killSignal}, onInternalError, context, controller},\n\tsignalOrError,\n\terrorArgument,\n) => {\n\tconst {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);\n\temitKillError(error, onInternalError);\n\tconst killResult = kill(signal);\n\tsetKillTimeout({\n\t\tkill,\n\t\tsignal,\n\t\tforceKillAfterDelay,\n\t\tkillSignal,\n\t\tkillResult,\n\t\tcontext,\n\t\tcontroller,\n\t});\n\treturn killResult;\n};\n\nconst parseKillArguments = (signalOrError, errorArgument, killSignal) => {\n\tconst [signal = killSignal, error] = isErrorInstance(signalOrError)\n\t\t? [undefined, signalOrError]\n\t\t: [signalOrError, errorArgument];\n\n\tif (typeof signal !== 'string' && !Number.isInteger(signal)) {\n\t\tthrow new TypeError(`The first argument must be an error instance or a signal name string/integer: ${String(signal)}`);\n\t}\n\n\tif (error !== undefined && !isErrorInstance(error)) {\n\t\tthrow new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);\n\t}\n\n\treturn {signal: normalizeSignalArgument(signal), error};\n};\n\n// Fails right away when calling `subprocess.kill(error)`.\n// Does not wait for actual signal termination.\n// Uses a deferred promise instead of the `error` event on the subprocess, as this is less intrusive.\nconst emitKillError = (error, onInternalError) => {\n\tif (error !== undefined) {\n\t\tonInternalError.reject(error);\n\t}\n};\n\nconst setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, context, controller}) => {\n\tif (signal === killSignal && killResult) {\n\t\tkillOnTimeout({\n\t\t\tkill,\n\t\t\tforceKillAfterDelay,\n\t\t\tcontext,\n\t\t\tcontrollerSignal: controller.signal,\n\t\t});\n\t}\n};\n\n// Forcefully terminate a subprocess after a timeout\nexport const killOnTimeout = async ({kill, forceKillAfterDelay, context, controllerSignal}) => {\n\tif (forceKillAfterDelay === false) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait setTimeout(forceKillAfterDelay, undefined, {signal: controllerSignal});\n\t\tif (kill('SIGKILL')) {\n\t\t\tcontext.isForcefullyTerminated ??= true;\n\t\t}\n\t} catch {}\n};\n","// When the subprocess fails, this is the error instance being returned.\n// If another error instance is being thrown, it is kept as `error.cause`.\nexport const getFinalError = (originalError, message, isSync) => {\n\tconst ErrorClass = isSync ? ExecaSyncError : ExecaError;\n\tconst options = originalError instanceof DiscardedError ? {} : {cause: originalError};\n\treturn new ErrorClass(message, options);\n};\n\n// Indicates that the error is used only to interrupt control flow, but not in the return value\nexport class DiscardedError extends Error {}\n\n// Proper way to set `error.name`: it should be inherited and non-enumerable\nconst setErrorName = (ErrorClass, value) => {\n\tObject.defineProperty(ErrorClass.prototype, 'name', {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t});\n\tObject.defineProperty(ErrorClass.prototype, execaErrorSymbol, {\n\t\tvalue: true,\n\t\twritable: false,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t});\n};\n\n// Unlike `instanceof`, this works across realms\nexport const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;\n\nconst execaErrorSymbol = Symbol('isExecaError');\n\nexport const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';\n\n// We use two different Error classes for async/sync methods since they have slightly different shape and types\nexport class ExecaError extends Error {}\nsetErrorName(ExecaError, ExecaError.name);\n\nexport class ExecaSyncError extends Error {}\nsetErrorName(ExecaSyncError, ExecaSyncError.name);\n","import {constants} from 'node:os';\nimport {signalsByName} from 'human-signals';\n\n// Normalize signals for comparison purpose.\n// Also validate the signal exists.\nexport const normalizeKillSignal = killSignal => {\n\tconst optionName = 'option `killSignal`';\n\tif (killSignal === 0) {\n\t\tthrow new TypeError(`Invalid ${optionName}: 0 cannot be used.`);\n\t}\n\n\treturn normalizeSignal(killSignal, optionName);\n};\n\nexport const normalizeSignalArgument = signal => signal === 0\n\t? signal\n\t: normalizeSignal(signal, '`subprocess.kill()`\\'s argument');\n\nconst normalizeSignal = (signalNameOrInteger, optionName) => {\n\tif (Number.isInteger(signalNameOrInteger)) {\n\t\treturn normalizeSignalInteger(signalNameOrInteger, optionName);\n\t}\n\n\tif (typeof signalNameOrInteger === 'string') {\n\t\treturn normalizeSignalName(signalNameOrInteger, optionName);\n\t}\n\n\tthrow new TypeError(`Invalid ${optionName} ${String(signalNameOrInteger)}: it must be a string or an integer.\\n${getAvailableSignals()}`);\n};\n\nconst normalizeSignalInteger = (signalInteger, optionName) => {\n\tif (signalsIntegerToName.has(signalInteger)) {\n\t\treturn signalsIntegerToName.get(signalInteger);\n\t}\n\n\tthrow new TypeError(`Invalid ${optionName} ${signalInteger}: this signal integer does not exist.\\n${getAvailableSignals()}`);\n};\n\nconst getSignalsIntegerToName = () => new Map(Object.entries(constants.signals)\n\t.reverse()\n\t.map(([signalName, signalInteger]) => [signalInteger, signalName]));\n\nconst signalsIntegerToName = getSignalsIntegerToName();\n\nconst normalizeSignalName = (signalName, optionName) => {\n\tif (signalName in constants.signals) {\n\t\treturn signalName;\n\t}\n\n\tif (signalName.toUpperCase() in constants.signals) {\n\t\tthrow new TypeError(`Invalid ${optionName} '${signalName}': please rename it to '${signalName.toUpperCase()}'.`);\n\t}\n\n\tthrow new TypeError(`Invalid ${optionName} '${signalName}': this signal name does not exist.\\n${getAvailableSignals()}`);\n};\n\nconst getAvailableSignals = () => `Available signal names: ${getAvailableSignalNames()}.\nAvailable signal numbers: ${getAvailableSignalIntegers()}.`;\n\nconst getAvailableSignalNames = () => Object.keys(constants.signals)\n\t.sort()\n\t.map(signalName => `'${signalName}'`)\n\t.join(', ');\n\nconst getAvailableSignalIntegers = () => [...new Set(Object.values(constants.signals)\n\t.sort((signalInteger, signalIntegerTwo) => signalInteger - signalIntegerTwo))]\n\t.join(', ');\n\n// Human-friendly description of a signal\nexport const getSignalDescription = signal => signalsByName[signal].description;\n","import{constants}from\"node:os\";\n\nimport{SIGRTMAX}from\"./realtime.js\";\nimport{getSignals}from\"./signals.js\";\n\n\n\nconst getSignalsByName=()=>{\nconst signals=getSignals();\nreturn Object.fromEntries(signals.map(getSignalByName))\n};\n\nconst getSignalByName=({\nname,\nnumber,\ndescription,\nsupported,\naction,\nforced,\nstandard\n})=>[name,{name,number,description,supported,action,forced,standard}];\n\nexport const signalsByName=getSignalsByName();\n\n\n\n\nconst getSignalsByNumber=()=>{\nconst signals=getSignals();\nconst length=SIGRTMAX+1;\nconst signalsA=Array.from({length},(value,number)=>\ngetSignalByNumber(number,signals)\n);\nreturn Object.assign({},...signalsA)\n};\n\nconst getSignalByNumber=(number,signals)=>{\nconst signal=findSignalByNumber(number,signals);\n\nif(signal===undefined){\nreturn{}\n}\n\nconst{name,description,supported,action,forced,standard}=signal;\nreturn{\n[number]:{\nname,\nnumber,\ndescription,\nsupported,\naction,\nforced,\nstandard\n}\n}\n};\n\n\n\nconst findSignalByNumber=(number,signals)=>{\nconst signal=signals.find(({name})=>constants.signals[name]===number);\n\nif(signal!==undefined){\nreturn signal\n}\n\nreturn signals.find((signalA)=>signalA.number===number)\n};\n\nexport const signalsByNumber=getSignalsByNumber();","\nexport const getRealtimeSignals=()=>{\nconst length=SIGRTMAX-SIGRTMIN+1;\nreturn Array.from({length},getRealtimeSignal)\n};\n\nconst getRealtimeSignal=(value,index)=>({\nname:`SIGRT${index+1}`,\nnumber:SIGRTMIN+index,\naction:\"terminate\",\ndescription:\"Application-specific signal (realtime)\",\nstandard:\"posix\"\n});\n\nconst SIGRTMIN=34;\nexport const SIGRTMAX=64;","import{constants}from\"node:os\";\n\nimport{SIGNALS}from\"./core.js\";\nimport{getRealtimeSignals}from\"./realtime.js\";\n\n\n\nexport const getSignals=()=>{\nconst realtimeSignals=getRealtimeSignals();\nconst signals=[...SIGNALS,...realtimeSignals].map(normalizeSignal);\nreturn signals\n};\n\n\n\n\n\n\n\nconst normalizeSignal=({\nname,\nnumber:defaultNumber,\ndescription,\naction,\nforced=false,\nstandard\n})=>{\nconst{\nsignals:{[name]:constantSignal}\n}=constants;\nconst supported=constantSignal!==undefined;\nconst number=supported?constantSignal:defaultNumber;\nreturn{name,number,description,supported,action,forced,standard}\n};","\n\nexport const SIGNALS=[\n{\nname:\"SIGHUP\",\nnumber:1,\naction:\"terminate\",\ndescription:\"Terminal closed\",\nstandard:\"posix\"\n},\n{\nname:\"SIGINT\",\nnumber:2,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-C\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGQUIT\",\nnumber:3,\naction:\"core\",\ndescription:\"User interruption with CTRL-\\\\\",\nstandard:\"posix\"\n},\n{\nname:\"SIGILL\",\nnumber:4,\naction:\"core\",\ndescription:\"Invalid machine instruction\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGTRAP\",\nnumber:5,\naction:\"core\",\ndescription:\"Debugger breakpoint\",\nstandard:\"posix\"\n},\n{\nname:\"SIGABRT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGIOT\",\nnumber:6,\naction:\"core\",\ndescription:\"Aborted\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGBUS\",\nnumber:7,\naction:\"core\",\ndescription:\n\"Bus error due to misaligned, non-existing address or paging error\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGEMT\",\nnumber:7,\naction:\"terminate\",\ndescription:\"Command should be emulated but is not implemented\",\nstandard:\"other\"\n},\n{\nname:\"SIGFPE\",\nnumber:8,\naction:\"core\",\ndescription:\"Floating point arithmetic error\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGKILL\",\nnumber:9,\naction:\"terminate\",\ndescription:\"Forced termination\",\nstandard:\"posix\",\nforced:true\n},\n{\nname:\"SIGUSR1\",\nnumber:10,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"\n},\n{\nname:\"SIGSEGV\",\nnumber:11,\naction:\"core\",\ndescription:\"Segmentation fault\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGUSR2\",\nnumber:12,\naction:\"terminate\",\ndescription:\"Application-specific signal\",\nstandard:\"posix\"\n},\n{\nname:\"SIGPIPE\",\nnumber:13,\naction:\"terminate\",\ndescription:\"Broken pipe or socket\",\nstandard:\"posix\"\n},\n{\nname:\"SIGALRM\",\nnumber:14,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"posix\"\n},\n{\nname:\"SIGTERM\",\nnumber:15,\naction:\"terminate\",\ndescription:\"Termination\",\nstandard:\"ansi\"\n},\n{\nname:\"SIGSTKFLT\",\nnumber:16,\naction:\"terminate\",\ndescription:\"Stack is empty or overflowed\",\nstandard:\"other\"\n},\n{\nname:\"SIGCHLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"posix\"\n},\n{\nname:\"SIGCLD\",\nnumber:17,\naction:\"ignore\",\ndescription:\"Child process terminated, paused or unpaused\",\nstandard:\"other\"\n},\n{\nname:\"SIGCONT\",\nnumber:18,\naction:\"unpause\",\ndescription:\"Unpaused\",\nstandard:\"posix\",\nforced:true\n},\n{\nname:\"SIGSTOP\",\nnumber:19,\naction:\"pause\",\ndescription:\"Paused\",\nstandard:\"posix\",\nforced:true\n},\n{\nname:\"SIGTSTP\",\nnumber:20,\naction:\"pause\",\ndescription:\"Paused using CTRL-Z or \\\"suspend\\\"\",\nstandard:\"posix\"\n},\n{\nname:\"SIGTTIN\",\nnumber:21,\naction:\"pause\",\ndescription:\"Background process cannot read terminal input\",\nstandard:\"posix\"\n},\n{\nname:\"SIGBREAK\",\nnumber:21,\naction:\"terminate\",\ndescription:\"User interruption with CTRL-BREAK\",\nstandard:\"other\"\n},\n{\nname:\"SIGTTOU\",\nnumber:22,\naction:\"pause\",\ndescription:\"Background process cannot write to terminal output\",\nstandard:\"posix\"\n},\n{\nname:\"SIGURG\",\nnumber:23,\naction:\"ignore\",\ndescription:\"Socket received out-of-band data\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGXCPU\",\nnumber:24,\naction:\"core\",\ndescription:\"Process timed out\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGXFSZ\",\nnumber:25,\naction:\"core\",\ndescription:\"File too big\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGVTALRM\",\nnumber:26,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGPROF\",\nnumber:27,\naction:\"terminate\",\ndescription:\"Timeout or timer\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGWINCH\",\nnumber:28,\naction:\"ignore\",\ndescription:\"Terminal window size changed\",\nstandard:\"bsd\"\n},\n{\nname:\"SIGIO\",\nnumber:29,\naction:\"terminate\",\ndescription:\"I/O is available\",\nstandard:\"other\"\n},\n{\nname:\"SIGPOLL\",\nnumber:29,\naction:\"terminate\",\ndescription:\"Watched event\",\nstandard:\"other\"\n},\n{\nname:\"SIGINFO\",\nnumber:29,\naction:\"ignore\",\ndescription:\"Request for process information\",\nstandard:\"other\"\n},\n{\nname:\"SIGPWR\",\nnumber:30,\naction:\"terminate\",\ndescription:\"Device running out of power\",\nstandard:\"systemv\"\n},\n{\nname:\"SIGSYS\",\nnumber:31,\naction:\"core\",\ndescription:\"Invalid system call\",\nstandard:\"other\"\n},\n{\nname:\"SIGUNUSED\",\nnumber:31,\naction:\"terminate\",\ndescription:\"Invalid system call\",\nstandard:\"other\"\n}];","import {once} from 'node:events';\n\n// Combines `util.aborted()` and `events.addAbortListener()`: promise-based and cleaned up with a stop signal\nexport const onAbortedSignal = async (mainSignal, stopSignal) => {\n\tif (!mainSignal.aborted) {\n\t\tawait once(mainSignal, 'abort', {signal: stopSignal});\n\t}\n};\n","import {onAbortedSignal} from '../utils/abort-signal.js';\n\n// Validate the `cancelSignal` option\nexport const validateCancelSignal = ({cancelSignal}) => {\n\tif (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== '[object AbortSignal]') {\n\t\tthrow new Error(`The \\`cancelSignal\\` option must be an AbortSignal: ${String(cancelSignal)}`);\n\t}\n};\n\n// Terminate the subprocess when aborting the `cancelSignal` option and `gracefulSignal` is `false`\nexport const throwOnCancel = ({subprocess, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel\n\t? []\n\t: [terminateOnCancel(subprocess, cancelSignal, context, controller)];\n\nconst terminateOnCancel = async (subprocess, cancelSignal, context, {signal}) => {\n\tawait onAbortedSignal(cancelSignal, signal);\n\tcontext.terminationReason ??= 'cancel';\n\tsubprocess.kill();\n\tthrow cancelSignal.reason;\n};\n","import {scheduler} from 'node:timers/promises';\nimport {sendOneMessage} from './send.js';\nimport {getIpcEmitter} from './forward.js';\nimport {validateConnection, getAbortDisconnectError, throwOnMissingParent} from './validation.js';\n\n// Send an IPC message so the subprocess performs a graceful termination\nexport const sendAbort = (subprocess, message) => {\n\tconst methodName = 'cancelSignal';\n\tvalidateConnection(methodName, false, subprocess.connected);\n\treturn sendOneMessage({\n\t\tanyProcess: subprocess,\n\t\tmethodName,\n\t\tisSubprocess: false,\n\t\twrappedMessage: {type: GRACEFUL_CANCEL_TYPE, message},\n\t\tmessage,\n\t});\n};\n\n// When the signal is being used, start listening for incoming messages.\n// Unbuffering messages takes one microtask to complete, so this must be async.\nexport const getCancelSignal = async ({anyProcess, channel, isSubprocess, ipc}) => {\n\tawait startIpc({\n\t\tanyProcess,\n\t\tchannel,\n\t\tisSubprocess,\n\t\tipc,\n\t});\n\treturn cancelController.signal;\n};\n\nconst startIpc = async ({anyProcess, channel, isSubprocess, ipc}) => {\n\tif (cancelListening) {\n\t\treturn;\n\t}\n\n\tcancelListening = true;\n\n\tif (!ipc) {\n\t\tthrowOnMissingParent();\n\t\treturn;\n\t}\n\n\tif (channel === null) {\n\t\tabortOnDisconnect();\n\t\treturn;\n\t}\n\n\tgetIpcEmitter(anyProcess, channel, isSubprocess);\n\tawait scheduler.yield();\n};\n\nlet cancelListening = false;\n\n// Reception of IPC message to perform a graceful termination\nexport const handleAbort = wrappedMessage => {\n\tif (wrappedMessage?.type !== GRACEFUL_CANCEL_TYPE) {\n\t\treturn false;\n\t}\n\n\tcancelController.abort(wrappedMessage.message);\n\treturn true;\n};\n\nconst GRACEFUL_CANCEL_TYPE = 'execa:ipc:cancel';\n\n// When the current process disconnects early, the subprocess `cancelSignal` is aborted.\n// Otherwise, the signal would never be able to be aborted later on.\nexport const abortOnDisconnect = () => {\n\tcancelController.abort(getAbortDisconnectError());\n};\n\nconst cancelController = new AbortController();\n","import {promisify} from 'node:util';\nimport {\n\tvalidateIpcMethod,\n\thandleEpipeError,\n\thandleSerializationError,\n\tdisconnect,\n} from './validation.js';\nimport {startSendMessage, endSendMessage} from './outgoing.js';\nimport {handleSendStrict, waitForStrictResponse} from './strict.js';\n\n// Like `[sub]process.send()` but promise-based.\n// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.\n// Users would still need to `await subprocess` after the method is done.\n// Also, this would prevent `unhandledRejection` event from being emitted, making it silent.\nexport const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {\n\tconst methodName = 'sendMessage';\n\tvalidateIpcMethod({\n\t\tmethodName,\n\t\tisSubprocess,\n\t\tipc,\n\t\tisConnected: anyProcess.connected,\n\t});\n\n\treturn sendMessageAsync({\n\t\tanyProcess,\n\t\tchannel,\n\t\tmethodName,\n\t\tisSubprocess,\n\t\tmessage,\n\t\tstrict,\n\t});\n};\n\nconst sendMessageAsync = async ({anyProcess, channel, methodName, isSubprocess, message, strict}) => {\n\tconst wrappedMessage = handleSendStrict({\n\t\tanyProcess,\n\t\tchannel,\n\t\tisSubprocess,\n\t\tmessage,\n\t\tstrict,\n\t});\n\tconst outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict);\n\ttry {\n\t\tawait sendOneMessage({\n\t\t\tanyProcess,\n\t\t\tmethodName,\n\t\t\tisSubprocess,\n\t\t\twrappedMessage,\n\t\t\tmessage,\n\t\t});\n\t} catch (error) {\n\t\tdisconnect(anyProcess);\n\t\tthrow error;\n\t} finally {\n\t\tendSendMessage(outgoingMessagesState);\n\t}\n};\n\n// Used internally by `cancelSignal`\nexport const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message}) => {\n\tconst sendMethod = getSendMethod(anyProcess);\n\n\ttry {\n\t\tawait Promise.all([\n\t\t\twaitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),\n\t\t\tsendMethod(wrappedMessage),\n\t\t]);\n\t} catch (error) {\n\t\thandleEpipeError({error, methodName, isSubprocess});\n\t\thandleSerializationError({\n\t\t\terror,\n\t\t\tmethodName,\n\t\t\tisSubprocess,\n\t\t\tmessage,\n\t\t});\n\t\tthrow error;\n\t}\n};\n\n// [sub]process.send() promisified, memoized\nconst getSendMethod = anyProcess => {\n\tif (PROCESS_SEND_METHODS.has(anyProcess)) {\n\t\treturn PROCESS_SEND_METHODS.get(anyProcess);\n\t}\n\n\tconst sendMethod = promisify(anyProcess.send.bind(anyProcess));\n\tPROCESS_SEND_METHODS.set(anyProcess, sendMethod);\n\treturn sendMethod;\n};\n\nconst PROCESS_SEND_METHODS = new WeakMap();\n","// Validate the IPC channel is connected before receiving/sending messages\nexport const validateIpcMethod = ({methodName, isSubprocess, ipc, isConnected}) => {\n\tvalidateIpcOption(methodName, isSubprocess, ipc);\n\tvalidateConnection(methodName, isSubprocess, isConnected);\n};\n\n// Better error message when forgetting to set `ipc: true` and using the IPC methods\nconst validateIpcOption = (methodName, isSubprocess, ipc) => {\n\tif (!ipc) {\n\t\tthrow new Error(`${getMethodName(methodName, isSubprocess)} can only be used if the \\`ipc\\` option is \\`true\\`.`);\n\t}\n};\n\n// Better error message when one process does not send/receive messages once the other process has disconnected.\n// This also makes it clear that any buffered messages are lost once either process has disconnected.\n// Also when aborting `cancelSignal` after disconnecting the IPC.\nexport const validateConnection = (methodName, isSubprocess, isConnected) => {\n\tif (!isConnected) {\n\t\tthrow new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);\n\t}\n};\n\n// When `getOneMessage()` could not complete due to an early disconnection\nexport const throwOnEarlyDisconnect = isSubprocess => {\n\tthrow new Error(`${getMethodName('getOneMessage', isSubprocess)} could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);\n};\n\n// When both processes use `sendMessage()` with `strict` at the same time\nexport const throwOnStrictDeadlockError = isSubprocess => {\n\tthrow new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.\nThis can be fixed by both sending a message and listening to incoming messages at the same time:\n\nconst [receivedMessage] = await Promise.all([\n\t${getMethodName('getOneMessage', isSubprocess)},\n\t${getMethodName('sendMessage', isSubprocess, 'message, {strict: true}')},\n]);`);\n};\n\n// When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response\nexport const getStrictResponseError = (error, isSubprocess) => new Error(`${getMethodName('sendMessage', isSubprocess)} failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});\n\n// When using `strict` but the other process was not listening for messages\nexport const throwOnMissingStrict = isSubprocess => {\n\tthrow new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);\n};\n\n// When using `strict` but the other process disconnected before receiving the message\nexport const throwOnStrictDisconnect = isSubprocess => {\n\tthrow new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);\n};\n\n// When the current process disconnects while the subprocess is listening to `cancelSignal`\nexport const getAbortDisconnectError = () => new Error(`\\`cancelSignal\\` aborted: the ${getOtherProcessName(true)} disconnected.`);\n\n// When the subprocess uses `cancelSignal` but not the current process\nexport const throwOnMissingParent = () => {\n\tthrow new Error('`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.');\n};\n\n// EPIPE can happen when sending a message to a subprocess that is closing but has not disconnected yet\nexport const handleEpipeError = ({error, methodName, isSubprocess}) => {\n\tif (error.code === 'EPIPE') {\n\t\tthrow new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, {cause: error});\n\t}\n};\n\n// Better error message when sending messages which cannot be serialized.\n// Works with both `serialization: 'advanced'` and `serialization: 'json'`.\nexport const handleSerializationError = ({error, methodName, isSubprocess, message}) => {\n\tif (isSerializationError(error)) {\n\t\tthrow new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, {cause: error});\n\t}\n};\n\nconst isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)\n\t|| SERIALIZATION_ERROR_MESSAGES.some(serializationErrorMessage => message.includes(serializationErrorMessage));\n\n// `error.code` set by Node.js when it failed to serialize the message\nconst SERIALIZATION_ERROR_CODES = new Set([\n\t// Message is `undefined`\n\t'ERR_MISSING_ARGS',\n\t// Message is a function, a bigint, a symbol\n\t'ERR_INVALID_ARG_TYPE',\n]);\n\n// `error.message` set by Node.js when it failed to serialize the message\nconst SERIALIZATION_ERROR_MESSAGES = [\n\t// Message is a promise or a proxy, with `serialization: 'advanced'`\n\t'could not be cloned',\n\t// Message has cycles, with `serialization: 'json'`\n\t'circular structure',\n\t// Message has cycles inside toJSON(), with `serialization: 'json'`\n\t'call stack size exceeded',\n];\n\nconst getMethodName = (methodName, isSubprocess, parameters = '') => methodName === 'cancelSignal'\n\t? '`cancelSignal`\\'s `controller.abort()`'\n\t: `${getNamespaceName(isSubprocess)}${methodName}(${parameters})`;\n\nconst getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';\n\nconst getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';\n\n// When any error arises, we disconnect the IPC.\n// Otherwise, it is likely that one of the processes will stop sending/receiving messages.\n// This would leave the other process hanging.\nexport const disconnect = anyProcess => {\n\tif (anyProcess.connected) {\n\t\tanyProcess.disconnect();\n\t}\n};\n","export const createDeferred = () => {\n\tconst methods = {};\n\tconst promise = new Promise((resolve, reject) => {\n\t\tObject.assign(methods, {resolve, reject});\n\t});\n\treturn Object.assign(promise, methods);\n};\n","import {parseFd} from './specific.js';\n\n// Retrieve stream targeted by the `to` option\nexport const getToStream = (destination, to = 'stdin') => {\n\tconst isWritable = true;\n\tconst {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);\n\tconst fdNumber = getFdNumber(fileDescriptors, to, isWritable);\n\tconst destinationStream = destination.stdio[fdNumber];\n\n\tif (destinationStream === null) {\n\t\tthrow new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));\n\t}\n\n\treturn destinationStream;\n};\n\n// Retrieve stream targeted by the `from` option\nexport const getFromStream = (source, from = 'stdout') => {\n\tconst isWritable = false;\n\tconst {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);\n\tconst fdNumber = getFdNumber(fileDescriptors, from, isWritable);\n\tconst sourceStream = fdNumber === 'all' ? source.all : source.stdio[fdNumber];\n\n\tif (sourceStream === null || sourceStream === undefined) {\n\t\tthrow new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));\n\t}\n\n\treturn sourceStream;\n};\n\n// Keeps track of the options passed to each Execa call\nexport const SUBPROCESS_OPTIONS = new WeakMap();\n\nconst getFdNumber = (fileDescriptors, fdName, isWritable) => {\n\tconst fdNumber = parseFdNumber(fdName, isWritable);\n\tvalidateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);\n\treturn fdNumber;\n};\n\nconst parseFdNumber = (fdName, isWritable) => {\n\tconst fdNumber = parseFd(fdName);\n\tif (fdNumber !== undefined) {\n\t\treturn fdNumber;\n\t}\n\n\tconst {validOptions, defaultValue} = isWritable\n\t\t? {validOptions: '\"stdin\"', defaultValue: 'stdin'}\n\t\t: {validOptions: '\"stdout\", \"stderr\", \"all\"', defaultValue: 'stdout'};\n\tthrow new TypeError(`\"${getOptionName(isWritable)}\" must not be \"${fdName}\".\nIt must be ${validOptions} or \"fd3\", \"fd4\" (and so on).\nIt is optional and defaults to \"${defaultValue}\".`);\n};\n\nconst validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {\n\tconst fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];\n\tif (fileDescriptor === undefined) {\n\t\tthrow new TypeError(`\"${getOptionName(isWritable)}\" must not be ${fdName}. That file descriptor does not exist.\nPlease set the \"stdio\" option to ensure that file descriptor exists.`);\n\t}\n\n\tif (fileDescriptor.direction === 'input' && !isWritable) {\n\t\tthrow new TypeError(`\"${getOptionName(isWritable)}\" must not be ${fdName}. It must be a readable stream, not writable.`);\n\t}\n\n\tif (fileDescriptor.direction !== 'input' && isWritable) {\n\t\tthrow new TypeError(`\"${getOptionName(isWritable)}\" must not be ${fdName}. It must be a writable stream, not readable.`);\n\t}\n};\n\nconst getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {\n\tif (fdNumber === 'all' && !options.all) {\n\t\treturn 'The \"all\" option must be true to use \"from: \\'all\\'\".';\n\t}\n\n\tconst {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);\n\treturn `The \"${optionName}: ${serializeOptionValue(optionValue)}\" option is incompatible with using \"${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}\".\nPlease set this option with \"pipe\" instead.`;\n};\n\nconst getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {\n\tconst usedDescriptor = getUsedDescriptor(fdNumber);\n\n\tif (usedDescriptor === 0 && stdin !== undefined) {\n\t\treturn {optionName: 'stdin', optionValue: stdin};\n\t}\n\n\tif (usedDescriptor === 1 && stdout !== undefined) {\n\t\treturn {optionName: 'stdout', optionValue: stdout};\n\t}\n\n\tif (usedDescriptor === 2 && stderr !== undefined) {\n\t\treturn {optionName: 'stderr', optionValue: stderr};\n\t}\n\n\treturn {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};\n};\n\nconst getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;\n\nconst getOptionName = isWritable => isWritable ? 'to' : 'from';\n\nexport const serializeOptionValue = value => {\n\tif (typeof value === 'string') {\n\t\treturn `'${value}'`;\n\t}\n\n\treturn typeof value === 'number' ? `${value}` : 'Stream';\n};\n","import {once} from 'node:events';\nimport {createDeferred} from '../utils/deferred.js';\nimport {incrementMaxListeners} from '../utils/max-listeners.js';\nimport {sendMessage} from './send.js';\nimport {throwOnMissingStrict, throwOnStrictDisconnect, throwOnStrictDeadlockError} from './validation.js';\nimport {getIpcEmitter} from './forward.js';\nimport {hasMessageListeners} from './outgoing.js';\n\n// When using the `strict` option, wrap the message with metadata during `sendMessage()`\nexport const handleSendStrict = ({anyProcess, channel, isSubprocess, message, strict}) => {\n\tif (!strict) {\n\t\treturn message;\n\t}\n\n\tconst ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);\n\tconst hasListeners = hasMessageListeners(anyProcess, ipcEmitter);\n\treturn {\n\t\tid: count++,\n\t\ttype: REQUEST_TYPE,\n\t\tmessage,\n\t\thasListeners,\n\t};\n};\n\nlet count = 0n;\n\n// Handles when both processes are calling `sendMessage()` with `strict` at the same time.\n// If neither process is listening, this would create a deadlock. We detect it and throw.\nexport const validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {\n\tif (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) {\n\t\treturn;\n\t}\n\n\tfor (const {id} of outgoingMessages) {\n\t\tif (id !== undefined) {\n\t\t\tSTRICT_RESPONSES[id].resolve({isDeadlock: true, hasListeners: false});\n\t\t}\n\t}\n};\n\n// The other process then sends the acknowledgment back as a response\nexport const handleStrictRequest = async ({wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter}) => {\n\tif (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected) {\n\t\treturn wrappedMessage;\n\t}\n\n\tconst {id, message} = wrappedMessage;\n\tconst response = {id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter)};\n\n\ttry {\n\t\tawait sendMessage({\n\t\t\tanyProcess,\n\t\t\tchannel,\n\t\t\tisSubprocess,\n\t\t\tipc: true,\n\t\t}, response);\n\t} catch (error) {\n\t\tipcEmitter.emit('strict:error', error);\n\t}\n\n\treturn message;\n};\n\n// Reception of the acknowledgment response\nexport const handleStrictResponse = wrappedMessage => {\n\tif (wrappedMessage?.type !== RESPONSE_TYPE) {\n\t\treturn false;\n\t}\n\n\tconst {id, message: hasListeners} = wrappedMessage;\n\tSTRICT_RESPONSES[id]?.resolve({isDeadlock: false, hasListeners});\n\treturn true;\n};\n\n// Wait for the other process to receive the message from `sendMessage()`\nexport const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {\n\tif (wrappedMessage?.type !== REQUEST_TYPE) {\n\t\treturn;\n\t}\n\n\tconst deferred = createDeferred();\n\tSTRICT_RESPONSES[wrappedMessage.id] = deferred;\n\tconst controller = new AbortController();\n\n\ttry {\n\t\tconst {isDeadlock, hasListeners} = await Promise.race([\n\t\t\tdeferred,\n\t\t\tthrowOnDisconnect(anyProcess, isSubprocess, controller),\n\t\t]);\n\n\t\tif (isDeadlock) {\n\t\t\tthrowOnStrictDeadlockError(isSubprocess);\n\t\t}\n\n\t\tif (!hasListeners) {\n\t\t\tthrowOnMissingStrict(isSubprocess);\n\t\t}\n\t} finally {\n\t\tcontroller.abort();\n\t\tdelete STRICT_RESPONSES[wrappedMessage.id];\n\t}\n};\n\nconst STRICT_RESPONSES = {};\n\nconst throwOnDisconnect = async (anyProcess, isSubprocess, {signal}) => {\n\tincrementMaxListeners(anyProcess, 1, signal);\n\tawait once(anyProcess, 'disconnect', {signal});\n\tthrowOnStrictDisconnect(isSubprocess);\n};\n\nconst REQUEST_TYPE = 'execa:ipc:request';\nconst RESPONSE_TYPE = 'execa:ipc:response';\n","import {addAbortListener} from 'node:events';\n\n// Temporarily increase the maximum number of listeners on an eventEmitter\nexport const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {\n\tconst maxListeners = eventEmitter.getMaxListeners();\n\tif (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {\n\t\treturn;\n\t}\n\n\teventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);\n\taddAbortListener(signal, () => {\n\t\teventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);\n\t});\n};\n","import {EventEmitter} from 'node:events';\nimport {onMessage, onDisconnect} from './incoming.js';\nimport {undoAddedReferences} from './reference.js';\n\n// Forward the `message` and `disconnect` events from the process and subprocess to a proxy emitter.\n// This prevents the `error` event from stopping IPC.\n// This also allows debouncing the `message` event.\nexport const getIpcEmitter = (anyProcess, channel, isSubprocess) => {\n\tif (IPC_EMITTERS.has(anyProcess)) {\n\t\treturn IPC_EMITTERS.get(anyProcess);\n\t}\n\n\t// Use an `EventEmitter`, like the `process` that is being proxied\n\t// eslint-disable-next-line unicorn/prefer-event-target\n\tconst ipcEmitter = new EventEmitter();\n\tipcEmitter.connected = true;\n\tIPC_EMITTERS.set(anyProcess, ipcEmitter);\n\tforwardEvents({\n\t\tipcEmitter,\n\t\tanyProcess,\n\t\tchannel,\n\t\tisSubprocess,\n\t});\n\treturn ipcEmitter;\n};\n\nconst IPC_EMITTERS = new WeakMap();\n\n// The `message` and `disconnect` events are buffered in the subprocess until the first listener is setup.\n// However, unbuffering happens after one tick, so this give enough time for the caller to setup the listener on the proxy emitter first.\n// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L721\nconst forwardEvents = ({ipcEmitter, anyProcess, channel, isSubprocess}) => {\n\tconst boundOnMessage = onMessage.bind(undefined, {\n\t\tanyProcess,\n\t\tchannel,\n\t\tisSubprocess,\n\t\tipcEmitter,\n\t});\n\tanyProcess.on('message', boundOnMessage);\n\tanyProcess.once('disconnect', onDisconnect.bind(undefined, {\n\t\tanyProcess,\n\t\tchannel,\n\t\tisSubprocess,\n\t\tipcEmitter,\n\t\tboundOnMessage,\n\t}));\n\tundoAddedReferences(channel, isSubprocess);\n};\n\n// Check whether there might still be some `message` events to receive\nexport const isConnected = anyProcess => {\n\tconst ipcEmitter = IPC_EMITTERS.get(anyProcess);\n\treturn ipcEmitter === undefined\n\t\t? anyProcess.channel !== null\n\t\t: ipcEmitter.connected;\n};\n","import {once} from 'node:events';\nimport {scheduler} from 'node:timers/promises';\nimport {waitForOutgoingMessages} from './outgoing.js';\nimport {redoAddedReferences} from './reference.js';\nimport {handleStrictRequest, handleStrictResponse} from './strict.js';\nimport {handleAbort, abortOnDisconnect} from './graceful.js';\n\n// By default, Node.js buffers `message` events.\n//  - Buffering happens when there is a `message` event is emitted but there is no handler.\n//  - As soon as a `message` event handler is set, all buffered `message` events are emitted, emptying the buffer.\n//  - This happens both in the current process and the subprocess.\n//  - See https://github.com/nodejs/node/blob/501546e8f37059cd577041e23941b640d0d4d406/lib/internal/child_process.js#L719\n// This is helpful. Notably, this allows sending messages to a subprocess that's still initializing.\n// However, it has several problems.\n//  - This works with `events.on()` but not `events.once()` since all buffered messages are emitted at once.\n//    For example, users cannot call `await getOneMessage()`/`getEachMessage()` multiple times in a row.\n//  - When a user intentionally starts listening to `message` at a specific point in time, past `message` events are replayed, which might be unexpected.\n//  - Buffering is unlimited, which might lead to an out-of-memory crash.\n//  - This does not work well with multiple consumers.\n//    For example, Execa consumes events with both `result.ipcOutput` and manual IPC calls like `getOneMessage()`.\n//    Since `result.ipcOutput` reads all incoming messages, no buffering happens for manual IPC calls.\n//  - Forgetting to setup a `message` listener, or setting it up too late, is a programming mistake.\n//    The default behavior does not allow users to realize they made that mistake.\n// To solve those problems, instead of buffering messages, we debounce them.\n// The `message` event so it is emitted at most once per macrotask.\nexport const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {\n\tif (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) {\n\t\treturn;\n\t}\n\n\tif (!INCOMING_MESSAGES.has(anyProcess)) {\n\t\tINCOMING_MESSAGES.set(anyProcess, []);\n\t}\n\n\tconst incomingMessages = INCOMING_MESSAGES.get(anyProcess);\n\tincomingMessages.push(wrappedMessage);\n\n\tif (incomingMessages.length > 1) {\n\t\treturn;\n\t}\n\n\twhile (incomingMessages.length > 0) {\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tawait waitForOutgoingMessages(anyProcess, ipcEmitter, wrappedMessage);\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tawait scheduler.yield();\n\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tconst message = await handleStrictRequest({\n\t\t\twrappedMessage: incomingMessages[0],\n\t\t\tanyProcess,\n\t\t\tchannel,\n\t\t\tisSubprocess,\n\t\t\tipcEmitter,\n\t\t});\n\n\t\tincomingMessages.shift();\n\t\tipcEmitter.emit('message', message);\n\t\tipcEmitter.emit('message:done');\n\t}\n};\n\n// If the `message` event is currently debounced, the `disconnect` event must wait for it\nexport const onDisconnect = async ({anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage}) => {\n\tabortOnDisconnect();\n\n\tconst incomingMessages = INCOMING_MESSAGES.get(anyProcess);\n\twhile (incomingMessages?.length > 0) {\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tawait once(ipcEmitter, 'message:done');\n\t}\n\n\tanyProcess.removeListener('message', boundOnMessage);\n\tredoAddedReferences(channel, isSubprocess);\n\tipcEmitter.connected = false;\n\tipcEmitter.emit('disconnect');\n};\n\nconst INCOMING_MESSAGES = new WeakMap();\n","// By default, Node.js keeps the subprocess alive while it has a `message` or `disconnect` listener.\n// We replicate the same logic for the events that we proxy.\n// This ensures the subprocess is kept alive while `getOneMessage()` and `getEachMessage()` are ongoing.\n// This is not a problem with `sendMessage()` since Node.js handles that method automatically.\n// We do not use `anyProcess.channel.ref()` since this would prevent the automatic `.channel.refCounted()` Node.js is doing.\n// We keep a reference to `anyProcess.channel` since it might be `null` while `getOneMessage()` or `getEachMessage()` is still processing debounced messages.\n// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L547\nexport const addReference = (channel, reference) => {\n\tif (reference) {\n\t\taddReferenceCount(channel);\n\t}\n};\n\nconst addReferenceCount = channel => {\n\tchannel.refCounted();\n};\n\nexport const removeReference = (channel, reference) => {\n\tif (reference) {\n\t\tremoveReferenceCount(channel);\n\t}\n};\n\nconst removeReferenceCount = channel => {\n\tchannel.unrefCounted();\n};\n\n// To proxy events, we setup some global listeners on the `message` and `disconnect` events.\n// Those should not keep the subprocess alive, so we remove the automatic counting that Node.js is doing.\n// See https://github.com/nodejs/node/blob/1b965270a9c273d4cf70e8808e9d28b9ada7844f/lib/child_process.js#L180\nexport const undoAddedReferences = (channel, isSubprocess) => {\n\tif (isSubprocess) {\n\t\tremoveReferenceCount(channel);\n\t\tremoveReferenceCount(channel);\n\t}\n};\n\n// Reverse it during `disconnect`\nexport const redoAddedReferences = (channel, isSubprocess) => {\n\tif (isSubprocess) {\n\t\taddReferenceCount(channel);\n\t\taddReferenceCount(channel);\n\t}\n};\n","import {createDeferred} from '../utils/deferred.js';\nimport {getFdSpecificValue} from '../arguments/specific.js';\nimport {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';\nimport {validateStrictDeadlock} from './strict.js';\n\n// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.\n// This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.\n// Without running into a race condition when the other process sends a response too fast, before the current process set up a listener.\nexport const startSendMessage = (anyProcess, wrappedMessage, strict) => {\n\tif (!OUTGOING_MESSAGES.has(anyProcess)) {\n\t\tOUTGOING_MESSAGES.set(anyProcess, new Set());\n\t}\n\n\tconst outgoingMessages = OUTGOING_MESSAGES.get(anyProcess);\n\tconst onMessageSent = createDeferred();\n\tconst id = strict ? wrappedMessage.id : undefined;\n\tconst outgoingMessage = {onMessageSent, id};\n\toutgoingMessages.add(outgoingMessage);\n\treturn {outgoingMessages, outgoingMessage};\n};\n\nexport const endSendMessage = ({outgoingMessages, outgoingMessage}) => {\n\toutgoingMessages.delete(outgoingMessage);\n\toutgoingMessage.onMessageSent.resolve();\n};\n\n// Await while `sendMessage()` is ongoing, unless there is already a `message` listener\nexport const waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => {\n\twhile (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {\n\t\tconst outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)];\n\t\tvalidateStrictDeadlock(outgoingMessages, wrappedMessage);\n\t\t// eslint-disable-next-line no-await-in-loop\n\t\tawait Promise.all(outgoingMessages.map(({onMessageSent}) => onMessageSent));\n\t}\n};\n\nconst OUTGOING_MESSAGES = new WeakMap();\n\n// Whether any `message` listener is setup\nexport const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);\n\n// When `buffer` is `false`, we set up a `message` listener that should be ignored.\n// That listener is only meant to intercept `strict` acknowledgement responses.\nconst getMinListenerCount = anyProcess => SUBPROCESS_OPTIONS.has(anyProcess)\n\t&& !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, 'ipc')\n\t? 1\n\t: 0;\n","import {onAbortedSignal} from '../utils/abort-signal.js';\nimport {sendAbort} from '../ipc/graceful.js';\nimport {killOnTimeout} from './kill.js';\n\n// Validate the `gracefulCancel` option\nexport const validateGracefulCancel = ({gracefulCancel, cancelSignal, ipc, serialization}) => {\n\tif (!gracefulCancel) {\n\t\treturn;\n\t}\n\n\tif (cancelSignal === undefined) {\n\t\tthrow new Error('The `cancelSignal` option must be defined when setting the `gracefulCancel` option.');\n\t}\n\n\tif (!ipc) {\n\t\tthrow new Error('The `ipc` option cannot be false when setting the `gracefulCancel` option.');\n\t}\n\n\tif (serialization === 'json') {\n\t\tthrow new Error('The `serialization` option cannot be \\'json\\' when setting the `gracefulCancel` option.');\n\t}\n};\n\n// Send abort reason to the subprocess when aborting the `cancelSignal` option and `gracefulCancel` is `true`\nexport const throwOnGracefulCancel = ({\n\tsubprocess,\n\tcancelSignal,\n\tgracefulCancel,\n\tforceKillAfterDelay,\n\tcontext,\n\tcontroller,\n}) => gracefulCancel\n\t? [sendOnAbort({\n\t\tsubprocess,\n\t\tcancelSignal,\n\t\tforceKillAfterDelay,\n\t\tcontext,\n\t\tcontroller,\n\t})]\n\t: [];\n\nconst sendOnAbort = async ({subprocess, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {\n\tawait onAbortedSignal(cancelSignal, signal);\n\tconst reason = getReason(cancelSignal);\n\tawait sendAbort(subprocess, reason);\n\tkillOnTimeout({\n\t\tkill: subprocess.kill,\n\t\tforceKillAfterDelay,\n\t\tcontext,\n\t\tcontrollerSignal: signal,\n\t});\n\tcontext.terminationReason ??= 'gracefulCancel';\n\tthrow cancelSignal.reason;\n};\n\n// The default `reason` is a DOMException, which is not serializable with V8\n// See https://github.com/nodejs/node/issues/53225\nconst getReason = ({reason}) => {\n\tif (!(reason instanceof DOMException)) {\n\t\treturn reason;\n\t}\n\n\tconst error = new Error(reason.message);\n\tObject.defineProperty(error, 'stack', {\n\t\tvalue: reason.stack,\n\t\tenumerable: false,\n\t\tconfigurable: true,\n\t\twritable: true,\n\t});\n\treturn error;\n};\n","import {setTimeout} from 'node:timers/promises';\nimport {DiscardedError} from '../return/final-error.js';\n\n// Validate `timeout` option\nexport const validateTimeout = ({timeout}) => {\n\tif (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {\n\t\tthrow new TypeError(`Expected the \\`timeout\\` option to be a non-negative integer, got \\`${timeout}\\` (${typeof timeout})`);\n\t}\n};\n\n// Fails when the `timeout` option is exceeded\nexport const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined\n\t? []\n\t: [killAfterTimeout(subprocess, timeout, context, controller)];\n\nconst killAfterTimeout = async (subprocess, timeout, context, {signal}) => {\n\tawait setTimeout(timeout, undefined, {signal});\n\tcontext.terminationReason ??= 'timeout';\n\tsubprocess.kill();\n\tthrow new DiscardedError();\n};\n","import {execPath, execArgv} from 'node:process';\nimport path from 'node:path';\nimport {safeNormalizeFileUrl} from '../arguments/file-url.js';\n\n// `execaNode()` is a shortcut for `execa(..., {node: true})`\nexport const mapNode = ({options}) => {\n\tif (options.node === false) {\n\t\tthrow new TypeError('The \"node\" option cannot be false with `execaNode()`.');\n\t}\n\n\treturn {options: {...options, node: true}};\n};\n\n// Applies the `node: true` option, and the related `nodePath`/`nodeOptions` options.\n// Modifies the file commands/arguments to ensure the same Node binary and flags are re-used.\n// Also adds `ipc: true` and `shell: false`.\nexport const handleNodeOption = (file, commandArguments, {\n\tnode: shouldHandleNode = false,\n\tnodePath = execPath,\n\tnodeOptions = execArgv.filter(nodeOption => !nodeOption.startsWith('--inspect')),\n\tcwd,\n\texecPath: formerNodePath,\n\t...options\n}) => {\n\tif (formerNodePath !== undefined) {\n\t\tthrow new TypeError('The \"execPath\" option has been removed. Please use the \"nodePath\" option instead.');\n\t}\n\n\tconst normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The \"nodePath\" option');\n\tconst resolvedNodePath = path.resolve(cwd, normalizedNodePath);\n\tconst newOptions = {\n\t\t...options,\n\t\tnodePath: resolvedNodePath,\n\t\tnode: shouldHandleNode,\n\t\tcwd,\n\t};\n\n\tif (!shouldHandleNode) {\n\t\treturn [file, commandArguments, newOptions];\n\t}\n\n\tif (path.basename(file, '.exe') === 'node') {\n\t\tthrow new TypeError('When the \"node\" option is true, the first argument does not need to be \"node\".');\n\t}\n\n\treturn [\n\t\tresolvedNodePath,\n\t\t[...nodeOptions, file, ...commandArguments],\n\t\t{ipc: true, ...newOptions, shell: false},\n\t];\n};\n","import {serialize} from 'node:v8';\n\n// Validate the `ipcInput` option\nexport const validateIpcInputOption = ({ipcInput, ipc, serialization}) => {\n\tif (ipcInput === undefined) {\n\t\treturn;\n\t}\n\n\tif (!ipc) {\n\t\tthrow new Error('The `ipcInput` option cannot be set unless the `ipc` option is `true`.');\n\t}\n\n\tvalidateIpcInput[serialization](ipcInput);\n};\n\nconst validateAdvancedInput = ipcInput => {\n\ttry {\n\t\tserialize(ipcInput);\n\t} catch (error) {\n\t\tthrow new Error('The `ipcInput` option is not serializable with a structured clone.', {cause: error});\n\t}\n};\n\nconst validateJsonInput = ipcInput => {\n\ttry {\n\t\tJSON.stringify(ipcInput);\n\t} catch (error) {\n\t\tthrow new Error('The `ipcInput` option is not serializable with JSON.', {cause: error});\n\t}\n};\n\nconst validateIpcInput = {\n\tadvanced: validateAdvancedInput,\n\tjson: validateJsonInput,\n};\n\n// When the `ipcInput` option is set, it is sent as an initial IPC message to the subprocess\nexport const sendIpcInput = async (subprocess, ipcInput) => {\n\tif (ipcInput === undefined) {\n\t\treturn;\n\t}\n\n\tawait subprocess.sendMessage(ipcInput);\n};\n","// Validate `encoding` option\nexport const validateEncoding = ({encoding}) => {\n\tif (ENCODINGS.has(encoding)) {\n\t\treturn;\n\t}\n\n\tconst correctEncoding = getCorrectEncoding(encoding);\n\tif (correctEncoding !== undefined) {\n\t\tthrow new TypeError(`Invalid option \\`encoding: ${serializeEncoding(encoding)}\\`.\nPlease rename it to ${serializeEncoding(correctEncoding)}.`);\n\t}\n\n\tconst correctEncodings = [...ENCODINGS].map(correctEncoding => serializeEncoding(correctEncoding)).join(', ');\n\tthrow new TypeError(`Invalid option \\`encoding: ${serializeEncoding(encoding)}\\`.\nPlease rename it to one of: ${correctEncodings}.`);\n};\n\nconst TEXT_ENCODINGS = new Set(['utf8', 'utf16le']);\nexport const BINARY_ENCODINGS = new Set(['buffer', 'hex', 'base64', 'base64url', 'latin1', 'ascii']);\nconst ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);\n\nconst getCorrectEncoding = encoding => {\n\tif (encoding === null) {\n\t\treturn 'buffer';\n\t}\n\n\tif (typeof encoding !== 'string') {\n\t\treturn;\n\t}\n\n\tconst lowerEncoding = encoding.toLowerCase();\n\tif (lowerEncoding in ENCODING_ALIASES) {\n\t\treturn ENCODING_ALIASES[lowerEncoding];\n\t}\n\n\tif (ENCODINGS.has(lowerEncoding)) {\n\t\treturn lowerEncoding;\n\t}\n};\n\nconst ENCODING_ALIASES = {\n\t// eslint-disable-next-line unicorn/text-encoding-identifier-case\n\t'utf-8': 'utf8',\n\t'utf-16le': 'utf16le',\n\t'ucs-2': 'utf16le',\n\tucs2: 'utf16le',\n\tbinary: 'latin1',\n};\n\nconst serializeEncoding = encoding => typeof encoding === 'string' ? `\"${encoding}\"` : String(encoding);\n","import {statSync} from 'node:fs';\nimport path from 'node:path';\nimport process from 'node:process';\nimport {safeNormalizeFileUrl} from './file-url.js';\n\n// Normalize `cwd` option\nexport const normalizeCwd = (cwd = getDefaultCwd()) => {\n\tconst cwdString = safeNormalizeFileUrl(cwd, 'The \"cwd\" option');\n\treturn path.resolve(cwdString);\n};\n\nconst getDefaultCwd = () => {\n\ttry {\n\t\treturn process.cwd();\n\t} catch (error) {\n\t\terror.message = `The current directory does not exist.\\n${error.message}`;\n\t\tthrow error;\n\t}\n};\n\n// When `cwd` option has an invalid value, provide with a better error message\nexport const fixCwdError = (originalMessage, cwd) => {\n\tif (cwd === getDefaultCwd()) {\n\t\treturn originalMessage;\n\t}\n\n\tlet cwdStat;\n\ttry {\n\t\tcwdStat = statSync(cwd);\n\t} catch (error) {\n\t\treturn `The \"cwd\" option is invalid: ${cwd}.\\n${error.message}\\n${originalMessage}`;\n\t}\n\n\tif (!cwdStat.isDirectory()) {\n\t\treturn `The \"cwd\" option is not a directory: ${cwd}.\\n${originalMessage}`;\n\t}\n\n\treturn originalMessage;\n};\n","// When the `shell` option is set, any command argument is concatenated as a single string by Node.js:\n// https://github.com/nodejs/node/blob/e38ce27f3ca0a65f68a31cedd984cddb927d4002/lib/child_process.js#L614-L624\n// However, since Node 24, it also prints a deprecation warning.\n// To avoid this warning, we perform that same operation before calling `node:child_process`.\n// Shells only understand strings, which is why Node.js performs that concatenation.\n// However, we rely on users splitting command arguments as an array.\n// For example, this allows us to easily detect which arguments are passed.\n// So we do want users to pass array of arguments even with `shell: true`, but we also want to avoid any warning.\nexport const concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0\n\t? [[file, ...commandArguments].join(' '), [], options]\n\t: [file, commandArguments, options];\n","import {inspect} from 'node:util';\nimport stripFinalNewline from 'strip-final-newline';\nimport {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';\nimport {fixCwdError} from '../arguments/cwd.js';\nimport {escapeLines} from '../arguments/escape.js';\nimport {getMaxBufferMessage} from '../io/max-buffer.js';\nimport {getSignalDescription} from '../terminate/signal.js';\nimport {DiscardedError, isExecaError} from './final-error.js';\n\n// Computes `error.message`, `error.shortMessage` and `error.originalMessage`\nexport const createMessages = ({\n\tstdio,\n\tall,\n\tipcOutput,\n\toriginalError,\n\tsignal,\n\tsignalDescription,\n\texitCode,\n\tescapedCommand,\n\ttimedOut,\n\tisCanceled,\n\tisGracefullyCanceled,\n\tisMaxBuffer,\n\tisForcefullyTerminated,\n\tforceKillAfterDelay,\n\tkillSignal,\n\tmaxBuffer,\n\ttimeout,\n\tcwd,\n}) => {\n\tconst errorCode = originalError?.code;\n\tconst prefix = getErrorPrefix({\n\t\toriginalError,\n\t\ttimedOut,\n\t\ttimeout,\n\t\tisMaxBuffer,\n\t\tmaxBuffer,\n\t\terrorCode,\n\t\tsignal,\n\t\tsignalDescription,\n\t\texitCode,\n\t\tisCanceled,\n\t\tisGracefullyCanceled,\n\t\tisForcefullyTerminated,\n\t\tforceKillAfterDelay,\n\t\tkillSignal,\n\t});\n\tconst originalMessage = getOriginalMessage(originalError, cwd);\n\tconst suffix = originalMessage === undefined ? '' : `\\n${originalMessage}`;\n\tconst shortMessage = `${prefix}: ${escapedCommand}${suffix}`;\n\tconst messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];\n\tconst message = [\n\t\tshortMessage,\n\t\t...messageStdio,\n\t\t...stdio.slice(3),\n\t\tipcOutput.map(ipcMessage => serializeIpcMessage(ipcMessage)).join('\\n'),\n\t]\n\t\t.map(messagePart => escapeLines(stripFinalNewline(serializeMessagePart(messagePart))))\n\t\t.filter(Boolean)\n\t\t.join('\\n\\n');\n\treturn {originalMessage, shortMessage, message};\n};\n\nconst getErrorPrefix = ({\n\toriginalError,\n\ttimedOut,\n\ttimeout,\n\tisMaxBuffer,\n\tmaxBuffer,\n\terrorCode,\n\tsignal,\n\tsignalDescription,\n\texitCode,\n\tisCanceled,\n\tisGracefullyCanceled,\n\tisForcefullyTerminated,\n\tforceKillAfterDelay,\n\tkillSignal,\n}) => {\n\tconst forcefulSuffix = getForcefulSuffix(isForcefullyTerminated, forceKillAfterDelay);\n\n\tif (timedOut) {\n\t\treturn `Command timed out after ${timeout} milliseconds${forcefulSuffix}`;\n\t}\n\n\tif (isGracefullyCanceled) {\n\t\tif (signal === undefined) {\n\t\t\treturn `Command was gracefully canceled with exit code ${exitCode}`;\n\t\t}\n\n\t\treturn isForcefullyTerminated\n\t\t\t? `Command was gracefully canceled${forcefulSuffix}`\n\t\t\t: `Command was gracefully canceled with ${signal} (${signalDescription})`;\n\t}\n\n\tif (isCanceled) {\n\t\treturn `Command was canceled${forcefulSuffix}`;\n\t}\n\n\tif (isMaxBuffer) {\n\t\treturn `${getMaxBufferMessage(originalError, maxBuffer)}${forcefulSuffix}`;\n\t}\n\n\tif (errorCode !== undefined) {\n\t\treturn `Command failed with ${errorCode}${forcefulSuffix}`;\n\t}\n\n\tif (isForcefullyTerminated) {\n\t\treturn `Command was killed with ${killSignal} (${getSignalDescription(killSignal)})${forcefulSuffix}`;\n\t}\n\n\tif (signal !== undefined) {\n\t\treturn `Command was killed with ${signal} (${signalDescription})`;\n\t}\n\n\tif (exitCode !== undefined) {\n\t\treturn `Command failed with exit code ${exitCode}`;\n\t}\n\n\treturn 'Command failed';\n};\n\nconst getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated\n\t? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds`\n\t: '';\n\nconst getOriginalMessage = (originalError, cwd) => {\n\tif (originalError instanceof DiscardedError) {\n\t\treturn;\n\t}\n\n\tconst originalMessage = isExecaError(originalError)\n\t\t? originalError.originalMessage\n\t\t: String(originalError?.message ?? originalError);\n\tconst escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));\n\treturn escapedOriginalMessage === '' ? undefined : escapedOriginalMessage;\n};\n\nconst serializeIpcMessage = ipcMessage => typeof ipcMessage === 'string'\n\t? ipcMessage\n\t: inspect(ipcMessage);\n\nconst serializeMessagePart = messagePart => Array.isArray(messagePart)\n\t? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\\n')\n\t: serializeMessageItem(messagePart);\n\nconst serializeMessageItem = messageItem => {\n\tif (typeof messageItem === 'string') {\n\t\treturn messageItem;\n\t}\n\n\tif (isUint8Array(messageItem)) {\n\t\treturn uint8ArrayToString(messageItem);\n\t}\n\n\treturn '';\n};\n","export default function stripFinalNewline(input) {\n\tif (typeof input === 'string') {\n\t\treturn stripFinalNewlineString(input);\n\t}\n\n\tif (!(ArrayBuffer.isView(input) && input.BYTES_PER_ELEMENT === 1)) {\n\t\tthrow new Error('Input must be a string or a Uint8Array');\n\t}\n\n\treturn stripFinalNewlineBinary(input);\n}\n\nconst stripFinalNewlineString = input =>\n\tinput.at(-1) === LF\n\t\t? input.slice(0, input.at(-2) === CR ? -2 : -1)\n\t\t: input;\n\nconst stripFinalNewlineBinary = input =>\n\tinput.at(-1) === LF_BINARY\n\t\t? input.subarray(0, input.at(-2) === CR_BINARY ? -2 : -1)\n\t\t: input;\n\nconst LF = '\\n';\nconst LF_BINARY = LF.codePointAt(0);\nconst CR = '\\r';\nconst CR_BINARY = CR.codePointAt(0);\n","import {on} from 'node:events';\nimport {finished} from 'node:stream/promises';\nimport {nodeImports} from './stream.js';\n\nObject.assign(nodeImports, {on, finished});\n\nexport {\n\tdefault,\n\tgetStreamAsArray,\n\tgetStreamAsArrayBuffer,\n\tgetStreamAsBuffer,\n\tMaxBufferError,\n} from './exports.js';\n","export function isStream(stream, {checkOpen = true} = {}) {\n\treturn stream !== null\n\t\t&& typeof stream === 'object'\n\t\t&& (stream.writable || stream.readable || !checkOpen || (stream.writable === undefined && stream.readable === undefined))\n\t\t&& typeof stream.pipe === 'function';\n}\n\nexport function isWritableStream(stream, {checkOpen = true} = {}) {\n\treturn isStream(stream, {checkOpen})\n\t\t&& (stream.writable || !checkOpen)\n\t\t&& typeof stream.write === 'function'\n\t\t&& typeof stream.end === 'function'\n\t\t&& typeof stream.writable === 'boolean'\n\t\t&& typeof stream.writableObjectMode === 'boolean'\n\t\t&& typeof stream.destroy === 'function'\n\t\t&& typeof stream.destroyed === 'boolean';\n}\n\nexport function isReadableStream(stream, {checkOpen = true} = {}) {\n\treturn isStream(stream, {checkOpen})\n\t\t&& (stream.readable || !checkOpen)\n\t\t&& typeof stream.read === 'function'\n\t\t&& typeof stream.readable === 'boolean'\n\t\t&& typeof stream.readableObjectMode === 'boolean'\n\t\t&& typeof stream.destroy === 'function'\n\t\t&& typeof stream.destroyed === 'boolean';\n}\n\nexport function isDuplexStream(stream, options) {\n\treturn isWritableStream(stream, options)\n\t\t&& isReadableStream(stream, options);\n}\n\nexport function isTransformStream(stream, options) {\n\treturn isDuplexStream(stream, options)\n\t\t&& typeof stream._transform === 'function';\n}\n","const a = Object.getPrototypeOf(\n  Object.getPrototypeOf(\n    /* istanbul ignore next */\n    async function* () {\n    }\n  ).prototype\n);\nclass c {\n  #t;\n  #n;\n  #r = !1;\n  #e = void 0;\n  constructor(e, t) {\n    this.#t = e, this.#n = t;\n  }\n  next() {\n    const e = () => this.#s();\n    return this.#e = this.#e ? this.#e.then(e, e) : e(), this.#e;\n  }\n  return(e) {\n    const t = () => this.#i(e);\n    return this.#e ? this.#e.then(t, t) : t();\n  }\n  async #s() {\n    if (this.#r)\n      return {\n        done: !0,\n        value: void 0\n      };\n    let e;\n    try {\n      e = await this.#t.read();\n    } catch (t) {\n      throw this.#e = void 0, this.#r = !0, this.#t.releaseLock(), t;\n    }\n    return e.done && (this.#e = void 0, this.#r = !0, this.#t.releaseLock()), e;\n  }\n  async #i(e) {\n    if (this.#r)\n      return {\n        done: !0,\n        value: e\n      };\n    if (this.#r = !0, !this.#n) {\n      const t = this.#t.cancel(e);\n      return this.#t.releaseLock(), await t, {\n        done: !0,\n        value: e\n      };\n    }\n    return this.#t.releaseLock(), {\n      done: !0,\n      value: e\n    };\n  }\n}\nconst n = Symbol();\nfunction i() {\n  return this[n].next();\n}\nObject.defineProperty(i, \"name\", { value: \"next\" });\nfunction o(r) {\n  return this[n].return(r);\n}\nObject.defineProperty(o, \"name\", { value: \"return\" });\nconst u = Object.create(a, {\n  next: {\n    enumerable: !0,\n    configurable: !0,\n    writable: !0,\n    value: i\n  },\n  return: {\n    enumerable: !0,\n    configurable: !0,\n    writable: !0,\n    value: o\n  }\n});\nfunction h({ preventCancel: r = !1 } = {}) {\n  const e = this.getReader(), t = new c(\n    e,\n    r\n  ), s = Object.create(u);\n  return s[n] = t, s;\n}\nexport {\n  h as asyncIterator\n};\n","import {isReadableStream} from 'is-stream';\nimport {asyncIterator} from '@sec-ant/readable-stream/ponyfill';\n\nexport const getAsyncIterable = stream => {\n\tif (isReadableStream(stream, {checkOpen: false}) && nodeImports.on !== undefined) {\n\t\treturn getStreamIterable(stream);\n\t}\n\n\tif (typeof stream?.[Symbol.asyncIterator] === 'function') {\n\t\treturn stream;\n\t}\n\n\t// `ReadableStream[Symbol.asyncIterator]` support is missing in multiple browsers, so we ponyfill it\n\tif (toString.call(stream) === '[object ReadableStream]') {\n\t\treturn asyncIterator.call(stream);\n\t}\n\n\tthrow new TypeError('The first argument must be a Readable, a ReadableStream, or an async iterable.');\n};\n\nconst {toString} = Object.prototype;\n\n// The default iterable for Node.js streams does not allow for multiple readers at once, so we re-implement it\nconst getStreamIterable = async function * (stream) {\n\tconst controller = new AbortController();\n\tconst state = {};\n\thandleStreamEnd(stream, controller, state);\n\n\ttry {\n\t\tfor await (const [chunk] of nodeImports.on(stream, 'data', {signal: controller.signal})) {\n\t\t\tyield chunk;\n\t\t}\n\t} catch (error) {\n\t\t// Stream failure, for example due to `stream.destroy(error)`\n\t\tif (state.error !== undefined) {\n\t\t\tthrow state.error;\n\t\t// `error` event directly emitted on stream\n\t\t} else if (!controller.signal.aborted) {\n\t\t\tthrow error;\n\t\t// Otherwise, stream completed successfully\n\t\t}\n\t\t// The `finally` block also runs when the caller throws, for example due to the `maxBuffer` option\n\t} finally {\n\t\tstream.destroy();\n\t}\n};\n\nconst handleStreamEnd = async (stream, controller, state) => {\n\ttry {\n\t\tawait nodeImports.finished(stream, {\n\t\t\tcleanup: true,\n\t\t\treadable: true,\n\t\t\twritable: false,\n\t\t\terror: false,\n\t\t});\n\t} catch (error) {\n\t\tstate.error = error;\n\t} finally {\n\t\tcontroller.abort();\n\t}\n};\n\n// Loaded by the Node entrypoint, but not by the browser one.\n// This prevents using dynamic imports.\nexport const nodeImports = {};\n","import {getAsyncIterable} from './stream.js';\n\nexport const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => {\n\tconst asyncIterable = getAsyncIterable(stream);\n\n\tconst state = init();\n\tstate.length = 0;\n\n\ttry {\n\t\tfor await (const chunk of asyncIterable) {\n\t\t\tconst chunkType = getChunkType(chunk);\n\t\t\tconst convertedChunk = convertChunk[chunkType](chunk, state);\n\t\t\tappendChunk({\n\t\t\t\tconvertedChunk,\n\t\t\t\tstate,\n\t\t\t\tgetSize,\n\t\t\t\ttruncateChunk,\n\t\t\t\taddChunk,\n\t\t\t\tmaxBuffer,\n\t\t\t});\n\t\t}\n\n\t\tappendFinalChunk({\n\t\t\tstate,\n\t\t\tconvertChunk,\n\t\t\tgetSize,\n\t\t\ttruncateChunk,\n\t\t\taddChunk,\n\t\t\tgetFinalChunk,\n\t\t\tmaxBuffer,\n\t\t});\n\t\treturn finalize(state);\n\t} catch (error) {\n\t\tconst normalizedError = typeof error === 'object' && error !== null ? error : new Error(error);\n\t\tnormalizedError.bufferedData = finalize(state);\n\t\tthrow normalizedError;\n\t}\n};\n\nconst appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => {\n\tconst convertedChunk = getFinalChunk(state);\n\tif (convertedChunk !== undefined) {\n\t\tappendChunk({\n\t\t\tconvertedChunk,\n\t\t\tstate,\n\t\t\tgetSize,\n\t\t\ttruncateChunk,\n\t\t\taddChunk,\n\t\t\tmaxBuffer,\n\t\t});\n\t}\n};\n\nconst appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => {\n\tconst chunkSize = getSize(convertedChunk);\n\tconst newLength = state.length + chunkSize;\n\n\tif (newLength <= maxBuffer) {\n\t\taddNewChunk(convertedChunk, state, addChunk, newLength);\n\t\treturn;\n\t}\n\n\tconst truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length);\n\n\tif (truncatedChunk !== undefined) {\n\t\taddNewChunk(truncatedChunk, state, addChunk, maxBuffer);\n\t}\n\n\tthrow new MaxBufferError();\n};\n\nconst addNewChunk = (convertedChunk, state, addChunk, newLength) => {\n\tstate.contents = addChunk(convertedChunk, state, newLength);\n\tstate.length = newLength;\n};\n\nconst getChunkType = chunk => {\n\tconst typeOfChunk = typeof chunk;\n\n\tif (typeOfChunk === 'string') {\n\t\treturn 'string';\n\t}\n\n\tif (typeOfChunk !== 'object' || chunk === null) {\n\t\treturn 'others';\n\t}\n\n\tif (globalThis.Buffer?.isBuffer(chunk)) {\n\t\treturn 'buffer';\n\t}\n\n\tconst prototypeName = objectToString.call(chunk);\n\n\tif (prototypeName === '[object ArrayBuffer]') {\n\t\treturn 'arrayBuffer';\n\t}\n\n\tif (prototypeName === '[object DataView]') {\n\t\treturn 'dataView';\n\t}\n\n\tif (\n\t\tNumber.isInteger(chunk.byteLength)\n\t\t&& Number.isInteger(chunk.byteOffset)\n\t\t&& objectToString.call(chunk.buffer) === '[object ArrayBuffer]'\n\t) {\n\t\treturn 'typedArray';\n\t}\n\n\treturn 'others';\n};\n\nconst {toString: objectToString} = Object.prototype;\n\nexport class MaxBufferError extends Error {\n\tname = 'MaxBufferError';\n\n\tconstructor() {\n\t\tsuper('maxBuffer exceeded');\n\t}\n}\n","export const identity = value => value;\n\nexport const noop = () => undefined;\n\nexport const getContentsProperty = ({contents}) => contents;\n\nexport const throwObjectStream = chunk => {\n\tthrow new Error(`Streams in object mode are not supported: ${String(chunk)}`);\n};\n\nexport const getLengthProperty = convertedChunk => convertedChunk.length;\n","import {getStreamContents} from './contents.js';\nimport {identity, noop, getContentsProperty} from './utils.js';\n\nexport async function getStreamAsArray(stream, options) {\n\treturn getStreamContents(stream, arrayMethods, options);\n}\n\nconst initArray = () => ({contents: []});\n\nconst increment = () => 1;\n\nconst addArrayChunk = (convertedChunk, {contents}) => {\n\tcontents.push(convertedChunk);\n\treturn contents;\n};\n\nconst arrayMethods = {\n\tinit: initArray,\n\tconvertChunk: {\n\t\tstring: identity,\n\t\tbuffer: identity,\n\t\tarrayBuffer: identity,\n\t\tdataView: identity,\n\t\ttypedArray: identity,\n\t\tothers: identity,\n\t},\n\tgetSize: increment,\n\ttruncateChunk: noop,\n\taddChunk: addArrayChunk,\n\tgetFinalChunk: noop,\n\tfinalize: getContentsProperty,\n};\n","import {getStreamContents} from './contents.js';\nimport {noop, throwObjectStream, getLengthProperty} from './utils.js';\n\nexport async function getStreamAsArrayBuffer(stream, options) {\n\treturn getStreamContents(stream, arrayBufferMethods, options);\n}\n\nconst initArrayBuffer = () => ({contents: new ArrayBuffer(0)});\n\nconst useTextEncoder = chunk => textEncoder.encode(chunk);\nconst textEncoder = new TextEncoder();\n\nconst useUint8Array = chunk => new Uint8Array(chunk);\n\nconst useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n\nconst truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);\n\n// `contents` is an increasingly growing `Uint8Array`.\nconst addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => {\n\tconst newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length);\n\tnew Uint8Array(newContents).set(convertedChunk, previousLength);\n\treturn newContents;\n};\n\n// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2.\n// This means its last bytes are zeroes (not stream data), which need to be\n// trimmed at the end with `ArrayBuffer.slice()`.\nconst resizeArrayBufferSlow = (contents, length) => {\n\tif (length <= contents.byteLength) {\n\t\treturn contents;\n\t}\n\n\tconst arrayBuffer = new ArrayBuffer(getNewContentsLength(length));\n\tnew Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);\n\treturn arrayBuffer;\n};\n\n// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of\n// the stream data. It does not include extraneous zeroes to trim at the end.\n// The underlying `ArrayBuffer` does allocate a number of bytes that is a power\n// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`.\nconst resizeArrayBuffer = (contents, length) => {\n\tif (length <= contents.maxByteLength) {\n\t\tcontents.resize(length);\n\t\treturn contents;\n\t}\n\n\tconst arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)});\n\tnew Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0);\n\treturn arrayBuffer;\n};\n\n// Retrieve the closest `length` that is both >= and a power of 2\nconst getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR));\n\nconst SCALE_FACTOR = 2;\n\nconst finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length);\n\n// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available\n// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead.\n// eslint-disable-next-line no-warning-comments\n// TODO: remove after dropping support for Node 20.\n// eslint-disable-next-line no-warning-comments\n// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available\nconst hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype;\n\nconst arrayBufferMethods = {\n\tinit: initArrayBuffer,\n\tconvertChunk: {\n\t\tstring: useTextEncoder,\n\t\tbuffer: useUint8Array,\n\t\tarrayBuffer: useUint8Array,\n\t\tdataView: useUint8ArrayWithOffset,\n\t\ttypedArray: useUint8ArrayWithOffset,\n\t\tothers: throwObjectStream,\n\t},\n\tgetSize: getLengthProperty,\n\ttruncateChunk: truncateArrayBufferChunk,\n\taddChunk: addArrayBufferChunk,\n\tgetFinalChunk: noop,\n\tfinalize: finalizeArrayBuffer,\n};\n","import {getStreamContents} from './contents.js';\nimport {\n\tidentity,\n\tgetContentsProperty,\n\tthrowObjectStream,\n\tgetLengthProperty,\n} from './utils.js';\n\nexport async function getStreamAsString(stream, options) {\n\treturn getStreamContents(stream, stringMethods, options);\n}\n\nconst initString = () => ({contents: '', textDecoder: new TextDecoder()});\n\nconst useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true});\n\nconst addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk;\n\nconst truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);\n\nconst getFinalStringChunk = ({textDecoder}) => {\n\tconst finalChunk = textDecoder.decode();\n\treturn finalChunk === '' ? undefined : finalChunk;\n};\n\nconst stringMethods = {\n\tinit: initString,\n\tconvertChunk: {\n\t\tstring: identity,\n\t\tbuffer: useTextDecoder,\n\t\tarrayBuffer: useTextDecoder,\n\t\tdataView: useTextDecoder,\n\t\ttypedArray: useTextDecoder,\n\t\tothers: throwObjectStream,\n\t},\n\tgetSize: getLengthProperty,\n\ttruncateChunk: truncateStringChunk,\n\taddChunk: addStringChunk,\n\tgetFinalChunk: getFinalStringChunk,\n\tfinalize: getContentsProperty,\n};\n","import {MaxBufferError} from 'get-stream';\nimport {getStreamName} from '../utils/standard-stream.js';\nimport {getFdSpecificValue} from '../arguments/specific.js';\n\n// When the `maxBuffer` option is hit, a MaxBufferError is thrown.\n// The stream is aborted, then specific information is kept for the error message.\nexport const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {\n\tif (!(error instanceof MaxBufferError)) {\n\t\tthrow error;\n\t}\n\n\tif (fdNumber === 'all') {\n\t\treturn error;\n\t}\n\n\tconst unit = getMaxBufferUnit(readableObjectMode, lines, encoding);\n\terror.maxBufferInfo = {fdNumber, unit};\n\tstream.destroy();\n\tthrow error;\n};\n\nconst getMaxBufferUnit = (readableObjectMode, lines, encoding) => {\n\tif (readableObjectMode) {\n\t\treturn 'objects';\n\t}\n\n\tif (lines) {\n\t\treturn 'lines';\n\t}\n\n\tif (encoding === 'buffer') {\n\t\treturn 'bytes';\n\t}\n\n\treturn 'characters';\n};\n\n// Check the `maxBuffer` option with `result.ipcOutput`\nexport const checkIpcMaxBuffer = (subprocess, ipcOutput, maxBuffer) => {\n\tif (ipcOutput.length !== maxBuffer) {\n\t\treturn;\n\t}\n\n\tconst error = new MaxBufferError();\n\terror.maxBufferInfo = {fdNumber: 'ipc'};\n\tthrow error;\n};\n\n// Error message when `maxBuffer` is hit\nexport const getMaxBufferMessage = (error, maxBuffer) => {\n\tconst {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);\n\treturn `Command's ${streamName} was larger than ${threshold} ${unit}`;\n};\n\nconst getMaxBufferInfo = (error, maxBuffer) => {\n\tif (error?.maxBufferInfo === undefined) {\n\t\treturn {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};\n\t}\n\n\tconst {maxBufferInfo: {fdNumber, unit}} = error;\n\tdelete error.maxBufferInfo;\n\n\tconst threshold = getFdSpecificValue(maxBuffer, fdNumber);\n\tif (fdNumber === 'ipc') {\n\t\treturn {streamName: 'IPC output', threshold, unit: 'messages'};\n\t}\n\n\treturn {streamName: getStreamName(fdNumber), threshold, unit};\n};\n\n// The only way to apply `maxBuffer` with `spawnSync()` is to use the native `maxBuffer` option Node.js provides.\n// However, this has multiple limitations, and cannot behave the exact same way as the async behavior.\n// When the `maxBuffer` is hit, a `ENOBUFS` error is thrown.\nexport const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'\n\t&& output !== null\n\t&& output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));\n\n// When `maxBuffer` is hit, ensure the result is truncated\nexport const truncateMaxBufferSync = (result, isMaxBuffer, maxBuffer) => {\n\tif (!isMaxBuffer) {\n\t\treturn result;\n\t}\n\n\tconst maxBufferValue = getMaxBufferSync(maxBuffer);\n\treturn result.length > maxBufferValue ? result.slice(0, maxBufferValue) : result;\n};\n\n// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`\nexport const getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer;\n","import {getSignalDescription} from '../terminate/signal.js';\nimport {getDurationMs} from './duration.js';\nimport {getFinalError} from './final-error.js';\nimport {createMessages} from './message.js';\n\n// Object returned on subprocess success\nexport const makeSuccessResult = ({\n\tcommand,\n\tescapedCommand,\n\tstdio,\n\tall,\n\tipcOutput,\n\toptions: {cwd},\n\tstartTime,\n}) => omitUndefinedProperties({\n\tcommand,\n\tescapedCommand,\n\tcwd,\n\tdurationMs: getDurationMs(startTime),\n\tfailed: false,\n\ttimedOut: false,\n\tisCanceled: false,\n\tisGracefullyCanceled: false,\n\tisTerminated: false,\n\tisMaxBuffer: false,\n\tisForcefullyTerminated: false,\n\texitCode: 0,\n\tstdout: stdio[1],\n\tstderr: stdio[2],\n\tall,\n\tstdio,\n\tipcOutput,\n\tpipedFrom: [],\n});\n\n// Object returned on subprocess failure before spawning\nexport const makeEarlyError = ({\n\terror,\n\tcommand,\n\tescapedCommand,\n\tfileDescriptors,\n\toptions,\n\tstartTime,\n\tisSync,\n}) => makeError({\n\terror,\n\tcommand,\n\tescapedCommand,\n\tstartTime,\n\ttimedOut: false,\n\tisCanceled: false,\n\tisGracefullyCanceled: false,\n\tisMaxBuffer: false,\n\tisForcefullyTerminated: false,\n\tstdio: Array.from({length: fileDescriptors.length}),\n\tipcOutput: [],\n\toptions,\n\tisSync,\n});\n\n// Object returned on subprocess failure\nexport const makeError = ({\n\terror: originalError,\n\tcommand,\n\tescapedCommand,\n\tstartTime,\n\ttimedOut,\n\tisCanceled,\n\tisGracefullyCanceled,\n\tisMaxBuffer,\n\tisForcefullyTerminated,\n\texitCode: rawExitCode,\n\tsignal: rawSignal,\n\tstdio,\n\tall,\n\tipcOutput,\n\toptions: {\n\t\ttimeoutDuration,\n\t\ttimeout = timeoutDuration,\n\t\tforceKillAfterDelay,\n\t\tkillSignal,\n\t\tcwd,\n\t\tmaxBuffer,\n\t},\n\tisSync,\n}) => {\n\tconst {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);\n\tconst {originalMessage, shortMessage, message} = createMessages({\n\t\tstdio,\n\t\tall,\n\t\tipcOutput,\n\t\toriginalError,\n\t\tsignal,\n\t\tsignalDescription,\n\t\texitCode,\n\t\tescapedCommand,\n\t\ttimedOut,\n\t\tisCanceled,\n\t\tisGracefullyCanceled,\n\t\tisMaxBuffer,\n\t\tisForcefullyTerminated,\n\t\tforceKillAfterDelay,\n\t\tkillSignal,\n\t\tmaxBuffer,\n\t\ttimeout,\n\t\tcwd,\n\t});\n\tconst error = getFinalError(originalError, message, isSync);\n\tObject.assign(error, getErrorProperties({\n\t\terror,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstartTime,\n\t\ttimedOut,\n\t\tisCanceled,\n\t\tisGracefullyCanceled,\n\t\tisMaxBuffer,\n\t\tisForcefullyTerminated,\n\t\texitCode,\n\t\tsignal,\n\t\tsignalDescription,\n\t\tstdio,\n\t\tall,\n\t\tipcOutput,\n\t\tcwd,\n\t\toriginalMessage,\n\t\tshortMessage,\n\t}));\n\treturn error;\n};\n\nconst getErrorProperties = ({\n\terror,\n\tcommand,\n\tescapedCommand,\n\tstartTime,\n\ttimedOut,\n\tisCanceled,\n\tisGracefullyCanceled,\n\tisMaxBuffer,\n\tisForcefullyTerminated,\n\texitCode,\n\tsignal,\n\tsignalDescription,\n\tstdio,\n\tall,\n\tipcOutput,\n\tcwd,\n\toriginalMessage,\n\tshortMessage,\n}) => omitUndefinedProperties({\n\tshortMessage,\n\toriginalMessage,\n\tcommand,\n\tescapedCommand,\n\tcwd,\n\tdurationMs: getDurationMs(startTime),\n\tfailed: true,\n\ttimedOut,\n\tisCanceled,\n\tisGracefullyCanceled,\n\tisTerminated: signal !== undefined,\n\tisMaxBuffer,\n\tisForcefullyTerminated,\n\texitCode,\n\tsignal,\n\tsignalDescription,\n\tcode: error.cause?.code,\n\tstdout: stdio[1],\n\tstderr: stdio[2],\n\tall,\n\tstdio,\n\tipcOutput,\n\tpipedFrom: [],\n});\n\nconst omitUndefinedProperties = result => Object.fromEntries(Object.entries(result).filter(([, value]) => value !== undefined));\n\n// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.\n// We normalize them to `undefined`\nconst normalizeExitPayload = (rawExitCode, rawSignal) => {\n\tconst exitCode = rawExitCode === null ? undefined : rawExitCode;\n\tconst signal = rawSignal === null ? undefined : rawSignal;\n\tconst signalDescription = signal === undefined ? undefined : getSignalDescription(rawSignal);\n\treturn {exitCode, signal, signalDescription};\n};\n","const toZeroIfInfinity = value => Number.isFinite(value) ? value : 0;\n\nfunction parseNumber(milliseconds) {\n\treturn {\n\t\tdays: Math.trunc(milliseconds / 86_400_000),\n\t\thours: Math.trunc(milliseconds / 3_600_000 % 24),\n\t\tminutes: Math.trunc(milliseconds / 60_000 % 60),\n\t\tseconds: Math.trunc(milliseconds / 1000 % 60),\n\t\tmilliseconds: Math.trunc(milliseconds % 1000),\n\t\tmicroseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1000) % 1000),\n\t\tnanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1000),\n\t};\n}\n\nfunction parseBigint(milliseconds) {\n\treturn {\n\t\tdays: milliseconds / 86_400_000n,\n\t\thours: milliseconds / 3_600_000n % 24n,\n\t\tminutes: milliseconds / 60_000n % 60n,\n\t\tseconds: milliseconds / 1000n % 60n,\n\t\tmilliseconds: milliseconds % 1000n,\n\t\tmicroseconds: 0n,\n\t\tnanoseconds: 0n,\n\t};\n}\n\nexport default function parseMilliseconds(milliseconds) {\n\tswitch (typeof milliseconds) {\n\t\tcase 'number': {\n\t\t\tif (Number.isFinite(milliseconds)) {\n\t\t\t\treturn parseNumber(milliseconds);\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'bigint': {\n\t\t\treturn parseBigint(milliseconds);\n\t\t}\n\n\t\t// No default\n\t}\n\n\tthrow new TypeError('Expected a finite number or bigint');\n}\n","import parseMilliseconds from 'parse-ms';\n\nconst isZero = value => value === 0 || value === 0n;\nconst pluralize = (word, count) => (count === 1 || count === 1n) ? word : `${word}s`;\n\nconst SECOND_ROUNDING_EPSILON = 0.000_000_1;\nconst ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;\n\nexport default function prettyMilliseconds(milliseconds, options) {\n\tconst isBigInt = typeof milliseconds === 'bigint';\n\tif (!isBigInt && !Number.isFinite(milliseconds)) {\n\t\tthrow new TypeError('Expected a finite number or bigint');\n\t}\n\n\toptions = {...options};\n\n\tconst sign = milliseconds < 0 ? '-' : '';\n\tmilliseconds = milliseconds < 0 ? -milliseconds : milliseconds; // Cannot use `Math.abs()` because of BigInt support.\n\n\tif (options.colonNotation) {\n\t\toptions.compact = false;\n\t\toptions.formatSubMilliseconds = false;\n\t\toptions.separateMilliseconds = false;\n\t\toptions.verbose = false;\n\t}\n\n\tif (options.compact) {\n\t\toptions.unitCount = 1;\n\t\toptions.secondsDecimalDigits = 0;\n\t\toptions.millisecondsDecimalDigits = 0;\n\t}\n\n\tlet result = [];\n\n\tconst floorDecimals = (value, decimalDigits) => {\n\t\tconst flooredInterimValue = Math.floor((value * (10 ** decimalDigits)) + SECOND_ROUNDING_EPSILON);\n\t\tconst flooredValue = Math.round(flooredInterimValue) / (10 ** decimalDigits);\n\t\treturn flooredValue.toFixed(decimalDigits);\n\t};\n\n\tconst add = (value, long, short, valueString) => {\n\t\tif (\n\t\t\t(result.length === 0 || !options.colonNotation)\n\t\t\t&& isZero(value)\n\t\t\t&& !(options.colonNotation && short === 'm')) {\n\t\t\treturn;\n\t\t}\n\n\t\tvalueString ??= String(value);\n\t\tif (options.colonNotation) {\n\t\t\tconst wholeDigits = valueString.includes('.') ? valueString.split('.')[0].length : valueString.length;\n\t\t\tconst minLength = result.length > 0 ? 2 : 1;\n\t\t\tvalueString = '0'.repeat(Math.max(0, minLength - wholeDigits)) + valueString;\n\t\t} else {\n\t\t\tvalueString += options.verbose ? ' ' + pluralize(long, value) : short;\n\t\t}\n\n\t\tresult.push(valueString);\n\t};\n\n\tconst parsed = parseMilliseconds(milliseconds);\n\tconst days = BigInt(parsed.days);\n\n\tif (options.hideYearAndDays) {\n\t\tadd((BigInt(days) * 24n) + BigInt(parsed.hours), 'hour', 'h');\n\t} else {\n\t\tif (options.hideYear) {\n\t\t\tadd(days, 'day', 'd');\n\t\t} else {\n\t\t\tadd(days / 365n, 'year', 'y');\n\t\t\tadd(days % 365n, 'day', 'd');\n\t\t}\n\n\t\tadd(Number(parsed.hours), 'hour', 'h');\n\t}\n\n\tadd(Number(parsed.minutes), 'minute', 'm');\n\n\tif (!options.hideSeconds) {\n\t\tif (\n\t\t\toptions.separateMilliseconds\n\t\t\t|| options.formatSubMilliseconds\n\t\t\t|| (!options.colonNotation && milliseconds < 1000 && !options.subSecondsAsDecimals)\n\t\t) {\n\t\t\tconst seconds = Number(parsed.seconds);\n\t\t\tconst milliseconds = Number(parsed.milliseconds);\n\t\t\tconst microseconds = Number(parsed.microseconds);\n\t\t\tconst nanoseconds = Number(parsed.nanoseconds);\n\n\t\t\tadd(seconds, 'second', 's');\n\n\t\t\tif (options.formatSubMilliseconds) {\n\t\t\t\tadd(milliseconds, 'millisecond', 'ms');\n\t\t\t\tadd(microseconds, 'microsecond', 'µs');\n\t\t\t\tadd(nanoseconds, 'nanosecond', 'ns');\n\t\t\t} else {\n\t\t\t\tconst millisecondsAndBelow\n\t\t\t\t\t= milliseconds\n\t\t\t\t\t+ (microseconds / 1000)\n\t\t\t\t\t+ (nanoseconds / 1e6);\n\n\t\t\t\tconst millisecondsDecimalDigits\n\t\t\t\t\t= typeof options.millisecondsDecimalDigits === 'number'\n\t\t\t\t\t\t? options.millisecondsDecimalDigits\n\t\t\t\t\t\t: 0;\n\n\t\t\t\tconst roundedMilliseconds = millisecondsAndBelow >= 1\n\t\t\t\t\t? Math.round(millisecondsAndBelow)\n\t\t\t\t\t: Math.ceil(millisecondsAndBelow);\n\n\t\t\t\tconst millisecondsString = millisecondsDecimalDigits\n\t\t\t\t\t? millisecondsAndBelow.toFixed(millisecondsDecimalDigits)\n\t\t\t\t\t: roundedMilliseconds;\n\n\t\t\t\tadd(\n\t\t\t\t\tNumber.parseFloat(millisecondsString),\n\t\t\t\t\t'millisecond',\n\t\t\t\t\t'ms',\n\t\t\t\t\tmillisecondsString,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tconst seconds = (\n\t\t\t\t(isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds)\n\t\t\t\t/ 1000\n\t\t\t) % 60;\n\t\t\tconst secondsDecimalDigits\n\t\t\t\t= typeof options.secondsDecimalDigits === 'number'\n\t\t\t\t\t? options.secondsDecimalDigits\n\t\t\t\t\t: 1;\n\t\t\tconst secondsFixed = floorDecimals(seconds, secondsDecimalDigits);\n\t\t\tconst secondsString = options.keepDecimalsOnWholeSeconds\n\t\t\t\t? secondsFixed\n\t\t\t\t: secondsFixed.replace(/\\.0+$/, '');\n\t\t\tadd(Number.parseFloat(secondsString), 'second', 's', secondsString);\n\t\t}\n\t}\n\n\tif (result.length === 0) {\n\t\treturn sign + '0' + (options.verbose ? ' milliseconds' : 'ms');\n\t}\n\n\tconst separator = options.colonNotation ? ':' : ' ';\n\tif (typeof options.unitCount === 'number') {\n\t\tresult = result.slice(0, Math.max(options.unitCount, 1));\n\t}\n\n\treturn sign + result.join(separator);\n}\n","import {verboseLog} from './log.js';\n\n// When `verbose` is `short|full|custom`, print each command's error when it fails\nexport const logError = (result, verboseInfo) => {\n\tif (result.failed) {\n\t\tverboseLog({\n\t\t\ttype: 'error',\n\t\t\tverboseMessage: result.shortMessage,\n\t\t\tverboseInfo,\n\t\t\tresult,\n\t\t});\n\t}\n};\n","import prettyMs from 'pretty-ms';\nimport {isVerbose} from './values.js';\nimport {verboseLog} from './log.js';\nimport {logError} from './error.js';\n\n// When `verbose` is `short|full|custom`, print each command's completion, duration and error\nexport const logResult = (result, verboseInfo) => {\n\tif (!isVerbose(verboseInfo)) {\n\t\treturn;\n\t}\n\n\tlogError(result, verboseInfo);\n\tlogDuration(result, verboseInfo);\n};\n\nconst logDuration = (result, verboseInfo) => {\n\tconst verboseMessage = `(done in ${prettyMs(result.durationMs)})`;\n\tverboseLog({\n\t\ttype: 'duration',\n\t\tverboseMessage,\n\t\tverboseInfo,\n\t\tresult,\n\t});\n};\n","import {logResult} from '../verbose/complete.js';\n\n// Applies the `reject` option.\n// Also print the final log line with `verbose`.\nexport const handleResult = (result, verboseInfo, {reject}) => {\n\tlogResult(result, verboseInfo);\n\n\tif (result.failed && reject) {\n\t\tthrow result;\n\t}\n\n\treturn result;\n};\n","import {readFileSync} from 'node:fs';\nimport {bufferToUint8Array} from '../utils/uint-array.js';\nimport {handleStdio} from './handle.js';\nimport {TYPE_TO_MESSAGE} from './type.js';\n\n// Normalize `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode\nexport const handleStdioSync = (options, verboseInfo) => handleStdio(addPropertiesSync, options, verboseInfo, true);\n\nconst forbiddenIfSync = ({type, optionName}) => {\n\tthrowInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);\n};\n\nconst forbiddenNativeIfSync = ({optionName, value}) => {\n\tif (value === 'ipc' || value === 'overlapped') {\n\t\tthrowInvalidSyncValue(optionName, `\"${value}\"`);\n\t}\n\n\treturn {};\n};\n\nconst throwInvalidSyncValue = (optionName, value) => {\n\tthrow new TypeError(`The \\`${optionName}\\` option cannot be ${value} with synchronous methods.`);\n};\n\n// Create streams used internally for redirecting when using specific values for the `std*` options, in sync mode.\n// For example, `stdin: {file}` reads the file synchronously, then passes it as the `input` option.\nconst addProperties = {\n\tgenerator() {},\n\tasyncGenerator: forbiddenIfSync,\n\twebStream: forbiddenIfSync,\n\tnodeStream: forbiddenIfSync,\n\twebTransform: forbiddenIfSync,\n\tduplex: forbiddenIfSync,\n\tasyncIterable: forbiddenIfSync,\n\tnative: forbiddenNativeIfSync,\n};\n\nconst addPropertiesSync = {\n\tinput: {\n\t\t...addProperties,\n\t\tfileUrl: ({value}) => ({contents: [bufferToUint8Array(readFileSync(value))]}),\n\t\tfilePath: ({value: {file}}) => ({contents: [bufferToUint8Array(readFileSync(file))]}),\n\t\tfileNumber: forbiddenIfSync,\n\t\titerable: ({value}) => ({contents: [...value]}),\n\t\tstring: ({value}) => ({contents: [value]}),\n\t\tuint8Array: ({value}) => ({contents: [value]}),\n\t},\n\toutput: {\n\t\t...addProperties,\n\t\tfileUrl: ({value}) => ({path: value}),\n\t\tfilePath: ({value: {file, append}}) => ({path: file, append}),\n\t\tfileNumber: ({value}) => ({path: value}),\n\t\titerable: forbiddenIfSync,\n\t\tstring: forbiddenIfSync,\n\t\tuint8Array: forbiddenIfSync,\n\t},\n};\n","import {isStream as isNodeStream, isDuplexStream} from 'is-stream';\nimport isPlainObj from 'is-plain-obj';\nimport {isUint8Array} from '../utils/uint-array.js';\n\n// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.\nexport const getStdioItemType = (value, optionName) => {\n\tif (isAsyncGenerator(value)) {\n\t\treturn 'asyncGenerator';\n\t}\n\n\tif (isSyncGenerator(value)) {\n\t\treturn 'generator';\n\t}\n\n\tif (isUrl(value)) {\n\t\treturn 'fileUrl';\n\t}\n\n\tif (isFilePathObject(value)) {\n\t\treturn 'filePath';\n\t}\n\n\tif (isWebStream(value)) {\n\t\treturn 'webStream';\n\t}\n\n\tif (isNodeStream(value, {checkOpen: false})) {\n\t\treturn 'native';\n\t}\n\n\tif (isUint8Array(value)) {\n\t\treturn 'uint8Array';\n\t}\n\n\tif (isAsyncIterableObject(value)) {\n\t\treturn 'asyncIterable';\n\t}\n\n\tif (isIterableObject(value)) {\n\t\treturn 'iterable';\n\t}\n\n\tif (isTransformStream(value)) {\n\t\treturn getTransformStreamType({transform: value}, optionName);\n\t}\n\n\tif (isTransformOptions(value)) {\n\t\treturn getTransformObjectType(value, optionName);\n\t}\n\n\treturn 'native';\n};\n\nconst getTransformObjectType = (value, optionName) => {\n\tif (isDuplexStream(value.transform, {checkOpen: false})) {\n\t\treturn getDuplexType(value, optionName);\n\t}\n\n\tif (isTransformStream(value.transform)) {\n\t\treturn getTransformStreamType(value, optionName);\n\t}\n\n\treturn getGeneratorObjectType(value, optionName);\n};\n\nconst getDuplexType = (value, optionName) => {\n\tvalidateNonGeneratorType(value, optionName, 'Duplex stream');\n\treturn 'duplex';\n};\n\nconst getTransformStreamType = (value, optionName) => {\n\tvalidateNonGeneratorType(value, optionName, 'web TransformStream');\n\treturn 'webTransform';\n};\n\nconst validateNonGeneratorType = ({final, binary, objectMode}, optionName, typeName) => {\n\tcheckUndefinedOption(final, `${optionName}.final`, typeName);\n\tcheckUndefinedOption(binary, `${optionName}.binary`, typeName);\n\tcheckBooleanOption(objectMode, `${optionName}.objectMode`);\n};\n\nconst checkUndefinedOption = (value, optionName, typeName) => {\n\tif (value !== undefined) {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option can only be defined when using a generator, not a ${typeName}.`);\n\t}\n};\n\nconst getGeneratorObjectType = ({transform, final, binary, objectMode}, optionName) => {\n\tif (transform !== undefined && !isGenerator(transform)) {\n\t\tthrow new TypeError(`The \\`${optionName}.transform\\` option must be a generator, a Duplex stream or a web TransformStream.`);\n\t}\n\n\tif (isDuplexStream(final, {checkOpen: false})) {\n\t\tthrow new TypeError(`The \\`${optionName}.final\\` option must not be a Duplex stream.`);\n\t}\n\n\tif (isTransformStream(final)) {\n\t\tthrow new TypeError(`The \\`${optionName}.final\\` option must not be a web TransformStream.`);\n\t}\n\n\tif (final !== undefined && !isGenerator(final)) {\n\t\tthrow new TypeError(`The \\`${optionName}.final\\` option must be a generator.`);\n\t}\n\n\tcheckBooleanOption(binary, `${optionName}.binary`);\n\tcheckBooleanOption(objectMode, `${optionName}.objectMode`);\n\n\treturn isAsyncGenerator(transform) || isAsyncGenerator(final) ? 'asyncGenerator' : 'generator';\n};\n\nconst checkBooleanOption = (value, optionName) => {\n\tif (value !== undefined && typeof value !== 'boolean') {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option must use a boolean.`);\n\t}\n};\n\nconst isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);\nexport const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';\nconst isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';\nconst isTransformOptions = value => isPlainObj(value)\n\t&& (value.transform !== undefined || value.final !== undefined);\n\nexport const isUrl = value => Object.prototype.toString.call(value) === '[object URL]';\nexport const isRegularUrl = value => isUrl(value) && value.protocol !== 'file:';\n\nconst isFilePathObject = value => isPlainObj(value)\n\t&& Object.keys(value).length > 0\n\t&& Object.keys(value).every(key => FILE_PATH_KEYS.has(key))\n\t&& isFilePathString(value.file);\nconst FILE_PATH_KEYS = new Set(['file', 'append']);\nexport const isFilePathString = file => typeof file === 'string';\n\nexport const isUnknownStdioString = (type, value) => type === 'native'\n\t&& typeof value === 'string'\n\t&& !KNOWN_STDIO_STRINGS.has(value);\nconst KNOWN_STDIO_STRINGS = new Set(['ipc', 'ignore', 'inherit', 'overlapped', 'pipe']);\n\nconst isReadableStream = value => Object.prototype.toString.call(value) === '[object ReadableStream]';\nexport const isWritableStream = value => Object.prototype.toString.call(value) === '[object WritableStream]';\nconst isWebStream = value => isReadableStream(value) || isWritableStream(value);\nconst isTransformStream = value => isReadableStream(value?.readable) && isWritableStream(value?.writable);\n\nconst isAsyncIterableObject = value => isObject(value) && typeof value[Symbol.asyncIterator] === 'function';\nconst isIterableObject = value => isObject(value) && typeof value[Symbol.iterator] === 'function';\nconst isObject = value => typeof value === 'object' && value !== null;\n\n// Types which modify `subprocess.std*`\nexport const TRANSFORM_TYPES = new Set(['generator', 'asyncGenerator', 'duplex', 'webTransform']);\n// Types which write to a file or a file descriptor\nexport const FILE_TYPES = new Set(['fileUrl', 'filePath', 'fileNumber']);\n// When two file descriptors of this type share the same target, we need to do some special logic\nexport const SPECIAL_DUPLICATE_TYPES_SYNC = new Set(['fileUrl', 'filePath']);\nexport const SPECIAL_DUPLICATE_TYPES = new Set([...SPECIAL_DUPLICATE_TYPES_SYNC, 'webStream', 'nodeStream']);\n// Do not allow two file descriptors of this type sharing the same target\nexport const FORBID_DUPLICATE_TYPES = new Set(['webTransform', 'duplex']);\n\n// Convert types to human-friendly strings for error messages\nexport const TYPE_TO_MESSAGE = {\n\tgenerator: 'a generator',\n\tasyncGenerator: 'an async generator',\n\tfileUrl: 'a file URL',\n\tfilePath: 'a file path string',\n\tfileNumber: 'a file descriptor number',\n\twebStream: 'a web stream',\n\tnodeStream: 'a Node.js stream',\n\twebTransform: 'a web TransformStream',\n\tduplex: 'a Duplex stream',\n\tnative: 'any value',\n\titerable: 'an iterable',\n\tasyncIterable: 'an async iterable',\n\tstring: 'a string',\n\tuint8Array: 'a Uint8Array',\n};\n","import {TRANSFORM_TYPES} from '../stdio/type.js';\n\n/*\nRetrieve the `objectMode`s of a single transform.\n`objectMode` determines the return value's type, i.e. the `readableObjectMode`.\nThe chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.\nThe last input's generator is read by `subprocess.stdin` which:\n- should not be in `objectMode` for performance reasons.\n- can only be strings, Buffers and Uint8Arrays.\nTherefore its `readableObjectMode` must be `false`.\nThe same applies to the first output's generator's `writableObjectMode`.\n*/\nexport const getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'\n\t? getOutputObjectModes(objectMode, index, newTransforms)\n\t: getInputObjectModes(objectMode, index, newTransforms);\n\nconst getOutputObjectModes = (objectMode, index, newTransforms) => {\n\tconst writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;\n\tconst readableObjectMode = objectMode ?? writableObjectMode;\n\treturn {writableObjectMode, readableObjectMode};\n};\n\nconst getInputObjectModes = (objectMode, index, newTransforms) => {\n\tconst writableObjectMode = index === 0\n\t\t? objectMode === true\n\t\t: newTransforms[index - 1].value.readableObjectMode;\n\tconst readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);\n\treturn {writableObjectMode, readableObjectMode};\n};\n\n// Retrieve the `objectMode` of a file descriptor, e.g. `stdout` or `stderr`\nexport const getFdObjectMode = (stdioItems, direction) => {\n\tconst lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));\n\tif (lastTransform === undefined) {\n\t\treturn false;\n\t}\n\n\treturn direction === 'input'\n\t\t? lastTransform.value.writableObjectMode\n\t\t: lastTransform.value.readableObjectMode;\n};\n","import isPlainObj from 'is-plain-obj';\nimport {BINARY_ENCODINGS} from '../arguments/encoding-option.js';\nimport {TRANSFORM_TYPES} from '../stdio/type.js';\nimport {getTransformObjectModes} from './object-mode.js';\n\n// Transforms generators/duplex/TransformStream can have multiple shapes.\n// This normalizes it and applies default values.\nexport const normalizeTransforms = (stdioItems, optionName, direction, options) => [\n\t...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),\n\t...getTransforms(stdioItems, optionName, direction, options),\n];\n\nconst getTransforms = (stdioItems, optionName, direction, {encoding}) => {\n\tconst transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));\n\tconst newTransforms = Array.from({length: transforms.length});\n\n\tfor (const [index, stdioItem] of Object.entries(transforms)) {\n\t\tnewTransforms[index] = normalizeTransform({\n\t\t\tstdioItem,\n\t\t\tindex: Number(index),\n\t\t\tnewTransforms,\n\t\t\toptionName,\n\t\t\tdirection,\n\t\t\tencoding,\n\t\t});\n\t}\n\n\treturn sortTransforms(newTransforms, direction);\n};\n\nconst normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {\n\tif (type === 'duplex') {\n\t\treturn normalizeDuplex({stdioItem, optionName});\n\t}\n\n\tif (type === 'webTransform') {\n\t\treturn normalizeTransformStream({\n\t\t\tstdioItem,\n\t\t\tindex,\n\t\t\tnewTransforms,\n\t\t\tdirection,\n\t\t});\n\t}\n\n\treturn normalizeGenerator({\n\t\tstdioItem,\n\t\tindex,\n\t\tnewTransforms,\n\t\tdirection,\n\t\tencoding,\n\t});\n};\n\nconst normalizeDuplex = ({\n\tstdioItem,\n\tstdioItem: {\n\t\tvalue: {\n\t\t\ttransform,\n\t\t\ttransform: {writableObjectMode, readableObjectMode},\n\t\t\tobjectMode = readableObjectMode,\n\t\t},\n\t},\n\toptionName,\n}) => {\n\tif (objectMode && !readableObjectMode) {\n\t\tthrow new TypeError(`The \\`${optionName}.objectMode\\` option can only be \\`true\\` if \\`new Duplex({objectMode: true})\\` is used.`);\n\t}\n\n\tif (!objectMode && readableObjectMode) {\n\t\tthrow new TypeError(`The \\`${optionName}.objectMode\\` option cannot be \\`false\\` if \\`new Duplex({objectMode: true})\\` is used.`);\n\t}\n\n\treturn {\n\t\t...stdioItem,\n\t\tvalue: {transform, writableObjectMode, readableObjectMode},\n\t};\n};\n\nconst normalizeTransformStream = ({stdioItem, stdioItem: {value}, index, newTransforms, direction}) => {\n\tconst {transform, objectMode} = isPlainObj(value) ? value : {transform: value};\n\tconst {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);\n\treturn ({\n\t\t...stdioItem,\n\t\tvalue: {transform, writableObjectMode, readableObjectMode},\n\t});\n};\n\nconst normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {\n\tconst {\n\t\ttransform,\n\t\tfinal,\n\t\tbinary: binaryOption = false,\n\t\tpreserveNewlines = false,\n\t\tobjectMode,\n\t} = isPlainObj(value) ? value : {transform: value};\n\tconst binary = binaryOption || BINARY_ENCODINGS.has(encoding);\n\tconst {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);\n\treturn {\n\t\t...stdioItem,\n\t\tvalue: {\n\t\t\ttransform,\n\t\t\tfinal,\n\t\t\tbinary,\n\t\t\tpreserveNewlines,\n\t\t\twritableObjectMode,\n\t\t\treadableObjectMode,\n\t\t},\n\t};\n};\n\nconst sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;\n","import process from 'node:process';\nimport {\n\tisStream as isNodeStream,\n\tisReadableStream as isNodeReadableStream,\n\tisWritableStream as isNodeWritableStream,\n} from 'is-stream';\nimport {isWritableStream} from './type.js';\n\n// For `stdio[fdNumber]` beyond stdin/stdout/stderr, we need to guess whether the value passed is intended for inputs or outputs.\n// This allows us to know whether to pipe _into_ or _from_ the stream.\n// When `stdio[fdNumber]` is a single value, this guess is fairly straightforward.\n// However, when it is an array instead, we also need to make sure the different values are not incompatible with each other.\nexport const getStreamDirection = (stdioItems, fdNumber, optionName) => {\n\tconst directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber));\n\n\tif (directions.includes('input') && directions.includes('output')) {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option must not be an array of both readable and writable values.`);\n\t}\n\n\treturn directions.find(Boolean) ?? DEFAULT_DIRECTION;\n};\n\nconst getStdioItemDirection = ({type, value}, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value);\n\n// `stdin`/`stdout`/`stderr` have a known direction\nconst KNOWN_DIRECTIONS = ['input', 'output', 'output'];\n\nconst anyDirection = () => undefined;\nconst alwaysInput = () => 'input';\n\n// `string` can only be added through the `input` option, i.e. does not need to be handled here\nconst guessStreamDirection = {\n\tgenerator: anyDirection,\n\tasyncGenerator: anyDirection,\n\tfileUrl: anyDirection,\n\tfilePath: anyDirection,\n\titerable: alwaysInput,\n\tasyncIterable: alwaysInput,\n\tuint8Array: alwaysInput,\n\twebStream: value => isWritableStream(value) ? 'output' : 'input',\n\tnodeStream(value) {\n\t\tif (!isNodeReadableStream(value, {checkOpen: false})) {\n\t\t\treturn 'output';\n\t\t}\n\n\t\treturn isNodeWritableStream(value, {checkOpen: false}) ? undefined : 'input';\n\t},\n\twebTransform: anyDirection,\n\tduplex: anyDirection,\n\tnative(value) {\n\t\tconst standardStreamDirection = getStandardStreamDirection(value);\n\t\tif (standardStreamDirection !== undefined) {\n\t\t\treturn standardStreamDirection;\n\t\t}\n\n\t\tif (isNodeStream(value, {checkOpen: false})) {\n\t\t\treturn guessStreamDirection.nodeStream(value);\n\t\t}\n\t},\n};\n\nconst getStandardStreamDirection = value => {\n\tif ([0, process.stdin].includes(value)) {\n\t\treturn 'input';\n\t}\n\n\tif ([1, 2, process.stdout, process.stderr].includes(value)) {\n\t\treturn 'output';\n\t}\n};\n\n// When ambiguous, we initially keep the direction as `undefined`.\n// This allows arrays of `stdio` values to resolve the ambiguity.\n// For example, `stdio[3]: DuplexStream` is ambiguous, but `stdio[3]: [DuplexStream, WritableStream]` is not.\n// When the ambiguity remains, we default to `output` since it is the most common use case for additional file descriptors.\nconst DEFAULT_DIRECTION = 'output';\n","// The `ipc` option adds an `ipc` item to the `stdio` option\nexport const normalizeIpcStdioArray = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')\n\t? [...stdioArray, 'ipc']\n\t: stdioArray;\n","import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';\nimport {normalizeIpcStdioArray} from '../ipc/array.js';\nimport {isFullVerbose} from '../verbose/values.js';\n\n// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.\n// Also normalize the `stdio` option.\nexport const normalizeStdioOption = ({stdio, ipc, buffer, ...options}, verboseInfo, isSync) => {\n\tconst stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));\n\treturn isSync\n\t\t? normalizeStdioSync(stdioArray, buffer, verboseInfo)\n\t\t: normalizeIpcStdioArray(stdioArray, ipc);\n};\n\nconst getStdioArray = (stdio, options) => {\n\tif (stdio === undefined) {\n\t\treturn STANDARD_STREAMS_ALIASES.map(alias => options[alias]);\n\t}\n\n\tif (hasAlias(options)) {\n\t\tthrow new Error(`It's not possible to provide \\`stdio\\` in combination with one of ${STANDARD_STREAMS_ALIASES.map(alias => `\\`${alias}\\``).join(', ')}`);\n\t}\n\n\tif (typeof stdio === 'string') {\n\t\treturn [stdio, stdio, stdio];\n\t}\n\n\tif (!Array.isArray(stdio)) {\n\t\tthrow new TypeError(`Expected \\`stdio\\` to be of type \\`string\\` or \\`Array\\`, got \\`${typeof stdio}\\``);\n\t}\n\n\tconst length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);\n\treturn Array.from({length}, (_, fdNumber) => stdio[fdNumber]);\n};\n\nconst hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);\n\nconst addDefaultValue = (stdioOption, fdNumber) => {\n\tif (Array.isArray(stdioOption)) {\n\t\treturn stdioOption.map(item => addDefaultValue(item, fdNumber));\n\t}\n\n\tif (stdioOption === null || stdioOption === undefined) {\n\t\treturn fdNumber >= STANDARD_STREAMS_ALIASES.length ? 'ignore' : 'pipe';\n\t}\n\n\treturn stdioOption;\n};\n\n// Using `buffer: false` with synchronous methods implies `stdout`/`stderr`: `ignore`.\n// Unless the output is needed, e.g. due to `verbose: 'full'` or to redirecting to a file.\nconst normalizeStdioSync = (stdioArray, buffer, verboseInfo) => stdioArray.map((stdioOption, fdNumber) =>\n\t!buffer[fdNumber]\n\t&& fdNumber !== 0\n\t&& !isFullVerbose(verboseInfo, fdNumber)\n\t&& isOutputPipeOnly(stdioOption)\n\t\t? 'ignore'\n\t\t: stdioOption);\n\nconst isOutputPipeOnly = stdioOption => stdioOption === 'pipe'\n\t|| (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));\n","import {readFileSync} from 'node:fs';\nimport tty from 'node:tty';\nimport {isStream as isNodeStream} from 'is-stream';\nimport {STANDARD_STREAMS} from '../utils/standard-stream.js';\nimport {bufferToUint8Array} from '../utils/uint-array.js';\nimport {serializeOptionValue} from '../arguments/fd-options.js';\n\n// When we use multiple `stdio` values for the same streams, we pass 'pipe' to `child_process.spawn()`.\n// We then emulate the piping done by core Node.js.\n// To do so, we transform the following values:\n//  - Node.js streams are marked as `type: nodeStream`\n//  - 'inherit' becomes `process.stdin|stdout|stderr`\n//  - any file descriptor integer becomes `process.stdio[fdNumber]`\n// All of the above transformations tell Execa to perform manual piping.\nexport const handleNativeStream = ({stdioItem, stdioItem: {type}, isStdioArray, fdNumber, direction, isSync}) => {\n\tif (!isStdioArray || type !== 'native') {\n\t\treturn stdioItem;\n\t}\n\n\treturn isSync\n\t\t? handleNativeStreamSync({stdioItem, fdNumber, direction})\n\t\t: handleNativeStreamAsync({stdioItem, fdNumber});\n};\n\n// Synchronous methods use a different logic.\n// 'inherit', file descriptors and process.std* are handled by readFileSync()/writeFileSync().\nconst handleNativeStreamSync = ({stdioItem, stdioItem: {value, optionName}, fdNumber, direction}) => {\n\tconst targetFd = getTargetFd({\n\t\tvalue,\n\t\toptionName,\n\t\tfdNumber,\n\t\tdirection,\n\t});\n\tif (targetFd !== undefined) {\n\t\treturn targetFd;\n\t}\n\n\tif (isNodeStream(value, {checkOpen: false})) {\n\t\tthrow new TypeError(`The \\`${optionName}: Stream\\` option cannot both be an array and include a stream with synchronous methods.`);\n\t}\n\n\treturn stdioItem;\n};\n\nconst getTargetFd = ({value, optionName, fdNumber, direction}) => {\n\tconst targetFdNumber = getTargetFdNumber(value, fdNumber);\n\tif (targetFdNumber === undefined) {\n\t\treturn;\n\t}\n\n\tif (direction === 'output') {\n\t\treturn {type: 'fileNumber', value: targetFdNumber, optionName};\n\t}\n\n\tif (tty.isatty(targetFdNumber)) {\n\t\tthrow new TypeError(`The \\`${optionName}: ${serializeOptionValue(value)}\\` option is invalid: it cannot be a TTY with synchronous methods.`);\n\t}\n\n\treturn {type: 'uint8Array', value: bufferToUint8Array(readFileSync(targetFdNumber)), optionName};\n};\n\nconst getTargetFdNumber = (value, fdNumber) => {\n\tif (value === 'inherit') {\n\t\treturn fdNumber;\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn value;\n\t}\n\n\tconst standardStreamIndex = STANDARD_STREAMS.indexOf(value);\n\tif (standardStreamIndex !== -1) {\n\t\treturn standardStreamIndex;\n\t}\n};\n\nconst handleNativeStreamAsync = ({stdioItem, stdioItem: {value, optionName}, fdNumber}) => {\n\tif (value === 'inherit') {\n\t\treturn {type: 'nodeStream', value: getStandardStream(fdNumber, value, optionName), optionName};\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn {type: 'nodeStream', value: getStandardStream(value, value, optionName), optionName};\n\t}\n\n\tif (isNodeStream(value, {checkOpen: false})) {\n\t\treturn {type: 'nodeStream', value, optionName};\n\t}\n\n\treturn stdioItem;\n};\n\n// Node.js does not allow to easily retrieve file descriptors beyond stdin/stdout/stderr as streams.\n//  - `fs.createReadStream()`/`fs.createWriteStream()` with the `fd` option do not work with character devices that use blocking reads/writes (such as interactive TTYs).\n//  - Using a TCP `Socket` would work but be rather complex to implement.\n// Since this is an edge case, we simply throw an error message.\n// See https://github.com/sindresorhus/execa/pull/643#discussion_r1435905707\nconst getStandardStream = (fdNumber, value, optionName) => {\n\tconst standardStream = STANDARD_STREAMS[fdNumber];\n\n\tif (standardStream === undefined) {\n\t\tthrow new TypeError(`The \\`${optionName}: ${value}\\` option is invalid: no such standard stream.`);\n\t}\n\n\treturn standardStream;\n};\n","import {isReadableStream} from 'is-stream';\nimport {isUint8Array} from '../utils/uint-array.js';\nimport {isUrl, isFilePathString} from './type.js';\n\n// Append the `stdin` option with the `input` and `inputFile` options\nexport const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 0\n\t? [\n\t\t...handleInputOption(input),\n\t\t...handleInputFileOption(inputFile),\n\t]\n\t: [];\n\nconst handleInputOption = input => input === undefined ? [] : [{\n\ttype: getInputType(input),\n\tvalue: input,\n\toptionName: 'input',\n}];\n\nconst getInputType = input => {\n\tif (isReadableStream(input, {checkOpen: false})) {\n\t\treturn 'nodeStream';\n\t}\n\n\tif (typeof input === 'string') {\n\t\treturn 'string';\n\t}\n\n\tif (isUint8Array(input)) {\n\t\treturn 'uint8Array';\n\t}\n\n\tthrow new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');\n};\n\nconst handleInputFileOption = inputFile => inputFile === undefined ? [] : [{\n\t...getInputFileType(inputFile),\n\toptionName: 'inputFile',\n}];\n\nconst getInputFileType = inputFile => {\n\tif (isUrl(inputFile)) {\n\t\treturn {type: 'fileUrl', value: inputFile};\n\t}\n\n\tif (isFilePathString(inputFile)) {\n\t\treturn {type: 'filePath', value: {file: inputFile}};\n\t}\n\n\tthrow new Error('The `inputFile` option must be a file path string or a file URL.');\n};\n","import {\n\tSPECIAL_DUPLICATE_TYPES_SYNC,\n\tSPECIAL_DUPLICATE_TYPES,\n\tFORBID_DUPLICATE_TYPES,\n\tTYPE_TO_MESSAGE,\n} from './type.js';\n\n// Duplicates in the same file descriptor is most likely an error.\n// However, this can be useful with generators.\nexport const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>\n\tstdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value\n\t\t|| indexOne >= indexTwo\n\t\t|| stdioItemOne.type === 'generator'\n\t\t|| stdioItemOne.type === 'asyncGenerator'));\n\n// Check if two file descriptors are sharing the same target.\n// For example `{stdout: {file: './output.txt'}, stderr: {file: './output.txt'}}`.\nexport const getDuplicateStream = ({stdioItem: {type, value, optionName}, direction, fileDescriptors, isSync}) => {\n\tconst otherStdioItems = getOtherStdioItems(fileDescriptors, type);\n\tif (otherStdioItems.length === 0) {\n\t\treturn;\n\t}\n\n\tif (isSync) {\n\t\tvalidateDuplicateStreamSync({\n\t\t\totherStdioItems,\n\t\t\ttype,\n\t\t\tvalue,\n\t\t\toptionName,\n\t\t\tdirection,\n\t\t});\n\t\treturn;\n\t}\n\n\tif (SPECIAL_DUPLICATE_TYPES.has(type)) {\n\t\treturn getDuplicateStreamInstance({\n\t\t\totherStdioItems,\n\t\t\ttype,\n\t\t\tvalue,\n\t\t\toptionName,\n\t\t\tdirection,\n\t\t});\n\t}\n\n\tif (FORBID_DUPLICATE_TYPES.has(type)) {\n\t\tvalidateDuplicateTransform({\n\t\t\totherStdioItems,\n\t\t\ttype,\n\t\t\tvalue,\n\t\t\toptionName,\n\t\t});\n\t}\n};\n\n// Values shared by multiple file descriptors\nconst getOtherStdioItems = (fileDescriptors, type) => fileDescriptors\n\t.flatMap(({direction, stdioItems}) => stdioItems\n\t\t.filter(stdioItem => stdioItem.type === type)\n\t\t.map((stdioItem => ({...stdioItem, direction}))));\n\n// With `execaSync()`, do not allow setting a file path both in input and output\nconst validateDuplicateStreamSync = ({otherStdioItems, type, value, optionName, direction}) => {\n\tif (SPECIAL_DUPLICATE_TYPES_SYNC.has(type)) {\n\t\tgetDuplicateStreamInstance({\n\t\t\totherStdioItems,\n\t\t\ttype,\n\t\t\tvalue,\n\t\t\toptionName,\n\t\t\tdirection,\n\t\t});\n\t}\n};\n\n// When two file descriptors share the file or stream, we need to re-use the same underlying stream.\n// Otherwise, the stream would be closed twice when piping ends.\n// This is only an issue with output file descriptors.\n// This is not a problem with generator functions since those create a new instance for each file descriptor.\n// We also forbid input and output file descriptors sharing the same file or stream, since that does not make sense.\nconst getDuplicateStreamInstance = ({otherStdioItems, type, value, optionName, direction}) => {\n\tconst duplicateStdioItems = otherStdioItems.filter(stdioItem => hasSameValue(stdioItem, value));\n\tif (duplicateStdioItems.length === 0) {\n\t\treturn;\n\t}\n\n\tconst differentStdioItem = duplicateStdioItems.find(stdioItem => stdioItem.direction !== direction);\n\tthrowOnDuplicateStream(differentStdioItem, optionName, type);\n\n\treturn direction === 'output' ? duplicateStdioItems[0].stream : undefined;\n};\n\nconst hasSameValue = ({type, value}, secondValue) => {\n\tif (type === 'filePath') {\n\t\treturn value.file === secondValue.file;\n\t}\n\n\tif (type === 'fileUrl') {\n\t\treturn value.href === secondValue.href;\n\t}\n\n\treturn value === secondValue;\n};\n\n// We do not allow two file descriptors to share the same Duplex or TransformStream.\n// This is because those are set directly to `subprocess.std*`.\n// For example, this could result in `subprocess.stdout` and `subprocess.stderr` being the same value.\n// This means reading from either would get data from both stdout and stderr.\nconst validateDuplicateTransform = ({otherStdioItems, type, value, optionName}) => {\n\tconst duplicateStdioItem = otherStdioItems.find(({value: {transform}}) => transform === value.transform);\n\tthrowOnDuplicateStream(duplicateStdioItem, optionName, type);\n};\n\nconst throwOnDuplicateStream = (stdioItem, optionName, type) => {\n\tif (stdioItem !== undefined) {\n\t\tthrow new TypeError(`The \\`${stdioItem.optionName}\\` and \\`${optionName}\\` options must not target ${TYPE_TO_MESSAGE[type]} that is the same.`);\n\t}\n};\n","import {getStreamName, isStandardStream} from '../utils/standard-stream.js';\nimport {normalizeTransforms} from '../transform/normalize.js';\nimport {getFdObjectMode} from '../transform/object-mode.js';\nimport {\n\tgetStdioItemType,\n\tisRegularUrl,\n\tisUnknownStdioString,\n\tFILE_TYPES,\n} from './type.js';\nimport {getStreamDirection} from './direction.js';\nimport {normalizeStdioOption} from './stdio-option.js';\nimport {handleNativeStream} from './native.js';\nimport {handleInputOptions} from './input-option.js';\nimport {filterDuplicates, getDuplicateStream} from './duplicate.js';\n\n// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode\n// They are converted into an array of `fileDescriptors`.\n// Each `fileDescriptor` is normalized, validated and contains all information necessary for further handling.\nexport const handleStdio = (addProperties, options, verboseInfo, isSync) => {\n\tconst stdio = normalizeStdioOption(options, verboseInfo, isSync);\n\tconst initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({\n\t\tstdioOption,\n\t\tfdNumber,\n\t\toptions,\n\t\tisSync,\n\t}));\n\tconst fileDescriptors = getFinalFileDescriptors({\n\t\tinitialFileDescriptors,\n\t\taddProperties,\n\t\toptions,\n\t\tisSync,\n\t});\n\toptions.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));\n\treturn fileDescriptors;\n};\n\nconst getFileDescriptor = ({stdioOption, fdNumber, options, isSync}) => {\n\tconst optionName = getStreamName(fdNumber);\n\tconst {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({\n\t\tstdioOption,\n\t\tfdNumber,\n\t\toptions,\n\t\toptionName,\n\t});\n\tconst direction = getStreamDirection(initialStdioItems, fdNumber, optionName);\n\tconst stdioItems = initialStdioItems.map(stdioItem => handleNativeStream({\n\t\tstdioItem,\n\t\tisStdioArray,\n\t\tfdNumber,\n\t\tdirection,\n\t\tisSync,\n\t}));\n\tconst normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);\n\tconst objectMode = getFdObjectMode(normalizedStdioItems, direction);\n\tvalidateFileObjectMode(normalizedStdioItems, objectMode);\n\treturn {direction, objectMode, stdioItems: normalizedStdioItems};\n};\n\n// We make sure passing an array with a single item behaves the same as passing that item without an array.\n// This is what users would expect.\n// For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.\nconst initializeStdioItems = ({stdioOption, fdNumber, options, optionName}) => {\n\tconst values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];\n\tconst initialStdioItems = [\n\t\t...values.map(value => initializeStdioItem(value, optionName)),\n\t\t...handleInputOptions(options, fdNumber),\n\t];\n\n\tconst stdioItems = filterDuplicates(initialStdioItems);\n\tconst isStdioArray = stdioItems.length > 1;\n\tvalidateStdioArray(stdioItems, isStdioArray, optionName);\n\tvalidateStreams(stdioItems);\n\treturn {stdioItems, isStdioArray};\n};\n\nconst initializeStdioItem = (value, optionName) => ({\n\ttype: getStdioItemType(value, optionName),\n\tvalue,\n\toptionName,\n});\n\nconst validateStdioArray = (stdioItems, isStdioArray, optionName) => {\n\tif (stdioItems.length === 0) {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option must not be an empty array.`);\n\t}\n\n\tif (!isStdioArray) {\n\t\treturn;\n\t}\n\n\tfor (const {value, optionName} of stdioItems) {\n\t\tif (INVALID_STDIO_ARRAY_OPTIONS.has(value)) {\n\t\t\tthrow new Error(`The \\`${optionName}\\` option must not include \\`${value}\\`.`);\n\t\t}\n\t}\n};\n\n// Using those `stdio` values together with others for the same stream does not make sense, so we make it fail.\n// However, we do allow it if the array has a single item.\nconst INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore', 'ipc']);\n\nconst validateStreams = stdioItems => {\n\tfor (const stdioItem of stdioItems) {\n\t\tvalidateFileStdio(stdioItem);\n\t}\n};\n\nconst validateFileStdio = ({type, value, optionName}) => {\n\tif (isRegularUrl(value)) {\n\t\tthrow new TypeError(`The \\`${optionName}: URL\\` option must use the \\`file:\\` scheme.\nFor example, you can use the \\`pathToFileURL()\\` method of the \\`url\\` core module.`);\n\t}\n\n\tif (isUnknownStdioString(type, value)) {\n\t\tthrow new TypeError(`The \\`${optionName}: { file: '...' }\\` option must be used instead of \\`${optionName}: '...'\\`.`);\n\t}\n};\n\nconst validateFileObjectMode = (stdioItems, objectMode) => {\n\tif (!objectMode) {\n\t\treturn;\n\t}\n\n\tconst fileStdioItem = stdioItems.find(({type}) => FILE_TYPES.has(type));\n\tif (fileStdioItem !== undefined) {\n\t\tthrow new TypeError(`The \\`${fileStdioItem.optionName}\\` option cannot use both files and transforms in objectMode.`);\n\t}\n};\n\n// Some `stdio` values require Execa to create streams.\n// For example, file paths create file read/write streams.\n// Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.\nconst getFinalFileDescriptors = ({initialFileDescriptors, addProperties, options, isSync}) => {\n\tconst fileDescriptors = [];\n\n\ttry {\n\t\tfor (const fileDescriptor of initialFileDescriptors) {\n\t\t\tfileDescriptors.push(getFinalFileDescriptor({\n\t\t\t\tfileDescriptor,\n\t\t\t\tfileDescriptors,\n\t\t\t\taddProperties,\n\t\t\t\toptions,\n\t\t\t\tisSync,\n\t\t\t}));\n\t\t}\n\n\t\treturn fileDescriptors;\n\t} catch (error) {\n\t\tcleanupCustomStreams(fileDescriptors);\n\t\tthrow error;\n\t}\n};\n\nconst getFinalFileDescriptor = ({\n\tfileDescriptor: {direction, objectMode, stdioItems},\n\tfileDescriptors,\n\taddProperties,\n\toptions,\n\tisSync,\n}) => {\n\tconst finalStdioItems = stdioItems.map(stdioItem => addStreamProperties({\n\t\tstdioItem,\n\t\taddProperties,\n\t\tdirection,\n\t\toptions,\n\t\tfileDescriptors,\n\t\tisSync,\n\t}));\n\treturn {direction, objectMode, stdioItems: finalStdioItems};\n};\n\nconst addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {\n\tconst duplicateStream = getDuplicateStream({\n\t\tstdioItem,\n\t\tdirection,\n\t\tfileDescriptors,\n\t\tisSync,\n\t});\n\n\tif (duplicateStream !== undefined) {\n\t\treturn {...stdioItem, stream: duplicateStream};\n\t}\n\n\treturn {\n\t\t...stdioItem,\n\t\t...addProperties[direction][stdioItem.type](stdioItem, options),\n\t};\n};\n\n// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.\n// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.\n// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.\n// Like this, an exception would be thrown, which would prevent spawning a subprocess.\nexport const cleanupCustomStreams = fileDescriptors => {\n\tfor (const {stdioItems} of fileDescriptors) {\n\t\tfor (const {stream} of stdioItems) {\n\t\t\tif (stream !== undefined && !isStandardStream(stream)) {\n\t\t\t\tstream.destroy();\n\t\t\t}\n\t\t}\n\t}\n};\n\n// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.\n// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `subprocess.std*`.\n// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.\nconst forwardStdio = stdioItems => {\n\tif (stdioItems.length > 1) {\n\t\treturn stdioItems.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';\n\t}\n\n\tconst [{type, value}] = stdioItems;\n\treturn type === 'native' ? value : 'pipe';\n};\n","import stripFinalNewlineFunction from 'strip-final-newline';\n\n// Apply `stripFinalNewline` option, which applies to `result.stdout|stderr|all|stdio[*]`.\n// If the `lines` option is used, it is applied on each line, but using a different function.\nexport const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)\n\t? stripFinalNewlineFunction(value)\n\t: value;\n\n// Retrieve `stripFinalNewline` option value, including with `subprocess.all`\nexport const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'\n\t? stripFinalNewline[1] || stripFinalNewline[2]\n\t: stripFinalNewline[fdNumber];\n","import {Transform, getDefaultHighWaterMark} from 'node:stream';\nimport {isAsyncGenerator} from '../stdio/type.js';\nimport {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';\nimport {getValidateTransformInput, getValidateTransformReturn} from './validate.js';\nimport {getEncodingTransformGenerator} from './encoding-transform.js';\nimport {\n\tpushChunks,\n\ttransformChunk,\n\tfinalChunks,\n\tdestroyTransform,\n} from './run-async.js';\nimport {\n\tpushChunksSync,\n\ttransformChunkSync,\n\tfinalChunksSync,\n\trunTransformSync,\n} from './run-sync.js';\n\n/*\nGenerators can be used to transform/filter standard streams.\n\nGenerators have a simple syntax, yet allows all of the following:\n- Sharing `state` between chunks\n- Flushing logic, by using a `final` function\n- Asynchronous logic\n- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`\n- Filtering, by using no `yield`\n\nTherefore, there is no need to allow Node.js or web transform streams.\n\nThe `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.\n\nChunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.\n\nTransform an array of generator functions into a `Transform` stream.\n`Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.\n*/\nexport const generatorToStream = ({\n\tvalue,\n\tvalue: {transform, final, writableObjectMode, readableObjectMode},\n\toptionName,\n}, {encoding}) => {\n\tconst state = {};\n\tconst generators = addInternalGenerators(value, encoding, optionName);\n\n\tconst transformAsync = isAsyncGenerator(transform);\n\tconst finalAsync = isAsyncGenerator(final);\n\tconst transformMethod = transformAsync\n\t\t? pushChunks.bind(undefined, transformChunk, state)\n\t\t: pushChunksSync.bind(undefined, transformChunkSync);\n\tconst finalMethod = transformAsync || finalAsync\n\t\t? pushChunks.bind(undefined, finalChunks, state)\n\t\t: pushChunksSync.bind(undefined, finalChunksSync);\n\tconst destroyMethod = transformAsync || finalAsync\n\t\t? destroyTransform.bind(undefined, state)\n\t\t: undefined;\n\n\tconst stream = new Transform({\n\t\twritableObjectMode,\n\t\twritableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),\n\t\treadableObjectMode,\n\t\treadableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),\n\t\ttransform(chunk, encoding, done) {\n\t\t\ttransformMethod([chunk, generators, 0], this, done);\n\t\t},\n\t\tflush(done) {\n\t\t\tfinalMethod([generators], this, done);\n\t\t},\n\t\tdestroy: destroyMethod,\n\t});\n\treturn {stream};\n};\n\n// Applies transform generators in sync mode\nexport const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {\n\tconst generators = stdioItems.filter(({type}) => type === 'generator');\n\tconst reversedGenerators = isInput ? generators.reverse() : generators;\n\n\tfor (const {value, optionName} of reversedGenerators) {\n\t\tconst generators = addInternalGenerators(value, encoding, optionName);\n\t\tchunks = runTransformSync(generators, chunks);\n\t}\n\n\treturn chunks;\n};\n\n// Generators used internally to convert the chunk type, validate it, and split into lines\nconst addInternalGenerators = (\n\t{transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},\n\tencoding,\n\toptionName,\n) => {\n\tconst state = {};\n\treturn [\n\t\t{transform: getValidateTransformInput(writableObjectMode, optionName)},\n\t\tgetEncodingTransformGenerator(binary, encoding, writableObjectMode),\n\t\tgetSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),\n\t\t{transform, final},\n\t\t{transform: getValidateTransformReturn(readableObjectMode, optionName)},\n\t\tgetAppendNewlineGenerator({\n\t\t\tbinary,\n\t\t\tpreserveNewlines,\n\t\t\treadableObjectMode,\n\t\t\tstate,\n\t\t}),\n\t].filter(Boolean);\n};\n","// Split chunks line-wise for generators passed to the `std*` options\nexport const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped\n\t? undefined\n\t: initializeSplitLines(preserveNewlines, state);\n\n// Same but for synchronous methods\nexport const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode\n\t? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))\n\t: splitLinesItemSync(chunk, preserveNewlines);\n\nconst splitLinesItemSync = (chunk, preserveNewlines) => {\n\tconst {transform, final} = initializeSplitLines(preserveNewlines, {});\n\treturn [...transform(chunk), ...final()];\n};\n\nconst initializeSplitLines = (preserveNewlines, state) => {\n\tstate.previousChunks = '';\n\treturn {\n\t\ttransform: splitGenerator.bind(undefined, state, preserveNewlines),\n\t\tfinal: linesFinal.bind(undefined, state),\n\t};\n};\n\n// This imperative logic is much faster than using `String.split()` and uses very low memory.\nconst splitGenerator = function * (state, preserveNewlines, chunk) {\n\tif (typeof chunk !== 'string') {\n\t\tyield chunk;\n\t\treturn;\n\t}\n\n\tlet {previousChunks} = state;\n\tlet start = -1;\n\n\tfor (let end = 0; end < chunk.length; end += 1) {\n\t\tif (chunk[end] === '\\n') {\n\t\t\tconst newlineLength = getNewlineLength(chunk, end, preserveNewlines, state);\n\t\t\tlet line = chunk.slice(start + 1, end + 1 - newlineLength);\n\n\t\t\tif (previousChunks.length > 0) {\n\t\t\t\tline = concatString(previousChunks, line);\n\t\t\t\tpreviousChunks = '';\n\t\t\t}\n\n\t\t\tyield line;\n\t\t\tstart = end;\n\t\t}\n\t}\n\n\tif (start !== chunk.length - 1) {\n\t\tpreviousChunks = concatString(previousChunks, chunk.slice(start + 1));\n\t}\n\n\tstate.previousChunks = previousChunks;\n};\n\nconst getNewlineLength = (chunk, end, preserveNewlines, state) => {\n\tif (preserveNewlines) {\n\t\treturn 0;\n\t}\n\n\tstate.isWindowsNewline = end !== 0 && chunk[end - 1] === '\\r';\n\treturn state.isWindowsNewline ? 2 : 1;\n};\n\nconst linesFinal = function * ({previousChunks}) {\n\tif (previousChunks.length > 0) {\n\t\tyield previousChunks;\n\t}\n};\n\n// Unless `preserveNewlines: true` is used, we strip the newline of each line.\n// This re-adds them after the user `transform` code has run.\nexport const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode\n\t? undefined\n\t: {transform: appendNewlineGenerator.bind(undefined, state)};\n\nconst appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {\n\tconst {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;\n\n\tif (chunk.at(-1) === LF) {\n\t\tyield chunk;\n\t\treturn;\n\t}\n\n\tconst newline = isWindowsNewline ? windowsNewline : unixNewline;\n\tyield concatBytes(chunk, newline);\n};\n\nconst concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;\n\nconst linesStringInfo = {\n\twindowsNewline: '\\r\\n',\n\tunixNewline: '\\n',\n\tLF: '\\n',\n\tconcatBytes: concatString,\n};\n\nconst concatUint8Array = (firstChunk, secondChunk) => {\n\tconst chunk = new Uint8Array(firstChunk.length + secondChunk.length);\n\tchunk.set(firstChunk, 0);\n\tchunk.set(secondChunk, firstChunk.length);\n\treturn chunk;\n};\n\nconst linesUint8ArrayInfo = {\n\twindowsNewline: new Uint8Array([0x0D, 0x0A]),\n\tunixNewline: new Uint8Array([0x0A]),\n\tLF: 0x0A,\n\tconcatBytes: concatUint8Array,\n};\n","import {Buffer} from 'node:buffer';\nimport {isUint8Array} from '../utils/uint-array.js';\n\n// Validate the type of chunk argument passed to transform generators\nexport const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode\n\t? undefined\n\t: validateStringTransformInput.bind(undefined, optionName);\n\nconst validateStringTransformInput = function * (optionName, chunk) {\n\tif (typeof chunk !== 'string' && !isUint8Array(chunk) && !Buffer.isBuffer(chunk)) {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option's transform must use \"objectMode: true\" to receive as input: ${typeof chunk}.`);\n\t}\n\n\tyield chunk;\n};\n\n// Validate the type of the value returned by transform generators\nexport const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode\n\t? validateObjectTransformReturn.bind(undefined, optionName)\n\t: validateStringTransformReturn.bind(undefined, optionName);\n\nconst validateObjectTransformReturn = function * (optionName, chunk) {\n\tvalidateEmptyReturn(optionName, chunk);\n\tyield chunk;\n};\n\nconst validateStringTransformReturn = function * (optionName, chunk) {\n\tvalidateEmptyReturn(optionName, chunk);\n\n\tif (typeof chunk !== 'string' && !isUint8Array(chunk)) {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`);\n\t}\n\n\tyield chunk;\n};\n\nconst validateEmptyReturn = (optionName, chunk) => {\n\tif (chunk === null || chunk === undefined) {\n\t\tthrow new TypeError(`The \\`${optionName}\\` option's function must not call \\`yield ${chunk}\\`.\nInstead, \\`yield\\` should either be called with a value, or not be called at all. For example:\n  if (condition) { yield value; }`);\n\t}\n};\n","import {Buffer} from 'node:buffer';\nimport {StringDecoder} from 'node:string_decoder';\nimport {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';\n\n/*\nWhen using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.\nChunks might be Buffer, Uint8Array or strings since:\n- `subprocess.stdout|stderr` emits Buffers\n- `subprocess.stdin.write()` accepts Buffer, Uint8Array or string\n- Previous generators might return Uint8Array or string\n\nHowever, those are converted to Buffer:\n- on writes: `Duplex.writable` `decodeStrings: true` default option\n- on reads: `Duplex.readable` `readableEncoding: null` default option\n*/\nexport const getEncodingTransformGenerator = (binary, encoding, skipped) => {\n\tif (skipped) {\n\t\treturn;\n\t}\n\n\tif (binary) {\n\t\treturn {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};\n\t}\n\n\tconst stringDecoder = new StringDecoder(encoding);\n\treturn {\n\t\ttransform: encodingStringGenerator.bind(undefined, stringDecoder),\n\t\tfinal: encodingStringFinal.bind(undefined, stringDecoder),\n\t};\n};\n\nconst encodingUint8ArrayGenerator = function * (textEncoder, chunk) {\n\tif (Buffer.isBuffer(chunk)) {\n\t\tyield bufferToUint8Array(chunk);\n\t} else if (typeof chunk === 'string') {\n\t\tyield textEncoder.encode(chunk);\n\t} else {\n\t\tyield chunk;\n\t}\n};\n\nconst encodingStringGenerator = function * (stringDecoder, chunk) {\n\tyield isUint8Array(chunk) ? stringDecoder.write(chunk) : chunk;\n};\n\nconst encodingStringFinal = function * (stringDecoder) {\n\tconst lastChunk = stringDecoder.end();\n\tif (lastChunk !== '') {\n\t\tyield lastChunk;\n\t}\n};\n","import {callbackify} from 'node:util';\n\n// Applies a series of generator functions asynchronously\nexport const pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {\n\tstate.currentIterable = getChunks(...getChunksArguments);\n\n\ttry {\n\t\tfor await (const chunk of state.currentIterable) {\n\t\t\ttransformStream.push(chunk);\n\t\t}\n\t} finally {\n\t\tdelete state.currentIterable;\n\t}\n});\n\n// For each new chunk, apply each `transform()` method\nexport const transformChunk = async function * (chunk, generators, index) {\n\tif (index === generators.length) {\n\t\tyield chunk;\n\t\treturn;\n\t}\n\n\tconst {transform = identityGenerator} = generators[index];\n\tfor await (const transformedChunk of transform(chunk)) {\n\t\tyield * transformChunk(transformedChunk, generators, index + 1);\n\t}\n};\n\n// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms\nexport const finalChunks = async function * (generators) {\n\tfor (const [index, {final}] of Object.entries(generators)) {\n\t\tyield * generatorFinalChunks(final, Number(index), generators);\n\t}\n};\n\nconst generatorFinalChunks = async function * (final, index, generators) {\n\tif (final === undefined) {\n\t\treturn;\n\t}\n\n\tfor await (const finalChunk of final()) {\n\t\tyield * transformChunk(finalChunk, generators, index + 1);\n\t}\n};\n\n// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors\nexport const destroyTransform = callbackify(async ({currentIterable}, error) => {\n\tif (currentIterable !== undefined) {\n\t\tawait (error ? currentIterable.throw(error) : currentIterable.return());\n\t\treturn;\n\t}\n\n\tif (error) {\n\t\tthrow error;\n\t}\n});\n\nconst identityGenerator = function * (chunk) {\n\tyield chunk;\n};\n","// Duplicate the code from `run-async.js` but as synchronous functions\nexport const pushChunksSync = (getChunksSync, getChunksArguments, transformStream, done) => {\n\ttry {\n\t\tfor (const chunk of getChunksSync(...getChunksArguments)) {\n\t\t\ttransformStream.push(chunk);\n\t\t}\n\n\t\tdone();\n\t} catch (error) {\n\t\tdone(error);\n\t}\n};\n\n// Run synchronous generators with `execaSync()`\nexport const runTransformSync = (generators, chunks) => [\n\t...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),\n\t...finalChunksSync(generators),\n];\n\nexport const transformChunkSync = function * (chunk, generators, index) {\n\tif (index === generators.length) {\n\t\tyield chunk;\n\t\treturn;\n\t}\n\n\tconst {transform = identityGenerator} = generators[index];\n\tfor (const transformedChunk of transform(chunk)) {\n\t\tyield * transformChunkSync(transformedChunk, generators, index + 1);\n\t}\n};\n\nexport const finalChunksSync = function * (generators) {\n\tfor (const [index, {final}] of Object.entries(generators)) {\n\t\tyield * generatorFinalChunksSync(final, Number(index), generators);\n\t}\n};\n\nconst generatorFinalChunksSync = function * (final, index, generators) {\n\tif (final === undefined) {\n\t\treturn;\n\t}\n\n\tfor (const finalChunk of final()) {\n\t\tyield * transformChunkSync(finalChunk, generators, index + 1);\n\t}\n};\n\nconst identityGenerator = function * (chunk) {\n\tyield chunk;\n};\n","import {runGeneratorsSync} from '../transform/generator.js';\nimport {joinToUint8Array, isUint8Array} from '../utils/uint-array.js';\nimport {TYPE_TO_MESSAGE} from '../stdio/type.js';\n\n// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option\nexport const addInputOptionsSync = (fileDescriptors, options) => {\n\tfor (const fdNumber of getInputFdNumbers(fileDescriptors)) {\n\t\taddInputOptionSync(fileDescriptors, fdNumber, options);\n\t}\n};\n\nconst getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)\n\t.filter(([, {direction}]) => direction === 'input')\n\t.map(([fdNumber]) => Number(fdNumber)));\n\nconst addInputOptionSync = (fileDescriptors, fdNumber, options) => {\n\tconst {stdioItems} = fileDescriptors[fdNumber];\n\tconst allStdioItems = stdioItems.filter(({contents}) => contents !== undefined);\n\tif (allStdioItems.length === 0) {\n\t\treturn;\n\t}\n\n\tif (fdNumber !== 0) {\n\t\tconst [{type, optionName}] = allStdioItems;\n\t\tthrow new TypeError(`Only the \\`stdin\\` option, not \\`${optionName}\\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);\n\t}\n\n\tconst allContents = allStdioItems.map(({contents}) => contents);\n\tconst transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));\n\toptions.input = joinToUint8Array(transformedContents);\n};\n\nconst applySingleInputGeneratorsSync = (contents, stdioItems) => {\n\tconst newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);\n\tvalidateSerializable(newContents);\n\treturn joinToUint8Array(newContents);\n};\n\nconst validateSerializable = newContents => {\n\tconst invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item));\n\tif (invalidItem !== undefined) {\n\t\tthrow new TypeError(`The \\`stdin\\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);\n\t}\n};\n","import {writeFileSync, appendFileSync} from 'node:fs';\nimport {shouldLogOutput, logLinesSync} from '../verbose/output.js';\nimport {runGeneratorsSync} from '../transform/generator.js';\nimport {splitLinesSync} from '../transform/split.js';\nimport {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';\nimport {FILE_TYPES} from '../stdio/type.js';\nimport {truncateMaxBufferSync} from './max-buffer.js';\n\n// Apply `stdout`/`stderr` options, after spawning, in sync mode\nexport const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {\n\tif (output === null) {\n\t\treturn {output: Array.from({length: 3})};\n\t}\n\n\tconst state = {};\n\tconst outputFiles = new Set([]);\n\tconst transformedOutput = output.map((result, fdNumber) =>\n\t\ttransformOutputResultSync({\n\t\t\tresult,\n\t\t\tfileDescriptors,\n\t\t\tfdNumber,\n\t\t\tstate,\n\t\t\toutputFiles,\n\t\t\tisMaxBuffer,\n\t\t\tverboseInfo,\n\t\t}, options));\n\treturn {output: transformedOutput, ...state};\n};\n\nconst transformOutputResultSync = (\n\t{result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo},\n\t{buffer, encoding, lines, stripFinalNewline, maxBuffer},\n) => {\n\tif (result === null) {\n\t\treturn;\n\t}\n\n\tconst truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer);\n\tconst uint8ArrayResult = bufferToUint8Array(truncatedResult);\n\tconst {stdioItems, objectMode} = fileDescriptors[fdNumber];\n\tconst chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);\n\tconst {serializedResult, finalResult = serializedResult} = serializeChunks({\n\t\tchunks,\n\t\tobjectMode,\n\t\tencoding,\n\t\tlines,\n\t\tstripFinalNewline,\n\t\tfdNumber,\n\t});\n\n\tlogOutputSync({\n\t\tserializedResult,\n\t\tfdNumber,\n\t\tstate,\n\t\tverboseInfo,\n\t\tencoding,\n\t\tstdioItems,\n\t\tobjectMode,\n\t});\n\n\tconst returnedResult = buffer[fdNumber] ? finalResult : undefined;\n\n\ttry {\n\t\tif (state.error === undefined) {\n\t\t\twriteToFiles(serializedResult, stdioItems, outputFiles);\n\t\t}\n\n\t\treturn returnedResult;\n\t} catch (error) {\n\t\tstate.error = error;\n\t\treturn returnedResult;\n\t}\n};\n\n// Applies transform generators to `stdout`/`stderr`\nconst runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {\n\ttry {\n\t\treturn runGeneratorsSync(chunks, stdioItems, encoding, false);\n\t} catch (error) {\n\t\tstate.error = error;\n\t\treturn chunks;\n\t}\n};\n\n// The contents is converted to three stages:\n//  - serializedResult: used when the target is a file path/URL or a file descriptor (including 'inherit')\n//  - finalResult/returnedResult: returned as `result.std*`\nconst serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {\n\tif (objectMode) {\n\t\treturn {serializedResult: chunks};\n\t}\n\n\tif (encoding === 'buffer') {\n\t\treturn {serializedResult: joinToUint8Array(chunks)};\n\t}\n\n\tconst serializedResult = joinToString(chunks, encoding);\n\tif (lines[fdNumber]) {\n\t\treturn {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};\n\t}\n\n\treturn {serializedResult};\n};\n\nconst logOutputSync = ({serializedResult, fdNumber, state, verboseInfo, encoding, stdioItems, objectMode}) => {\n\tif (!shouldLogOutput({\n\t\tstdioItems,\n\t\tencoding,\n\t\tverboseInfo,\n\t\tfdNumber,\n\t})) {\n\t\treturn;\n\t}\n\n\tconst linesArray = splitLinesSync(serializedResult, false, objectMode);\n\n\ttry {\n\t\tlogLinesSync(linesArray, fdNumber, verboseInfo);\n\t} catch (error) {\n\t\tstate.error ??= error;\n\t}\n};\n\n// When the `std*` target is a file path/URL or a file descriptor\nconst writeToFiles = (serializedResult, stdioItems, outputFiles) => {\n\tfor (const {path, append} of stdioItems.filter(({type}) => FILE_TYPES.has(type))) {\n\t\tconst pathString = typeof path === 'string' ? path : path.toString();\n\t\tif (append || outputFiles.has(pathString)) {\n\t\t\tappendFileSync(path, serializedResult);\n\t\t} else {\n\t\t\toutputFiles.add(pathString);\n\t\t\twriteFileSync(path, serializedResult);\n\t\t}\n\t}\n};\n","import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';\nimport {TRANSFORM_TYPES} from '../stdio/type.js';\nimport {verboseLog, serializeVerboseMessage} from './log.js';\nimport {isFullVerbose} from './values.js';\n\n// `ignore` opts-out of `verbose` for a specific stream.\n// `ipc` cannot use piping.\n// `inherit` would result in double printing.\n// They can also lead to double printing when passing file descriptor integers or `process.std*`.\n// This only leaves with `pipe` and `overlapped`.\nexport const shouldLogOutput = ({stdioItems, encoding, verboseInfo, fdNumber}) => fdNumber !== 'all'\n\t&& isFullVerbose(verboseInfo, fdNumber)\n\t&& !BINARY_ENCODINGS.has(encoding)\n\t&& fdUsesVerbose(fdNumber)\n\t&& (stdioItems.some(({type, value}) => type === 'native' && PIPED_STDIO_VALUES.has(value))\n\t|| stdioItems.every(({type}) => TRANSFORM_TYPES.has(type)));\n\n// Printing input streams would be confusing.\n// Files and streams can produce big outputs, which we don't want to print.\n// We could print `stdio[3+]` but it often is redirected to files and streams, with the same issue.\n// So we only print stdout and stderr.\nconst fdUsesVerbose = fdNumber => fdNumber === 1 || fdNumber === 2;\n\nconst PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped']);\n\n// `verbose: 'full'` printing logic with async methods\nexport const logLines = async (linesIterable, stream, fdNumber, verboseInfo) => {\n\tfor await (const line of linesIterable) {\n\t\tif (!isPipingStream(stream)) {\n\t\t\tlogLine(line, fdNumber, verboseInfo);\n\t\t}\n\t}\n};\n\n// `verbose: 'full'` printing logic with sync methods\nexport const logLinesSync = (linesArray, fdNumber, verboseInfo) => {\n\tfor (const line of linesArray) {\n\t\tlogLine(line, fdNumber, verboseInfo);\n\t}\n};\n\n// When `subprocess.stdout|stderr.pipe()` is called, `verbose` becomes a noop.\n// This prevents the following problems:\n//  - `.pipe()` achieves the same result as using `stdout: 'inherit'`, `stdout: stream`, etc. which also make `verbose` a noop.\n//    For example, `subprocess.stdout.pipe(process.stdin)` would print each line twice.\n//  - When chaining subprocesses with `subprocess.pipe(otherSubprocess)`, only the last one should print its output.\n// Detecting whether `.pipe()` is impossible without monkey-patching it, so we use the following undocumented property.\n// This is not a critical behavior since changes of the following property would only make `verbose` more verbose.\nconst isPipingStream = stream => stream._readableState.pipes.length > 0;\n\n// When `verbose` is `full`, print stdout|stderr\nconst logLine = (line, fdNumber, verboseInfo) => {\n\tconst verboseMessage = serializeVerboseMessage(line);\n\tverboseLog({\n\t\ttype: 'output',\n\t\tverboseMessage,\n\t\tfdNumber,\n\t\tverboseInfo,\n\t});\n};\n","import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';\nimport {stripNewline} from '../io/strip-newline.js';\n\n// Retrieve `result.all` with synchronous methods\nexport const getAllSync = ([, stdout, stderr], options) => {\n\tif (!options.all) {\n\t\treturn;\n\t}\n\n\tif (stdout === undefined) {\n\t\treturn stderr;\n\t}\n\n\tif (stderr === undefined) {\n\t\treturn stdout;\n\t}\n\n\tif (Array.isArray(stdout)) {\n\t\treturn Array.isArray(stderr)\n\t\t\t? [...stdout, ...stderr]\n\t\t\t: [...stdout, stripNewline(stderr, options, 'all')];\n\t}\n\n\tif (Array.isArray(stderr)) {\n\t\treturn [stripNewline(stdout, options, 'all'), ...stderr];\n\t}\n\n\tif (isUint8Array(stdout) && isUint8Array(stderr)) {\n\t\treturn concatUint8Arrays([stdout, stderr]);\n\t}\n\n\treturn `${stdout}${stderr}`;\n};\n","import {once} from 'node:events';\nimport {DiscardedError} from '../return/final-error.js';\n\n// If `error` is emitted before `spawn`, `exit` will never be emitted.\n// However, `error` might be emitted after `spawn`.\n// In that case, `exit` will still be emitted.\n// Since the `exit` event contains the signal name, we want to make sure we are listening for it.\n// This function also takes into account the following unlikely cases:\n//  - `exit` being emitted in the same microtask as `spawn`\n//  - `error` being emitted multiple times\nexport const waitForExit = async (subprocess, context) => {\n\tconst [exitCode, signal] = await waitForExitOrError(subprocess);\n\tcontext.isForcefullyTerminated ??= false;\n\treturn [exitCode, signal];\n};\n\nconst waitForExitOrError = async subprocess => {\n\tconst [spawnPayload, exitPayload] = await Promise.allSettled([\n\t\tonce(subprocess, 'spawn'),\n\t\tonce(subprocess, 'exit'),\n\t]);\n\n\tif (spawnPayload.status === 'rejected') {\n\t\treturn [];\n\t}\n\n\treturn exitPayload.status === 'rejected'\n\t\t? waitForSubprocessExit(subprocess)\n\t\t: exitPayload.value;\n};\n\nconst waitForSubprocessExit = async subprocess => {\n\ttry {\n\t\treturn await once(subprocess, 'exit');\n\t} catch {\n\t\treturn waitForSubprocessExit(subprocess);\n\t}\n};\n\n// Retrieve the final exit code and|or signal name\nexport const waitForSuccessfulExit = async exitPromise => {\n\tconst [exitCode, signal] = await exitPromise;\n\n\tif (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {\n\t\tthrow new DiscardedError();\n\t}\n\n\treturn [exitCode, signal];\n};\n\n// When the subprocess fails due to an `error` event\nconst isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;\n// When the subprocess fails due to a non-0 exit code or to a signal termination\nexport const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;\n","import {DiscardedError} from '../return/final-error.js';\nimport {isMaxBufferSync} from '../io/max-buffer.js';\nimport {isFailedExit} from './exit-async.js';\n\n// Retrieve exit code, signal name and error information, with synchronous methods\nexport const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer}) => {\n\tconst resultError = getResultError(error, exitCode, signal);\n\tconst timedOut = resultError?.code === 'ETIMEDOUT';\n\tconst isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);\n\treturn {\n\t\tresultError,\n\t\texitCode,\n\t\tsignal,\n\t\ttimedOut,\n\t\tisMaxBuffer,\n\t};\n};\n\nconst getResultError = (error, exitCode, signal) => {\n\tif (error !== undefined) {\n\t\treturn error;\n\t}\n\n\treturn isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;\n};\n","import {setMaxListeners} from 'node:events';\nimport {spawn} from 'node:child_process';\nimport {MaxBufferError} from 'get-stream';\nimport {handleCommand} from '../arguments/command.js';\nimport {normalizeOptions} from '../arguments/options.js';\nimport {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';\nimport {concatenateShell} from '../arguments/shell.js';\nimport {addIpcMethods} from '../ipc/methods.js';\nimport {makeError, makeSuccessResult} from '../return/result.js';\nimport {handleResult} from '../return/reject.js';\nimport {handleEarlyError} from '../return/early-error.js';\nimport {handleStdioAsync} from '../stdio/handle-async.js';\nimport {stripNewline} from '../io/strip-newline.js';\nimport {pipeOutputAsync} from '../io/output-async.js';\nimport {subprocessKill} from '../terminate/kill.js';\nimport {cleanupOnExit} from '../terminate/cleanup.js';\nimport {pipeToSubprocess} from '../pipe/setup.js';\nimport {makeAllStream} from '../resolve/all-async.js';\nimport {waitForSubprocessResult} from '../resolve/wait-subprocess.js';\nimport {addConvertedStreams} from '../convert/add.js';\nimport {createDeferred} from '../utils/deferred.js';\nimport {mergePromise} from './promise.js';\n\n// Main shared logic for all async methods: `execa()`, `$`, `execaNode()`\nexport const execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {\n\tconst {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleAsyncArguments(rawFile, rawArguments, rawOptions);\n\tconst {subprocess, promise} = spawnSubprocessAsync({\n\t\tfile,\n\t\tcommandArguments,\n\t\toptions,\n\t\tstartTime,\n\t\tverboseInfo,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tfileDescriptors,\n\t});\n\tsubprocess.pipe = pipeToSubprocess.bind(undefined, {\n\t\tsource: subprocess,\n\t\tsourcePromise: promise,\n\t\tboundOptions: {},\n\t\tcreateNested,\n\t});\n\tmergePromise(subprocess, promise);\n\tSUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});\n\treturn subprocess;\n};\n\n// Compute arguments to pass to `child_process.spawn()`\nconst handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {\n\tconst {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);\n\tconst {file, commandArguments, options: normalizedOptions} = normalizeOptions(rawFile, rawArguments, rawOptions);\n\tconst options = handleAsyncOptions(normalizedOptions);\n\tconst fileDescriptors = handleStdioAsync(options, verboseInfo);\n\treturn {\n\t\tfile,\n\t\tcommandArguments,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstartTime,\n\t\tverboseInfo,\n\t\toptions,\n\t\tfileDescriptors,\n\t};\n};\n\n// Options normalization logic specific to async methods.\n// Prevent passing the `timeout` option directly to `child_process.spawn()`.\nconst handleAsyncOptions = ({timeout, signal, ...options}) => {\n\tif (signal !== undefined) {\n\t\tthrow new TypeError('The \"signal\" option has been renamed to \"cancelSignal\" instead.');\n\t}\n\n\treturn {...options, timeoutDuration: timeout};\n};\n\nconst spawnSubprocessAsync = ({file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {\n\tlet subprocess;\n\ttry {\n\t\tsubprocess = spawn(...concatenateShell(file, commandArguments, options));\n\t} catch (error) {\n\t\treturn handleEarlyError({\n\t\t\terror,\n\t\t\tcommand,\n\t\t\tescapedCommand,\n\t\t\tfileDescriptors,\n\t\t\toptions,\n\t\t\tstartTime,\n\t\t\tverboseInfo,\n\t\t});\n\t}\n\n\tconst controller = new AbortController();\n\tsetMaxListeners(Number.POSITIVE_INFINITY, controller.signal);\n\n\tconst originalStreams = [...subprocess.stdio];\n\tpipeOutputAsync(subprocess, fileDescriptors, controller);\n\tcleanupOnExit(subprocess, options, controller);\n\n\tconst context = {};\n\tconst onInternalError = createDeferred();\n\tsubprocess.kill = subprocessKill.bind(undefined, {\n\t\tkill: subprocess.kill.bind(subprocess),\n\t\toptions,\n\t\tonInternalError,\n\t\tcontext,\n\t\tcontroller,\n\t});\n\tsubprocess.all = makeAllStream(subprocess, options);\n\taddConvertedStreams(subprocess, options);\n\taddIpcMethods(subprocess, options);\n\n\tconst promise = handlePromise({\n\t\tsubprocess,\n\t\toptions,\n\t\tstartTime,\n\t\tverboseInfo,\n\t\tfileDescriptors,\n\t\toriginalStreams,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tcontext,\n\t\tonInternalError,\n\t\tcontroller,\n\t});\n\treturn {subprocess, promise};\n};\n\n// Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away\nconst handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller}) => {\n\tconst [\n\t\terrorInfo,\n\t\t[exitCode, signal],\n\t\tstdioResults,\n\t\tallResult,\n\t\tipcOutput,\n\t] = await waitForSubprocessResult({\n\t\tsubprocess,\n\t\toptions,\n\t\tcontext,\n\t\tverboseInfo,\n\t\tfileDescriptors,\n\t\toriginalStreams,\n\t\tonInternalError,\n\t\tcontroller,\n\t});\n\tcontroller.abort();\n\tonInternalError.resolve();\n\n\tconst stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber));\n\tconst all = stripNewline(allResult, options, 'all');\n\tconst result = getAsyncResult({\n\t\terrorInfo,\n\t\texitCode,\n\t\tsignal,\n\t\tstdio,\n\t\tall,\n\t\tipcOutput,\n\t\tcontext,\n\t\toptions,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstartTime,\n\t});\n\treturn handleResult(result, verboseInfo, options);\n};\n\nconst getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo\n\t? makeError({\n\t\terror: errorInfo.error,\n\t\tcommand,\n\t\tescapedCommand,\n\t\ttimedOut: context.terminationReason === 'timeout',\n\t\tisCanceled: context.terminationReason === 'cancel' || context.terminationReason === 'gracefulCancel',\n\t\tisGracefullyCanceled: context.terminationReason === 'gracefulCancel',\n\t\tisMaxBuffer: errorInfo.error instanceof MaxBufferError,\n\t\tisForcefullyTerminated: context.isForcefullyTerminated,\n\t\texitCode,\n\t\tsignal,\n\t\tstdio,\n\t\tall,\n\t\tipcOutput,\n\t\toptions,\n\t\tstartTime,\n\t\tisSync: false,\n\t})\n\t: makeSuccessResult({\n\t\tcommand,\n\t\tescapedCommand,\n\t\tstdio,\n\t\tall,\n\t\tipcOutput,\n\t\toptions,\n\t\tstartTime,\n\t});\n","import process from 'node:process';\nimport {sendMessage} from './send.js';\nimport {getOneMessage} from './get-one.js';\nimport {getEachMessage} from './get-each.js';\nimport {getCancelSignal} from './graceful.js';\n\n// Add promise-based IPC methods in current process\nexport const addIpcMethods = (subprocess, {ipc}) => {\n\tObject.assign(subprocess, getIpcMethods(subprocess, false, ipc));\n};\n\n// Get promise-based IPC in the subprocess\nexport const getIpcExport = () => {\n\tconst anyProcess = process;\n\tconst isSubprocess = true;\n\tconst ipc = process.channel !== undefined;\n\n\treturn {\n\t\t...getIpcMethods(anyProcess, isSubprocess, ipc),\n\t\tgetCancelSignal: getCancelSignal.bind(undefined, {\n\t\t\tanyProcess,\n\t\t\tchannel: anyProcess.channel,\n\t\t\tisSubprocess,\n\t\t\tipc,\n\t\t}),\n\t};\n};\n\n// Retrieve the `ipc` shared by both the current process and the subprocess\nconst getIpcMethods = (anyProcess, isSubprocess, ipc) => ({\n\tsendMessage: sendMessage.bind(undefined, {\n\t\tanyProcess,\n\t\tchannel: anyProcess.channel,\n\t\tisSubprocess,\n\t\tipc,\n\t}),\n\tgetOneMessage: getOneMessage.bind(undefined, {\n\t\tanyProcess,\n\t\tchannel: anyProcess.channel,\n\t\tisSubprocess,\n\t\tipc,\n\t}),\n\tgetEachMessage: getEachMessage.bind(undefined, {\n\t\tanyProcess,\n\t\tchannel: anyProcess.channel,\n\t\tisSubprocess,\n\t\tipc,\n\t}),\n});\n","import {once, on} from 'node:events';\nimport {\n\tvalidateIpcMethod,\n\tthrowOnEarlyDisconnect,\n\tdisconnect,\n\tgetStrictResponseError,\n} from './validation.js';\nimport {getIpcEmitter, isConnected} from './forward.js';\nimport {addReference, removeReference} from './reference.js';\n\n// Like `[sub]process.once('message')` but promise-based\nexport const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true, filter} = {}) => {\n\tvalidateIpcMethod({\n\t\tmethodName: 'getOneMessage',\n\t\tisSubprocess,\n\t\tipc,\n\t\tisConnected: isConnected(anyProcess),\n\t});\n\n\treturn getOneMessageAsync({\n\t\tanyProcess,\n\t\tchannel,\n\t\tisSubprocess,\n\t\tfilter,\n\t\treference,\n\t});\n};\n\nconst getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter, reference}) => {\n\taddReference(channel, reference);\n\tconst ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);\n\tconst controller = new AbortController();\n\ttry {\n\t\treturn await Promise.race([\n\t\t\tgetMessage(ipcEmitter, filter, controller),\n\t\t\tthrowOnDisconnect(ipcEmitter, isSubprocess, controller),\n\t\t\tthrowOnStrictError(ipcEmitter, isSubprocess, controller),\n\t\t]);\n\t} catch (error) {\n\t\tdisconnect(anyProcess);\n\t\tthrow error;\n\t} finally {\n\t\tcontroller.abort();\n\t\tremoveReference(channel, reference);\n\t}\n};\n\nconst getMessage = async (ipcEmitter, filter, {signal}) => {\n\tif (filter === undefined) {\n\t\tconst [message] = await once(ipcEmitter, 'message', {signal});\n\t\treturn message;\n\t}\n\n\tfor await (const [message] of on(ipcEmitter, 'message', {signal})) {\n\t\tif (filter(message)) {\n\t\t\treturn message;\n\t\t}\n\t}\n};\n\nconst throwOnDisconnect = async (ipcEmitter, isSubprocess, {signal}) => {\n\tawait once(ipcEmitter, 'disconnect', {signal});\n\tthrowOnEarlyDisconnect(isSubprocess);\n};\n\nconst throwOnStrictError = async (ipcEmitter, isSubprocess, {signal}) => {\n\tconst [error] = await once(ipcEmitter, 'strict:error', {signal});\n\tthrow getStrictResponseError(error, isSubprocess);\n};\n","import {once, on} from 'node:events';\nimport {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';\nimport {getIpcEmitter, isConnected} from './forward.js';\nimport {addReference, removeReference} from './reference.js';\n\n// Like `[sub]process.on('message')` but promise-based\nexport const getEachMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true} = {}) => loopOnMessages({\n\tanyProcess,\n\tchannel,\n\tisSubprocess,\n\tipc,\n\tshouldAwait: !isSubprocess,\n\treference,\n});\n\n// Same but used internally\nexport const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference}) => {\n\tvalidateIpcMethod({\n\t\tmethodName: 'getEachMessage',\n\t\tisSubprocess,\n\t\tipc,\n\t\tisConnected: isConnected(anyProcess),\n\t});\n\n\taddReference(channel, reference);\n\tconst ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);\n\tconst controller = new AbortController();\n\tconst state = {};\n\tstopOnDisconnect(anyProcess, ipcEmitter, controller);\n\tabortOnStrictError({\n\t\tipcEmitter,\n\t\tisSubprocess,\n\t\tcontroller,\n\t\tstate,\n\t});\n\treturn iterateOnMessages({\n\t\tanyProcess,\n\t\tchannel,\n\t\tipcEmitter,\n\t\tisSubprocess,\n\t\tshouldAwait,\n\t\tcontroller,\n\t\tstate,\n\t\treference,\n\t});\n};\n\nconst stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {\n\ttry {\n\t\tawait once(ipcEmitter, 'disconnect', {signal: controller.signal});\n\t\tcontroller.abort();\n\t} catch {}\n};\n\nconst abortOnStrictError = async ({ipcEmitter, isSubprocess, controller, state}) => {\n\ttry {\n\t\tconst [error] = await once(ipcEmitter, 'strict:error', {signal: controller.signal});\n\t\tstate.error = getStrictResponseError(error, isSubprocess);\n\t\tcontroller.abort();\n\t} catch {}\n};\n\nconst iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference}) {\n\ttry {\n\t\tfor await (const [message] of on(ipcEmitter, 'message', {signal: controller.signal})) {\n\t\t\tthrowIfStrictError(state);\n\t\t\tyield message;\n\t\t}\n\t} catch {\n\t\tthrowIfStrictError(state);\n\t} finally {\n\t\tcontroller.abort();\n\t\tremoveReference(channel, reference);\n\n\t\tif (!isSubprocess) {\n\t\t\tdisconnect(anyProcess);\n\t\t}\n\n\t\tif (shouldAwait) {\n\t\t\tawait anyProcess;\n\t\t}\n\t}\n};\n\nconst throwIfStrictError = ({error}) => {\n\tif (error) {\n\t\tthrow error;\n\t}\n};\n","import {ChildProcess} from 'node:child_process';\nimport {\n\tPassThrough,\n\tReadable,\n\tWritable,\n\tDuplex,\n} from 'node:stream';\nimport {cleanupCustomStreams} from '../stdio/handle.js';\nimport {makeEarlyError} from './result.js';\nimport {handleResult} from './reject.js';\n\n// When the subprocess fails to spawn.\n// We ensure the returned error is always both a promise and a subprocess.\nexport const handleEarlyError = ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => {\n\tcleanupCustomStreams(fileDescriptors);\n\n\tconst subprocess = new ChildProcess();\n\tcreateDummyStreams(subprocess, fileDescriptors);\n\tObject.assign(subprocess, {readable, writable, duplex});\n\n\tconst earlyError = makeEarlyError({\n\t\terror,\n\t\tcommand,\n\t\tescapedCommand,\n\t\tfileDescriptors,\n\t\toptions,\n\t\tstartTime,\n\t\tisSync: false,\n\t});\n\tconst promise = handleDummyPromise(earlyError, verboseInfo, options);\n\treturn {subprocess, promise};\n};\n\nconst createDummyStreams = (subprocess, fileDescriptors) => {\n\tconst stdin = createDummyStream();\n\tconst stdout = createDummyStream();\n\tconst stderr = createDummyStream();\n\tconst extraStdio = Array.from({length: fileDescriptors.length - 3}, createDummyStream);\n\tconst all = createDummyStream();\n\tconst stdio = [stdin, stdout, stderr, ...extraStdio];\n\tObject.assign(subprocess, {\n\t\tstdin,\n\t\tstdout,\n\t\tstderr,\n\t\tall,\n\t\tstdio,\n\t});\n};\n\nconst createDummyStream = () => {\n\tconst stream = new PassThrough();\n\tstream.end();\n\treturn stream;\n};\n\nconst readable = () => new Readable({read() {}});\nconst writable = () => new Writable({write() {}});\nconst duplex = () => new Duplex({read() {}, write() {}});\n\nconst handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);\n","import {createReadStream, createWriteStream} from 'node:fs';\nimport {Buffer} from 'node:buffer';\nimport {Readable, Writable, Duplex} from 'node:stream';\nimport {generatorToStream} from '../transform/generator.js';\nimport {handleStdio} from './handle.js';\nimport {TYPE_TO_MESSAGE} from './type.js';\n\n// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode\nexport const handleStdioAsync = (options, verboseInfo) => handleStdio(addPropertiesAsync, options, verboseInfo, false);\n\nconst forbiddenIfAsync = ({type, optionName}) => {\n\tthrow new TypeError(`The \\`${optionName}\\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);\n};\n\n// Create streams used internally for piping when using specific values for the `std*` options, in async mode.\n// For example, `stdout: {file}` creates a file stream, which is piped from/to.\nconst addProperties = {\n\tfileNumber: forbiddenIfAsync,\n\tgenerator: generatorToStream,\n\tasyncGenerator: generatorToStream,\n\tnodeStream: ({value}) => ({stream: value}),\n\twebTransform({value: {transform, writableObjectMode, readableObjectMode}}) {\n\t\tconst objectMode = writableObjectMode || readableObjectMode;\n\t\tconst stream = Duplex.fromWeb(transform, {objectMode});\n\t\treturn {stream};\n\t},\n\tduplex: ({value: {transform}}) => ({stream: transform}),\n\tnative() {},\n};\n\nconst addPropertiesAsync = {\n\tinput: {\n\t\t...addProperties,\n\t\tfileUrl: ({value}) => ({stream: createReadStream(value)}),\n\t\tfilePath: ({value: {file}}) => ({stream: createReadStream(file)}),\n\t\twebStream: ({value}) => ({stream: Readable.fromWeb(value)}),\n\t\titerable: ({value}) => ({stream: Readable.from(value)}),\n\t\tasyncIterable: ({value}) => ({stream: Readable.from(value)}),\n\t\tstring: ({value}) => ({stream: Readable.from(value)}),\n\t\tuint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),\n\t},\n\toutput: {\n\t\t...addProperties,\n\t\tfileUrl: ({value}) => ({stream: createWriteStream(value)}),\n\t\tfilePath: ({value: {file, append}}) => ({stream: createWriteStream(file, append ? {flags: 'a'} : {})}),\n\t\twebStream: ({value}) => ({stream: Writable.fromWeb(value)}),\n\t\titerable: forbiddenIfAsync,\n\t\tasyncIterable: forbiddenIfAsync,\n\t\tstring: forbiddenIfAsync,\n\t\tuint8Array: forbiddenIfAsync,\n\t},\n};\n","import {on, once} from 'node:events';\nimport {PassThrough as PassThroughStream, getDefaultHighWaterMark} from 'node:stream';\nimport {finished} from 'node:stream/promises';\n\nexport default function mergeStreams(streams) {\n\tif (!Array.isArray(streams)) {\n\t\tthrow new TypeError(`Expected an array, got \\`${typeof streams}\\`.`);\n\t}\n\n\tfor (const stream of streams) {\n\t\tvalidateStream(stream);\n\t}\n\n\tconst objectMode = streams.some(({readableObjectMode}) => readableObjectMode);\n\tconst highWaterMark = getHighWaterMark(streams, objectMode);\n\tconst passThroughStream = new MergedStream({\n\t\tobjectMode,\n\t\twritableHighWaterMark: highWaterMark,\n\t\treadableHighWaterMark: highWaterMark,\n\t});\n\n\tfor (const stream of streams) {\n\t\tpassThroughStream.add(stream);\n\t}\n\n\treturn passThroughStream;\n}\n\nconst getHighWaterMark = (streams, objectMode) => {\n\tif (streams.length === 0) {\n\t\treturn getDefaultHighWaterMark(objectMode);\n\t}\n\n\tconst highWaterMarks = streams\n\t\t.filter(({readableObjectMode}) => readableObjectMode === objectMode)\n\t\t.map(({readableHighWaterMark}) => readableHighWaterMark);\n\treturn Math.max(...highWaterMarks);\n};\n\nclass MergedStream extends PassThroughStream {\n\t#streams = new Set([]);\n\t#ended = new Set([]);\n\t#aborted = new Set([]);\n\t#onFinished;\n\t#unpipeEvent = Symbol('unpipe');\n\t#streamPromises = new WeakMap();\n\n\tadd(stream) {\n\t\tvalidateStream(stream);\n\n\t\tif (this.#streams.has(stream)) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#streams.add(stream);\n\n\t\tthis.#onFinished ??= onMergedStreamFinished(this, this.#streams, this.#unpipeEvent);\n\t\tconst streamPromise = endWhenStreamsDone({\n\t\t\tpassThroughStream: this,\n\t\t\tstream,\n\t\t\tstreams: this.#streams,\n\t\t\tended: this.#ended,\n\t\t\taborted: this.#aborted,\n\t\t\tonFinished: this.#onFinished,\n\t\t\tunpipeEvent: this.#unpipeEvent,\n\t\t});\n\t\tthis.#streamPromises.set(stream, streamPromise);\n\n\t\tstream.pipe(this, {end: false});\n\t}\n\n\tasync remove(stream) {\n\t\tvalidateStream(stream);\n\n\t\tif (!this.#streams.has(stream)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst streamPromise = this.#streamPromises.get(stream);\n\t\tif (streamPromise === undefined) {\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.#streamPromises.delete(stream);\n\n\t\tstream.unpipe(this);\n\t\tawait streamPromise;\n\t\treturn true;\n\t}\n}\n\nconst onMergedStreamFinished = async (passThroughStream, streams, unpipeEvent) => {\n\tupdateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_COUNT);\n\tconst controller = new AbortController();\n\n\ttry {\n\t\tawait Promise.race([\n\t\t\tonMergedStreamEnd(passThroughStream, controller),\n\t\t\tonInputStreamsUnpipe(passThroughStream, streams, unpipeEvent, controller),\n\t\t]);\n\t} finally {\n\t\tcontroller.abort();\n\t\tupdateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_COUNT);\n\t}\n};\n\nconst onMergedStreamEnd = async (passThroughStream, {signal}) => {\n\ttry {\n\t\tawait finished(passThroughStream, {signal, cleanup: true});\n\t} catch (error) {\n\t\terrorOrAbortStream(passThroughStream, error);\n\t\tthrow error;\n\t}\n};\n\nconst onInputStreamsUnpipe = async (passThroughStream, streams, unpipeEvent, {signal}) => {\n\tfor await (const [unpipedStream] of on(passThroughStream, 'unpipe', {signal})) {\n\t\tif (streams.has(unpipedStream)) {\n\t\t\tunpipedStream.emit(unpipeEvent);\n\t\t}\n\t}\n};\n\nconst validateStream = stream => {\n\tif (typeof stream?.pipe !== 'function') {\n\t\tthrow new TypeError(`Expected a readable stream, got: \\`${typeof stream}\\`.`);\n\t}\n};\n\nconst endWhenStreamsDone = async ({passThroughStream, stream, streams, ended, aborted, onFinished, unpipeEvent}) => {\n\tupdateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_PER_STREAM);\n\tconst controller = new AbortController();\n\n\ttry {\n\t\tawait Promise.race([\n\t\t\tafterMergedStreamFinished(onFinished, stream, controller),\n\t\t\tonInputStreamEnd({\n\t\t\t\tpassThroughStream,\n\t\t\t\tstream,\n\t\t\t\tstreams,\n\t\t\t\tended,\n\t\t\t\taborted,\n\t\t\t\tcontroller,\n\t\t\t}),\n\t\t\tonInputStreamUnpipe({\n\t\t\t\tstream,\n\t\t\t\tstreams,\n\t\t\t\tended,\n\t\t\t\taborted,\n\t\t\t\tunpipeEvent,\n\t\t\t\tcontroller,\n\t\t\t}),\n\t\t]);\n\t} finally {\n\t\tcontroller.abort();\n\t\tupdateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_PER_STREAM);\n\t}\n\n\tif (streams.size > 0 && streams.size === ended.size + aborted.size) {\n\t\tif (ended.size === 0 && aborted.size > 0) {\n\t\t\tabortStream(passThroughStream);\n\t\t} else {\n\t\t\tendStream(passThroughStream);\n\t\t}\n\t}\n};\n\nconst afterMergedStreamFinished = async (onFinished, stream, {signal}) => {\n\ttry {\n\t\tawait onFinished;\n\t\tif (!signal.aborted) {\n\t\t\tabortStream(stream);\n\t\t}\n\t} catch (error) {\n\t\tif (!signal.aborted) {\n\t\t\terrorOrAbortStream(stream, error);\n\t\t}\n\t}\n};\n\nconst onInputStreamEnd = async ({passThroughStream, stream, streams, ended, aborted, controller: {signal}}) => {\n\ttry {\n\t\tawait finished(stream, {\n\t\t\tsignal,\n\t\t\tcleanup: true,\n\t\t\treadable: true,\n\t\t\twritable: false,\n\t\t});\n\t\tif (streams.has(stream)) {\n\t\t\tended.add(stream);\n\t\t}\n\t} catch (error) {\n\t\tif (signal.aborted || !streams.has(stream)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (isAbortError(error)) {\n\t\t\taborted.add(stream);\n\t\t} else {\n\t\t\terrorStream(passThroughStream, error);\n\t\t}\n\t}\n};\n\nconst onInputStreamUnpipe = async ({stream, streams, ended, aborted, unpipeEvent, controller: {signal}}) => {\n\tawait once(stream, unpipeEvent, {signal});\n\n\tif (!stream.readable) {\n\t\treturn once(signal, 'abort', {signal});\n\t}\n\n\tstreams.delete(stream);\n\tended.delete(stream);\n\taborted.delete(stream);\n};\n\nconst endStream = stream => {\n\tif (stream.writable) {\n\t\tstream.end();\n\t}\n};\n\nconst errorOrAbortStream = (stream, error) => {\n\tif (isAbortError(error)) {\n\t\tabortStream(stream);\n\t} else {\n\t\terrorStream(stream, error);\n\t}\n};\n\n// This is the error thrown by `finished()` on `stream.destroy()`\nconst isAbortError = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';\n\nconst abortStream = stream => {\n\tif (stream.readable || stream.writable) {\n\t\tstream.destroy();\n\t}\n};\n\n// `stream.destroy(error)` crashes the process with `uncaughtException` if no `error` event listener exists on `stream`.\n// We take care of error handling on user behalf, so we do not want this to happen.\nconst errorStream = (stream, error) => {\n\tif (!stream.destroyed) {\n\t\tstream.once('error', noop);\n\t\tstream.destroy(error);\n\t}\n};\n\nconst noop = () => {};\n\nconst updateMaxListeners = (passThroughStream, increment) => {\n\tconst maxListeners = passThroughStream.getMaxListeners();\n\tif (maxListeners !== 0 && maxListeners !== Number.POSITIVE_INFINITY) {\n\t\tpassThroughStream.setMaxListeners(maxListeners + increment);\n\t}\n};\n\n// Number of times `passThroughStream.on()` is called regardless of streams:\n//  - once due to `finished(passThroughStream)`\n//  - once due to `on(passThroughStream)`\nconst PASSTHROUGH_LISTENERS_COUNT = 2;\n\n// Number of times `passThroughStream.on()` is called per stream:\n//  - once due to `stream.pipe(passThroughStream)`\nconst PASSTHROUGH_LISTENERS_PER_STREAM = 1;\n","import {finished} from 'node:stream/promises';\nimport {isStandardStream} from '../utils/standard-stream.js';\n\n// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams\nexport const pipeStreams = (source, destination) => {\n\tsource.pipe(destination);\n\tonSourceFinish(source, destination);\n\tonDestinationFinish(source, destination);\n};\n\n// `source.pipe(destination)` makes `destination` end when `source` ends.\n// But it does not propagate aborts or errors. This function does it.\nconst onSourceFinish = async (source, destination) => {\n\tif (isStandardStream(source) || isStandardStream(destination)) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait finished(source, {cleanup: true, readable: true, writable: false});\n\t} catch {}\n\n\tendDestinationStream(destination);\n};\n\nexport const endDestinationStream = destination => {\n\tif (destination.writable) {\n\t\tdestination.end();\n\t}\n};\n\n// We do the same thing in the other direction as well.\nconst onDestinationFinish = async (source, destination) => {\n\tif (isStandardStream(source) || isStandardStream(destination)) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait finished(destination, {cleanup: true, readable: false, writable: true});\n\t} catch {}\n\n\tabortSourceStream(source);\n};\n\nexport const abortSourceStream = source => {\n\tif (source.readable) {\n\t\tsource.destroy();\n\t}\n};\n","import mergeStreams from '@sindresorhus/merge-streams';\nimport {isStandardStream} from '../utils/standard-stream.js';\nimport {incrementMaxListeners} from '../utils/max-listeners.js';\nimport {TRANSFORM_TYPES} from '../stdio/type.js';\nimport {pipeStreams} from './pipeline.js';\n\n// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode\n// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended\nexport const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {\n\tconst pipeGroups = new Map();\n\n\tfor (const [fdNumber, {stdioItems, direction}] of Object.entries(fileDescriptors)) {\n\t\tfor (const {stream} of stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type))) {\n\t\t\tpipeTransform(subprocess, stream, direction, fdNumber);\n\t\t}\n\n\t\tfor (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {\n\t\t\tpipeStdioItem({\n\t\t\t\tsubprocess,\n\t\t\t\tstream,\n\t\t\t\tdirection,\n\t\t\t\tfdNumber,\n\t\t\t\tpipeGroups,\n\t\t\t\tcontroller,\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const [outputStream, inputStreams] of pipeGroups.entries()) {\n\t\tconst inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);\n\t\tpipeStreams(inputStream, outputStream);\n\t}\n};\n\n// When using transforms, `subprocess.stdin|stdout|stderr|stdio` is directly mutated\nconst pipeTransform = (subprocess, stream, direction, fdNumber) => {\n\tif (direction === 'output') {\n\t\tpipeStreams(subprocess.stdio[fdNumber], stream);\n\t} else {\n\t\tpipeStreams(stream, subprocess.stdio[fdNumber]);\n\t}\n\n\tconst streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];\n\tif (streamProperty !== undefined) {\n\t\tsubprocess[streamProperty] = stream;\n\t}\n\n\tsubprocess.stdio[fdNumber] = stream;\n};\n\nconst SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];\n\n// Most `std*` option values involve piping `subprocess.std*` to a stream.\n// The stream is either passed by the user or created internally.\nconst pipeStdioItem = ({subprocess, stream, direction, fdNumber, pipeGroups, controller}) => {\n\tif (stream === undefined) {\n\t\treturn;\n\t}\n\n\tsetStandardStreamMaxListeners(stream, controller);\n\n\tconst [inputStream, outputStream] = direction === 'output'\n\t\t? [stream, subprocess.stdio[fdNumber]]\n\t\t: [subprocess.stdio[fdNumber], stream];\n\tconst outputStreams = pipeGroups.get(inputStream) ?? [];\n\tpipeGroups.set(inputStream, [...outputStreams, outputStream]);\n};\n\n// Multiple subprocesses might be piping from/to `process.std*` at the same time.\n// This is not necessarily an error and should not print a `maxListeners` warning.\nconst setStandardStreamMaxListeners = (stream, {signal}) => {\n\tif (isStandardStream(stream)) {\n\t\tincrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);\n\t}\n};\n\n// `source.pipe(destination)` adds at most 1 listener for each event.\n// If `stdin` option is an array, the values might be combined with `merge-streams`.\n// That library also listens for `source` end, which adds 1 more listener.\nconst MAX_LISTENERS_INCREMENT = 2;\n","import {addAbortListener} from 'node:events';\nimport {onExit} from 'signal-exit';\n\n// If the `cleanup` option is used, call `subprocess.kill()` when the parent process exits\nexport const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {\n\tif (!cleanup || detached) {\n\t\treturn;\n\t}\n\n\tconst removeExitHandler = onExit(() => {\n\t\tsubprocess.kill();\n\t});\n\taddAbortListener(signal, () => {\n\t\tremoveExitHandler();\n\t});\n};\n","/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems.  Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL.  It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals: NodeJS.Signals[] = []\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM')\n\nif (process.platform !== 'win32') {\n  signals.push(\n    'SIGALRM',\n    'SIGABRT',\n    'SIGVTALRM',\n    'SIGXCPU',\n    'SIGXFSZ',\n    'SIGUSR2',\n    'SIGTRAP',\n    'SIGSYS',\n    'SIGQUIT',\n    'SIGIOT'\n    // should detect profiler and enable/disable accordingly.\n    // see #21\n    // 'SIGPROF'\n  )\n}\n\nif (process.platform === 'linux') {\n  signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT')\n}\n","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js'\nexport { signals }\n\n// just a loosened process type so we can do some evil things\ntype ProcessRE = NodeJS.Process & {\n  reallyExit: (code?: number | undefined | null) => any\n  emit: (ev: string, ...a: any[]) => any\n}\n\nconst processOk = (process: any): process is ProcessRE =>\n  !!process &&\n  typeof process === 'object' &&\n  typeof process.removeListener === 'function' &&\n  typeof process.emit === 'function' &&\n  typeof process.reallyExit === 'function' &&\n  typeof process.listeners === 'function' &&\n  typeof process.kill === 'function' &&\n  typeof process.pid === 'number' &&\n  typeof process.on === 'function'\n\nconst kExitEmitter = Symbol.for('signal-exit emitter')\nconst global: typeof globalThis & { [kExitEmitter]?: Emitter } = globalThis\nconst ObjectDefineProperty = Object.defineProperty.bind(Object)\n\n/**\n * A function that takes an exit code and signal as arguments\n *\n * In the case of signal exits *only*, a return value of true\n * will indicate that the signal is being handled, and we should\n * not synthetically exit with the signal we received. Regardless\n * of the handler return value, the handler is unloaded when an\n * otherwise fatal signal is received, so you get exactly 1 shot\n * at it, unless you add another onExit handler at that point.\n *\n * In the case of numeric code exits, we may already have committed\n * to exiting the process, for example via a fatal exception or\n * unhandled promise rejection, so it is impossible to stop safely.\n */\nexport type Handler = (\n  code: number | null | undefined,\n  signal: NodeJS.Signals | null\n) => true | void\ntype ExitEvent = 'afterExit' | 'exit'\ntype Emitted = { [k in ExitEvent]: boolean }\ntype Listeners = { [k in ExitEvent]: Handler[] }\n\n// teeny special purpose ee\nclass Emitter {\n  emitted: Emitted = {\n    afterExit: false,\n    exit: false,\n  }\n\n  listeners: Listeners = {\n    afterExit: [],\n    exit: [],\n  }\n\n  count: number = 0\n  id: number = Math.random()\n\n  constructor() {\n    if (global[kExitEmitter]) {\n      return global[kExitEmitter]\n    }\n    ObjectDefineProperty(global, kExitEmitter, {\n      value: this,\n      writable: false,\n      enumerable: false,\n      configurable: false,\n    })\n  }\n\n  on(ev: ExitEvent, fn: Handler) {\n    this.listeners[ev].push(fn)\n  }\n\n  removeListener(ev: ExitEvent, fn: Handler) {\n    const list = this.listeners[ev]\n    const i = list.indexOf(fn)\n    /* c8 ignore start */\n    if (i === -1) {\n      return\n    }\n    /* c8 ignore stop */\n    if (i === 0 && list.length === 1) {\n      list.length = 0\n    } else {\n      list.splice(i, 1)\n    }\n  }\n\n  emit(\n    ev: ExitEvent,\n    code: number | null | undefined,\n    signal: NodeJS.Signals | null\n  ): boolean {\n    if (this.emitted[ev]) {\n      return false\n    }\n    this.emitted[ev] = true\n    let ret: boolean = false\n    for (const fn of this.listeners[ev]) {\n      ret = fn(code, signal) === true || ret\n    }\n    if (ev === 'exit') {\n      ret = this.emit('afterExit', code, signal) || ret\n    }\n    return ret\n  }\n}\n\nabstract class SignalExitBase {\n  abstract onExit(cb: Handler, opts?: { alwaysLast?: boolean }): () => void\n  abstract load(): void\n  abstract unload(): void\n}\n\nconst signalExitWrap = <T extends SignalExitBase>(handler: T) => {\n  return {\n    onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n      return handler.onExit(cb, opts)\n    },\n    load() {\n      return handler.load()\n    },\n    unload() {\n      return handler.unload()\n    },\n  }\n}\n\nclass SignalExitFallback extends SignalExitBase {\n  onExit() {\n    return () => {}\n  }\n  load() {}\n  unload() {}\n}\n\nclass SignalExit extends SignalExitBase {\n  // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n  // so use a supported signal instead\n  /* c8 ignore start */\n  #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP'\n  /* c8 ignore stop */\n  #emitter = new Emitter()\n  #process: ProcessRE\n  #originalProcessEmit: ProcessRE['emit']\n  #originalProcessReallyExit: ProcessRE['reallyExit']\n\n  #sigListeners: { [k in NodeJS.Signals]?: () => void } = {}\n  #loaded: boolean = false\n\n  constructor(process: ProcessRE) {\n    super()\n    this.#process = process\n    // { <signal>: <listener fn>, ... }\n    this.#sigListeners = {}\n    for (const sig of signals) {\n      this.#sigListeners[sig] = () => {\n        // If there are no other listeners, an exit is coming!\n        // Simplest way: remove us and then re-send the signal.\n        // We know that this will kill the process, so we can\n        // safely emit now.\n        const listeners = this.#process.listeners(sig)\n        let { count } = this.#emitter\n        // This is a workaround for the fact that signal-exit v3 and signal\n        // exit v4 are not aware of each other, and each will attempt to let\n        // the other handle it, so neither of them do. To correct this, we\n        // detect if we're the only handler *except* for previous versions\n        // of signal-exit, and increment by the count of listeners it has\n        // created.\n        /* c8 ignore start */\n        const p = process as unknown as {\n          __signal_exit_emitter__?: { count: number }\n        }\n        if (\n          typeof p.__signal_exit_emitter__ === 'object' &&\n          typeof p.__signal_exit_emitter__.count === 'number'\n        ) {\n          count += p.__signal_exit_emitter__.count\n        }\n        /* c8 ignore stop */\n        if (listeners.length === count) {\n          this.unload()\n          const ret = this.#emitter.emit('exit', null, sig)\n          /* c8 ignore start */\n          const s = sig === 'SIGHUP' ? this.#hupSig : sig\n          if (!ret) process.kill(process.pid, s)\n          /* c8 ignore stop */\n        }\n      }\n    }\n\n    this.#originalProcessReallyExit = process.reallyExit\n    this.#originalProcessEmit = process.emit\n  }\n\n  onExit(cb: Handler, opts?: { alwaysLast?: boolean }) {\n    /* c8 ignore start */\n    if (!processOk(this.#process)) {\n      return () => {}\n    }\n    /* c8 ignore stop */\n\n    if (this.#loaded === false) {\n      this.load()\n    }\n\n    const ev = opts?.alwaysLast ? 'afterExit' : 'exit'\n    this.#emitter.on(ev, cb)\n    return () => {\n      this.#emitter.removeListener(ev, cb)\n      if (\n        this.#emitter.listeners['exit'].length === 0 &&\n        this.#emitter.listeners['afterExit'].length === 0\n      ) {\n        this.unload()\n      }\n    }\n  }\n\n  load() {\n    if (this.#loaded) {\n      return\n    }\n    this.#loaded = true\n\n    // This is the number of onSignalExit's that are in play.\n    // It's important so that we can count the correct number of\n    // listeners on signals, and don't wait for the other one to\n    // handle it instead of us.\n    this.#emitter.count += 1\n\n    for (const sig of signals) {\n      try {\n        const fn = this.#sigListeners[sig]\n        if (fn) this.#process.on(sig, fn)\n      } catch (_) {}\n    }\n\n    this.#process.emit = (ev: string, ...a: any[]) => {\n      return this.#processEmit(ev, ...a)\n    }\n    this.#process.reallyExit = (code?: number | null | undefined) => {\n      return this.#processReallyExit(code)\n    }\n  }\n\n  unload() {\n    if (!this.#loaded) {\n      return\n    }\n    this.#loaded = false\n\n    signals.forEach(sig => {\n      const listener = this.#sigListeners[sig]\n      /* c8 ignore start */\n      if (!listener) {\n        throw new Error('Listener not defined for signal: ' + sig)\n      }\n      /* c8 ignore stop */\n      try {\n        this.#process.removeListener(sig, listener)\n        /* c8 ignore start */\n      } catch (_) {}\n      /* c8 ignore stop */\n    })\n    this.#process.emit = this.#originalProcessEmit\n    this.#process.reallyExit = this.#originalProcessReallyExit\n    this.#emitter.count -= 1\n  }\n\n  #processReallyExit(code?: number | null | undefined) {\n    /* c8 ignore start */\n    if (!processOk(this.#process)) {\n      return 0\n    }\n    this.#process.exitCode = code || 0\n    /* c8 ignore stop */\n\n    this.#emitter.emit('exit', this.#process.exitCode, null)\n    return this.#originalProcessReallyExit.call(\n      this.#process,\n      this.#process.exitCode\n    )\n  }\n\n  #processEmit(ev: string, ...args: any[]): any {\n    const og = this.#originalProcessEmit\n    if (ev === 'exit' && processOk(this.#process)) {\n      if (typeof args[0] === 'number') {\n        this.#process.exitCode = args[0]\n        /* c8 ignore start */\n      }\n      /* c8 ignore start */\n      const ret = og.call(this.#process, ev, ...args)\n      /* c8 ignore start */\n      this.#emitter.emit('exit', this.#process.exitCode, null)\n      /* c8 ignore stop */\n      return ret\n    } else {\n      return og.call(this.#process, ev, ...args)\n    }\n  }\n}\n\nconst process = globalThis.process\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const {\n  /**\n   * Called when the process is exiting, whether via signal, explicit\n   * exit, or running out of stuff to do.\n   *\n   * If the global process object is not suitable for instrumentation,\n   * then this will be a no-op.\n   *\n   * Returns a function that may be used to unload signal-exit.\n   */\n  onExit,\n\n  /**\n   * Load the listeners.  Likely you never need to call this, unless\n   * doing a rather deep integration with signal-exit functionality.\n   * Mostly exposed for the benefit of testing.\n   *\n   * @internal\n   */\n  load,\n\n  /**\n   * Unload the listeners.  Likely you never need to call this, unless\n   * doing a rather deep integration with signal-exit functionality.\n   * Mostly exposed for the benefit of testing.\n   *\n   * @internal\n   */\n  unload,\n} = signalExitWrap(\n  processOk(process) ? new SignalExit(process) : new SignalExitFallback()\n)\n","import {normalizeParameters} from '../methods/parameters.js';\nimport {getStartTime} from '../return/duration.js';\nimport {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';\nimport {isDenoExecPath} from '../arguments/file-url.js';\n\n// Normalize and validate arguments passed to `source.pipe(destination)`\nexport const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {\n\tconst startTime = getStartTime();\n\tconst {\n\t\tdestination,\n\t\tdestinationStream,\n\t\tdestinationError,\n\t\tfrom,\n\t\tunpipeSignal,\n\t} = getDestinationStream(boundOptions, createNested, pipeArguments);\n\tconst {sourceStream, sourceError} = getSourceStream(source, from);\n\tconst {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);\n\treturn {\n\t\tsourcePromise,\n\t\tsourceStream,\n\t\tsourceOptions,\n\t\tsourceError,\n\t\tdestination,\n\t\tdestinationStream,\n\t\tdestinationError,\n\t\tunpipeSignal,\n\t\tfileDescriptors,\n\t\tstartTime,\n\t};\n};\n\nconst getDestinationStream = (boundOptions, createNested, pipeArguments) => {\n\ttry {\n\t\tconst {\n\t\t\tdestination,\n\t\t\tpipeOptions: {from, to, unpipeSignal} = {},\n\t\t} = getDestination(boundOptions, createNested, ...pipeArguments);\n\t\tconst destinationStream = getToStream(destination, to);\n\t\treturn {\n\t\t\tdestination,\n\t\t\tdestinationStream,\n\t\t\tfrom,\n\t\t\tunpipeSignal,\n\t\t};\n\t} catch (error) {\n\t\treturn {destinationError: error};\n\t}\n};\n\n// Piping subprocesses can use three syntaxes:\n//  - source.pipe('command', commandArguments, pipeOptionsOrDestinationOptions)\n//  - source.pipe`command commandArgument` or source.pipe(pipeOptionsOrDestinationOptions)`command commandArgument`\n//  - source.pipe(execa(...), pipeOptions)\nconst getDestination = (boundOptions, createNested, firstArgument, ...pipeArguments) => {\n\tif (Array.isArray(firstArgument)) {\n\t\tconst destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...pipeArguments);\n\t\treturn {destination, pipeOptions: boundOptions};\n\t}\n\n\tif (typeof firstArgument === 'string' || firstArgument instanceof URL || isDenoExecPath(firstArgument)) {\n\t\tif (Object.keys(boundOptions).length > 0) {\n\t\t\tthrow new TypeError('Please use .pipe(\"file\", ..., options) or .pipe(execa(\"file\", ..., options)) instead of .pipe(options)(\"file\", ...).');\n\t\t}\n\n\t\tconst [rawFile, rawArguments, rawOptions] = normalizeParameters(firstArgument, ...pipeArguments);\n\t\tconst destination = createNested(mapDestinationArguments)(rawFile, rawArguments, rawOptions);\n\t\treturn {destination, pipeOptions: rawOptions};\n\t}\n\n\tif (SUBPROCESS_OPTIONS.has(firstArgument)) {\n\t\tif (Object.keys(boundOptions).length > 0) {\n\t\t\tthrow new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');\n\t\t}\n\n\t\treturn {destination: firstArgument, pipeOptions: pipeArguments[0]};\n\t}\n\n\tthrow new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);\n};\n\n// Force `stdin: 'pipe'` with the destination subprocess\nconst mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});\n\nconst getSourceStream = (source, from) => {\n\ttry {\n\t\tconst sourceStream = getFromStream(source, from);\n\t\treturn {sourceStream};\n\t} catch (error) {\n\t\treturn {sourceError: error};\n\t}\n};\n","import {makeEarlyError} from '../return/result.js';\nimport {abortSourceStream, endDestinationStream} from '../io/pipeline.js';\n\n// When passing invalid arguments to `source.pipe()`, throw asynchronously.\n// We also abort both subprocesses.\nexport const handlePipeArgumentsError = ({\n\tsourceStream,\n\tsourceError,\n\tdestinationStream,\n\tdestinationError,\n\tfileDescriptors,\n\tsourceOptions,\n\tstartTime,\n}) => {\n\tconst error = getPipeArgumentsError({\n\t\tsourceStream,\n\t\tsourceError,\n\t\tdestinationStream,\n\t\tdestinationError,\n\t});\n\tif (error !== undefined) {\n\t\tthrow createNonCommandError({\n\t\t\terror,\n\t\t\tfileDescriptors,\n\t\t\tsourceOptions,\n\t\t\tstartTime,\n\t\t});\n\t}\n};\n\nconst getPipeArgumentsError = ({sourceStream, sourceError, destinationStream, destinationError}) => {\n\tif (sourceError !== undefined && destinationError !== undefined) {\n\t\treturn destinationError;\n\t}\n\n\tif (destinationError !== undefined) {\n\t\tabortSourceStream(sourceStream);\n\t\treturn destinationError;\n\t}\n\n\tif (sourceError !== undefined) {\n\t\tendDestinationStream(destinationStream);\n\t\treturn sourceError;\n\t}\n};\n\n// Specific error return value when passing invalid arguments to `subprocess.pipe()` or when using `unpipeSignal`\nexport const createNonCommandError = ({error, fileDescriptors, sourceOptions, startTime}) => makeEarlyError({\n\terror,\n\tcommand: PIPE_COMMAND_MESSAGE,\n\tescapedCommand: PIPE_COMMAND_MESSAGE,\n\tfileDescriptors,\n\toptions: sourceOptions,\n\tstartTime,\n\tisSync: false,\n});\n\nconst PIPE_COMMAND_MESSAGE = 'source.pipe(destination)';\n","// Like Bash, we await both subprocesses. This is unlike some other shells which only await the destination subprocess.\n// Like Bash with the `pipefail` option, if either subprocess fails, the whole pipe fails.\n// Like Bash, if both subprocesses fail, we return the failure of the destination.\n// This ensures both subprocesses' errors are present, using `error.pipedFrom`.\nexport const waitForBothSubprocesses = async subprocessPromises => {\n\tconst [\n\t\t{status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason},\n\t\t{status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason},\n\t] = await subprocessPromises;\n\n\tif (!destinationResult.pipedFrom.includes(sourceResult)) {\n\t\tdestinationResult.pipedFrom.push(sourceResult);\n\t}\n\n\tif (destinationStatus === 'rejected') {\n\t\tthrow destinationResult;\n\t}\n\n\tif (sourceStatus === 'rejected') {\n\t\tthrow sourceResult;\n\t}\n\n\treturn destinationResult;\n};\n","import {finished} from 'node:stream/promises';\nimport mergeStreams from '@sindresorhus/merge-streams';\nimport {incrementMaxListeners} from '../utils/max-listeners.js';\nimport {pipeStreams} from '../io/pipeline.js';\n\n// The piping behavior is like Bash.\n// In particular, when one subprocess exits, the other is not terminated by a signal.\n// Instead, its stdout (for the source) or stdin (for the destination) closes.\n// If the subprocess uses it, it will make it error with SIGPIPE or EPIPE (for the source) or end (for the destination).\n// If it does not use it, it will continue running.\n// This allows for subprocesses to gracefully exit and lower the coupling between subprocesses.\nexport const pipeSubprocessStream = (sourceStream, destinationStream, maxListenersController) => {\n\tconst mergedStream = MERGED_STREAMS.has(destinationStream)\n\t\t? pipeMoreSubprocessStream(sourceStream, destinationStream)\n\t\t: pipeFirstSubprocessStream(sourceStream, destinationStream);\n\tincrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal);\n\tincrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal);\n\tcleanupMergedStreamsMap(destinationStream);\n\treturn mergedStream;\n};\n\n// We use `merge-streams` to allow for multiple sources to pipe to the same destination.\nconst pipeFirstSubprocessStream = (sourceStream, destinationStream) => {\n\tconst mergedStream = mergeStreams([sourceStream]);\n\tpipeStreams(mergedStream, destinationStream);\n\tMERGED_STREAMS.set(destinationStream, mergedStream);\n\treturn mergedStream;\n};\n\nconst pipeMoreSubprocessStream = (sourceStream, destinationStream) => {\n\tconst mergedStream = MERGED_STREAMS.get(destinationStream);\n\tmergedStream.add(sourceStream);\n\treturn mergedStream;\n};\n\nconst cleanupMergedStreamsMap = async destinationStream => {\n\ttry {\n\t\tawait finished(destinationStream, {cleanup: true, readable: false, writable: true});\n\t} catch {}\n\n\tMERGED_STREAMS.delete(destinationStream);\n};\n\nconst MERGED_STREAMS = new WeakMap();\n\n// Number of listeners set up on `sourceStream` by each `sourceStream.pipe(destinationStream)`\n// Those are added by `merge-streams`\nconst SOURCE_LISTENERS_PER_PIPE = 2;\n// Number of listeners set up on `destinationStream` by each `sourceStream.pipe(destinationStream)`\n// Those are added by `finished()` in `cleanupMergedStreamsMap()`\nconst DESTINATION_LISTENERS_PER_PIPE = 1;\n","import {aborted} from 'node:util';\nimport {createNonCommandError} from './throw.js';\n\n// When passing an `unpipeSignal` option, abort piping when the signal is aborted.\n// However, do not terminate the subprocesses.\nexport const unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined\n\t? []\n\t: [unpipeOnSignalAbort(unpipeSignal, unpipeContext)];\n\nconst unpipeOnSignalAbort = async (unpipeSignal, {sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime}) => {\n\tawait aborted(unpipeSignal, sourceStream);\n\tawait mergedStream.remove(sourceStream);\n\tconst error = new Error('Pipe canceled by `unpipeSignal` option.');\n\tthrow createNonCommandError({\n\t\terror,\n\t\tfileDescriptors,\n\t\tsourceOptions,\n\t\tstartTime,\n\t});\n};\n","import isPlainObject from 'is-plain-obj';\nimport {normalizePipeArguments} from './pipe-arguments.js';\nimport {handlePipeArgumentsError} from './throw.js';\nimport {waitForBothSubprocesses} from './sequence.js';\nimport {pipeSubprocessStream} from './streaming.js';\nimport {unpipeOnAbort} from './abort.js';\n\n// Pipe a subprocess' `stdout`/`stderr`/`stdio` into another subprocess' `stdin`\nexport const pipeToSubprocess = (sourceInfo, ...pipeArguments) => {\n\tif (isPlainObject(pipeArguments[0])) {\n\t\treturn pipeToSubprocess.bind(undefined, {\n\t\t\t...sourceInfo,\n\t\t\tboundOptions: {...sourceInfo.boundOptions, ...pipeArguments[0]},\n\t\t});\n\t}\n\n\tconst {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...pipeArguments);\n\tconst promise = handlePipePromise({...normalizedInfo, destination});\n\tpromise.pipe = pipeToSubprocess.bind(undefined, {\n\t\t...sourceInfo,\n\t\tsource: destination,\n\t\tsourcePromise: promise,\n\t\tboundOptions: {},\n\t});\n\treturn promise;\n};\n\n// Asynchronous logic when piping subprocesses\nconst handlePipePromise = async ({\n\tsourcePromise,\n\tsourceStream,\n\tsourceOptions,\n\tsourceError,\n\tdestination,\n\tdestinationStream,\n\tdestinationError,\n\tunpipeSignal,\n\tfileDescriptors,\n\tstartTime,\n}) => {\n\tconst subprocessPromises = getSubprocessPromises(sourcePromise, destination);\n\thandlePipeArgumentsError({\n\t\tsourceStream,\n\t\tsourceError,\n\t\tdestinationStream,\n\t\tdestinationError,\n\t\tfileDescriptors,\n\t\tsourceOptions,\n\t\tstartTime,\n\t});\n\tconst maxListenersController = new AbortController();\n\ttry {\n\t\tconst mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);\n\t\treturn await Promise.race([\n\t\t\twaitForBothSubprocesses(subprocessPromises),\n\t\t\t...unpipeOnAbort(unpipeSignal, {\n\t\t\t\tsourceStream,\n\t\t\t\tmergedStream,\n\t\t\t\tsourceOptions,\n\t\t\t\tfileDescriptors,\n\t\t\t\tstartTime,\n\t\t\t}),\n\t\t]);\n\t} finally {\n\t\tmaxListenersController.abort();\n\t}\n};\n\n// `.pipe()` awaits the subprocess promises.\n// When invalid arguments are passed to `.pipe()`, we throw an error, which prevents awaiting them.\n// We need to ensure this does not create unhandled rejections.\nconst getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);\n","import {setImmediate} from 'node:timers/promises';\nimport getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';\nimport {isArrayBuffer} from '../utils/uint-array.js';\nimport {shouldLogOutput, logLines} from '../verbose/output.js';\nimport {iterateForResult} from './iterate.js';\nimport {handleMaxBuffer} from './max-buffer.js';\nimport {getStripFinalNewline} from './strip-newline.js';\n\n// Retrieve `result.stdout|stderr|all|stdio[*]`\nexport const getStreamOutput = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {\n\tconst logPromise = logOutputAsync({\n\t\tstream,\n\t\tonStreamEnd,\n\t\tfdNumber,\n\t\tencoding,\n\t\tallMixed,\n\t\tverboseInfo,\n\t\tstreamInfo,\n\t});\n\n\tif (!buffer) {\n\t\tawait Promise.all([resumeStream(stream), logPromise]);\n\t\treturn;\n\t}\n\n\tconst stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);\n\tconst iterable = iterateForResult({\n\t\tstream,\n\t\tonStreamEnd,\n\t\tlines,\n\t\tencoding,\n\t\tstripFinalNewline: stripFinalNewlineValue,\n\t\tallMixed,\n\t});\n\tconst [output] = await Promise.all([\n\t\tgetStreamContents({\n\t\t\tstream,\n\t\t\titerable,\n\t\t\tfdNumber,\n\t\t\tencoding,\n\t\t\tmaxBuffer,\n\t\t\tlines,\n\t\t}),\n\t\tlogPromise,\n\t]);\n\treturn output;\n};\n\nconst logOutputAsync = async ({stream, onStreamEnd, fdNumber, encoding, allMixed, verboseInfo, streamInfo: {fileDescriptors}}) => {\n\tif (!shouldLogOutput({\n\t\tstdioItems: fileDescriptors[fdNumber]?.stdioItems,\n\t\tencoding,\n\t\tverboseInfo,\n\t\tfdNumber,\n\t})) {\n\t\treturn;\n\t}\n\n\tconst linesIterable = iterateForResult({\n\t\tstream,\n\t\tonStreamEnd,\n\t\tlines: true,\n\t\tencoding,\n\t\tstripFinalNewline: true,\n\t\tallMixed,\n\t});\n\tawait logLines(linesIterable, stream, fdNumber, verboseInfo);\n};\n\n// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away\n// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r1465496310\nconst resumeStream = async stream => {\n\tawait setImmediate();\n\tif (stream.readableFlowing === null) {\n\t\tstream.resume();\n\t}\n};\n\nconst getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {\n\ttry {\n\t\tif (readableObjectMode || lines) {\n\t\t\treturn await getStreamAsArray(iterable, {maxBuffer});\n\t\t}\n\n\t\tif (encoding === 'buffer') {\n\t\t\treturn new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));\n\t\t}\n\n\t\treturn await getStream(iterable, {maxBuffer});\n\t} catch (error) {\n\t\treturn handleBufferedData(handleMaxBuffer({\n\t\t\terror,\n\t\t\tstream,\n\t\t\treadableObjectMode,\n\t\t\tlines,\n\t\t\tencoding,\n\t\t\tfdNumber,\n\t\t}));\n\t}\n};\n\n// On failure, `result.stdout|stderr|all` should contain the currently buffered stream\n// They are automatically closed and flushed by Node.js when the subprocess exits\n// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve\nexport const getBufferedData = async streamPromise => {\n\ttry {\n\t\treturn await streamPromise;\n\t} catch (error) {\n\t\treturn handleBufferedData(error);\n\t}\n};\n\n// Ensure we are returning Uint8Arrays when using `encoding: 'buffer'`\nconst handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)\n\t? new Uint8Array(bufferedData)\n\t: bufferedData;\n","import {on} from 'node:events';\nimport {getDefaultHighWaterMark} from 'node:stream';\nimport {getEncodingTransformGenerator} from '../transform/encoding-transform.js';\nimport {getSplitLinesGenerator} from '../transform/split.js';\nimport {transformChunkSync, finalChunksSync} from '../transform/run-sync.js';\n\n// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`\nexport const iterateOnSubprocessStream = ({subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines}) => {\n\tconst controller = new AbortController();\n\tstopReadingOnExit(subprocess, controller);\n\treturn iterateOnStream({\n\t\tstream: subprocessStdout,\n\t\tcontroller,\n\t\tbinary,\n\t\tshouldEncode: !subprocessStdout.readableObjectMode && shouldEncode,\n\t\tencoding,\n\t\tshouldSplit: !subprocessStdout.readableObjectMode,\n\t\tpreserveNewlines,\n\t});\n};\n\nconst stopReadingOnExit = async (subprocess, controller) => {\n\ttry {\n\t\tawait subprocess;\n\t} catch {} finally {\n\t\tcontroller.abort();\n\t}\n};\n\n// Iterate over lines of `subprocess.stdout`, used by `result.stdout` and the `verbose: 'full'` option.\n// Applies the `lines` and `encoding` options.\nexport const iterateForResult = ({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed}) => {\n\tconst controller = new AbortController();\n\tstopReadingOnStreamEnd(onStreamEnd, controller, stream);\n\tconst objectMode = stream.readableObjectMode && !allMixed;\n\treturn iterateOnStream({\n\t\tstream,\n\t\tcontroller,\n\t\tbinary: encoding === 'buffer',\n\t\tshouldEncode: !objectMode,\n\t\tencoding,\n\t\tshouldSplit: !objectMode && lines,\n\t\tpreserveNewlines: !stripFinalNewline,\n\t});\n};\n\nconst stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {\n\ttry {\n\t\tawait onStreamEnd;\n\t} catch {\n\t\tstream.destroy();\n\t} finally {\n\t\tcontroller.abort();\n\t}\n};\n\nconst iterateOnStream = ({stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => {\n\tconst onStdoutChunk = on(stream, 'data', {\n\t\tsignal: controller.signal,\n\t\thighWaterMark: HIGH_WATER_MARK,\n\t\t// Backward compatibility with older name for this option\n\t\t// See https://github.com/nodejs/node/pull/52080#discussion_r1525227861\n\t\t// @todo Remove after removing support for Node 21\n\t\thighWatermark: HIGH_WATER_MARK,\n\t});\n\treturn iterateOnData({\n\t\tonStdoutChunk,\n\t\tcontroller,\n\t\tbinary,\n\t\tshouldEncode,\n\t\tencoding,\n\t\tshouldSplit,\n\t\tpreserveNewlines,\n\t});\n};\n\nexport const DEFAULT_OBJECT_HIGH_WATER_MARK = getDefaultHighWaterMark(true);\n\n// The `highWaterMark` of `events.on()` is measured in number of events, not in bytes.\n// Not knowing the average amount of bytes per `data` event, we use the same heuristic as streams in objectMode, since they have the same issue.\n// Therefore, we use the value of `getDefaultHighWaterMark(true)`.\n// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.\nconst HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;\n\nconst iterateOnData = async function * ({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) {\n\tconst generators = getGenerators({\n\t\tbinary,\n\t\tshouldEncode,\n\t\tencoding,\n\t\tshouldSplit,\n\t\tpreserveNewlines,\n\t});\n\n\ttry {\n\t\tfor await (const [chunk] of onStdoutChunk) {\n\t\t\tyield * transformChunkSync(chunk, generators, 0);\n\t\t}\n\t} catch (error) {\n\t\tif (!controller.signal.aborted) {\n\t\t\tthrow error;\n\t\t}\n\t} finally {\n\t\tyield * finalChunksSync(generators);\n\t}\n};\n\nconst getGenerators = ({binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => [\n\tgetEncodingTransformGenerator(binary, encoding, !shouldEncode),\n\tgetSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {}),\n].filter(Boolean);\n","import {finished} from 'node:stream/promises';\n\n// Wraps `finished(stream)` to handle the following case:\n//  - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.\n//  - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.\nexport const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {\n\tconst state = handleStdinDestroy(stream, streamInfo);\n\tconst abortController = new AbortController();\n\ttry {\n\t\tawait Promise.race([\n\t\t\t...(stopOnExit ? [streamInfo.exitPromise] : []),\n\t\t\tfinished(stream, {cleanup: true, signal: abortController.signal}),\n\t\t]);\n\t} catch (error) {\n\t\tif (!state.stdinCleanedUp) {\n\t\t\thandleStreamError(error, fdNumber, streamInfo, isSameDirection);\n\t\t}\n\t} finally {\n\t\tabortController.abort();\n\t}\n};\n\n// If `subprocess.stdin` is destroyed before being fully written to, it is considered aborted and should throw an error.\n// This can happen for example when user called `subprocess.stdin.destroy()` before `subprocess.stdin.end()`.\n// However, Node.js calls `subprocess.stdin.destroy()` on exit for cleanup purposes.\n// https://github.com/nodejs/node/blob/0b4cdb4b42956cbd7019058e409e06700a199e11/lib/internal/child_process.js#L278\n// This is normal and should not throw an error.\n// Therefore, we need to differentiate between both situations to know whether to throw an error.\n// Unfortunately, events (`close`, `error`, `end`, `exit`) cannot be used because `.destroy()` can take an arbitrary amount of time.\n// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.\n// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.\n// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.\n// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.\nconst handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => {\n\tconst state = {stdinCleanedUp: false};\n\tif (stream === originalStdin) {\n\t\tspyOnStdinDestroy(stream, subprocess, state);\n\t}\n\n\treturn state;\n};\n\nconst spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {\n\tconst {_destroy} = subprocessStdin;\n\tsubprocessStdin._destroy = (...destroyArguments) => {\n\t\tsetStdinCleanedUp(subprocess, state);\n\t\t_destroy.call(subprocessStdin, ...destroyArguments);\n\t};\n};\n\nconst setStdinCleanedUp = ({exitCode, signalCode}, state) => {\n\tif (exitCode !== null || signalCode !== null) {\n\t\tstate.stdinCleanedUp = true;\n\t}\n};\n\n// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.\n// When one stream errors, the error is propagated to the other streams on the same file descriptor.\n// Those other streams might have a different direction due to the above.\n// When this happens, the direction of both the initial stream and the others should then be taken into account.\n// Therefore, we keep track of whether a stream error is currently propagating.\nconst handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {\n\tif (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {\n\t\tthrow error;\n\t}\n};\n\nconst shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {\n\tif (streamInfo.propagating) {\n\t\treturn isStreamEpipe(error) || isStreamAbort(error);\n\t}\n\n\tstreamInfo.propagating = true;\n\treturn isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection\n\t\t? isStreamEpipe(error)\n\t\t: isStreamAbort(error);\n};\n\n// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.\n// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.\n// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).\n// However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.\n// For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.\nexport const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';\n\n// When `stream.destroy()` is called without an `error` argument, stream is aborted.\n// This is the only way to abort a readable stream, which can be useful in some instances.\n// Therefore, we ignore this error on readable streams.\nexport const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';\n\n// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.\n// When piping subprocesses, the source subprocess usually decides when to stop piping.\n// However, there are some instances when the destination does instead, such as `... | head -n1`.\n// It notifies the source by using `EPIPE`.\n// Therefore, we ignore this error on writable streams.\nconst isStreamEpipe = error => error?.code === 'EPIPE';\n","import {getStreamOutput} from '../io/contents.js';\nimport {waitForStream, isInputFileDescriptor} from './wait-stream.js';\n\n// Read the contents of `subprocess.std*` and|or wait for its completion\nexport const waitForStdioStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({\n\tstream,\n\tfdNumber,\n\tencoding,\n\tbuffer: buffer[fdNumber],\n\tmaxBuffer: maxBuffer[fdNumber],\n\tlines: lines[fdNumber],\n\tallMixed: false,\n\tstripFinalNewline,\n\tverboseInfo,\n\tstreamInfo,\n}));\n\n// Read the contents of `subprocess.std*` or `subprocess.all` and|or wait for its completion\nexport const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {\n\tif (!stream) {\n\t\treturn;\n\t}\n\n\tconst onStreamEnd = waitForStream(stream, fdNumber, streamInfo);\n\tif (isInputFileDescriptor(streamInfo, fdNumber)) {\n\t\tawait onStreamEnd;\n\t\treturn;\n\t}\n\n\tconst [output] = await Promise.all([\n\t\tgetStreamOutput({\n\t\t\tstream,\n\t\t\tonStreamEnd,\n\t\t\tfdNumber,\n\t\t\tencoding,\n\t\t\tbuffer,\n\t\t\tmaxBuffer,\n\t\t\tlines,\n\t\t\tallMixed,\n\t\t\tstripFinalNewline,\n\t\t\tverboseInfo,\n\t\t\tstreamInfo,\n\t\t}),\n\t\tonStreamEnd,\n\t]);\n\treturn output;\n};\n","import mergeStreams from '@sindresorhus/merge-streams';\nimport {waitForSubprocessStream} from './stdio.js';\n\n// `all` interleaves `stdout` and `stderr`\nexport const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)\n\t? mergeStreams([stdout, stderr].filter(Boolean))\n\t: undefined;\n\n// Read the contents of `subprocess.all` and|or wait for its completion\nexport const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({\n\t...getAllStream(subprocess, buffer),\n\tfdNumber: 'all',\n\tencoding,\n\tmaxBuffer: maxBuffer[1] + maxBuffer[2],\n\tlines: lines[1] || lines[2],\n\tallMixed: getAllMixed(subprocess),\n\tstripFinalNewline,\n\tverboseInfo,\n\tstreamInfo,\n});\n\nconst getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {\n\tconst buffer = bufferStdout || bufferStderr;\n\tif (!buffer) {\n\t\treturn {stream: all, buffer};\n\t}\n\n\tif (!bufferStdout) {\n\t\treturn {stream: stderr, buffer};\n\t}\n\n\tif (!bufferStderr) {\n\t\treturn {stream: stdout, buffer};\n\t}\n\n\treturn {stream: all, buffer};\n};\n\n// When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:\n//  - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk\n//  - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array\n// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.\nconst getAllMixed = ({all, stdout, stderr}) => all\n\t&& stdout\n\t&& stderr\n\t&& stdout.readableObjectMode !== stderr.readableObjectMode;\n","import {once} from 'node:events';\nimport {isStream as isNodeStream} from 'is-stream';\nimport {throwOnTimeout} from '../terminate/timeout.js';\nimport {throwOnCancel} from '../terminate/cancel.js';\nimport {throwOnGracefulCancel} from '../terminate/graceful.js';\nimport {isStandardStream} from '../utils/standard-stream.js';\nimport {TRANSFORM_TYPES} from '../stdio/type.js';\nimport {getBufferedData} from '../io/contents.js';\nimport {waitForIpcOutput, getBufferedIpcOutput} from '../ipc/buffer-messages.js';\nimport {sendIpcInput} from '../ipc/ipc-input.js';\nimport {waitForAllStream} from './all-async.js';\nimport {waitForStdioStreams} from './stdio.js';\nimport {waitForExit, waitForSuccessfulExit} from './exit-async.js';\nimport {waitForStream} from './wait-stream.js';\n\n// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)\nexport const waitForSubprocessResult = async ({\n\tsubprocess,\n\toptions: {\n\t\tencoding,\n\t\tbuffer,\n\t\tmaxBuffer,\n\t\tlines,\n\t\ttimeoutDuration: timeout,\n\t\tcancelSignal,\n\t\tgracefulCancel,\n\t\tforceKillAfterDelay,\n\t\tstripFinalNewline,\n\t\tipc,\n\t\tipcInput,\n\t},\n\tcontext,\n\tverboseInfo,\n\tfileDescriptors,\n\toriginalStreams,\n\tonInternalError,\n\tcontroller,\n}) => {\n\tconst exitPromise = waitForExit(subprocess, context);\n\tconst streamInfo = {\n\t\toriginalStreams,\n\t\tfileDescriptors,\n\t\tsubprocess,\n\t\texitPromise,\n\t\tpropagating: false,\n\t};\n\n\tconst stdioPromises = waitForStdioStreams({\n\t\tsubprocess,\n\t\tencoding,\n\t\tbuffer,\n\t\tmaxBuffer,\n\t\tlines,\n\t\tstripFinalNewline,\n\t\tverboseInfo,\n\t\tstreamInfo,\n\t});\n\tconst allPromise = waitForAllStream({\n\t\tsubprocess,\n\t\tencoding,\n\t\tbuffer,\n\t\tmaxBuffer,\n\t\tlines,\n\t\tstripFinalNewline,\n\t\tverboseInfo,\n\t\tstreamInfo,\n\t});\n\tconst ipcOutput = [];\n\tconst ipcOutputPromise = waitForIpcOutput({\n\t\tsubprocess,\n\t\tbuffer,\n\t\tmaxBuffer,\n\t\tipc,\n\t\tipcOutput,\n\t\tverboseInfo,\n\t});\n\tconst originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);\n\tconst customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);\n\n\ttry {\n\t\treturn await Promise.race([\n\t\t\tPromise.all([\n\t\t\t\t{},\n\t\t\t\twaitForSuccessfulExit(exitPromise),\n\t\t\t\tPromise.all(stdioPromises),\n\t\t\t\tallPromise,\n\t\t\t\tipcOutputPromise,\n\t\t\t\tsendIpcInput(subprocess, ipcInput),\n\t\t\t\t...originalPromises,\n\t\t\t\t...customStreamsEndPromises,\n\t\t\t]),\n\t\t\tonInternalError,\n\t\t\tthrowOnSubprocessError(subprocess, controller),\n\t\t\t...throwOnTimeout(subprocess, timeout, context, controller),\n\t\t\t...throwOnCancel({\n\t\t\t\tsubprocess,\n\t\t\t\tcancelSignal,\n\t\t\t\tgracefulCancel,\n\t\t\t\tcontext,\n\t\t\t\tcontroller,\n\t\t\t}),\n\t\t\t...throwOnGracefulCancel({\n\t\t\t\tsubprocess,\n\t\t\t\tcancelSignal,\n\t\t\t\tgracefulCancel,\n\t\t\t\tforceKillAfterDelay,\n\t\t\t\tcontext,\n\t\t\t\tcontroller,\n\t\t\t}),\n\t\t]);\n\t} catch (error) {\n\t\tcontext.terminationReason ??= 'other';\n\t\treturn Promise.all([\n\t\t\t{error},\n\t\t\texitPromise,\n\t\t\tPromise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise))),\n\t\t\tgetBufferedData(allPromise),\n\t\t\tgetBufferedIpcOutput(ipcOutputPromise, ipcOutput),\n\t\t\tPromise.allSettled(originalPromises),\n\t\t\tPromise.allSettled(customStreamsEndPromises),\n\t\t]);\n\t}\n};\n\n// Transforms replace `subprocess.std*`, which means they are not exposed to users.\n// However, we still want to wait for their completion.\nconst waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>\n\toriginalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]\n\t\t? undefined\n\t\t: waitForStream(stream, fdNumber, streamInfo));\n\n// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.\n// The `.pipe()` method automatically ends that stream when `subprocess` ends.\n// This makes sure we wait for the completion of those streams, in order to catch any error.\nconst waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({stdioItems}, fdNumber) => stdioItems\n\t.filter(({value, stream = value}) => isNodeStream(stream, {checkOpen: false}) && !isStandardStream(stream))\n\t.map(({type, value, stream = value}) => waitForStream(stream, fdNumber, streamInfo, {\n\t\tisSameDirection: TRANSFORM_TYPES.has(type),\n\t\tstopOnExit: type === 'native',\n\t})));\n\n// Fails when the subprocess emits an `error` event\nconst throwOnSubprocessError = async (subprocess, {signal}) => {\n\tconst [error] = await once(subprocess, 'error', {signal});\n\tthrow error;\n};\n","import {verboseLog, serializeVerboseMessage} from './log.js';\nimport {isFullVerbose} from './values.js';\n\n// When `verbose` is `'full'`, print IPC messages from the subprocess\nexport const shouldLogIpc = verboseInfo => isFullVerbose(verboseInfo, 'ipc');\n\nexport const logIpcOutput = (message, verboseInfo) => {\n\tconst verboseMessage = serializeVerboseMessage(message);\n\tverboseLog({\n\t\ttype: 'ipc',\n\t\tverboseMessage,\n\t\tfdNumber: 'ipc',\n\t\tverboseInfo,\n\t});\n};\n","import {checkIpcMaxBuffer} from '../io/max-buffer.js';\nimport {shouldLogIpc, logIpcOutput} from '../verbose/ipc.js';\nimport {getFdSpecificValue} from '../arguments/specific.js';\nimport {loopOnMessages} from './get-each.js';\n\n// Iterate through IPC messages sent by the subprocess\nexport const waitForIpcOutput = async ({\n\tsubprocess,\n\tbuffer: bufferArray,\n\tmaxBuffer: maxBufferArray,\n\tipc,\n\tipcOutput,\n\tverboseInfo,\n}) => {\n\tif (!ipc) {\n\t\treturn ipcOutput;\n\t}\n\n\tconst isVerbose = shouldLogIpc(verboseInfo);\n\tconst buffer = getFdSpecificValue(bufferArray, 'ipc');\n\tconst maxBuffer = getFdSpecificValue(maxBufferArray, 'ipc');\n\n\tfor await (const message of loopOnMessages({\n\t\tanyProcess: subprocess,\n\t\tchannel: subprocess.channel,\n\t\tisSubprocess: false,\n\t\tipc,\n\t\tshouldAwait: false,\n\t\treference: true,\n\t})) {\n\t\tif (buffer) {\n\t\t\tcheckIpcMaxBuffer(subprocess, ipcOutput, maxBuffer);\n\t\t\tipcOutput.push(message);\n\t\t}\n\n\t\tif (isVerbose) {\n\t\t\tlogIpcOutput(message, verboseInfo);\n\t\t}\n\t}\n\n\treturn ipcOutput;\n};\n\nexport const getBufferedIpcOutput = async (ipcOutputPromise, ipcOutput) => {\n\tawait Promise.allSettled([ipcOutputPromise]);\n\treturn ipcOutput;\n};\n","import {createDeferred} from '../utils/deferred.js';\n\n// When using multiple `.readable()`/`.writable()`/`.duplex()`, `final` and `destroy` should wait for other streams\nexport const initializeConcurrentStreams = () => ({\n\treadableDestroy: new WeakMap(),\n\twritableFinal: new WeakMap(),\n\twritableDestroy: new WeakMap(),\n});\n\n// Each file descriptor + `waitName` has its own array of promises.\n// Each promise is a single `.readable()`/`.writable()`/`.duplex()` call.\nexport const addConcurrentStream = (concurrentStreams, stream, waitName) => {\n\tconst weakMap = concurrentStreams[waitName];\n\tif (!weakMap.has(stream)) {\n\t\tweakMap.set(stream, []);\n\t}\n\n\tconst promises = weakMap.get(stream);\n\tconst promise = createDeferred();\n\tpromises.push(promise);\n\tconst resolve = promise.resolve.bind(promise);\n\treturn {resolve, promises};\n};\n\n// Wait for other streams, but stop waiting when subprocess ends\nexport const waitForConcurrentStreams = async ({resolve, promises}, subprocess) => {\n\tresolve();\n\tconst [isSubprocessExit] = await Promise.race([\n\t\tPromise.allSettled([true, subprocess]),\n\t\tPromise.all([false, ...promises]),\n\t]);\n\treturn !isSubprocessExit;\n};\n","import {Readable} from 'node:stream';\nimport {callbackify} from 'node:util';\nimport {BINARY_ENCODINGS} from '../arguments/encoding-option.js';\nimport {getFromStream} from '../arguments/fd-options.js';\nimport {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';\nimport {createDeferred} from '../utils/deferred.js';\nimport {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';\nimport {\n\tsafeWaitForSubprocessStdin,\n\twaitForSubprocessStdout,\n\twaitForSubprocess,\n\tdestroyOtherStream,\n} from './shared.js';\n\n// Create a `Readable` stream that forwards from `stdout` and awaits the subprocess\nexport const createReadable = ({subprocess, concurrentStreams, encoding}, {from, binary: binaryOption = true, preserveNewlines = true} = {}) => {\n\tconst binary = binaryOption || BINARY_ENCODINGS.has(encoding);\n\tconst {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);\n\tconst {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);\n\tconst {read, onStdoutDataDone} = getReadableMethods({\n\t\tsubprocessStdout,\n\t\tsubprocess,\n\t\tbinary,\n\t\tencoding,\n\t\tpreserveNewlines,\n\t});\n\tconst readable = new Readable({\n\t\tread,\n\t\tdestroy: callbackify(onReadableDestroy.bind(undefined, {subprocessStdout, subprocess, waitReadableDestroy})),\n\t\thighWaterMark: readableHighWaterMark,\n\t\tobjectMode: readableObjectMode,\n\t\tencoding: readableEncoding,\n\t});\n\tonStdoutFinished({\n\t\tsubprocessStdout,\n\t\tonStdoutDataDone,\n\t\treadable,\n\t\tsubprocess,\n\t});\n\treturn readable;\n};\n\n// Retrieve `stdout` (or other stream depending on `from`)\nexport const getSubprocessStdout = (subprocess, from, concurrentStreams) => {\n\tconst subprocessStdout = getFromStream(subprocess, from);\n\tconst waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, 'readableDestroy');\n\treturn {subprocessStdout, waitReadableDestroy};\n};\n\nexport const getReadableOptions = ({readableEncoding, readableObjectMode, readableHighWaterMark}, binary) => binary\n\t? {readableEncoding, readableObjectMode, readableHighWaterMark}\n\t: {readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK};\n\nexport const getReadableMethods = ({subprocessStdout, subprocess, binary, encoding, preserveNewlines}) => {\n\tconst onStdoutDataDone = createDeferred();\n\tconst onStdoutData = iterateOnSubprocessStream({\n\t\tsubprocessStdout,\n\t\tsubprocess,\n\t\tbinary,\n\t\tshouldEncode: !binary,\n\t\tencoding,\n\t\tpreserveNewlines,\n\t});\n\n\treturn {\n\t\tread() {\n\t\t\tonRead(this, onStdoutData, onStdoutDataDone);\n\t\t},\n\t\tonStdoutDataDone,\n\t};\n};\n\n// Forwards data from `stdout` to `readable`\nconst onRead = async (readable, onStdoutData, onStdoutDataDone) => {\n\ttry {\n\t\tconst {value, done} = await onStdoutData.next();\n\t\tif (done) {\n\t\t\tonStdoutDataDone.resolve();\n\t\t} else {\n\t\t\treadable.push(value);\n\t\t}\n\t} catch {}\n};\n\n// When `subprocess.stdout` ends/aborts/errors, do the same on `readable`.\n// Await the subprocess, for the same reason as above.\nexport const onStdoutFinished = async ({subprocessStdout, onStdoutDataDone, readable, subprocess, subprocessStdin}) => {\n\ttry {\n\t\tawait waitForSubprocessStdout(subprocessStdout);\n\t\tawait subprocess;\n\t\tawait safeWaitForSubprocessStdin(subprocessStdin);\n\t\tawait onStdoutDataDone;\n\n\t\tif (readable.readable) {\n\t\t\treadable.push(null);\n\t\t}\n\t} catch (error) {\n\t\tawait safeWaitForSubprocessStdin(subprocessStdin);\n\t\tdestroyOtherReadable(readable, error);\n\t}\n};\n\n// When `readable` aborts/errors, do the same on `subprocess.stdout`\nexport const onReadableDestroy = async ({subprocessStdout, subprocess, waitReadableDestroy}, error) => {\n\tif (await waitForConcurrentStreams(waitReadableDestroy, subprocess)) {\n\t\tdestroyOtherReadable(subprocessStdout, error);\n\t\tawait waitForSubprocess(subprocess, error);\n\t}\n};\n\nconst destroyOtherReadable = (stream, error) => {\n\tdestroyOtherStream(stream, stream.readable, error);\n};\n","import {finished} from 'node:stream/promises';\nimport {isStreamAbort} from '../resolve/wait-stream.js';\n\nexport const safeWaitForSubprocessStdin = async subprocessStdin => {\n\tif (subprocessStdin === undefined) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait waitForSubprocessStdin(subprocessStdin);\n\t} catch {}\n};\n\nexport const safeWaitForSubprocessStdout = async subprocessStdout => {\n\tif (subprocessStdout === undefined) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait waitForSubprocessStdout(subprocessStdout);\n\t} catch {}\n};\n\nexport const waitForSubprocessStdin = async subprocessStdin => {\n\tawait finished(subprocessStdin, {cleanup: true, readable: false, writable: true});\n};\n\nexport const waitForSubprocessStdout = async subprocessStdout => {\n\tawait finished(subprocessStdout, {cleanup: true, readable: true, writable: false});\n};\n\n// When `readable` or `writable` aborts/errors, awaits the subprocess, for the reason mentioned above\nexport const waitForSubprocess = async (subprocess, error) => {\n\tawait subprocess;\n\tif (error) {\n\t\tthrow error;\n\t}\n};\n\nexport const destroyOtherStream = (stream, isOpen, error) => {\n\tif (error && !isStreamAbort(error)) {\n\t\tstream.destroy(error);\n\t} else if (isOpen) {\n\t\tstream.destroy();\n\t}\n};\n","import {Writable} from 'node:stream';\nimport {callbackify} from 'node:util';\nimport {getToStream} from '../arguments/fd-options.js';\nimport {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';\nimport {\n\tsafeWaitForSubprocessStdout,\n\twaitForSubprocessStdin,\n\twaitForSubprocess,\n\tdestroyOtherStream,\n} from './shared.js';\n\n// Create a `Writable` stream that forwards to `stdin` and awaits the subprocess\nexport const createWritable = ({subprocess, concurrentStreams}, {to} = {}) => {\n\tconst {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);\n\tconst writable = new Writable({\n\t\t...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),\n\t\tdestroy: callbackify(onWritableDestroy.bind(undefined, {\n\t\t\tsubprocessStdin,\n\t\t\tsubprocess,\n\t\t\twaitWritableFinal,\n\t\t\twaitWritableDestroy,\n\t\t})),\n\t\thighWaterMark: subprocessStdin.writableHighWaterMark,\n\t\tobjectMode: subprocessStdin.writableObjectMode,\n\t});\n\tonStdinFinished(subprocessStdin, writable);\n\treturn writable;\n};\n\n// Retrieve `stdin` (or other stream depending on `to`)\nexport const getSubprocessStdin = (subprocess, to, concurrentStreams) => {\n\tconst subprocessStdin = getToStream(subprocess, to);\n\tconst waitWritableFinal = addConcurrentStream(concurrentStreams, subprocessStdin, 'writableFinal');\n\tconst waitWritableDestroy = addConcurrentStream(concurrentStreams, subprocessStdin, 'writableDestroy');\n\treturn {subprocessStdin, waitWritableFinal, waitWritableDestroy};\n};\n\nexport const getWritableMethods = (subprocessStdin, subprocess, waitWritableFinal) => ({\n\twrite: onWrite.bind(undefined, subprocessStdin),\n\tfinal: callbackify(onWritableFinal.bind(undefined, subprocessStdin, subprocess, waitWritableFinal)),\n});\n\n// Forwards data from `writable` to `stdin`\nconst onWrite = (subprocessStdin, chunk, encoding, done) => {\n\tif (subprocessStdin.write(chunk, encoding)) {\n\t\tdone();\n\t} else {\n\t\tsubprocessStdin.once('drain', done);\n\t}\n};\n\n// Ensures that the writable `final` and readable `end` events awaits the subprocess.\n// Like this, any subprocess failure is propagated as a stream `error` event, instead of being lost.\n// The user does not need to `await` the subprocess anymore, but now needs to await the stream completion or error.\n// When multiple writables are targeting the same stream, they wait for each other, unless the subprocess ends first.\nconst onWritableFinal = async (subprocessStdin, subprocess, waitWritableFinal) => {\n\tif (await waitForConcurrentStreams(waitWritableFinal, subprocess)) {\n\t\tif (subprocessStdin.writable) {\n\t\t\tsubprocessStdin.end();\n\t\t}\n\n\t\tawait subprocess;\n\t}\n};\n\n// When `subprocess.stdin` ends/aborts/errors, do the same on `writable`.\nexport const onStdinFinished = async (subprocessStdin, writable, subprocessStdout) => {\n\ttry {\n\t\tawait waitForSubprocessStdin(subprocessStdin);\n\t\tif (writable.writable) {\n\t\t\twritable.end();\n\t\t}\n\t} catch (error) {\n\t\tawait safeWaitForSubprocessStdout(subprocessStdout);\n\t\tdestroyOtherWritable(writable, error);\n\t}\n};\n\n// When `writable` aborts/errors, do the same on `subprocess.stdin`\nexport const onWritableDestroy = async ({subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy}, error) => {\n\tawait waitForConcurrentStreams(waitWritableFinal, subprocess);\n\tif (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {\n\t\tdestroyOtherWritable(subprocessStdin, error);\n\t\tawait waitForSubprocess(subprocess, error);\n\t}\n};\n\nconst destroyOtherWritable = (stream, error) => {\n\tdestroyOtherStream(stream, stream.writable, error);\n};\n","import {Duplex} from 'node:stream';\nimport {callbackify} from 'node:util';\nimport {BINARY_ENCODINGS} from '../arguments/encoding-option.js';\nimport {\n\tgetSubprocessStdout,\n\tgetReadableOptions,\n\tgetReadableMethods,\n\tonStdoutFinished,\n\tonReadableDestroy,\n} from './readable.js';\nimport {\n\tgetSubprocessStdin,\n\tgetWritableMethods,\n\tonStdinFinished,\n\tonWritableDestroy,\n} from './writable.js';\n\n// Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`\nexport const createDuplex = ({subprocess, concurrentStreams, encoding}, {from, to, binary: binaryOption = true, preserveNewlines = true} = {}) => {\n\tconst binary = binaryOption || BINARY_ENCODINGS.has(encoding);\n\tconst {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);\n\tconst {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);\n\tconst {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);\n\tconst {read, onStdoutDataDone} = getReadableMethods({\n\t\tsubprocessStdout,\n\t\tsubprocess,\n\t\tbinary,\n\t\tencoding,\n\t\tpreserveNewlines,\n\t});\n\tconst duplex = new Duplex({\n\t\tread,\n\t\t...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),\n\t\tdestroy: callbackify(onDuplexDestroy.bind(undefined, {\n\t\t\tsubprocessStdout,\n\t\t\tsubprocessStdin,\n\t\t\tsubprocess,\n\t\t\twaitReadableDestroy,\n\t\t\twaitWritableFinal,\n\t\t\twaitWritableDestroy,\n\t\t})),\n\t\treadableHighWaterMark,\n\t\twritableHighWaterMark: subprocessStdin.writableHighWaterMark,\n\t\treadableObjectMode,\n\t\twritableObjectMode: subprocessStdin.writableObjectMode,\n\t\tencoding: readableEncoding,\n\t});\n\tonStdoutFinished({\n\t\tsubprocessStdout,\n\t\tonStdoutDataDone,\n\t\treadable: duplex,\n\t\tsubprocess,\n\t\tsubprocessStdin,\n\t});\n\tonStdinFinished(subprocessStdin, duplex, subprocessStdout);\n\treturn duplex;\n};\n\nconst onDuplexDestroy = async ({subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy}, error) => {\n\tawait Promise.all([\n\t\tonReadableDestroy({subprocessStdout, subprocess, waitReadableDestroy}, error),\n\t\tonWritableDestroy({\n\t\t\tsubprocessStdin,\n\t\t\tsubprocess,\n\t\t\twaitWritableFinal,\n\t\t\twaitWritableDestroy,\n\t\t}, error),\n\t]);\n};\n","import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';\nimport {getFromStream} from '../arguments/fd-options.js';\nimport {iterateOnSubprocessStream} from '../io/iterate.js';\n\n// Convert the subprocess to an async iterable\nexport const createIterable = (subprocess, encoding, {\n\tfrom,\n\tbinary: binaryOption = false,\n\tpreserveNewlines = false,\n} = {}) => {\n\tconst binary = binaryOption || BINARY_ENCODINGS.has(encoding);\n\tconst subprocessStdout = getFromStream(subprocess, from);\n\tconst onStdoutData = iterateOnSubprocessStream({\n\t\tsubprocessStdout,\n\t\tsubprocess,\n\t\tbinary,\n\t\tshouldEncode: true,\n\t\tencoding,\n\t\tpreserveNewlines,\n\t});\n\treturn iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess);\n};\n\nconst iterateOnStdoutData = async function * (onStdoutData, subprocessStdout, subprocess) {\n\ttry {\n\t\tyield * onStdoutData;\n\t} finally {\n\t\tif (subprocessStdout.readable) {\n\t\t\tsubprocessStdout.destroy();\n\t\t}\n\n\t\tawait subprocess;\n\t}\n};\n","import {initializeConcurrentStreams} from './concurrent.js';\nimport {createReadable} from './readable.js';\nimport {createWritable} from './writable.js';\nimport {createDuplex} from './duplex.js';\nimport {createIterable} from './iterable.js';\n\n// Add methods to convert the subprocess to a stream or iterable\nexport const addConvertedStreams = (subprocess, {encoding}) => {\n\tconst concurrentStreams = initializeConcurrentStreams();\n\tsubprocess.readable = createReadable.bind(undefined, {subprocess, concurrentStreams, encoding});\n\tsubprocess.writable = createWritable.bind(undefined, {subprocess, concurrentStreams});\n\tsubprocess.duplex = createDuplex.bind(undefined, {subprocess, concurrentStreams, encoding});\n\tsubprocess.iterable = createIterable.bind(undefined, subprocess, encoding);\n\tsubprocess[Symbol.asyncIterator] = createIterable.bind(undefined, subprocess, encoding, {});\n};\n","// The return value is a mixin of `subprocess` and `Promise`\nexport const mergePromise = (subprocess, promise) => {\n\tfor (const [property, descriptor] of descriptors) {\n\t\tconst value = descriptor.value.bind(promise);\n\t\tReflect.defineProperty(subprocess, property, {...descriptor, value});\n\t}\n};\n\n// eslint-disable-next-line unicorn/prefer-top-level-await\nconst nativePromisePrototype = (async () => {})().constructor.prototype;\n\nconst descriptors = ['then', 'catch', 'finally'].map(property => [\n\tproperty,\n\tReflect.getOwnPropertyDescriptor(nativePromisePrototype, property),\n]);\n","import isPlainObject from 'is-plain-obj';\nimport {FD_SPECIFIC_OPTIONS} from '../arguments/specific.js';\n\n// Deep merge specific options like `env`. Shallow merge the other ones.\nexport const mergeOptions = (boundOptions, options) => {\n\tconst newOptions = Object.fromEntries(\n\t\tObject.entries(options).map(([optionName, optionValue]) => [\n\t\t\toptionName,\n\t\t\tmergeOption(optionName, boundOptions[optionName], optionValue),\n\t\t]),\n\t);\n\treturn {...boundOptions, ...newOptions};\n};\n\nconst mergeOption = (optionName, boundOptionValue, optionValue) => {\n\tif (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {\n\t\treturn {...boundOptionValue, ...optionValue};\n\t}\n\n\treturn optionValue;\n};\n\nconst DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);\n","import isPlainObject from 'is-plain-obj';\nimport {normalizeParameters} from './parameters.js';\nimport {isTemplateString, parseTemplates} from './template.js';\nimport {execaCoreSync} from './main-sync.js';\nimport {execaCoreAsync} from './main-async.js';\nimport {mergeOptions} from './bind.js';\n\n// Wraps every exported methods to provide the following features:\n//  - template string syntax: execa`command argument`\n//  - options binding: boundExeca = execa(options)\n//  - optional argument/options: execa(file), execa(file, args), execa(file, options), execa(file, args, options)\n// `mapArguments()` and `setBoundExeca()` allows for method-specific logic.\nexport const createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => {\n\tconst createNested = (mapArguments, boundOptions, setBoundExeca) => createExeca(mapArguments, boundOptions, deepOptions, setBoundExeca);\n\tconst boundExeca = (...execaArguments) => callBoundExeca({\n\t\tmapArguments,\n\t\tdeepOptions,\n\t\tboundOptions,\n\t\tsetBoundExeca,\n\t\tcreateNested,\n\t}, ...execaArguments);\n\n\tif (setBoundExeca !== undefined) {\n\t\tsetBoundExeca(boundExeca, createNested, boundOptions);\n\t}\n\n\treturn boundExeca;\n};\n\nconst callBoundExeca = ({mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested}, firstArgument, ...nextArguments) => {\n\tif (isPlainObject(firstArgument)) {\n\t\treturn createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca);\n\t}\n\n\tconst {file, commandArguments, options, isSync} = parseArguments({\n\t\tmapArguments,\n\t\tfirstArgument,\n\t\tnextArguments,\n\t\tdeepOptions,\n\t\tboundOptions,\n\t});\n\treturn isSync\n\t\t? execaCoreSync(file, commandArguments, options)\n\t\t: execaCoreAsync(file, commandArguments, options, createNested);\n};\n\nconst parseArguments = ({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions}) => {\n\tconst callArguments = isTemplateString(firstArgument)\n\t\t? parseTemplates(firstArgument, nextArguments)\n\t\t: [firstArgument, ...nextArguments];\n\tconst [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments);\n\tconst mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions);\n\tconst {\n\t\tfile = initialFile,\n\t\tcommandArguments = initialArguments,\n\t\toptions = mergedOptions,\n\t\tisSync = false,\n\t} = mapArguments({file: initialFile, commandArguments: initialArguments, options: mergedOptions});\n\treturn {\n\t\tfile,\n\t\tcommandArguments,\n\t\toptions,\n\t\tisSync,\n\t};\n};\n","// Main logic for `execaCommand()`\nexport const mapCommandAsync = ({file, commandArguments}) => parseCommand(file, commandArguments);\n\n// Main logic for `execaCommandSync()`\nexport const mapCommandSync = ({file, commandArguments}) => ({...parseCommand(file, commandArguments), isSync: true});\n\n// Convert `execaCommand(command)` into `execa(file, ...commandArguments)`\nconst parseCommand = (command, unusedArguments) => {\n\tif (unusedArguments.length > 0) {\n\t\tthrow new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`);\n\t}\n\n\tconst [file, ...commandArguments] = parseCommandString(command);\n\treturn {file, commandArguments};\n};\n\n// Convert `command` string into an array of file or arguments to pass to $`${...fileOrCommandArguments}`\nexport const parseCommandString = command => {\n\tif (typeof command !== 'string') {\n\t\tthrow new TypeError(`The command must be a string: ${String(command)}.`);\n\t}\n\n\tconst trimmedCommand = command.trim();\n\tif (trimmedCommand === '') {\n\t\treturn [];\n\t}\n\n\tconst tokens = [];\n\tfor (const token of trimmedCommand.split(SPACES_REGEXP)) {\n\t\t// Allow spaces to be escaped by a backslash if not meant as a delimiter\n\t\tconst previousToken = tokens.at(-1);\n\t\tif (previousToken && previousToken.endsWith('\\\\')) {\n\t\t\t// Merge previous token with current one\n\t\t\ttokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;\n\t\t} else {\n\t\t\ttokens.push(token);\n\t\t}\n\t}\n\n\treturn tokens;\n};\n\nconst SPACES_REGEXP = / +/g;\n","// Sets `$.sync` and `$.s`\nexport const setScriptSync = (boundExeca, createNested, boundOptions) => {\n\tboundExeca.sync = createNested(mapScriptSync, boundOptions);\n\tboundExeca.s = boundExeca.sync;\n};\n\n// Main logic for `$`\nexport const mapScriptAsync = ({options}) => getScriptOptions(options);\n\n// Main logic for `$.sync`\nconst mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});\n\n// `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`\nconst getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});\n\nconst getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined\n\t? {stdin: 'inherit'}\n\t: {};\n\n// When using $(...).pipe(...), most script-friendly options should apply to both commands.\n// However, some options (like `stdin: 'inherit'`) would create issues with piping, i.e. cannot be deep.\nexport const deepScriptOptions = {preferLocal: true};\n","import {createExeca} from './lib/methods/create.js';\nimport {mapCommandAsync, mapCommandSync} from './lib/methods/command.js';\nimport {mapNode} from './lib/methods/node.js';\nimport {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/methods/script.js';\nimport {getIpcExport} from './lib/ipc/methods.js';\n\nexport {parseCommandString} from './lib/methods/command.js';\nexport {ExecaError, ExecaSyncError} from './lib/return/final-error.js';\n\nexport const execa = createExeca(() => ({}));\nexport const execaSync = createExeca(() => ({isSync: true}));\nexport const execaCommand = createExeca(mapCommandAsync);\nexport const execaCommandSync = createExeca(mapCommandSync);\nexport const execaNode = createExeca(mapNode);\nexport const $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);\n\nconst {\n\tsendMessage,\n\tgetOneMessage,\n\tgetEachMessage,\n\tgetCancelSignal,\n} = getIpcExport();\nexport {\n\tsendMessage,\n\tgetOneMessage,\n\tgetEachMessage,\n\tgetCancelSignal,\n};\n","import {\n  REMIX_ERROR_CODES\n} from \"./chunk-GC2MOT3U.js\";\nimport {\n  RemixError\n} from \"./chunk-7XJGOKEO.js\";\n\n// src/infrastructure/repo/gitRepo.ts\nimport fs from \"fs/promises\";\nimport { createHash } from \"crypto\";\nimport os from \"os\";\nimport path from \"path\";\n\n// src/infrastructure/git/gitAdapter.ts\nimport { execa } from \"execa\";\nfunction createGitCommandPlan(params) {\n  return {\n    command: \"git\",\n    args: [...params.args],\n    cwd: params.cwd,\n    ...params.env ? { env: params.env } : {},\n    ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},\n    ...params.maxBuffer !== void 0 ? { maxBuffer: params.maxBuffer } : {},\n    ...params.stripFinalNewline !== void 0 ? { stripFinalNewline: params.stripFinalNewline } : {},\n    ...params.reject !== void 0 ? { reject: params.reject } : {},\n    ...params.stderr !== void 0 ? { stderr: params.stderr } : {}\n  };\n}\nfunction createSystemGitAdapter() {\n  return {\n    async run(plan) {\n      const res = await execa(plan.command, plan.args, {\n        cwd: plan.cwd,\n        reject: plan.reject ?? false,\n        stderr: plan.stderr ?? \"pipe\",\n        ...plan.env ? { env: plan.env } : {},\n        ...plan.timeoutMs !== void 0 ? { timeout: plan.timeoutMs } : {},\n        ...plan.maxBuffer !== void 0 ? { maxBuffer: plan.maxBuffer } : {},\n        ...plan.stripFinalNewline !== void 0 ? { stripFinalNewline: plan.stripFinalNewline } : {}\n      });\n      return {\n        exitCode: res.exitCode ?? -1,\n        stdout: String(res.stdout ?? \"\"),\n        stderr: String(res.stderr ?? \"\"),\n        timedOut: res.timedOut === true\n      };\n    }\n  };\n}\n\n// src/infrastructure/repo/gitRepo.ts\nvar GIT_REMOTE_PROTOCOL_RE = /^(https?|ssh):\\/\\//i;\nvar SCP_LIKE_GIT_REMOTE_RE = /^(?<user>[^@\\s]+)@(?<host>[^:\\s]+):(?<path>[^\\\\\\s]+)$/;\nvar CANONICAL_GIT_REMOTE_RE = /^(?<host>(?:localhost|[a-z0-9.-]+))\\/(?<path>[^\\\\\\s]+)$/i;\nasync function runGit(args, cwd) {\n  const res = await createSystemGitAdapter().run(createGitCommandPlan({ args, cwd, reject: true, stderr: \"ignore\" }));\n  return String(res.stdout || \"\").trim();\n}\nasync function runGitWithEnv(args, cwd, env) {\n  const res = await createSystemGitAdapter().run(createGitCommandPlan({ args, cwd, env, reject: true, stderr: \"ignore\" }));\n  return String(res.stdout || \"\").trim();\n}\nasync function runGitRaw(args, cwd) {\n  const res = await createSystemGitAdapter().run(createGitCommandPlan({ args, cwd, stripFinalNewline: false, reject: true, stderr: \"ignore\" }));\n  return String(res.stdout || \"\");\n}\nasync function runGitRawWithEnv(args, cwd, env) {\n  const res = await createSystemGitAdapter().run(createGitCommandPlan({ args, cwd, env, stripFinalNewline: false, reject: true, stderr: \"ignore\" }));\n  return String(res.stdout || \"\");\n}\nasync function runGitDetailed(args, cwd) {\n  const res = await createSystemGitAdapter().run(createGitCommandPlan({ args, cwd }));\n  return {\n    exitCode: res.exitCode,\n    stdout: String(res.stdout || \"\"),\n    stderr: String(res.stderr || \"\")\n  };\n}\nfunction cleanRepoPath(value) {\n  return value.trim().replace(/^\\/+/, \"\").replace(/\\/+$/, \"\").replace(/\\.git$/i, \"\");\n}\nfunction normalizeGitRemote(remote) {\n  const raw = String(remote ?? \"\").trim();\n  if (!raw) return null;\n  const canonicalMatch = raw.match(CANONICAL_GIT_REMOTE_RE);\n  if (canonicalMatch?.groups?.host && canonicalMatch.groups.path) {\n    const repoPath = cleanRepoPath(canonicalMatch.groups.path);\n    if (!repoPath) return null;\n    return `${canonicalMatch.groups.host}/${repoPath}`.toLowerCase();\n  }\n  if (GIT_REMOTE_PROTOCOL_RE.test(raw)) {\n    try {\n      const url = new URL(raw);\n      const repoPath = cleanRepoPath(url.pathname);\n      if (!url.hostname || !repoPath) return null;\n      return `${url.hostname}/${repoPath}`.toLowerCase();\n    } catch {\n      return null;\n    }\n  }\n  const scpMatch = raw.match(SCP_LIKE_GIT_REMOTE_RE);\n  if (scpMatch?.groups?.host && scpMatch.groups.path) {\n    const repoPath = cleanRepoPath(scpMatch.groups.path);\n    if (!repoPath) return null;\n    return `${scpMatch.groups.host}/${repoPath}`.toLowerCase();\n  }\n  return null;\n}\nfunction sanitizeRefFragment(value) {\n  return value.trim().replace(/[^A-Za-z0-9._/-]+/g, \"-\").replace(/\\/{2,}/g, \"/\").replace(/^\\/+|\\/+$/g, \"\").replace(/^-+|-+$/g, \"\").slice(0, 120);\n}\nfunction normalizeRepoRelativePath(value) {\n  const normalized = path.posix.normalize(value.replace(/\\\\/g, \"/\").trim());\n  if (!normalized || normalized === \".\" || normalized === \"..\" || normalized.startsWith(\"../\") || path.posix.isAbsolute(normalized)) {\n    throw new RemixError(\"Git returned an invalid repository-relative path.\", {\n      exitCode: 1,\n      hint: `Path: ${value}`\n    });\n  }\n  return normalized;\n}\nfunction sha256Hex(value) {\n  return createHash(\"sha256\").update(value).digest(\"hex\");\n}\nfunction resolveGitReportedPath(cwd, reportedPath) {\n  const value = reportedPath.trim();\n  if (!value) {\n    throw new RemixError(\"Git returned an empty internal path.\", { exitCode: 1 });\n  }\n  return path.isAbsolute(value) ? value : path.resolve(cwd, value);\n}\nfunction parseGitNameStatusZ(stdout) {\n  const tokens = stdout.split(\"\\0\");\n  const entries = [];\n  for (let i = 0; i < tokens.length; i += 1) {\n    const rawToken = tokens[i];\n    if (!rawToken) continue;\n    let status = rawToken;\n    let inlinePath = null;\n    const tabIdx = rawToken.indexOf(\"\t\");\n    if (tabIdx >= 0) {\n      status = rawToken.slice(0, tabIdx);\n      inlinePath = rawToken.slice(tabIdx + 1) || null;\n    }\n    const kind = status[0]?.toUpperCase() ?? \"\";\n    if (kind === \"R\" || kind === \"C\") {\n      const oldPath = inlinePath ?? tokens[++i] ?? \"\";\n      const newPath = tokens[++i] ?? \"\";\n      if (!newPath) continue;\n      entries.push({\n        status,\n        path: normalizeRepoRelativePath(newPath),\n        oldPath: oldPath ? normalizeRepoRelativePath(oldPath) : null\n      });\n      continue;\n    }\n    const nextPath = inlinePath ?? tokens[++i] ?? \"\";\n    if (!nextPath) continue;\n    entries.push({\n      status,\n      path: normalizeRepoRelativePath(nextPath),\n      oldPath: null\n    });\n  }\n  return entries;\n}\nfunction buildStagePlan(entries) {\n  const updatePaths = /* @__PURE__ */ new Set();\n  const addPaths = /* @__PURE__ */ new Set();\n  for (const entry of entries) {\n    const kind = entry.status[0]?.toUpperCase() ?? \"\";\n    if (kind === \"A\" || kind === \"C\") {\n      addPaths.add(entry.path);\n      continue;\n    }\n    if (kind === \"R\") {\n      if (entry.oldPath) updatePaths.add(entry.oldPath);\n      addPaths.add(entry.path);\n      continue;\n    }\n    updatePaths.add(entry.path);\n  }\n  const expectedPaths = /* @__PURE__ */ new Set([...updatePaths, ...addPaths]);\n  return {\n    updatePaths: Array.from(updatePaths).sort(),\n    addPaths: Array.from(addPaths).sort(),\n    expectedPaths: Array.from(expectedPaths).sort()\n  };\n}\nasync function findGitRoot(startDir) {\n  try {\n    const root = await runGit([\"rev-parse\", \"--show-toplevel\"], startDir);\n    if (!root) throw new Error(\"empty\");\n    return root;\n  } catch {\n    throw new RemixError(\"Not inside a git repository.\", {\n      exitCode: 2,\n      hint: \"Run this command from the root of the repository or one of its subdirectories.\"\n    });\n  }\n}\nasync function getAbsoluteGitDir(cwd) {\n  try {\n    const gitDir = await runGit([\"rev-parse\", \"--absolute-git-dir\"], cwd);\n    return resolveGitReportedPath(cwd, gitDir);\n  } catch {\n    throw new RemixError(\"Failed to resolve the git directory.\", {\n      exitCode: 1,\n      hint: \"Ensure the current working directory is inside a valid git repository.\"\n    });\n  }\n}\nasync function getGitCommonDir(cwd) {\n  try {\n    const commonDir = await runGit([\"rev-parse\", \"--git-common-dir\"], cwd);\n    return resolveGitReportedPath(cwd, commonDir);\n  } catch {\n    throw new RemixError(\"Failed to resolve the git common directory.\", {\n      exitCode: 1,\n      hint: \"Ensure the current working directory is inside a valid git repository.\"\n    });\n  }\n}\nasync function getGitPath(cwd, relativePath) {\n  try {\n    const gitPath = await runGit([\"rev-parse\", \"--git-path\", relativePath], cwd);\n    return resolveGitReportedPath(cwd, gitPath);\n  } catch {\n    throw new RemixError(\"Failed to resolve a git-managed path.\", {\n      exitCode: 1,\n      hint: `Path: ${relativePath}`\n    });\n  }\n}\nasync function getCurrentBranch(cwd) {\n  try {\n    const branch = await runGit([\"branch\", \"--show-current\"], cwd);\n    return branch || null;\n  } catch {\n    return null;\n  }\n}\nasync function checkoutLocalBranch(cwd, branchName) {\n  const normalized = sanitizeRefFragment(branchName);\n  if (!normalized) {\n    throw new RemixError(\"Preferred local branch name is invalid.\", {\n      exitCode: 2,\n      hint: `Branch: ${branchName}`\n    });\n  }\n  const res = await runGitDetailed([\"checkout\", \"-B\", normalized], cwd);\n  if (res.exitCode !== 0) {\n    const detail = [res.stderr.trim(), res.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to prepare the preferred local branch.\", {\n      exitCode: 1,\n      hint: detail || `Git could not switch the checkout to ${normalized}.`\n    });\n  }\n  return normalized;\n}\nasync function getRemoteOriginUrl(cwd) {\n  try {\n    const url = await runGit([\"config\", \"--get\", \"remote.origin.url\"], cwd);\n    return url || null;\n  } catch {\n    return null;\n  }\n}\nasync function setRemoteOriginUrl(cwd, remoteUrl) {\n  const normalized = String(remoteUrl ?? \"\").trim();\n  if (!normalized) return;\n  const existing = await runGitDetailed([\"remote\", \"get-url\", \"origin\"], cwd);\n  if (existing.exitCode === 0) {\n    const setUrl = await runGitDetailed([\"remote\", \"set-url\", \"origin\", normalized], cwd);\n    if (setUrl.exitCode !== 0) {\n      const detail = [setUrl.stderr.trim(), setUrl.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n      throw new RemixError(\"Failed to update the local git origin remote.\", {\n        exitCode: 1,\n        hint: detail || normalized\n      });\n    }\n    return;\n  }\n  const addRemote = await runGitDetailed([\"remote\", \"add\", \"origin\", normalized], cwd);\n  if (addRemote.exitCode !== 0) {\n    const detail = [addRemote.stderr.trim(), addRemote.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to write the local git origin remote.\", {\n      exitCode: 1,\n      hint: detail || normalized\n    });\n  }\n}\nasync function getDefaultBranch(cwd) {\n  try {\n    const ref = await runGit([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], cwd);\n    if (!ref) return null;\n    const suffix = ref.replace(/^refs\\/remotes\\/origin\\//, \"\").trim();\n    return suffix || null;\n  } catch {\n    return null;\n  }\n}\nasync function listUntrackedFiles(cwd) {\n  try {\n    const out = await runGit([\"ls-files\", \"--others\", \"--exclude-standard\"], cwd);\n    return out.split(\"\\n\").map((line) => line.trim()).filter(Boolean);\n  } catch {\n    return [];\n  }\n}\nasync function getWorkingTreeDiff(cwd) {\n  const untracked = await listUntrackedFiles(cwd);\n  if (untracked.length > 0) {\n    throw new RemixError(\"Untracked files are not included in git diff mode.\", {\n      exitCode: 2,\n      hint: \"Add the files to git before retrying so the worktree diff can include them.\"\n    });\n  }\n  try {\n    return await runGitRaw([\"diff\", \"--binary\", \"--no-ext-diff\", \"HEAD\"], cwd);\n  } catch {\n    throw new RemixError(\"Failed to generate git diff.\", { exitCode: 1 });\n  }\n}\nasync function getWorkspaceDiff(cwd) {\n  const snapshot = await getWorkspaceSnapshot(cwd);\n  return {\n    diff: snapshot.diff,\n    includedUntrackedPaths: snapshot.includedUntrackedPaths\n  };\n}\nasync function getWorkspaceSnapshot(cwd) {\n  const headCommitHash = await getHeadCommitHash(cwd);\n  if (!headCommitHash) {\n    throw new RemixError(\"Failed to resolve local HEAD commit.\", { exitCode: 1 });\n  }\n  const includedUntrackedPaths = Array.from(new Set((await listUntrackedFiles(cwd)).map((entry) => normalizeRepoRelativePath(entry))));\n  const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), \"remix-index-\"));\n  const tempIndexPath = path.join(tempDir, \"index\");\n  const env = { ...process.env, GIT_INDEX_FILE: tempIndexPath };\n  try {\n    try {\n      await runGitWithEnv([\"read-tree\", \"HEAD\"], cwd, env);\n      await runGitWithEnv([\"add\", \"-A\", \"--\", \".\"], cwd, env);\n      const diff = await runGitRawWithEnv([\"diff\", \"--binary\", \"--no-ext-diff\", \"--cached\", \"HEAD\"], cwd, env);\n      const nameStatus = await runGitRawWithEnv([\"diff\", \"--name-status\", \"--find-renames\", \"-z\", \"--cached\", \"HEAD\"], cwd, env);\n      const pathEntries = parseGitNameStatusZ(nameStatus);\n      return {\n        diff,\n        diffSha256: sha256Hex(diff),\n        includedUntrackedPaths,\n        pathEntries,\n        stagePlan: buildStagePlan(pathEntries)\n      };\n    } catch {\n      throw new RemixError(\"Failed to generate workspace diff.\", {\n        exitCode: 1,\n        hint: \"Git could not snapshot the current workspace into an isolated index.\"\n      });\n    }\n  } finally {\n    await fs.rm(tempDir, { recursive: true, force: true }).catch(() => void 0);\n  }\n}\nasync function writeTempUnifiedDiffBackup(diff, prefix = \"remix-add-backup\") {\n  const safePrefix = prefix.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"remix-add-backup\";\n  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), `${safePrefix}-`));\n  const backupPath = path.join(tmpDir, \"submitted.diff\");\n  await fs.writeFile(backupPath, diff, \"utf8\");\n  return { backupPath, diffSha256: sha256Hex(diff) };\n}\nasync function applyUnifiedDiffToWorktree(cwd, diff, operation = \"`remix collab pull`\") {\n  const normalizedDiff = String(diff ?? \"\");\n  if (!normalizedDiff.trim()) {\n    throw new RemixError(\"Diff is empty.\", { exitCode: 2, hint: `${operation} requires a non-empty diff.` });\n  }\n  const { backupPath, diffSha256 } = await writeTempUnifiedDiffBackup(normalizedDiff, \"remix-apply-diff\");\n  try {\n    const applyRes = await runGitDetailed([\"apply\", \"--binary\", \"--whitespace=nowarn\", backupPath], cwd);\n    if (applyRes.exitCode !== 0) {\n      const detail = [applyRes.stderr.trim(), applyRes.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n      throw new RemixError(\"Failed to apply unified diff to the local working tree.\", {\n        exitCode: 1,\n        hint: detail || `${operation} could not apply the server diff to the current working tree.`\n      });\n    }\n    return { diffSha256 };\n  } finally {\n    await fs.rm(path.dirname(backupPath), { recursive: true, force: true }).catch(() => void 0);\n  }\n}\nasync function getHeadCommitHash(cwd) {\n  try {\n    const hash = await runGit([\"rev-parse\", \"HEAD\"], cwd);\n    return hash || null;\n  } catch {\n    return null;\n  }\n}\nasync function createGitBundle(cwd, bundleName = \"repository.bundle\") {\n  const headCommitHash = await getHeadCommitHash(cwd);\n  if (!headCommitHash) {\n    throw new RemixError(\"Failed to resolve local HEAD commit.\", { exitCode: 1 });\n  }\n  const safeName = bundleName.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), \"remix-bundle-\"));\n  const bundlePath = path.join(tmpDir, safeName);\n  const res = await runGitDetailed([\"bundle\", \"create\", bundlePath, \"--all\"], cwd);\n  if (res.exitCode !== 0) {\n    const detail = [res.stderr.trim(), res.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to create repository bundle.\", {\n      exitCode: 1,\n      hint: detail || \"Git could not create the bundle artifact.\"\n    });\n  }\n  return { bundlePath, headCommitHash };\n}\nasync function getWorktreeStatus(cwd) {\n  try {\n    const out = await runGit([\"status\", \"--porcelain\"], cwd);\n    const entries = out.split(\"\\n\").map((line) => line.trimEnd()).filter(Boolean);\n    return { isClean: entries.length === 0, entries };\n  } catch {\n    return { isClean: false, entries: [] };\n  }\n}\nasync function captureRepoSnapshot(cwd, options) {\n  const [branch, headCommitHash, worktreeStatus] = await Promise.all([\n    getCurrentBranch(cwd),\n    getHeadCommitHash(cwd),\n    getWorktreeStatus(cwd)\n  ]);\n  const workspaceDiffSha256 = options?.includeWorkspaceDiffHash ? (await getWorkspaceSnapshot(cwd)).diffSha256 : null;\n  return {\n    branch,\n    headCommitHash,\n    statusEntries: worktreeStatus.entries,\n    statusSha256: sha256Hex(worktreeStatus.entries.join(\"\\n\")),\n    workspaceDiffSha256\n  };\n}\nasync function assertRepoSnapshotUnchanged(cwd, snapshot, params) {\n  const current = await captureRepoSnapshot(cwd, {\n    includeWorkspaceDiffHash: snapshot.workspaceDiffSha256 !== null\n  });\n  const changes = [];\n  if (current.branch !== snapshot.branch) {\n    changes.push(`Branch changed: ${snapshot.branch ?? \"(detached)\"} -> ${current.branch ?? \"(detached)\"}`);\n  }\n  if (current.headCommitHash !== snapshot.headCommitHash) {\n    changes.push(`HEAD changed: ${snapshot.headCommitHash ?? \"(missing)\"} -> ${current.headCommitHash ?? \"(missing)\"}`);\n  }\n  if (current.statusSha256 !== snapshot.statusSha256) {\n    changes.push(\"Working tree status changed.\");\n  }\n  if (snapshot.workspaceDiffSha256 !== null && current.workspaceDiffSha256 !== snapshot.workspaceDiffSha256) {\n    changes.push(\"Workspace diff changed.\");\n  }\n  if (changes.length === 0) return;\n  const operation = params?.operation?.trim() || \"this Remix operation\";\n  const hint = [\n    `Operation: ${operation}`,\n    ...changes,\n    params?.recoveryHint?.trim() || \"Review the local changes, then rerun the operation.\"\n  ].filter(Boolean).join(\"\\n\");\n  throw new RemixError(\"Repository state changed during the operation.\", {\n    code: REMIX_ERROR_CODES.REPO_STATE_CHANGED_DURING_OPERATION,\n    exitCode: 2,\n    hint\n  });\n}\nasync function ensureCleanWorktree(cwd, operation = \"`remix collab sync`\") {\n  const status = await getWorktreeStatus(cwd);\n  if (status.isClean) return;\n  const preview = status.entries.slice(0, 10).join(\"\\n\");\n  const suffix = status.entries.length > 10 ? `\n...and ${status.entries.length - 10} more` : \"\";\n  throw new RemixError(`Working tree must be clean before running ${operation}.`, {\n    exitCode: 2,\n    hint: `Commit, stash, or discard local changes first.\n\n${preview}${suffix}`\n  });\n}\nasync function discardTrackedChanges(cwd, operation = \"the Remix operation\") {\n  const res = await runGitDetailed([\"reset\", \"--hard\", \"HEAD\"], cwd);\n  if (res.exitCode !== 0) {\n    const detail = [res.stderr.trim(), res.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(`Failed to discard local tracked changes while running ${operation}.`, {\n      exitCode: 1,\n      hint: detail || \"Git could not reset tracked changes back to HEAD.\"\n    });\n  }\n  const hash = await getHeadCommitHash(cwd);\n  if (!hash) {\n    throw new RemixError(\"Failed to resolve local HEAD after discarding tracked changes.\", { exitCode: 1 });\n  }\n  return hash;\n}\nasync function requireCurrentBranch(cwd) {\n  const branch = await getCurrentBranch(cwd);\n  if (!branch) {\n    throw new RemixError(\"`remix collab sync` requires a checked out local branch.\", {\n      exitCode: 2,\n      hint: \"Checkout a branch before syncing.\"\n    });\n  }\n  return branch;\n}\nasync function importGitBundle(cwd, bundlePath, bundleRef) {\n  const verifyRes = await runGitDetailed([\"bundle\", \"verify\", bundlePath], cwd);\n  if (verifyRes.exitCode !== 0) {\n    const detail = [verifyRes.stderr.trim(), verifyRes.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to verify sync bundle.\", {\n      exitCode: 1,\n      hint: detail || \"Git bundle verification failed.\"\n    });\n  }\n  const fetchRes = await runGitDetailed([\"fetch\", \"--quiet\", bundlePath, bundleRef], cwd);\n  if (fetchRes.exitCode !== 0) {\n    const detail = [fetchRes.stderr.trim(), fetchRes.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to import sync bundle.\", {\n      exitCode: 1,\n      hint: detail || \"Git could not fetch objects from the sync bundle.\"\n    });\n  }\n}\nasync function cloneGitBundleToDirectory(bundlePath, targetDir) {\n  const parentDir = path.dirname(targetDir);\n  const cloneRes = await runGitDetailed([\"clone\", bundlePath, targetDir], parentDir);\n  if (cloneRes.exitCode !== 0) {\n    const detail = [cloneRes.stderr.trim(), cloneRes.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to create local remix checkout.\", {\n      exitCode: 1,\n      hint: detail || \"Git could not clone the remix repository bundle.\"\n    });\n  }\n  const remoteRemoveRes = await runGitDetailed([\"remote\", \"remove\", \"origin\"], targetDir);\n  if (remoteRemoveRes.exitCode !== 0) {\n    const detail = [remoteRemoveRes.stderr.trim(), remoteRemoveRes.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to finalize local remix checkout.\", {\n      exitCode: 1,\n      hint: detail || \"Git could not remove the temporary bundle origin.\"\n    });\n  }\n}\nasync function ensureGitInfoExcludeEntries(cwd, entries) {\n  const excludePath = await getGitPath(cwd, \"info/exclude\");\n  await fs.mkdir(path.dirname(excludePath), { recursive: true });\n  let current = \"\";\n  try {\n    current = await fs.readFile(excludePath, \"utf8\");\n  } catch {\n  }\n  const lines = new Set(current.split(\"\\n\").map((line) => line.trim()).filter(Boolean));\n  let changed = false;\n  for (const entry of entries) {\n    const normalized = entry.trim();\n    if (!normalized || lines.has(normalized)) continue;\n    lines.add(normalized);\n    changed = true;\n  }\n  if (!changed) return;\n  await fs.writeFile(excludePath, `${Array.from(lines).join(\"\\n\")}\n`, \"utf8\");\n}\nasync function ensureCommitExists(cwd, commitHash) {\n  const res = await runGitDetailed([\"cat-file\", \"-e\", `${commitHash}^{commit}`], cwd);\n  if (res.exitCode === 0) return;\n  throw new RemixError(\"Expected target commit is missing after bundle import.\", {\n    exitCode: 1,\n    hint: `Commit ${commitHash} is not available in the local repository.`\n  });\n}\nasync function fastForwardToCommit(cwd, commitHash) {\n  const res = await runGitDetailed([\"merge\", \"--ff-only\", commitHash], cwd);\n  if (res.exitCode !== 0) {\n    const detail = [res.stderr.trim(), res.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to fast-forward local branch.\", {\n      exitCode: 1,\n      hint: detail || \"Git could not fast-forward to the target commit.\"\n    });\n  }\n  const hash = await getHeadCommitHash(cwd);\n  if (!hash) throw new RemixError(\"Failed to resolve local HEAD after fast-forward sync.\", { exitCode: 1 });\n  return hash;\n}\nasync function createBackupBranch(cwd, params) {\n  const sourceCommitHash = params?.sourceCommitHash?.trim() || await getHeadCommitHash(cwd);\n  if (!sourceCommitHash) {\n    throw new RemixError(\"Failed to resolve local HEAD before creating reconcile backup.\", { exitCode: 1 });\n  }\n  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, \"-\");\n  const branchFragment = sanitizeRefFragment(params?.branchName?.trim() || \"current-branch\");\n  const prefix = sanitizeRefFragment(params?.prefix?.trim() || \"remix/reconcile-backup\");\n  const backupBranchName = `${prefix}/${branchFragment}-${timestamp}`;\n  const createRes = await runGitDetailed([\"branch\", backupBranchName, sourceCommitHash], cwd);\n  if (createRes.exitCode !== 0) {\n    const detail = [createRes.stderr.trim(), createRes.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(\"Failed to create reconcile backup branch.\", {\n      exitCode: 1,\n      hint: detail || \"Git could not create the safety backup branch.\"\n    });\n  }\n  return { branchName: backupBranchName, commitHash: sourceCommitHash };\n}\nasync function hardResetToCommit(cwd, commitHash, operation = \"`remix collab reconcile`\") {\n  const res = await runGitDetailed([\"reset\", \"--hard\", commitHash], cwd);\n  if (res.exitCode !== 0) {\n    const detail = [res.stderr.trim(), res.stdout.trim()].filter(Boolean).join(\"\\n\\n\");\n    throw new RemixError(`Failed to move local branch while running ${operation}.`, {\n      exitCode: 1,\n      hint: detail || `Git could not reset the current branch to ${commitHash}.`\n    });\n  }\n  const hash = await getHeadCommitHash(cwd);\n  if (!hash) {\n    throw new RemixError(\"Failed to resolve local HEAD after resetting branch.\", { exitCode: 1 });\n  }\n  return hash;\n}\nasync function buildRepoFingerprint(params) {\n  const remote = normalizeGitRemote(params.remoteUrl);\n  const defaultBranch = params.defaultBranch?.trim().toLowerCase() || \"\";\n  const payload = remote ? { remote, defaultBranch } : { local: path.resolve(params.gitRoot).toLowerCase(), defaultBranch };\n  return createHash(\"sha256\").update(JSON.stringify(payload)).digest(\"hex\");\n}\nfunction summarizeUnifiedDiff(diff) {\n  const lines = diff.split(\"\\n\");\n  let changedFilesCount = 0;\n  let insertions = 0;\n  let deletions = 0;\n  for (const line of lines) {\n    if (line.startsWith(\"diff --git \")) changedFilesCount += 1;\n    if (line.startsWith(\"+\") && !line.startsWith(\"+++\")) insertions += 1;\n    if (line.startsWith(\"-\") && !line.startsWith(\"---\")) deletions += 1;\n  }\n  return { changedFilesCount, insertions, deletions };\n}\n\nexport {\n  createGitCommandPlan,\n  createSystemGitAdapter,\n  normalizeGitRemote,\n  findGitRoot,\n  getAbsoluteGitDir,\n  getGitCommonDir,\n  getGitPath,\n  getCurrentBranch,\n  checkoutLocalBranch,\n  getRemoteOriginUrl,\n  setRemoteOriginUrl,\n  getDefaultBranch,\n  listUntrackedFiles,\n  getWorkingTreeDiff,\n  getWorkspaceDiff,\n  writeTempUnifiedDiffBackup,\n  applyUnifiedDiffToWorktree,\n  getHeadCommitHash,\n  createGitBundle,\n  getWorktreeStatus,\n  captureRepoSnapshot,\n  assertRepoSnapshotUnchanged,\n  ensureCleanWorktree,\n  discardTrackedChanges,\n  requireCurrentBranch,\n  importGitBundle,\n  cloneGitBundleToDirectory,\n  ensureGitInfoExcludeEntries,\n  ensureCommitExists,\n  fastForwardToCommit,\n  createBackupBranch,\n  hardResetToCommit,\n  buildRepoFingerprint,\n  summarizeUnifiedDiff\n};\n","import {\n  getCurrentBranch\n} from \"./chunk-FA6PTZQI.js\";\nimport {\n  RemixError\n} from \"./chunk-7XJGOKEO.js\";\n\n// src/infrastructure/binding/collabBindingStore.ts\nimport fs2 from \"fs/promises\";\nimport path2 from \"path\";\n\n// src/shared/fs.ts\nimport fs from \"fs/promises\";\nimport path from \"path\";\nasync function reserveDirectory(targetDir) {\n  try {\n    await fs.mkdir(targetDir);\n    return targetDir;\n  } catch (error) {\n    if (error?.code === \"EEXIST\") {\n      throw new RemixError(\"Output directory already exists.\", {\n        exitCode: 2,\n        hint: `Choose an empty destination path: ${targetDir}`\n      });\n    }\n    throw error;\n  }\n}\nasync function reserveAvailableDirPath(preferredDir) {\n  const parent = path.dirname(preferredDir);\n  const base = path.basename(preferredDir);\n  for (let i = 1; i <= 1e3; i += 1) {\n    const candidate = i === 1 ? preferredDir : path.join(parent, `${base}-${i}`);\n    try {\n      await fs.mkdir(candidate);\n      return candidate;\n    } catch (error) {\n      if (error?.code === \"EEXIST\") continue;\n      throw error;\n    }\n  }\n  throw new RemixError(\"No available output directory name.\", {\n    exitCode: 2,\n    hint: `Tried ${base} through ${base}-1000 under ${parent}.`\n  });\n}\nasync function writeJsonAtomic(filePath, value) {\n  const dir = path.dirname(filePath);\n  await fs.mkdir(dir, { recursive: true });\n  const tmp = `${filePath}.tmp-${Date.now()}`;\n  await fs.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, \"utf8\");\n  await fs.rename(tmp, filePath);\n}\n\n// src/infrastructure/binding/collabBindingStore.ts\nfunction getCollabBindingPath(repoRoot) {\n  return path2.join(repoRoot, \".remix\", \"config.json\");\n}\nfunction buildBindingFileV3(params) {\n  return {\n    schemaVersion: 3,\n    repoFingerprint: params.repoFingerprint,\n    remoteUrl: params.remoteUrl,\n    defaultBranch: params.defaultBranch,\n    branchBindings: params.branchBindings,\n    ...params.explicitRootBinding ? { explicitRootBinding: params.explicitRootBinding } : {}\n  };\n}\nfunction normalizeBranchName(value) {\n  const normalized = String(value ?? \"\").trim();\n  return normalized || null;\n}\nfunction normalizeProjectId(value) {\n  const normalized = String(value ?? \"\").trim();\n  return normalized || null;\n}\nasync function readCurrentBranchOrNull(repoRoot) {\n  try {\n    return normalizeBranchName(await getCurrentBranch(repoRoot));\n  } catch {\n    return null;\n  }\n}\nfunction normalizeBranchBinding(value) {\n  if (!value?.currentAppId || !value?.upstreamAppId) return null;\n  return {\n    projectId: normalizeProjectId(value.projectId),\n    currentAppId: value.currentAppId,\n    upstreamAppId: value.upstreamAppId,\n    threadId: value.threadId ?? null,\n    laneId: value.laneId ?? null,\n    bindingMode: value.bindingMode === \"legacy\" ? \"legacy\" : value.bindingMode === \"explicit_root\" ? \"explicit_root\" : \"lane\"\n  };\n}\nfunction buildResolvedBinding(params) {\n  if (!params.binding) return null;\n  return {\n    schemaVersion: 3,\n    projectId: params.binding.projectId ?? params.fallbackProjectId,\n    currentAppId: params.binding.currentAppId,\n    upstreamAppId: params.binding.upstreamAppId,\n    threadId: params.binding.threadId,\n    repoFingerprint: params.repoFingerprint,\n    remoteUrl: params.remoteUrl,\n    defaultBranch: params.defaultBranch,\n    laneId: params.binding.laneId,\n    branchName: params.branchName,\n    bindingMode: params.binding.bindingMode\n  };\n}\nfunction deriveFallbackProjectId(params) {\n  const candidates = [\n    params.currentBranch ? params.branchBindings[params.currentBranch]?.projectId ?? null : null,\n    params.defaultBranch ? params.branchBindings[params.defaultBranch]?.projectId ?? null : null,\n    ...Object.values(params.branchBindings).map((binding) => binding.projectId),\n    params.legacyProjectId\n  ];\n  for (const candidate of candidates) {\n    if (candidate) return candidate;\n  }\n  return null;\n}\nasync function readCollabBindingState(repoRoot, options) {\n  try {\n    const persist = options?.persist === true;\n    const filePath = getCollabBindingPath(repoRoot);\n    const raw = await fs2.readFile(filePath, \"utf8\");\n    const parsed = JSON.parse(raw);\n    if (!parsed || typeof parsed !== \"object\") return null;\n    const currentBranch = await readCurrentBranchOrNull(repoRoot);\n    if (parsed.schemaVersion === 1) {\n      if (!parsed.currentAppId || !parsed.upstreamAppId) return null;\n      const projectId = normalizeProjectId(parsed.projectId);\n      const preferredBranch = normalizeBranchName(parsed.preferredBranch ?? parsed.defaultBranch ?? null);\n      const branchKey = preferredBranch ?? currentBranch ?? null;\n      const branchBindings2 = branchKey ? {\n        [branchKey]: {\n          projectId,\n          currentAppId: parsed.currentAppId,\n          upstreamAppId: parsed.upstreamAppId,\n          threadId: parsed.threadId ?? null,\n          laneId: null,\n          bindingMode: \"legacy\"\n        }\n      } : {};\n      const migratedFile = buildBindingFileV3({\n        repoFingerprint: parsed.repoFingerprint ?? null,\n        remoteUrl: parsed.remoteUrl ?? null,\n        defaultBranch: parsed.defaultBranch ?? null,\n        branchBindings: branchBindings2\n      });\n      if (persist) {\n        try {\n          await writeJsonAtomic(filePath, migratedFile);\n        } catch {\n        }\n      }\n      return {\n        schemaVersion: 3,\n        projectId,\n        repoFingerprint: migratedFile.repoFingerprint,\n        remoteUrl: migratedFile.remoteUrl,\n        defaultBranch: migratedFile.defaultBranch,\n        currentBranch,\n        branchBindings: migratedFile.branchBindings,\n        explicitRootBinding: null,\n        binding: buildResolvedBinding({\n          fallbackProjectId: projectId,\n          repoFingerprint: migratedFile.repoFingerprint,\n          remoteUrl: migratedFile.remoteUrl,\n          defaultBranch: migratedFile.defaultBranch,\n          branchName: branchKey,\n          binding: branchKey ? migratedFile.branchBindings[branchKey] : null\n        })\n      };\n    }\n    if (parsed.schemaVersion !== 2 && parsed.schemaVersion !== 3) return null;\n    const file = parsed;\n    let shouldPersistNormalizedBranchBindings = false;\n    const legacyProjectId = normalizeProjectId(file.projectId);\n    const branchBindings = Object.fromEntries(\n      Object.entries(file.branchBindings ?? {}).map(([branchName, branchBinding]) => {\n        const normalized = normalizeBranchBinding(branchBinding);\n        const rawProjectId = branchBinding && typeof branchBinding === \"object\" && \"projectId\" in branchBinding ? normalizeProjectId(branchBinding.projectId) : null;\n        const rawBindingMode = branchBinding && typeof branchBinding === \"object\" && \"bindingMode\" in branchBinding ? branchBinding.bindingMode : null;\n        const hasLegacyPreferredBranch = Boolean(branchBinding) && typeof branchBinding === \"object\" && \"preferredBranch\" in branchBinding;\n        let normalizedWithProject = normalized;\n        if (normalizedWithProject && !normalizedWithProject.projectId && legacyProjectId) {\n          normalizedWithProject = {\n            ...normalizedWithProject,\n            projectId: legacyProjectId\n          };\n        }\n        if (normalizedWithProject && (rawBindingMode !== normalizedWithProject.bindingMode || hasLegacyPreferredBranch || rawProjectId !== normalizedWithProject.projectId)) {\n          shouldPersistNormalizedBranchBindings = true;\n        }\n        return [branchName, normalizedWithProject];\n      }).filter((entry) => Boolean(entry[1]))\n    );\n    const legacyExplicitBinding = normalizeBranchBinding(file.explicitBinding ?? null);\n    const legacyExplicitBranch = currentBranch ?? normalizeBranchName(file.defaultBranch);\n    if (legacyExplicitBinding && legacyExplicitBranch) {\n      branchBindings[legacyExplicitBranch] = {\n        ...legacyExplicitBinding,\n        projectId: legacyExplicitBinding.projectId ?? branchBindings[legacyExplicitBranch]?.projectId ?? legacyProjectId,\n        bindingMode: \"lane\"\n      };\n      shouldPersistNormalizedBranchBindings = true;\n    }\n    let explicitRootBinding = normalizeBranchBinding(file.explicitRootBinding ?? null);\n    if (explicitRootBinding && !explicitRootBinding.projectId && legacyProjectId) {\n      explicitRootBinding = {\n        ...explicitRootBinding,\n        projectId: legacyProjectId\n      };\n      shouldPersistNormalizedBranchBindings = true;\n    }\n    if (explicitRootBinding && explicitRootBinding.bindingMode !== \"explicit_root\") {\n      explicitRootBinding = {\n        ...explicitRootBinding,\n        bindingMode: \"explicit_root\"\n      };\n      shouldPersistNormalizedBranchBindings = true;\n    }\n    if (persist && (\"explicitBinding\" in file || \"explicitRootBinding\" in file || shouldPersistNormalizedBranchBindings || parsed.schemaVersion === 2)) {\n      try {\n        await writeJsonAtomic(\n          filePath,\n          buildBindingFileV3({\n            repoFingerprint: file.repoFingerprint ?? null,\n            remoteUrl: file.remoteUrl ?? null,\n            defaultBranch: file.defaultBranch ?? null,\n            branchBindings,\n            explicitRootBinding\n          })\n        );\n      } catch {\n      }\n    }\n    const resolvedBranch = currentBranch ?? normalizeBranchName(file.defaultBranch);\n    const fallbackProjectId = deriveFallbackProjectId({\n      branchBindings,\n      currentBranch: resolvedBranch,\n      defaultBranch: normalizeBranchName(file.defaultBranch),\n      legacyProjectId: explicitRootBinding?.projectId ?? legacyProjectId\n    });\n    const resolvedBinding = buildResolvedBinding({\n      fallbackProjectId,\n      repoFingerprint: file.repoFingerprint ?? null,\n      remoteUrl: file.remoteUrl ?? null,\n      defaultBranch: file.defaultBranch ?? null,\n      branchName: resolvedBranch,\n      binding: resolvedBranch ? branchBindings[resolvedBranch] ?? null : null\n    }) ?? (resolvedBranch && resolvedBranch === normalizeBranchName(file.defaultBranch) && explicitRootBinding ? buildResolvedBinding({\n      fallbackProjectId,\n      repoFingerprint: file.repoFingerprint ?? null,\n      remoteUrl: file.remoteUrl ?? null,\n      defaultBranch: file.defaultBranch ?? null,\n      branchName: normalizeBranchName(file.defaultBranch),\n      binding: explicitRootBinding\n    }) : null);\n    return {\n      schemaVersion: parsed.schemaVersion,\n      projectId: fallbackProjectId,\n      repoFingerprint: file.repoFingerprint ?? null,\n      remoteUrl: file.remoteUrl ?? null,\n      defaultBranch: file.defaultBranch ?? null,\n      currentBranch,\n      branchBindings,\n      explicitRootBinding: buildResolvedBinding({\n        fallbackProjectId,\n        repoFingerprint: file.repoFingerprint ?? null,\n        remoteUrl: file.remoteUrl ?? null,\n        defaultBranch: file.defaultBranch ?? null,\n        branchName: normalizeBranchName(file.defaultBranch),\n        binding: explicitRootBinding\n      }),\n      binding: resolvedBinding\n    };\n  } catch {\n    return null;\n  }\n}\nasync function readCollabBinding(repoRoot) {\n  const state = await readCollabBindingState(repoRoot);\n  return state?.binding ?? null;\n}\nasync function writeCollabBinding(repoRoot, binding) {\n  const filePath = getCollabBindingPath(repoRoot);\n  const currentBranch = await readCurrentBranchOrNull(repoRoot);\n  const branchName = normalizeBranchName(binding.branchName) ?? currentBranch ?? binding.defaultBranch ?? \"main\";\n  const existing = await readCollabBindingState(repoRoot, { persist: true });\n  const branchBindings = { ...existing?.branchBindings ?? {} };\n  branchBindings[branchName] = {\n    projectId: normalizeProjectId(binding.projectId) ?? branchBindings[branchName]?.projectId ?? existing?.projectId ?? null,\n    currentAppId: binding.currentAppId,\n    upstreamAppId: binding.upstreamAppId,\n    threadId: binding.threadId ?? null,\n    laneId: binding.laneId ?? null,\n    bindingMode: binding.bindingMode ?? \"lane\"\n  };\n  const explicitRootBinding = binding.bindingMode === \"explicit_root\" ? {\n    ...branchBindings[branchName],\n    bindingMode: \"explicit_root\"\n  } : existing?.explicitRootBinding ? {\n    projectId: existing.explicitRootBinding.projectId,\n    currentAppId: existing.explicitRootBinding.currentAppId,\n    upstreamAppId: existing.explicitRootBinding.upstreamAppId,\n    threadId: existing.explicitRootBinding.threadId,\n    laneId: existing.explicitRootBinding.laneId,\n    bindingMode: \"explicit_root\"\n  } : null;\n  await writeJsonAtomic(\n    filePath,\n    buildBindingFileV3({\n      repoFingerprint: binding.repoFingerprint ?? null,\n      remoteUrl: binding.remoteUrl ?? null,\n      defaultBranch: binding.defaultBranch ?? null,\n      branchBindings,\n      explicitRootBinding\n    })\n  );\n  return filePath;\n}\nasync function writeCollabBindingSnapshot(params) {\n  const filePath = getCollabBindingPath(params.repoRoot);\n  await writeJsonAtomic(\n    filePath,\n    buildBindingFileV3({\n      repoFingerprint: params.repoFingerprint,\n      remoteUrl: params.remoteUrl,\n      defaultBranch: params.defaultBranch,\n      branchBindings: params.branchBindings,\n      explicitRootBinding: params.explicitRootBinding ?? null\n    })\n  );\n  return filePath;\n}\n\nexport {\n  reserveDirectory,\n  reserveAvailableDirPath,\n  writeJsonAtomic,\n  getCollabBindingPath,\n  readCollabBindingState,\n  readCollabBinding,\n  writeCollabBinding,\n  writeCollabBindingSnapshot\n};\n","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n    util.assertEqual = (_) => { };\n    function assertIs(_arg) { }\n    util.assertIs = assertIs;\n    function assertNever(_x) {\n        throw new Error();\n    }\n    util.assertNever = assertNever;\n    util.arrayToEnum = (items) => {\n        const obj = {};\n        for (const item of items) {\n            obj[item] = item;\n        }\n        return obj;\n    };\n    util.getValidEnumValues = (obj) => {\n        const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n        const filtered = {};\n        for (const k of validKeys) {\n            filtered[k] = obj[k];\n        }\n        return util.objectValues(filtered);\n    };\n    util.objectValues = (obj) => {\n        return util.objectKeys(obj).map(function (e) {\n            return obj[e];\n        });\n    };\n    util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n        ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n        : (object) => {\n            const keys = [];\n            for (const key in object) {\n                if (Object.prototype.hasOwnProperty.call(object, key)) {\n                    keys.push(key);\n                }\n            }\n            return keys;\n        };\n    util.find = (arr, checker) => {\n        for (const item of arr) {\n            if (checker(item))\n                return item;\n        }\n        return undefined;\n    };\n    util.isInteger = typeof Number.isInteger === \"function\"\n        ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n        : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n    function joinValues(array, separator = \" | \") {\n        return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n    }\n    util.joinValues = joinValues;\n    util.jsonStringifyReplacer = (_, value) => {\n        if (typeof value === \"bigint\") {\n            return value.toString();\n        }\n        return value;\n    };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n    objectUtil.mergeShapes = (first, second) => {\n        return {\n            ...first,\n            ...second, // second overwrites first\n        };\n    };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n    \"string\",\n    \"nan\",\n    \"number\",\n    \"integer\",\n    \"float\",\n    \"boolean\",\n    \"date\",\n    \"bigint\",\n    \"symbol\",\n    \"function\",\n    \"undefined\",\n    \"null\",\n    \"array\",\n    \"object\",\n    \"unknown\",\n    \"promise\",\n    \"void\",\n    \"never\",\n    \"map\",\n    \"set\",\n]);\nexport const getParsedType = (data) => {\n    const t = typeof data;\n    switch (t) {\n        case \"undefined\":\n            return ZodParsedType.undefined;\n        case \"string\":\n            return ZodParsedType.string;\n        case \"number\":\n            return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n        case \"boolean\":\n            return ZodParsedType.boolean;\n        case \"function\":\n            return ZodParsedType.function;\n        case \"bigint\":\n            return ZodParsedType.bigint;\n        case \"symbol\":\n            return ZodParsedType.symbol;\n        case \"object\":\n            if (Array.isArray(data)) {\n                return ZodParsedType.array;\n            }\n            if (data === null) {\n                return ZodParsedType.null;\n            }\n            if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n                return ZodParsedType.promise;\n            }\n            if (typeof Map !== \"undefined\" && data instanceof Map) {\n                return ZodParsedType.map;\n            }\n            if (typeof Set !== \"undefined\" && data instanceof Set) {\n                return ZodParsedType.set;\n            }\n            if (typeof Date !== \"undefined\" && data instanceof Date) {\n                return ZodParsedType.date;\n            }\n            return ZodParsedType.object;\n        default:\n            return ZodParsedType.unknown;\n    }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n    \"invalid_type\",\n    \"invalid_literal\",\n    \"custom\",\n    \"invalid_union\",\n    \"invalid_union_discriminator\",\n    \"invalid_enum_value\",\n    \"unrecognized_keys\",\n    \"invalid_arguments\",\n    \"invalid_return_type\",\n    \"invalid_date\",\n    \"invalid_string\",\n    \"too_small\",\n    \"too_big\",\n    \"invalid_intersection_types\",\n    \"not_multiple_of\",\n    \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n    const json = JSON.stringify(obj, null, 2);\n    return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n    get errors() {\n        return this.issues;\n    }\n    constructor(issues) {\n        super();\n        this.issues = [];\n        this.addIssue = (sub) => {\n            this.issues = [...this.issues, sub];\n        };\n        this.addIssues = (subs = []) => {\n            this.issues = [...this.issues, ...subs];\n        };\n        const actualProto = new.target.prototype;\n        if (Object.setPrototypeOf) {\n            // eslint-disable-next-line ban/ban\n            Object.setPrototypeOf(this, actualProto);\n        }\n        else {\n            this.__proto__ = actualProto;\n        }\n        this.name = \"ZodError\";\n        this.issues = issues;\n    }\n    format(_mapper) {\n        const mapper = _mapper ||\n            function (issue) {\n                return issue.message;\n            };\n        const fieldErrors = { _errors: [] };\n        const processError = (error) => {\n            for (const issue of error.issues) {\n                if (issue.code === \"invalid_union\") {\n                    issue.unionErrors.map(processError);\n                }\n                else if (issue.code === \"invalid_return_type\") {\n                    processError(issue.returnTypeError);\n                }\n                else if (issue.code === \"invalid_arguments\") {\n                    processError(issue.argumentsError);\n                }\n                else if (issue.path.length === 0) {\n                    fieldErrors._errors.push(mapper(issue));\n                }\n                else {\n                    let curr = fieldErrors;\n                    let i = 0;\n                    while (i < issue.path.length) {\n                        const el = issue.path[i];\n                        const terminal = i === issue.path.length - 1;\n                        if (!terminal) {\n                            curr[el] = curr[el] || { _errors: [] };\n                            // if (typeof el === \"string\") {\n                            //   curr[el] = curr[el] || { _errors: [] };\n                            // } else if (typeof el === \"number\") {\n                            //   const errorArray: any = [];\n                            //   errorArray._errors = [];\n                            //   curr[el] = curr[el] || errorArray;\n                            // }\n                        }\n                        else {\n                            curr[el] = curr[el] || { _errors: [] };\n                            curr[el]._errors.push(mapper(issue));\n                        }\n                        curr = curr[el];\n                        i++;\n                    }\n                }\n            }\n        };\n        processError(this);\n        return fieldErrors;\n    }\n    static assert(value) {\n        if (!(value instanceof ZodError)) {\n            throw new Error(`Not a ZodError: ${value}`);\n        }\n    }\n    toString() {\n        return this.message;\n    }\n    get message() {\n        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n    }\n    get isEmpty() {\n        return this.issues.length === 0;\n    }\n    flatten(mapper = (issue) => issue.message) {\n        const fieldErrors = {};\n        const formErrors = [];\n        for (const sub of this.issues) {\n            if (sub.path.length > 0) {\n                const firstEl = sub.path[0];\n                fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n                fieldErrors[firstEl].push(mapper(sub));\n            }\n            else {\n                formErrors.push(mapper(sub));\n            }\n        }\n        return { formErrors, fieldErrors };\n    }\n    get formErrors() {\n        return this.flatten();\n    }\n}\nZodError.create = (issues) => {\n    const error = new ZodError(issues);\n    return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n    let message;\n    switch (issue.code) {\n        case ZodIssueCode.invalid_type:\n            if (issue.received === ZodParsedType.undefined) {\n                message = \"Required\";\n            }\n            else {\n                message = `Expected ${issue.expected}, received ${issue.received}`;\n            }\n            break;\n        case ZodIssueCode.invalid_literal:\n            message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n            break;\n        case ZodIssueCode.unrecognized_keys:\n            message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n            break;\n        case ZodIssueCode.invalid_union:\n            message = `Invalid input`;\n            break;\n        case ZodIssueCode.invalid_union_discriminator:\n            message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n            break;\n        case ZodIssueCode.invalid_enum_value:\n            message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n            break;\n        case ZodIssueCode.invalid_arguments:\n            message = `Invalid function arguments`;\n            break;\n        case ZodIssueCode.invalid_return_type:\n            message = `Invalid function return type`;\n            break;\n        case ZodIssueCode.invalid_date:\n            message = `Invalid date`;\n            break;\n        case ZodIssueCode.invalid_string:\n            if (typeof issue.validation === \"object\") {\n                if (\"includes\" in issue.validation) {\n                    message = `Invalid input: must include \"${issue.validation.includes}\"`;\n                    if (typeof issue.validation.position === \"number\") {\n                        message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n                    }\n                }\n                else if (\"startsWith\" in issue.validation) {\n                    message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n                }\n                else if (\"endsWith\" in issue.validation) {\n                    message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n                }\n                else {\n                    util.assertNever(issue.validation);\n                }\n            }\n            else if (issue.validation !== \"regex\") {\n                message = `Invalid ${issue.validation}`;\n            }\n            else {\n                message = \"Invalid\";\n            }\n            break;\n        case ZodIssueCode.too_small:\n            if (issue.type === \"array\")\n                message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n            else if (issue.type === \"string\")\n                message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n            else if (issue.type === \"number\")\n                message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n            else if (issue.type === \"bigint\")\n                message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n            else if (issue.type === \"date\")\n                message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n            else\n                message = \"Invalid input\";\n            break;\n        case ZodIssueCode.too_big:\n            if (issue.type === \"array\")\n                message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n            else if (issue.type === \"string\")\n                message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n            else if (issue.type === \"number\")\n                message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n            else if (issue.type === \"bigint\")\n                message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n            else if (issue.type === \"date\")\n                message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n            else\n                message = \"Invalid input\";\n            break;\n        case ZodIssueCode.custom:\n            message = `Invalid input`;\n            break;\n        case ZodIssueCode.invalid_intersection_types:\n            message = `Intersection results could not be merged`;\n            break;\n        case ZodIssueCode.not_multiple_of:\n            message = `Number must be a multiple of ${issue.multipleOf}`;\n            break;\n        case ZodIssueCode.not_finite:\n            message = \"Number must be finite\";\n            break;\n        default:\n            message = _ctx.defaultError;\n            util.assertNever(issue);\n    }\n    return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n    overrideErrorMap = map;\n}\nexport function getErrorMap() {\n    return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n    const { data, path, errorMaps, issueData } = params;\n    const fullPath = [...path, ...(issueData.path || [])];\n    const fullIssue = {\n        ...issueData,\n        path: fullPath,\n    };\n    if (issueData.message !== undefined) {\n        return {\n            ...issueData,\n            path: fullPath,\n            message: issueData.message,\n        };\n    }\n    let errorMessage = \"\";\n    const maps = errorMaps\n        .filter((m) => !!m)\n        .slice()\n        .reverse();\n    for (const map of maps) {\n        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n    }\n    return {\n        ...issueData,\n        path: fullPath,\n        message: errorMessage,\n    };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n    const overrideMap = getErrorMap();\n    const issue = makeIssue({\n        issueData: issueData,\n        data: ctx.data,\n        path: ctx.path,\n        errorMaps: [\n            ctx.common.contextualErrorMap, // contextual error map is first priority\n            ctx.schemaErrorMap, // then schema-bound map if available\n            overrideMap, // then global override map\n            overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n        ].filter((x) => !!x),\n    });\n    ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n    constructor() {\n        this.value = \"valid\";\n    }\n    dirty() {\n        if (this.value === \"valid\")\n            this.value = \"dirty\";\n    }\n    abort() {\n        if (this.value !== \"aborted\")\n            this.value = \"aborted\";\n    }\n    static mergeArray(status, results) {\n        const arrayValue = [];\n        for (const s of results) {\n            if (s.status === \"aborted\")\n                return INVALID;\n            if (s.status === \"dirty\")\n                status.dirty();\n            arrayValue.push(s.value);\n        }\n        return { status: status.value, value: arrayValue };\n    }\n    static async mergeObjectAsync(status, pairs) {\n        const syncPairs = [];\n        for (const pair of pairs) {\n            const key = await pair.key;\n            const value = await pair.value;\n            syncPairs.push({\n                key,\n                value,\n            });\n        }\n        return ParseStatus.mergeObjectSync(status, syncPairs);\n    }\n    static mergeObjectSync(status, pairs) {\n        const finalObject = {};\n        for (const pair of pairs) {\n            const { key, value } = pair;\n            if (key.status === \"aborted\")\n                return INVALID;\n            if (value.status === \"aborted\")\n                return INVALID;\n            if (key.status === \"dirty\")\n                status.dirty();\n            if (value.status === \"dirty\")\n                status.dirty();\n            if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n                finalObject[key.value] = value.value;\n            }\n        }\n        return { status: status.value, value: finalObject };\n    }\n}\nexport const INVALID = Object.freeze({\n    status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n    errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n    // biome-ignore lint:\n    errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n    constructor(parent, value, path, key) {\n        this._cachedPath = [];\n        this.parent = parent;\n        this.data = value;\n        this._path = path;\n        this._key = key;\n    }\n    get path() {\n        if (!this._cachedPath.length) {\n            if (Array.isArray(this._key)) {\n                this._cachedPath.push(...this._path, ...this._key);\n            }\n            else {\n                this._cachedPath.push(...this._path, this._key);\n            }\n        }\n        return this._cachedPath;\n    }\n}\nconst handleResult = (ctx, result) => {\n    if (isValid(result)) {\n        return { success: true, data: result.value };\n    }\n    else {\n        if (!ctx.common.issues.length) {\n            throw new Error(\"Validation failed but no issues detected.\");\n        }\n        return {\n            success: false,\n            get error() {\n                if (this._error)\n                    return this._error;\n                const error = new ZodError(ctx.common.issues);\n                this._error = error;\n                return this._error;\n            },\n        };\n    }\n};\nfunction processCreateParams(params) {\n    if (!params)\n        return {};\n    const { errorMap, invalid_type_error, required_error, description } = params;\n    if (errorMap && (invalid_type_error || required_error)) {\n        throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n    }\n    if (errorMap)\n        return { errorMap: errorMap, description };\n    const customMap = (iss, ctx) => {\n        const { message } = params;\n        if (iss.code === \"invalid_enum_value\") {\n            return { message: message ?? ctx.defaultError };\n        }\n        if (typeof ctx.data === \"undefined\") {\n            return { message: message ?? required_error ?? ctx.defaultError };\n        }\n        if (iss.code !== \"invalid_type\")\n            return { message: ctx.defaultError };\n        return { message: message ?? invalid_type_error ?? ctx.defaultError };\n    };\n    return { errorMap: customMap, description };\n}\nexport class ZodType {\n    get description() {\n        return this._def.description;\n    }\n    _getType(input) {\n        return getParsedType(input.data);\n    }\n    _getOrReturnCtx(input, ctx) {\n        return (ctx || {\n            common: input.parent.common,\n            data: input.data,\n            parsedType: getParsedType(input.data),\n            schemaErrorMap: this._def.errorMap,\n            path: input.path,\n            parent: input.parent,\n        });\n    }\n    _processInputParams(input) {\n        return {\n            status: new ParseStatus(),\n            ctx: {\n                common: input.parent.common,\n                data: input.data,\n                parsedType: getParsedType(input.data),\n                schemaErrorMap: this._def.errorMap,\n                path: input.path,\n                parent: input.parent,\n            },\n        };\n    }\n    _parseSync(input) {\n        const result = this._parse(input);\n        if (isAsync(result)) {\n            throw new Error(\"Synchronous parse encountered promise.\");\n        }\n        return result;\n    }\n    _parseAsync(input) {\n        const result = this._parse(input);\n        return Promise.resolve(result);\n    }\n    parse(data, params) {\n        const result = this.safeParse(data, params);\n        if (result.success)\n            return result.data;\n        throw result.error;\n    }\n    safeParse(data, params) {\n        const ctx = {\n            common: {\n                issues: [],\n                async: params?.async ?? false,\n                contextualErrorMap: params?.errorMap,\n            },\n            path: params?.path || [],\n            schemaErrorMap: this._def.errorMap,\n            parent: null,\n            data,\n            parsedType: getParsedType(data),\n        };\n        const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n        return handleResult(ctx, result);\n    }\n    \"~validate\"(data) {\n        const ctx = {\n            common: {\n                issues: [],\n                async: !!this[\"~standard\"].async,\n            },\n            path: [],\n            schemaErrorMap: this._def.errorMap,\n            parent: null,\n            data,\n            parsedType: getParsedType(data),\n        };\n        if (!this[\"~standard\"].async) {\n            try {\n                const result = this._parseSync({ data, path: [], parent: ctx });\n                return isValid(result)\n                    ? {\n                        value: result.value,\n                    }\n                    : {\n                        issues: ctx.common.issues,\n                    };\n            }\n            catch (err) {\n                if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n                    this[\"~standard\"].async = true;\n                }\n                ctx.common = {\n                    issues: [],\n                    async: true,\n                };\n            }\n        }\n        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n            ? {\n                value: result.value,\n            }\n            : {\n                issues: ctx.common.issues,\n            });\n    }\n    async parseAsync(data, params) {\n        const result = await this.safeParseAsync(data, params);\n        if (result.success)\n            return result.data;\n        throw result.error;\n    }\n    async safeParseAsync(data, params) {\n        const ctx = {\n            common: {\n                issues: [],\n                contextualErrorMap: params?.errorMap,\n                async: true,\n            },\n            path: params?.path || [],\n            schemaErrorMap: this._def.errorMap,\n            parent: null,\n            data,\n            parsedType: getParsedType(data),\n        };\n        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n        return handleResult(ctx, result);\n    }\n    refine(check, message) {\n        const getIssueProperties = (val) => {\n            if (typeof message === \"string\" || typeof message === \"undefined\") {\n                return { message };\n            }\n            else if (typeof message === \"function\") {\n                return message(val);\n            }\n            else {\n                return message;\n            }\n        };\n        return this._refinement((val, ctx) => {\n            const result = check(val);\n            const setError = () => ctx.addIssue({\n                code: ZodIssueCode.custom,\n                ...getIssueProperties(val),\n            });\n            if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n                return result.then((data) => {\n                    if (!data) {\n                        setError();\n                        return false;\n                    }\n                    else {\n                        return true;\n                    }\n                });\n            }\n            if (!result) {\n                setError();\n                return false;\n            }\n            else {\n                return true;\n            }\n        });\n    }\n    refinement(check, refinementData) {\n        return this._refinement((val, ctx) => {\n            if (!check(val)) {\n                ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n                return false;\n            }\n            else {\n                return true;\n            }\n        });\n    }\n    _refinement(refinement) {\n        return new ZodEffects({\n            schema: this,\n            typeName: ZodFirstPartyTypeKind.ZodEffects,\n            effect: { type: \"refinement\", refinement },\n        });\n    }\n    superRefine(refinement) {\n        return this._refinement(refinement);\n    }\n    constructor(def) {\n        /** Alias of safeParseAsync */\n        this.spa = this.safeParseAsync;\n        this._def = def;\n        this.parse = this.parse.bind(this);\n        this.safeParse = this.safeParse.bind(this);\n        this.parseAsync = this.parseAsync.bind(this);\n        this.safeParseAsync = this.safeParseAsync.bind(this);\n        this.spa = this.spa.bind(this);\n        this.refine = this.refine.bind(this);\n        this.refinement = this.refinement.bind(this);\n        this.superRefine = this.superRefine.bind(this);\n        this.optional = this.optional.bind(this);\n        this.nullable = this.nullable.bind(this);\n        this.nullish = this.nullish.bind(this);\n        this.array = this.array.bind(this);\n        this.promise = this.promise.bind(this);\n        this.or = this.or.bind(this);\n        this.and = this.and.bind(this);\n        this.transform = this.transform.bind(this);\n        this.brand = this.brand.bind(this);\n        this.default = this.default.bind(this);\n        this.catch = this.catch.bind(this);\n        this.describe = this.describe.bind(this);\n        this.pipe = this.pipe.bind(this);\n        this.readonly = this.readonly.bind(this);\n        this.isNullable = this.isNullable.bind(this);\n        this.isOptional = this.isOptional.bind(this);\n        this[\"~standard\"] = {\n            version: 1,\n            vendor: \"zod\",\n            validate: (data) => this[\"~validate\"](data),\n        };\n    }\n    optional() {\n        return ZodOptional.create(this, this._def);\n    }\n    nullable() {\n        return ZodNullable.create(this, this._def);\n    }\n    nullish() {\n        return this.nullable().optional();\n    }\n    array() {\n        return ZodArray.create(this);\n    }\n    promise() {\n        return ZodPromise.create(this, this._def);\n    }\n    or(option) {\n        return ZodUnion.create([this, option], this._def);\n    }\n    and(incoming) {\n        return ZodIntersection.create(this, incoming, this._def);\n    }\n    transform(transform) {\n        return new ZodEffects({\n            ...processCreateParams(this._def),\n            schema: this,\n            typeName: ZodFirstPartyTypeKind.ZodEffects,\n            effect: { type: \"transform\", transform },\n        });\n    }\n    default(def) {\n        const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n        return new ZodDefault({\n            ...processCreateParams(this._def),\n            innerType: this,\n            defaultValue: defaultValueFunc,\n            typeName: ZodFirstPartyTypeKind.ZodDefault,\n        });\n    }\n    brand() {\n        return new ZodBranded({\n            typeName: ZodFirstPartyTypeKind.ZodBranded,\n            type: this,\n            ...processCreateParams(this._def),\n        });\n    }\n    catch(def) {\n        const catchValueFunc = typeof def === \"function\" ? def : () => def;\n        return new ZodCatch({\n            ...processCreateParams(this._def),\n            innerType: this,\n            catchValue: catchValueFunc,\n            typeName: ZodFirstPartyTypeKind.ZodCatch,\n        });\n    }\n    describe(description) {\n        const This = this.constructor;\n        return new This({\n            ...this._def,\n            description,\n        });\n    }\n    pipe(target) {\n        return ZodPipeline.create(this, target);\n    }\n    readonly() {\n        return ZodReadonly.create(this);\n    }\n    isOptional() {\n        return this.safeParse(undefined).success;\n    }\n    isNullable() {\n        return this.safeParse(null).success;\n    }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n//   /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n//   /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n//   /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n//   /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n//   /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n    let secondsRegexSource = `[0-5]\\\\d`;\n    if (args.precision) {\n        secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n    }\n    else if (args.precision == null) {\n        secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n    }\n    const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n    return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n    return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n    let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n    const opts = [];\n    opts.push(args.local ? `Z?` : `Z`);\n    if (args.offset)\n        opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n    regex = `${regex}(${opts.join(\"|\")})`;\n    return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n    if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n        return true;\n    }\n    if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n        return true;\n    }\n    return false;\n}\nfunction isValidJWT(jwt, alg) {\n    if (!jwtRegex.test(jwt))\n        return false;\n    try {\n        const [header] = jwt.split(\".\");\n        if (!header)\n            return false;\n        // Convert base64url to base64\n        const base64 = header\n            .replace(/-/g, \"+\")\n            .replace(/_/g, \"/\")\n            .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n        const decoded = JSON.parse(atob(base64));\n        if (typeof decoded !== \"object\" || decoded === null)\n            return false;\n        if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n            return false;\n        if (!decoded.alg)\n            return false;\n        if (alg && decoded.alg !== alg)\n            return false;\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nfunction isValidCidr(ip, version) {\n    if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n        return true;\n    }\n    if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n        return true;\n    }\n    return false;\n}\nexport class ZodString extends ZodType {\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = String(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.string) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.string,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const status = new ParseStatus();\n        let ctx = undefined;\n        for (const check of this._def.checks) {\n            if (check.kind === \"min\") {\n                if (input.data.length < check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        minimum: check.value,\n                        type: \"string\",\n                        inclusive: true,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                if (input.data.length > check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        maximum: check.value,\n                        type: \"string\",\n                        inclusive: true,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"length\") {\n                const tooBig = input.data.length > check.value;\n                const tooSmall = input.data.length < check.value;\n                if (tooBig || tooSmall) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    if (tooBig) {\n                        addIssueToContext(ctx, {\n                            code: ZodIssueCode.too_big,\n                            maximum: check.value,\n                            type: \"string\",\n                            inclusive: true,\n                            exact: true,\n                            message: check.message,\n                        });\n                    }\n                    else if (tooSmall) {\n                        addIssueToContext(ctx, {\n                            code: ZodIssueCode.too_small,\n                            minimum: check.value,\n                            type: \"string\",\n                            inclusive: true,\n                            exact: true,\n                            message: check.message,\n                        });\n                    }\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"email\") {\n                if (!emailRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"email\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"emoji\") {\n                if (!emojiRegex) {\n                    emojiRegex = new RegExp(_emojiRegex, \"u\");\n                }\n                if (!emojiRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"emoji\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"uuid\") {\n                if (!uuidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"uuid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"nanoid\") {\n                if (!nanoidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"nanoid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"cuid\") {\n                if (!cuidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"cuid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"cuid2\") {\n                if (!cuid2Regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"cuid2\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"ulid\") {\n                if (!ulidRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"ulid\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"url\") {\n                try {\n                    new URL(input.data);\n                }\n                catch {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"url\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"regex\") {\n                check.regex.lastIndex = 0;\n                const testResult = check.regex.test(input.data);\n                if (!testResult) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"regex\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"trim\") {\n                input.data = input.data.trim();\n            }\n            else if (check.kind === \"includes\") {\n                if (!input.data.includes(check.value, check.position)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: { includes: check.value, position: check.position },\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"toLowerCase\") {\n                input.data = input.data.toLowerCase();\n            }\n            else if (check.kind === \"toUpperCase\") {\n                input.data = input.data.toUpperCase();\n            }\n            else if (check.kind === \"startsWith\") {\n                if (!input.data.startsWith(check.value)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: { startsWith: check.value },\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"endsWith\") {\n                if (!input.data.endsWith(check.value)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: { endsWith: check.value },\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"datetime\") {\n                const regex = datetimeRegex(check);\n                if (!regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: \"datetime\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"date\") {\n                const regex = dateRegex;\n                if (!regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: \"date\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"time\") {\n                const regex = timeRegex(check);\n                if (!regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_string,\n                        validation: \"time\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"duration\") {\n                if (!durationRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"duration\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"ip\") {\n                if (!isValidIP(input.data, check.version)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"ip\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"jwt\") {\n                if (!isValidJWT(input.data, check.alg)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"jwt\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"cidr\") {\n                if (!isValidCidr(input.data, check.version)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"cidr\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"base64\") {\n                if (!base64Regex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"base64\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"base64url\") {\n                if (!base64urlRegex.test(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        validation: \"base64url\",\n                        code: ZodIssueCode.invalid_string,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return { status: status.value, value: input.data };\n    }\n    _regex(regex, validation, message) {\n        return this.refinement((data) => regex.test(data), {\n            validation,\n            code: ZodIssueCode.invalid_string,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    _addCheck(check) {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    email(message) {\n        return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n    }\n    url(message) {\n        return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n    }\n    emoji(message) {\n        return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n    }\n    uuid(message) {\n        return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n    }\n    nanoid(message) {\n        return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n    }\n    cuid(message) {\n        return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n    }\n    cuid2(message) {\n        return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n    }\n    ulid(message) {\n        return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n    }\n    base64(message) {\n        return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n    }\n    base64url(message) {\n        // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n        return this._addCheck({\n            kind: \"base64url\",\n            ...errorUtil.errToObj(message),\n        });\n    }\n    jwt(options) {\n        return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n    }\n    ip(options) {\n        return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n    }\n    cidr(options) {\n        return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n    }\n    datetime(options) {\n        if (typeof options === \"string\") {\n            return this._addCheck({\n                kind: \"datetime\",\n                precision: null,\n                offset: false,\n                local: false,\n                message: options,\n            });\n        }\n        return this._addCheck({\n            kind: \"datetime\",\n            precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n            offset: options?.offset ?? false,\n            local: options?.local ?? false,\n            ...errorUtil.errToObj(options?.message),\n        });\n    }\n    date(message) {\n        return this._addCheck({ kind: \"date\", message });\n    }\n    time(options) {\n        if (typeof options === \"string\") {\n            return this._addCheck({\n                kind: \"time\",\n                precision: null,\n                message: options,\n            });\n        }\n        return this._addCheck({\n            kind: \"time\",\n            precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n            ...errorUtil.errToObj(options?.message),\n        });\n    }\n    duration(message) {\n        return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n    }\n    regex(regex, message) {\n        return this._addCheck({\n            kind: \"regex\",\n            regex: regex,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    includes(value, options) {\n        return this._addCheck({\n            kind: \"includes\",\n            value: value,\n            position: options?.position,\n            ...errorUtil.errToObj(options?.message),\n        });\n    }\n    startsWith(value, message) {\n        return this._addCheck({\n            kind: \"startsWith\",\n            value: value,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    endsWith(value, message) {\n        return this._addCheck({\n            kind: \"endsWith\",\n            value: value,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    min(minLength, message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: minLength,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    max(maxLength, message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: maxLength,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    length(len, message) {\n        return this._addCheck({\n            kind: \"length\",\n            value: len,\n            ...errorUtil.errToObj(message),\n        });\n    }\n    /**\n     * Equivalent to `.min(1)`\n     */\n    nonempty(message) {\n        return this.min(1, errorUtil.errToObj(message));\n    }\n    trim() {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, { kind: \"trim\" }],\n        });\n    }\n    toLowerCase() {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n        });\n    }\n    toUpperCase() {\n        return new ZodString({\n            ...this._def,\n            checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n        });\n    }\n    get isDatetime() {\n        return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n    }\n    get isDate() {\n        return !!this._def.checks.find((ch) => ch.kind === \"date\");\n    }\n    get isTime() {\n        return !!this._def.checks.find((ch) => ch.kind === \"time\");\n    }\n    get isDuration() {\n        return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n    }\n    get isEmail() {\n        return !!this._def.checks.find((ch) => ch.kind === \"email\");\n    }\n    get isURL() {\n        return !!this._def.checks.find((ch) => ch.kind === \"url\");\n    }\n    get isEmoji() {\n        return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n    }\n    get isUUID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n    }\n    get isNANOID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n    }\n    get isCUID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n    }\n    get isCUID2() {\n        return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n    }\n    get isULID() {\n        return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n    }\n    get isIP() {\n        return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n    }\n    get isCIDR() {\n        return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n    }\n    get isBase64() {\n        return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n    }\n    get isBase64url() {\n        // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n        return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n    }\n    get minLength() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min;\n    }\n    get maxLength() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max;\n    }\n}\nZodString.create = (params) => {\n    return new ZodString({\n        checks: [],\n        typeName: ZodFirstPartyTypeKind.ZodString,\n        coerce: params?.coerce ?? false,\n        ...processCreateParams(params),\n    });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n    const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n    const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n    const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n    const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n    return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n    constructor() {\n        super(...arguments);\n        this.min = this.gte;\n        this.max = this.lte;\n        this.step = this.multipleOf;\n    }\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = Number(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.number) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.number,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        let ctx = undefined;\n        const status = new ParseStatus();\n        for (const check of this._def.checks) {\n            if (check.kind === \"int\") {\n                if (!util.isInteger(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.invalid_type,\n                        expected: \"integer\",\n                        received: \"float\",\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"min\") {\n                const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n                if (tooSmall) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        minimum: check.value,\n                        type: \"number\",\n                        inclusive: check.inclusive,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n                if (tooBig) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        maximum: check.value,\n                        type: \"number\",\n                        inclusive: check.inclusive,\n                        exact: false,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"multipleOf\") {\n                if (floatSafeRemainder(input.data, check.value) !== 0) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.not_multiple_of,\n                        multipleOf: check.value,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"finite\") {\n                if (!Number.isFinite(input.data)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.not_finite,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return { status: status.value, value: input.data };\n    }\n    gte(value, message) {\n        return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n    }\n    gt(value, message) {\n        return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n    }\n    lte(value, message) {\n        return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n    }\n    lt(value, message) {\n        return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n    }\n    setLimit(kind, value, inclusive, message) {\n        return new ZodNumber({\n            ...this._def,\n            checks: [\n                ...this._def.checks,\n                {\n                    kind,\n                    value,\n                    inclusive,\n                    message: errorUtil.toString(message),\n                },\n            ],\n        });\n    }\n    _addCheck(check) {\n        return new ZodNumber({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    int(message) {\n        return this._addCheck({\n            kind: \"int\",\n            message: errorUtil.toString(message),\n        });\n    }\n    positive(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: 0,\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    negative(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: 0,\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonpositive(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: 0,\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonnegative(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: 0,\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    multipleOf(value, message) {\n        return this._addCheck({\n            kind: \"multipleOf\",\n            value: value,\n            message: errorUtil.toString(message),\n        });\n    }\n    finite(message) {\n        return this._addCheck({\n            kind: \"finite\",\n            message: errorUtil.toString(message),\n        });\n    }\n    safe(message) {\n        return this._addCheck({\n            kind: \"min\",\n            inclusive: true,\n            value: Number.MIN_SAFE_INTEGER,\n            message: errorUtil.toString(message),\n        })._addCheck({\n            kind: \"max\",\n            inclusive: true,\n            value: Number.MAX_SAFE_INTEGER,\n            message: errorUtil.toString(message),\n        });\n    }\n    get minValue() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min;\n    }\n    get maxValue() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max;\n    }\n    get isInt() {\n        return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n    }\n    get isFinite() {\n        let max = null;\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n                return true;\n            }\n            else if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n            else if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return Number.isFinite(min) && Number.isFinite(max);\n    }\n}\nZodNumber.create = (params) => {\n    return new ZodNumber({\n        checks: [],\n        typeName: ZodFirstPartyTypeKind.ZodNumber,\n        coerce: params?.coerce || false,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodBigInt extends ZodType {\n    constructor() {\n        super(...arguments);\n        this.min = this.gte;\n        this.max = this.lte;\n    }\n    _parse(input) {\n        if (this._def.coerce) {\n            try {\n                input.data = BigInt(input.data);\n            }\n            catch {\n                return this._getInvalidInput(input);\n            }\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.bigint) {\n            return this._getInvalidInput(input);\n        }\n        let ctx = undefined;\n        const status = new ParseStatus();\n        for (const check of this._def.checks) {\n            if (check.kind === \"min\") {\n                const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n                if (tooSmall) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        type: \"bigint\",\n                        minimum: check.value,\n                        inclusive: check.inclusive,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n                if (tooBig) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        type: \"bigint\",\n                        maximum: check.value,\n                        inclusive: check.inclusive,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"multipleOf\") {\n                if (input.data % check.value !== BigInt(0)) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.not_multiple_of,\n                        multipleOf: check.value,\n                        message: check.message,\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return { status: status.value, value: input.data };\n    }\n    _getInvalidInput(input) {\n        const ctx = this._getOrReturnCtx(input);\n        addIssueToContext(ctx, {\n            code: ZodIssueCode.invalid_type,\n            expected: ZodParsedType.bigint,\n            received: ctx.parsedType,\n        });\n        return INVALID;\n    }\n    gte(value, message) {\n        return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n    }\n    gt(value, message) {\n        return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n    }\n    lte(value, message) {\n        return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n    }\n    lt(value, message) {\n        return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n    }\n    setLimit(kind, value, inclusive, message) {\n        return new ZodBigInt({\n            ...this._def,\n            checks: [\n                ...this._def.checks,\n                {\n                    kind,\n                    value,\n                    inclusive,\n                    message: errorUtil.toString(message),\n                },\n            ],\n        });\n    }\n    _addCheck(check) {\n        return new ZodBigInt({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    positive(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: BigInt(0),\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    negative(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: BigInt(0),\n            inclusive: false,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonpositive(message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: BigInt(0),\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    nonnegative(message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: BigInt(0),\n            inclusive: true,\n            message: errorUtil.toString(message),\n        });\n    }\n    multipleOf(value, message) {\n        return this._addCheck({\n            kind: \"multipleOf\",\n            value,\n            message: errorUtil.toString(message),\n        });\n    }\n    get minValue() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min;\n    }\n    get maxValue() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max;\n    }\n}\nZodBigInt.create = (params) => {\n    return new ZodBigInt({\n        checks: [],\n        typeName: ZodFirstPartyTypeKind.ZodBigInt,\n        coerce: params?.coerce ?? false,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodBoolean extends ZodType {\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = Boolean(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.boolean) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.boolean,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodBoolean.create = (params) => {\n    return new ZodBoolean({\n        typeName: ZodFirstPartyTypeKind.ZodBoolean,\n        coerce: params?.coerce || false,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodDate extends ZodType {\n    _parse(input) {\n        if (this._def.coerce) {\n            input.data = new Date(input.data);\n        }\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.date) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.date,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        if (Number.isNaN(input.data.getTime())) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_date,\n            });\n            return INVALID;\n        }\n        const status = new ParseStatus();\n        let ctx = undefined;\n        for (const check of this._def.checks) {\n            if (check.kind === \"min\") {\n                if (input.data.getTime() < check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_small,\n                        message: check.message,\n                        inclusive: true,\n                        exact: false,\n                        minimum: check.value,\n                        type: \"date\",\n                    });\n                    status.dirty();\n                }\n            }\n            else if (check.kind === \"max\") {\n                if (input.data.getTime() > check.value) {\n                    ctx = this._getOrReturnCtx(input, ctx);\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.too_big,\n                        message: check.message,\n                        inclusive: true,\n                        exact: false,\n                        maximum: check.value,\n                        type: \"date\",\n                    });\n                    status.dirty();\n                }\n            }\n            else {\n                util.assertNever(check);\n            }\n        }\n        return {\n            status: status.value,\n            value: new Date(input.data.getTime()),\n        };\n    }\n    _addCheck(check) {\n        return new ZodDate({\n            ...this._def,\n            checks: [...this._def.checks, check],\n        });\n    }\n    min(minDate, message) {\n        return this._addCheck({\n            kind: \"min\",\n            value: minDate.getTime(),\n            message: errorUtil.toString(message),\n        });\n    }\n    max(maxDate, message) {\n        return this._addCheck({\n            kind: \"max\",\n            value: maxDate.getTime(),\n            message: errorUtil.toString(message),\n        });\n    }\n    get minDate() {\n        let min = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"min\") {\n                if (min === null || ch.value > min)\n                    min = ch.value;\n            }\n        }\n        return min != null ? new Date(min) : null;\n    }\n    get maxDate() {\n        let max = null;\n        for (const ch of this._def.checks) {\n            if (ch.kind === \"max\") {\n                if (max === null || ch.value < max)\n                    max = ch.value;\n            }\n        }\n        return max != null ? new Date(max) : null;\n    }\n}\nZodDate.create = (params) => {\n    return new ZodDate({\n        checks: [],\n        coerce: params?.coerce || false,\n        typeName: ZodFirstPartyTypeKind.ZodDate,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodSymbol extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.symbol) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.symbol,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodSymbol.create = (params) => {\n    return new ZodSymbol({\n        typeName: ZodFirstPartyTypeKind.ZodSymbol,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodUndefined extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.undefined) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.undefined,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodUndefined.create = (params) => {\n    return new ZodUndefined({\n        typeName: ZodFirstPartyTypeKind.ZodUndefined,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNull extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.null) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.null,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodNull.create = (params) => {\n    return new ZodNull({\n        typeName: ZodFirstPartyTypeKind.ZodNull,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodAny extends ZodType {\n    constructor() {\n        super(...arguments);\n        // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n        this._any = true;\n    }\n    _parse(input) {\n        return OK(input.data);\n    }\n}\nZodAny.create = (params) => {\n    return new ZodAny({\n        typeName: ZodFirstPartyTypeKind.ZodAny,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodUnknown extends ZodType {\n    constructor() {\n        super(...arguments);\n        // required\n        this._unknown = true;\n    }\n    _parse(input) {\n        return OK(input.data);\n    }\n}\nZodUnknown.create = (params) => {\n    return new ZodUnknown({\n        typeName: ZodFirstPartyTypeKind.ZodUnknown,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNever extends ZodType {\n    _parse(input) {\n        const ctx = this._getOrReturnCtx(input);\n        addIssueToContext(ctx, {\n            code: ZodIssueCode.invalid_type,\n            expected: ZodParsedType.never,\n            received: ctx.parsedType,\n        });\n        return INVALID;\n    }\n}\nZodNever.create = (params) => {\n    return new ZodNever({\n        typeName: ZodFirstPartyTypeKind.ZodNever,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodVoid extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.undefined) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.void,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n}\nZodVoid.create = (params) => {\n    return new ZodVoid({\n        typeName: ZodFirstPartyTypeKind.ZodVoid,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodArray extends ZodType {\n    _parse(input) {\n        const { ctx, status } = this._processInputParams(input);\n        const def = this._def;\n        if (ctx.parsedType !== ZodParsedType.array) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.array,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        if (def.exactLength !== null) {\n            const tooBig = ctx.data.length > def.exactLength.value;\n            const tooSmall = ctx.data.length < def.exactLength.value;\n            if (tooBig || tooSmall) {\n                addIssueToContext(ctx, {\n                    code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n                    minimum: (tooSmall ? def.exactLength.value : undefined),\n                    maximum: (tooBig ? def.exactLength.value : undefined),\n                    type: \"array\",\n                    inclusive: true,\n                    exact: true,\n                    message: def.exactLength.message,\n                });\n                status.dirty();\n            }\n        }\n        if (def.minLength !== null) {\n            if (ctx.data.length < def.minLength.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_small,\n                    minimum: def.minLength.value,\n                    type: \"array\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.minLength.message,\n                });\n                status.dirty();\n            }\n        }\n        if (def.maxLength !== null) {\n            if (ctx.data.length > def.maxLength.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_big,\n                    maximum: def.maxLength.value,\n                    type: \"array\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.maxLength.message,\n                });\n                status.dirty();\n            }\n        }\n        if (ctx.common.async) {\n            return Promise.all([...ctx.data].map((item, i) => {\n                return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n            })).then((result) => {\n                return ParseStatus.mergeArray(status, result);\n            });\n        }\n        const result = [...ctx.data].map((item, i) => {\n            return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n        });\n        return ParseStatus.mergeArray(status, result);\n    }\n    get element() {\n        return this._def.type;\n    }\n    min(minLength, message) {\n        return new ZodArray({\n            ...this._def,\n            minLength: { value: minLength, message: errorUtil.toString(message) },\n        });\n    }\n    max(maxLength, message) {\n        return new ZodArray({\n            ...this._def,\n            maxLength: { value: maxLength, message: errorUtil.toString(message) },\n        });\n    }\n    length(len, message) {\n        return new ZodArray({\n            ...this._def,\n            exactLength: { value: len, message: errorUtil.toString(message) },\n        });\n    }\n    nonempty(message) {\n        return this.min(1, message);\n    }\n}\nZodArray.create = (schema, params) => {\n    return new ZodArray({\n        type: schema,\n        minLength: null,\n        maxLength: null,\n        exactLength: null,\n        typeName: ZodFirstPartyTypeKind.ZodArray,\n        ...processCreateParams(params),\n    });\n};\nfunction deepPartialify(schema) {\n    if (schema instanceof ZodObject) {\n        const newShape = {};\n        for (const key in schema.shape) {\n            const fieldSchema = schema.shape[key];\n            newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n        }\n        return new ZodObject({\n            ...schema._def,\n            shape: () => newShape,\n        });\n    }\n    else if (schema instanceof ZodArray) {\n        return new ZodArray({\n            ...schema._def,\n            type: deepPartialify(schema.element),\n        });\n    }\n    else if (schema instanceof ZodOptional) {\n        return ZodOptional.create(deepPartialify(schema.unwrap()));\n    }\n    else if (schema instanceof ZodNullable) {\n        return ZodNullable.create(deepPartialify(schema.unwrap()));\n    }\n    else if (schema instanceof ZodTuple) {\n        return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n    }\n    else {\n        return schema;\n    }\n}\nexport class ZodObject extends ZodType {\n    constructor() {\n        super(...arguments);\n        this._cached = null;\n        /**\n         * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n         * If you want to pass through unknown properties, use `.passthrough()` instead.\n         */\n        this.nonstrict = this.passthrough;\n        // extend<\n        //   Augmentation extends ZodRawShape,\n        //   NewOutput extends util.flatten<{\n        //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n        //       ? Augmentation[k][\"_output\"]\n        //       : k extends keyof Output\n        //       ? Output[k]\n        //       : never;\n        //   }>,\n        //   NewInput extends util.flatten<{\n        //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n        //       ? Augmentation[k][\"_input\"]\n        //       : k extends keyof Input\n        //       ? Input[k]\n        //       : never;\n        //   }>\n        // >(\n        //   augmentation: Augmentation\n        // ): ZodObject<\n        //   extendShape<T, Augmentation>,\n        //   UnknownKeys,\n        //   Catchall,\n        //   NewOutput,\n        //   NewInput\n        // > {\n        //   return new ZodObject({\n        //     ...this._def,\n        //     shape: () => ({\n        //       ...this._def.shape(),\n        //       ...augmentation,\n        //     }),\n        //   }) as any;\n        // }\n        /**\n         * @deprecated Use `.extend` instead\n         *  */\n        this.augment = this.extend;\n    }\n    _getCached() {\n        if (this._cached !== null)\n            return this._cached;\n        const shape = this._def.shape();\n        const keys = util.objectKeys(shape);\n        this._cached = { shape, keys };\n        return this._cached;\n    }\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.object) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.object,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const { status, ctx } = this._processInputParams(input);\n        const { shape, keys: shapeKeys } = this._getCached();\n        const extraKeys = [];\n        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n            for (const key in ctx.data) {\n                if (!shapeKeys.includes(key)) {\n                    extraKeys.push(key);\n                }\n            }\n        }\n        const pairs = [];\n        for (const key of shapeKeys) {\n            const keyValidator = shape[key];\n            const value = ctx.data[key];\n            pairs.push({\n                key: { status: \"valid\", value: key },\n                value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n                alwaysSet: key in ctx.data,\n            });\n        }\n        if (this._def.catchall instanceof ZodNever) {\n            const unknownKeys = this._def.unknownKeys;\n            if (unknownKeys === \"passthrough\") {\n                for (const key of extraKeys) {\n                    pairs.push({\n                        key: { status: \"valid\", value: key },\n                        value: { status: \"valid\", value: ctx.data[key] },\n                    });\n                }\n            }\n            else if (unknownKeys === \"strict\") {\n                if (extraKeys.length > 0) {\n                    addIssueToContext(ctx, {\n                        code: ZodIssueCode.unrecognized_keys,\n                        keys: extraKeys,\n                    });\n                    status.dirty();\n                }\n            }\n            else if (unknownKeys === \"strip\") {\n            }\n            else {\n                throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n            }\n        }\n        else {\n            // run catchall validation\n            const catchall = this._def.catchall;\n            for (const key of extraKeys) {\n                const value = ctx.data[key];\n                pairs.push({\n                    key: { status: \"valid\", value: key },\n                    value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n                    ),\n                    alwaysSet: key in ctx.data,\n                });\n            }\n        }\n        if (ctx.common.async) {\n            return Promise.resolve()\n                .then(async () => {\n                const syncPairs = [];\n                for (const pair of pairs) {\n                    const key = await pair.key;\n                    const value = await pair.value;\n                    syncPairs.push({\n                        key,\n                        value,\n                        alwaysSet: pair.alwaysSet,\n                    });\n                }\n                return syncPairs;\n            })\n                .then((syncPairs) => {\n                return ParseStatus.mergeObjectSync(status, syncPairs);\n            });\n        }\n        else {\n            return ParseStatus.mergeObjectSync(status, pairs);\n        }\n    }\n    get shape() {\n        return this._def.shape();\n    }\n    strict(message) {\n        errorUtil.errToObj;\n        return new ZodObject({\n            ...this._def,\n            unknownKeys: \"strict\",\n            ...(message !== undefined\n                ? {\n                    errorMap: (issue, ctx) => {\n                        const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n                        if (issue.code === \"unrecognized_keys\")\n                            return {\n                                message: errorUtil.errToObj(message).message ?? defaultError,\n                            };\n                        return {\n                            message: defaultError,\n                        };\n                    },\n                }\n                : {}),\n        });\n    }\n    strip() {\n        return new ZodObject({\n            ...this._def,\n            unknownKeys: \"strip\",\n        });\n    }\n    passthrough() {\n        return new ZodObject({\n            ...this._def,\n            unknownKeys: \"passthrough\",\n        });\n    }\n    // const AugmentFactory =\n    //   <Def extends ZodObjectDef>(def: Def) =>\n    //   <Augmentation extends ZodRawShape>(\n    //     augmentation: Augmentation\n    //   ): ZodObject<\n    //     extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n    //     Def[\"unknownKeys\"],\n    //     Def[\"catchall\"]\n    //   > => {\n    //     return new ZodObject({\n    //       ...def,\n    //       shape: () => ({\n    //         ...def.shape(),\n    //         ...augmentation,\n    //       }),\n    //     }) as any;\n    //   };\n    extend(augmentation) {\n        return new ZodObject({\n            ...this._def,\n            shape: () => ({\n                ...this._def.shape(),\n                ...augmentation,\n            }),\n        });\n    }\n    /**\n     * Prior to zod@1.0.12 there was a bug in the\n     * inferred type of merged objects. Please\n     * upgrade if you are experiencing issues.\n     */\n    merge(merging) {\n        const merged = new ZodObject({\n            unknownKeys: merging._def.unknownKeys,\n            catchall: merging._def.catchall,\n            shape: () => ({\n                ...this._def.shape(),\n                ...merging._def.shape(),\n            }),\n            typeName: ZodFirstPartyTypeKind.ZodObject,\n        });\n        return merged;\n    }\n    // merge<\n    //   Incoming extends AnyZodObject,\n    //   Augmentation extends Incoming[\"shape\"],\n    //   NewOutput extends {\n    //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n    //       ? Augmentation[k][\"_output\"]\n    //       : k extends keyof Output\n    //       ? Output[k]\n    //       : never;\n    //   },\n    //   NewInput extends {\n    //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n    //       ? Augmentation[k][\"_input\"]\n    //       : k extends keyof Input\n    //       ? Input[k]\n    //       : never;\n    //   }\n    // >(\n    //   merging: Incoming\n    // ): ZodObject<\n    //   extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n    //   Incoming[\"_def\"][\"unknownKeys\"],\n    //   Incoming[\"_def\"][\"catchall\"],\n    //   NewOutput,\n    //   NewInput\n    // > {\n    //   const merged: any = new ZodObject({\n    //     unknownKeys: merging._def.unknownKeys,\n    //     catchall: merging._def.catchall,\n    //     shape: () =>\n    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n    //     typeName: ZodFirstPartyTypeKind.ZodObject,\n    //   }) as any;\n    //   return merged;\n    // }\n    setKey(key, schema) {\n        return this.augment({ [key]: schema });\n    }\n    // merge<Incoming extends AnyZodObject>(\n    //   merging: Incoming\n    // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n    // ZodObject<\n    //   extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n    //   Incoming[\"_def\"][\"unknownKeys\"],\n    //   Incoming[\"_def\"][\"catchall\"]\n    // > {\n    //   // const mergedShape = objectUtil.mergeShapes(\n    //   //   this._def.shape(),\n    //   //   merging._def.shape()\n    //   // );\n    //   const merged: any = new ZodObject({\n    //     unknownKeys: merging._def.unknownKeys,\n    //     catchall: merging._def.catchall,\n    //     shape: () =>\n    //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n    //     typeName: ZodFirstPartyTypeKind.ZodObject,\n    //   }) as any;\n    //   return merged;\n    // }\n    catchall(index) {\n        return new ZodObject({\n            ...this._def,\n            catchall: index,\n        });\n    }\n    pick(mask) {\n        const shape = {};\n        for (const key of util.objectKeys(mask)) {\n            if (mask[key] && this.shape[key]) {\n                shape[key] = this.shape[key];\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => shape,\n        });\n    }\n    omit(mask) {\n        const shape = {};\n        for (const key of util.objectKeys(this.shape)) {\n            if (!mask[key]) {\n                shape[key] = this.shape[key];\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => shape,\n        });\n    }\n    /**\n     * @deprecated\n     */\n    deepPartial() {\n        return deepPartialify(this);\n    }\n    partial(mask) {\n        const newShape = {};\n        for (const key of util.objectKeys(this.shape)) {\n            const fieldSchema = this.shape[key];\n            if (mask && !mask[key]) {\n                newShape[key] = fieldSchema;\n            }\n            else {\n                newShape[key] = fieldSchema.optional();\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => newShape,\n        });\n    }\n    required(mask) {\n        const newShape = {};\n        for (const key of util.objectKeys(this.shape)) {\n            if (mask && !mask[key]) {\n                newShape[key] = this.shape[key];\n            }\n            else {\n                const fieldSchema = this.shape[key];\n                let newField = fieldSchema;\n                while (newField instanceof ZodOptional) {\n                    newField = newField._def.innerType;\n                }\n                newShape[key] = newField;\n            }\n        }\n        return new ZodObject({\n            ...this._def,\n            shape: () => newShape,\n        });\n    }\n    keyof() {\n        return createZodEnum(util.objectKeys(this.shape));\n    }\n}\nZodObject.create = (shape, params) => {\n    return new ZodObject({\n        shape: () => shape,\n        unknownKeys: \"strip\",\n        catchall: ZodNever.create(),\n        typeName: ZodFirstPartyTypeKind.ZodObject,\n        ...processCreateParams(params),\n    });\n};\nZodObject.strictCreate = (shape, params) => {\n    return new ZodObject({\n        shape: () => shape,\n        unknownKeys: \"strict\",\n        catchall: ZodNever.create(),\n        typeName: ZodFirstPartyTypeKind.ZodObject,\n        ...processCreateParams(params),\n    });\n};\nZodObject.lazycreate = (shape, params) => {\n    return new ZodObject({\n        shape,\n        unknownKeys: \"strip\",\n        catchall: ZodNever.create(),\n        typeName: ZodFirstPartyTypeKind.ZodObject,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodUnion extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        const options = this._def.options;\n        function handleResults(results) {\n            // return first issue-free validation if it exists\n            for (const result of results) {\n                if (result.result.status === \"valid\") {\n                    return result.result;\n                }\n            }\n            for (const result of results) {\n                if (result.result.status === \"dirty\") {\n                    // add issues from dirty option\n                    ctx.common.issues.push(...result.ctx.common.issues);\n                    return result.result;\n                }\n            }\n            // return invalid\n            const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_union,\n                unionErrors,\n            });\n            return INVALID;\n        }\n        if (ctx.common.async) {\n            return Promise.all(options.map(async (option) => {\n                const childCtx = {\n                    ...ctx,\n                    common: {\n                        ...ctx.common,\n                        issues: [],\n                    },\n                    parent: null,\n                };\n                return {\n                    result: await option._parseAsync({\n                        data: ctx.data,\n                        path: ctx.path,\n                        parent: childCtx,\n                    }),\n                    ctx: childCtx,\n                };\n            })).then(handleResults);\n        }\n        else {\n            let dirty = undefined;\n            const issues = [];\n            for (const option of options) {\n                const childCtx = {\n                    ...ctx,\n                    common: {\n                        ...ctx.common,\n                        issues: [],\n                    },\n                    parent: null,\n                };\n                const result = option._parseSync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: childCtx,\n                });\n                if (result.status === \"valid\") {\n                    return result;\n                }\n                else if (result.status === \"dirty\" && !dirty) {\n                    dirty = { result, ctx: childCtx };\n                }\n                if (childCtx.common.issues.length) {\n                    issues.push(childCtx.common.issues);\n                }\n            }\n            if (dirty) {\n                ctx.common.issues.push(...dirty.ctx.common.issues);\n                return dirty.result;\n            }\n            const unionErrors = issues.map((issues) => new ZodError(issues));\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_union,\n                unionErrors,\n            });\n            return INVALID;\n        }\n    }\n    get options() {\n        return this._def.options;\n    }\n}\nZodUnion.create = (types, params) => {\n    return new ZodUnion({\n        options: types,\n        typeName: ZodFirstPartyTypeKind.ZodUnion,\n        ...processCreateParams(params),\n    });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n//////////                                 //////////\n//////////      ZodDiscriminatedUnion      //////////\n//////////                                 //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n    if (type instanceof ZodLazy) {\n        return getDiscriminator(type.schema);\n    }\n    else if (type instanceof ZodEffects) {\n        return getDiscriminator(type.innerType());\n    }\n    else if (type instanceof ZodLiteral) {\n        return [type.value];\n    }\n    else if (type instanceof ZodEnum) {\n        return type.options;\n    }\n    else if (type instanceof ZodNativeEnum) {\n        // eslint-disable-next-line ban/ban\n        return util.objectValues(type.enum);\n    }\n    else if (type instanceof ZodDefault) {\n        return getDiscriminator(type._def.innerType);\n    }\n    else if (type instanceof ZodUndefined) {\n        return [undefined];\n    }\n    else if (type instanceof ZodNull) {\n        return [null];\n    }\n    else if (type instanceof ZodOptional) {\n        return [undefined, ...getDiscriminator(type.unwrap())];\n    }\n    else if (type instanceof ZodNullable) {\n        return [null, ...getDiscriminator(type.unwrap())];\n    }\n    else if (type instanceof ZodBranded) {\n        return getDiscriminator(type.unwrap());\n    }\n    else if (type instanceof ZodReadonly) {\n        return getDiscriminator(type.unwrap());\n    }\n    else if (type instanceof ZodCatch) {\n        return getDiscriminator(type._def.innerType);\n    }\n    else {\n        return [];\n    }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.object) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.object,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const discriminator = this.discriminator;\n        const discriminatorValue = ctx.data[discriminator];\n        const option = this.optionsMap.get(discriminatorValue);\n        if (!option) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_union_discriminator,\n                options: Array.from(this.optionsMap.keys()),\n                path: [discriminator],\n            });\n            return INVALID;\n        }\n        if (ctx.common.async) {\n            return option._parseAsync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            });\n        }\n        else {\n            return option._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            });\n        }\n    }\n    get discriminator() {\n        return this._def.discriminator;\n    }\n    get options() {\n        return this._def.options;\n    }\n    get optionsMap() {\n        return this._def.optionsMap;\n    }\n    /**\n     * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n     * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n     * have a different value for each object in the union.\n     * @param discriminator the name of the discriminator property\n     * @param types an array of object schemas\n     * @param params\n     */\n    static create(discriminator, options, params) {\n        // Get all the valid discriminator values\n        const optionsMap = new Map();\n        // try {\n        for (const type of options) {\n            const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n            if (!discriminatorValues.length) {\n                throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n            }\n            for (const value of discriminatorValues) {\n                if (optionsMap.has(value)) {\n                    throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n                }\n                optionsMap.set(value, type);\n            }\n        }\n        return new ZodDiscriminatedUnion({\n            typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n            discriminator,\n            options,\n            optionsMap,\n            ...processCreateParams(params),\n        });\n    }\n}\nfunction mergeValues(a, b) {\n    const aType = getParsedType(a);\n    const bType = getParsedType(b);\n    if (a === b) {\n        return { valid: true, data: a };\n    }\n    else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n        const bKeys = util.objectKeys(b);\n        const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n        const newObj = { ...a, ...b };\n        for (const key of sharedKeys) {\n            const sharedValue = mergeValues(a[key], b[key]);\n            if (!sharedValue.valid) {\n                return { valid: false };\n            }\n            newObj[key] = sharedValue.data;\n        }\n        return { valid: true, data: newObj };\n    }\n    else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n        if (a.length !== b.length) {\n            return { valid: false };\n        }\n        const newArray = [];\n        for (let index = 0; index < a.length; index++) {\n            const itemA = a[index];\n            const itemB = b[index];\n            const sharedValue = mergeValues(itemA, itemB);\n            if (!sharedValue.valid) {\n                return { valid: false };\n            }\n            newArray.push(sharedValue.data);\n        }\n        return { valid: true, data: newArray };\n    }\n    else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n        return { valid: true, data: a };\n    }\n    else {\n        return { valid: false };\n    }\n}\nexport class ZodIntersection extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        const handleParsed = (parsedLeft, parsedRight) => {\n            if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n                return INVALID;\n            }\n            const merged = mergeValues(parsedLeft.value, parsedRight.value);\n            if (!merged.valid) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.invalid_intersection_types,\n                });\n                return INVALID;\n            }\n            if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n                status.dirty();\n            }\n            return { status: status.value, value: merged.data };\n        };\n        if (ctx.common.async) {\n            return Promise.all([\n                this._def.left._parseAsync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                }),\n                this._def.right._parseAsync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                }),\n            ]).then(([left, right]) => handleParsed(left, right));\n        }\n        else {\n            return handleParsed(this._def.left._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            }), this._def.right._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            }));\n        }\n    }\n}\nZodIntersection.create = (left, right, params) => {\n    return new ZodIntersection({\n        left: left,\n        right: right,\n        typeName: ZodFirstPartyTypeKind.ZodIntersection,\n        ...processCreateParams(params),\n    });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.array) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.array,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        if (ctx.data.length < this._def.items.length) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.too_small,\n                minimum: this._def.items.length,\n                inclusive: true,\n                exact: false,\n                type: \"array\",\n            });\n            return INVALID;\n        }\n        const rest = this._def.rest;\n        if (!rest && ctx.data.length > this._def.items.length) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.too_big,\n                maximum: this._def.items.length,\n                inclusive: true,\n                exact: false,\n                type: \"array\",\n            });\n            status.dirty();\n        }\n        const items = [...ctx.data]\n            .map((item, itemIndex) => {\n            const schema = this._def.items[itemIndex] || this._def.rest;\n            if (!schema)\n                return null;\n            return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n        })\n            .filter((x) => !!x); // filter nulls\n        if (ctx.common.async) {\n            return Promise.all(items).then((results) => {\n                return ParseStatus.mergeArray(status, results);\n            });\n        }\n        else {\n            return ParseStatus.mergeArray(status, items);\n        }\n    }\n    get items() {\n        return this._def.items;\n    }\n    rest(rest) {\n        return new ZodTuple({\n            ...this._def,\n            rest,\n        });\n    }\n}\nZodTuple.create = (schemas, params) => {\n    if (!Array.isArray(schemas)) {\n        throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n    }\n    return new ZodTuple({\n        items: schemas,\n        typeName: ZodFirstPartyTypeKind.ZodTuple,\n        rest: null,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodRecord extends ZodType {\n    get keySchema() {\n        return this._def.keyType;\n    }\n    get valueSchema() {\n        return this._def.valueType;\n    }\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.object) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.object,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const pairs = [];\n        const keyType = this._def.keyType;\n        const valueType = this._def.valueType;\n        for (const key in ctx.data) {\n            pairs.push({\n                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n                value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n                alwaysSet: key in ctx.data,\n            });\n        }\n        if (ctx.common.async) {\n            return ParseStatus.mergeObjectAsync(status, pairs);\n        }\n        else {\n            return ParseStatus.mergeObjectSync(status, pairs);\n        }\n    }\n    get element() {\n        return this._def.valueType;\n    }\n    static create(first, second, third) {\n        if (second instanceof ZodType) {\n            return new ZodRecord({\n                keyType: first,\n                valueType: second,\n                typeName: ZodFirstPartyTypeKind.ZodRecord,\n                ...processCreateParams(third),\n            });\n        }\n        return new ZodRecord({\n            keyType: ZodString.create(),\n            valueType: first,\n            typeName: ZodFirstPartyTypeKind.ZodRecord,\n            ...processCreateParams(second),\n        });\n    }\n}\nexport class ZodMap extends ZodType {\n    get keySchema() {\n        return this._def.keyType;\n    }\n    get valueSchema() {\n        return this._def.valueType;\n    }\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.map) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.map,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const keyType = this._def.keyType;\n        const valueType = this._def.valueType;\n        const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n            return {\n                key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n                value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n            };\n        });\n        if (ctx.common.async) {\n            const finalMap = new Map();\n            return Promise.resolve().then(async () => {\n                for (const pair of pairs) {\n                    const key = await pair.key;\n                    const value = await pair.value;\n                    if (key.status === \"aborted\" || value.status === \"aborted\") {\n                        return INVALID;\n                    }\n                    if (key.status === \"dirty\" || value.status === \"dirty\") {\n                        status.dirty();\n                    }\n                    finalMap.set(key.value, value.value);\n                }\n                return { status: status.value, value: finalMap };\n            });\n        }\n        else {\n            const finalMap = new Map();\n            for (const pair of pairs) {\n                const key = pair.key;\n                const value = pair.value;\n                if (key.status === \"aborted\" || value.status === \"aborted\") {\n                    return INVALID;\n                }\n                if (key.status === \"dirty\" || value.status === \"dirty\") {\n                    status.dirty();\n                }\n                finalMap.set(key.value, value.value);\n            }\n            return { status: status.value, value: finalMap };\n        }\n    }\n}\nZodMap.create = (keyType, valueType, params) => {\n    return new ZodMap({\n        valueType,\n        keyType,\n        typeName: ZodFirstPartyTypeKind.ZodMap,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodSet extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.set) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.set,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const def = this._def;\n        if (def.minSize !== null) {\n            if (ctx.data.size < def.minSize.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_small,\n                    minimum: def.minSize.value,\n                    type: \"set\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.minSize.message,\n                });\n                status.dirty();\n            }\n        }\n        if (def.maxSize !== null) {\n            if (ctx.data.size > def.maxSize.value) {\n                addIssueToContext(ctx, {\n                    code: ZodIssueCode.too_big,\n                    maximum: def.maxSize.value,\n                    type: \"set\",\n                    inclusive: true,\n                    exact: false,\n                    message: def.maxSize.message,\n                });\n                status.dirty();\n            }\n        }\n        const valueType = this._def.valueType;\n        function finalizeSet(elements) {\n            const parsedSet = new Set();\n            for (const element of elements) {\n                if (element.status === \"aborted\")\n                    return INVALID;\n                if (element.status === \"dirty\")\n                    status.dirty();\n                parsedSet.add(element.value);\n            }\n            return { status: status.value, value: parsedSet };\n        }\n        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n        if (ctx.common.async) {\n            return Promise.all(elements).then((elements) => finalizeSet(elements));\n        }\n        else {\n            return finalizeSet(elements);\n        }\n    }\n    min(minSize, message) {\n        return new ZodSet({\n            ...this._def,\n            minSize: { value: minSize, message: errorUtil.toString(message) },\n        });\n    }\n    max(maxSize, message) {\n        return new ZodSet({\n            ...this._def,\n            maxSize: { value: maxSize, message: errorUtil.toString(message) },\n        });\n    }\n    size(size, message) {\n        return this.min(size, message).max(size, message);\n    }\n    nonempty(message) {\n        return this.min(1, message);\n    }\n}\nZodSet.create = (valueType, params) => {\n    return new ZodSet({\n        valueType,\n        minSize: null,\n        maxSize: null,\n        typeName: ZodFirstPartyTypeKind.ZodSet,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodFunction extends ZodType {\n    constructor() {\n        super(...arguments);\n        this.validate = this.implement;\n    }\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.function) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.function,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        function makeArgsIssue(args, error) {\n            return makeIssue({\n                data: args,\n                path: ctx.path,\n                errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n                issueData: {\n                    code: ZodIssueCode.invalid_arguments,\n                    argumentsError: error,\n                },\n            });\n        }\n        function makeReturnsIssue(returns, error) {\n            return makeIssue({\n                data: returns,\n                path: ctx.path,\n                errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n                issueData: {\n                    code: ZodIssueCode.invalid_return_type,\n                    returnTypeError: error,\n                },\n            });\n        }\n        const params = { errorMap: ctx.common.contextualErrorMap };\n        const fn = ctx.data;\n        if (this._def.returns instanceof ZodPromise) {\n            // Would love a way to avoid disabling this rule, but we need\n            // an alias (using an arrow function was what caused 2651).\n            // eslint-disable-next-line @typescript-eslint/no-this-alias\n            const me = this;\n            return OK(async function (...args) {\n                const error = new ZodError([]);\n                const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n                    error.addIssue(makeArgsIssue(args, e));\n                    throw error;\n                });\n                const result = await Reflect.apply(fn, this, parsedArgs);\n                const parsedReturns = await me._def.returns._def.type\n                    .parseAsync(result, params)\n                    .catch((e) => {\n                    error.addIssue(makeReturnsIssue(result, e));\n                    throw error;\n                });\n                return parsedReturns;\n            });\n        }\n        else {\n            // Would love a way to avoid disabling this rule, but we need\n            // an alias (using an arrow function was what caused 2651).\n            // eslint-disable-next-line @typescript-eslint/no-this-alias\n            const me = this;\n            return OK(function (...args) {\n                const parsedArgs = me._def.args.safeParse(args, params);\n                if (!parsedArgs.success) {\n                    throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n                }\n                const result = Reflect.apply(fn, this, parsedArgs.data);\n                const parsedReturns = me._def.returns.safeParse(result, params);\n                if (!parsedReturns.success) {\n                    throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n                }\n                return parsedReturns.data;\n            });\n        }\n    }\n    parameters() {\n        return this._def.args;\n    }\n    returnType() {\n        return this._def.returns;\n    }\n    args(...items) {\n        return new ZodFunction({\n            ...this._def,\n            args: ZodTuple.create(items).rest(ZodUnknown.create()),\n        });\n    }\n    returns(returnType) {\n        return new ZodFunction({\n            ...this._def,\n            returns: returnType,\n        });\n    }\n    implement(func) {\n        const validatedFunc = this.parse(func);\n        return validatedFunc;\n    }\n    strictImplement(func) {\n        const validatedFunc = this.parse(func);\n        return validatedFunc;\n    }\n    static create(args, returns, params) {\n        return new ZodFunction({\n            args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n            returns: returns || ZodUnknown.create(),\n            typeName: ZodFirstPartyTypeKind.ZodFunction,\n            ...processCreateParams(params),\n        });\n    }\n}\nexport class ZodLazy extends ZodType {\n    get schema() {\n        return this._def.getter();\n    }\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        const lazySchema = this._def.getter();\n        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n    }\n}\nZodLazy.create = (getter, params) => {\n    return new ZodLazy({\n        getter: getter,\n        typeName: ZodFirstPartyTypeKind.ZodLazy,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodLiteral extends ZodType {\n    _parse(input) {\n        if (input.data !== this._def.value) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                received: ctx.data,\n                code: ZodIssueCode.invalid_literal,\n                expected: this._def.value,\n            });\n            return INVALID;\n        }\n        return { status: \"valid\", value: input.data };\n    }\n    get value() {\n        return this._def.value;\n    }\n}\nZodLiteral.create = (value, params) => {\n    return new ZodLiteral({\n        value: value,\n        typeName: ZodFirstPartyTypeKind.ZodLiteral,\n        ...processCreateParams(params),\n    });\n};\nfunction createZodEnum(values, params) {\n    return new ZodEnum({\n        values,\n        typeName: ZodFirstPartyTypeKind.ZodEnum,\n        ...processCreateParams(params),\n    });\n}\nexport class ZodEnum extends ZodType {\n    _parse(input) {\n        if (typeof input.data !== \"string\") {\n            const ctx = this._getOrReturnCtx(input);\n            const expectedValues = this._def.values;\n            addIssueToContext(ctx, {\n                expected: util.joinValues(expectedValues),\n                received: ctx.parsedType,\n                code: ZodIssueCode.invalid_type,\n            });\n            return INVALID;\n        }\n        if (!this._cache) {\n            this._cache = new Set(this._def.values);\n        }\n        if (!this._cache.has(input.data)) {\n            const ctx = this._getOrReturnCtx(input);\n            const expectedValues = this._def.values;\n            addIssueToContext(ctx, {\n                received: ctx.data,\n                code: ZodIssueCode.invalid_enum_value,\n                options: expectedValues,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n    get options() {\n        return this._def.values;\n    }\n    get enum() {\n        const enumValues = {};\n        for (const val of this._def.values) {\n            enumValues[val] = val;\n        }\n        return enumValues;\n    }\n    get Values() {\n        const enumValues = {};\n        for (const val of this._def.values) {\n            enumValues[val] = val;\n        }\n        return enumValues;\n    }\n    get Enum() {\n        const enumValues = {};\n        for (const val of this._def.values) {\n            enumValues[val] = val;\n        }\n        return enumValues;\n    }\n    extract(values, newDef = this._def) {\n        return ZodEnum.create(values, {\n            ...this._def,\n            ...newDef,\n        });\n    }\n    exclude(values, newDef = this._def) {\n        return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n            ...this._def,\n            ...newDef,\n        });\n    }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n    _parse(input) {\n        const nativeEnumValues = util.getValidEnumValues(this._def.values);\n        const ctx = this._getOrReturnCtx(input);\n        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n            const expectedValues = util.objectValues(nativeEnumValues);\n            addIssueToContext(ctx, {\n                expected: util.joinValues(expectedValues),\n                received: ctx.parsedType,\n                code: ZodIssueCode.invalid_type,\n            });\n            return INVALID;\n        }\n        if (!this._cache) {\n            this._cache = new Set(util.getValidEnumValues(this._def.values));\n        }\n        if (!this._cache.has(input.data)) {\n            const expectedValues = util.objectValues(nativeEnumValues);\n            addIssueToContext(ctx, {\n                received: ctx.data,\n                code: ZodIssueCode.invalid_enum_value,\n                options: expectedValues,\n            });\n            return INVALID;\n        }\n        return OK(input.data);\n    }\n    get enum() {\n        return this._def.values;\n    }\n}\nZodNativeEnum.create = (values, params) => {\n    return new ZodNativeEnum({\n        values: values,\n        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodPromise extends ZodType {\n    unwrap() {\n        return this._def.type;\n    }\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.promise,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n        return OK(promisified.then((data) => {\n            return this._def.type.parseAsync(data, {\n                path: ctx.path,\n                errorMap: ctx.common.contextualErrorMap,\n            });\n        }));\n    }\n}\nZodPromise.create = (schema, params) => {\n    return new ZodPromise({\n        type: schema,\n        typeName: ZodFirstPartyTypeKind.ZodPromise,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodEffects extends ZodType {\n    innerType() {\n        return this._def.schema;\n    }\n    sourceType() {\n        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n            ? this._def.schema.sourceType()\n            : this._def.schema;\n    }\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        const effect = this._def.effect || null;\n        const checkCtx = {\n            addIssue: (arg) => {\n                addIssueToContext(ctx, arg);\n                if (arg.fatal) {\n                    status.abort();\n                }\n                else {\n                    status.dirty();\n                }\n            },\n            get path() {\n                return ctx.path;\n            },\n        };\n        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n        if (effect.type === \"preprocess\") {\n            const processed = effect.transform(ctx.data, checkCtx);\n            if (ctx.common.async) {\n                return Promise.resolve(processed).then(async (processed) => {\n                    if (status.value === \"aborted\")\n                        return INVALID;\n                    const result = await this._def.schema._parseAsync({\n                        data: processed,\n                        path: ctx.path,\n                        parent: ctx,\n                    });\n                    if (result.status === \"aborted\")\n                        return INVALID;\n                    if (result.status === \"dirty\")\n                        return DIRTY(result.value);\n                    if (status.value === \"dirty\")\n                        return DIRTY(result.value);\n                    return result;\n                });\n            }\n            else {\n                if (status.value === \"aborted\")\n                    return INVALID;\n                const result = this._def.schema._parseSync({\n                    data: processed,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (result.status === \"aborted\")\n                    return INVALID;\n                if (result.status === \"dirty\")\n                    return DIRTY(result.value);\n                if (status.value === \"dirty\")\n                    return DIRTY(result.value);\n                return result;\n            }\n        }\n        if (effect.type === \"refinement\") {\n            const executeRefinement = (acc) => {\n                const result = effect.refinement(acc, checkCtx);\n                if (ctx.common.async) {\n                    return Promise.resolve(result);\n                }\n                if (result instanceof Promise) {\n                    throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n                }\n                return acc;\n            };\n            if (ctx.common.async === false) {\n                const inner = this._def.schema._parseSync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (inner.status === \"aborted\")\n                    return INVALID;\n                if (inner.status === \"dirty\")\n                    status.dirty();\n                // return value is ignored\n                executeRefinement(inner.value);\n                return { status: status.value, value: inner.value };\n            }\n            else {\n                return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n                    if (inner.status === \"aborted\")\n                        return INVALID;\n                    if (inner.status === \"dirty\")\n                        status.dirty();\n                    return executeRefinement(inner.value).then(() => {\n                        return { status: status.value, value: inner.value };\n                    });\n                });\n            }\n        }\n        if (effect.type === \"transform\") {\n            if (ctx.common.async === false) {\n                const base = this._def.schema._parseSync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (!isValid(base))\n                    return INVALID;\n                const result = effect.transform(base.value, checkCtx);\n                if (result instanceof Promise) {\n                    throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n                }\n                return { status: status.value, value: result };\n            }\n            else {\n                return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n                    if (!isValid(base))\n                        return INVALID;\n                    return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n                        status: status.value,\n                        value: result,\n                    }));\n                });\n            }\n        }\n        util.assertNever(effect);\n    }\n}\nZodEffects.create = (schema, effect, params) => {\n    return new ZodEffects({\n        schema,\n        typeName: ZodFirstPartyTypeKind.ZodEffects,\n        effect,\n        ...processCreateParams(params),\n    });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n    return new ZodEffects({\n        schema,\n        effect: { type: \"preprocess\", transform: preprocess },\n        typeName: ZodFirstPartyTypeKind.ZodEffects,\n        ...processCreateParams(params),\n    });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType === ZodParsedType.undefined) {\n            return OK(undefined);\n        }\n        return this._def.innerType._parse(input);\n    }\n    unwrap() {\n        return this._def.innerType;\n    }\n}\nZodOptional.create = (type, params) => {\n    return new ZodOptional({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodOptional,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNullable extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType === ZodParsedType.null) {\n            return OK(null);\n        }\n        return this._def.innerType._parse(input);\n    }\n    unwrap() {\n        return this._def.innerType;\n    }\n}\nZodNullable.create = (type, params) => {\n    return new ZodNullable({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodNullable,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodDefault extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        let data = ctx.data;\n        if (ctx.parsedType === ZodParsedType.undefined) {\n            data = this._def.defaultValue();\n        }\n        return this._def.innerType._parse({\n            data,\n            path: ctx.path,\n            parent: ctx,\n        });\n    }\n    removeDefault() {\n        return this._def.innerType;\n    }\n}\nZodDefault.create = (type, params) => {\n    return new ZodDefault({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodDefault,\n        defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodCatch extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        // newCtx is used to not collect issues from inner types in ctx\n        const newCtx = {\n            ...ctx,\n            common: {\n                ...ctx.common,\n                issues: [],\n            },\n        };\n        const result = this._def.innerType._parse({\n            data: newCtx.data,\n            path: newCtx.path,\n            parent: {\n                ...newCtx,\n            },\n        });\n        if (isAsync(result)) {\n            return result.then((result) => {\n                return {\n                    status: \"valid\",\n                    value: result.status === \"valid\"\n                        ? result.value\n                        : this._def.catchValue({\n                            get error() {\n                                return new ZodError(newCtx.common.issues);\n                            },\n                            input: newCtx.data,\n                        }),\n                };\n            });\n        }\n        else {\n            return {\n                status: \"valid\",\n                value: result.status === \"valid\"\n                    ? result.value\n                    : this._def.catchValue({\n                        get error() {\n                            return new ZodError(newCtx.common.issues);\n                        },\n                        input: newCtx.data,\n                    }),\n            };\n        }\n    }\n    removeCatch() {\n        return this._def.innerType;\n    }\n}\nZodCatch.create = (type, params) => {\n    return new ZodCatch({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodCatch,\n        catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n        ...processCreateParams(params),\n    });\n};\nexport class ZodNaN extends ZodType {\n    _parse(input) {\n        const parsedType = this._getType(input);\n        if (parsedType !== ZodParsedType.nan) {\n            const ctx = this._getOrReturnCtx(input);\n            addIssueToContext(ctx, {\n                code: ZodIssueCode.invalid_type,\n                expected: ZodParsedType.nan,\n                received: ctx.parsedType,\n            });\n            return INVALID;\n        }\n        return { status: \"valid\", value: input.data };\n    }\n}\nZodNaN.create = (params) => {\n    return new ZodNaN({\n        typeName: ZodFirstPartyTypeKind.ZodNaN,\n        ...processCreateParams(params),\n    });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n    _parse(input) {\n        const { ctx } = this._processInputParams(input);\n        const data = ctx.data;\n        return this._def.type._parse({\n            data,\n            path: ctx.path,\n            parent: ctx,\n        });\n    }\n    unwrap() {\n        return this._def.type;\n    }\n}\nexport class ZodPipeline extends ZodType {\n    _parse(input) {\n        const { status, ctx } = this._processInputParams(input);\n        if (ctx.common.async) {\n            const handleAsync = async () => {\n                const inResult = await this._def.in._parseAsync({\n                    data: ctx.data,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n                if (inResult.status === \"aborted\")\n                    return INVALID;\n                if (inResult.status === \"dirty\") {\n                    status.dirty();\n                    return DIRTY(inResult.value);\n                }\n                else {\n                    return this._def.out._parseAsync({\n                        data: inResult.value,\n                        path: ctx.path,\n                        parent: ctx,\n                    });\n                }\n            };\n            return handleAsync();\n        }\n        else {\n            const inResult = this._def.in._parseSync({\n                data: ctx.data,\n                path: ctx.path,\n                parent: ctx,\n            });\n            if (inResult.status === \"aborted\")\n                return INVALID;\n            if (inResult.status === \"dirty\") {\n                status.dirty();\n                return {\n                    status: \"dirty\",\n                    value: inResult.value,\n                };\n            }\n            else {\n                return this._def.out._parseSync({\n                    data: inResult.value,\n                    path: ctx.path,\n                    parent: ctx,\n                });\n            }\n        }\n    }\n    static create(a, b) {\n        return new ZodPipeline({\n            in: a,\n            out: b,\n            typeName: ZodFirstPartyTypeKind.ZodPipeline,\n        });\n    }\n}\nexport class ZodReadonly extends ZodType {\n    _parse(input) {\n        const result = this._def.innerType._parse(input);\n        const freeze = (data) => {\n            if (isValid(data)) {\n                data.value = Object.freeze(data.value);\n            }\n            return data;\n        };\n        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n    }\n    unwrap() {\n        return this._def.innerType;\n    }\n}\nZodReadonly.create = (type, params) => {\n    return new ZodReadonly({\n        innerType: type,\n        typeName: ZodFirstPartyTypeKind.ZodReadonly,\n        ...processCreateParams(params),\n    });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n//////////                    //////////\n//////////      z.custom      //////////\n//////////                    //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n    const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n    const p2 = typeof p === \"string\" ? { message: p } : p;\n    return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n    if (check)\n        return ZodAny.create().superRefine((data, ctx) => {\n            const r = check(data);\n            if (r instanceof Promise) {\n                return r.then((r) => {\n                    if (!r) {\n                        const params = cleanParams(_params, data);\n                        const _fatal = params.fatal ?? fatal ?? true;\n                        ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n                    }\n                });\n            }\n            if (!r) {\n                const params = cleanParams(_params, data);\n                const _fatal = params.fatal ?? fatal ?? true;\n                ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n            }\n            return;\n        });\n    return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n    object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n    ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n    ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n    ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n    ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n    ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n    ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n    ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n    ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n    ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n    ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n    ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n    ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n    ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n    ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n    ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n    ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n    ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n    ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n    ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n    ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n    ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n    ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n    ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n    ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n    ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n    ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n    ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n    ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n    ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n    ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n    ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n    ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n    ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n    ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n    ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n    ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n    constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n    message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n    string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n    number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n    boolean: ((arg) => ZodBoolean.create({\n        ...arg,\n        coerce: true,\n    })),\n    bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n    date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import \"./chunk-HZNEDSRS.js\";\nimport {\n  getCollabBindingPath,\n  readCollabBinding,\n  readCollabBindingState,\n  reserveAvailableDirPath,\n  reserveDirectory,\n  writeCollabBinding,\n  writeCollabBindingSnapshot,\n  writeJsonAtomic\n} from \"./chunk-GNW6FA4J.js\";\nimport {\n  applyUnifiedDiffToWorktree,\n  assertRepoSnapshotUnchanged,\n  buildRepoFingerprint,\n  captureRepoSnapshot,\n  checkoutLocalBranch,\n  cloneGitBundleToDirectory,\n  createGitBundle,\n  createGitCommandPlan,\n  createSystemGitAdapter,\n  ensureCleanWorktree,\n  ensureGitInfoExcludeEntries,\n  findGitRoot,\n  getCurrentBranch,\n  getDefaultBranch,\n  getGitCommonDir,\n  getHeadCommitHash,\n  getRemoteOriginUrl,\n  getWorktreeStatus,\n  normalizeGitRemote,\n  requireCurrentBranch,\n  setRemoteOriginUrl,\n  summarizeUnifiedDiff\n} from \"./chunk-FA6PTZQI.js\";\nimport {\n  REMIX_ERROR_CODES\n} from \"./chunk-GC2MOT3U.js\";\nimport {\n  RemixError\n} from \"./chunk-7XJGOKEO.js\";\n\n// src/application/collab/contracts.ts\nimport { z } from \"zod\";\nvar sourceId = z.string().trim().min(1).max(500);\nvar sourceTurnIds = {\n  nativeTurnId: sourceId.optional(),\n  turnId: sourceId.optional()\n};\nvar SourceConversationSchema = z.discriminatedUnion(\"provider\", [\n  z.object({\n    provider: z.literal(\"cursor\"),\n    conversationId: sourceId,\n    ...sourceTurnIds\n  }).strict(),\n  z.object({\n    provider: z.literal(\"claude\"),\n    sessionId: sourceId,\n    ...sourceTurnIds\n  }).strict(),\n  z.object({\n    provider: z.literal(\"codex\"),\n    sessionId: sourceId,\n    ...sourceTurnIds\n  }).strict()\n]);\n\n// src/application/collab/appDeltaCache.ts\nvar APP_DELTA_CACHE_TTL_MS = 5e3;\nvar appDeltaCache = /* @__PURE__ */ new Map();\nvar cacheClock = () => Date.now();\nfunction buildAppDeltaCacheKey(appId, payload) {\n  return [\n    appId,\n    payload.baseHeadHash,\n    payload.targetHeadHash ?? \"\",\n    payload.baseRevisionId ?? \"\",\n    payload.targetRevisionId ?? \"\",\n    payload.localSnapshotHash ?? \"\",\n    payload.repoFingerprint ?? \"\",\n    payload.remoteUrl ?? \"\",\n    payload.defaultBranch ?? \"\"\n  ].join(\"|\");\n}\nfunction readAppDeltaCache(key) {\n  const entry = appDeltaCache.get(key);\n  if (!entry) return void 0;\n  if (cacheClock() - entry.cachedAt > APP_DELTA_CACHE_TTL_MS) {\n    appDeltaCache.delete(key);\n    return void 0;\n  }\n  return entry.value;\n}\nfunction writeAppDeltaCache(key, value) {\n  appDeltaCache.set(key, { value, cachedAt: cacheClock() });\n}\nasync function getAppDeltaCached(api, appId, payload) {\n  const key = buildAppDeltaCacheKey(appId, payload);\n  const cached = readAppDeltaCache(key);\n  if (cached !== void 0) return cached;\n  const fresh = await api.getAppDelta(appId, payload);\n  writeAppDeltaCache(key, fresh);\n  return fresh;\n}\nfunction invalidateAppDeltaCacheForApp(appId) {\n  const prefix = `${appId}|`;\n  for (const key of appDeltaCache.keys()) {\n    if (key.startsWith(prefix)) appDeltaCache.delete(key);\n  }\n}\n\n// src/application/collab/appHeadCache.ts\nvar APP_HEAD_CACHE_TTL_MS = 5e3;\nvar appHeadCache = /* @__PURE__ */ new Map();\nvar cacheClock2 = () => Date.now();\nfunction readAppHeadCache(appId) {\n  const entry = appHeadCache.get(appId);\n  if (!entry) return void 0;\n  if (cacheClock2() - entry.cachedAt > APP_HEAD_CACHE_TTL_MS) {\n    appHeadCache.delete(appId);\n    return void 0;\n  }\n  return entry.value;\n}\nfunction writeAppHeadCache(appId, value) {\n  appHeadCache.set(appId, { value, cachedAt: cacheClock2() });\n}\nasync function getAppHeadCached(api, appId) {\n  const cached = readAppHeadCache(appId);\n  if (cached !== void 0) return cached;\n  const fresh = await api.getAppHead(appId);\n  writeAppHeadCache(appId, fresh);\n  return fresh;\n}\nfunction invalidateAppHeadCache(appId) {\n  appHeadCache.delete(appId);\n}\n\n// src/application/collab/branchPolicy.ts\nfunction describeBranch(value) {\n  const normalized = String(value ?? \"\").trim();\n  return normalized || \"(detached)\";\n}\nfunction isBoundBranchMatch(currentBranch, branchName) {\n  const current = String(currentBranch ?? \"\").trim();\n  const expected = String(branchName ?? \"\").trim();\n  if (!expected || !current) return true;\n  return current === expected;\n}\nfunction buildBranchMismatchHint(params) {\n  const overrideFlag = params.overrideFlag?.trim() || \"--allow-branch-mismatch\";\n  return [\n    `Current branch: ${describeBranch(params.currentBranch)}`,\n    `Bound branch: ${describeBranch(params.branchName)}`,\n    `Switch to ${describeBranch(params.branchName)} or rerun with ${overrideFlag} if this is intentional.`\n  ].join(\"\\n\");\n}\nfunction assertBoundBranchMatch(params) {\n  if (params.allowBranchMismatch) return;\n  if (isBoundBranchMatch(params.currentBranch, params.branchName)) return;\n  throw new RemixError(`Current branch does not match this checkout's bound Remix branch while running ${params.operation}.`, {\n    code: REMIX_ERROR_CODES.PREFERRED_BRANCH_MISMATCH,\n    exitCode: 2,\n    hint: buildBranchMismatchHint({\n      currentBranch: params.currentBranch,\n      branchName: params.branchName,\n      overrideFlag: params.overrideFlag\n    })\n  });\n}\n\n// src/infrastructure/collab/asyncJobStore.ts\nimport { randomUUID } from \"crypto\";\nimport fs from \"fs/promises\";\nimport path2 from \"path\";\n\n// src/infrastructure/collab/statePaths.ts\nimport { createHash } from \"crypto\";\nimport os from \"os\";\nimport path from \"path\";\nfunction sha256Hex(value) {\n  return createHash(\"sha256\").update(value).digest(\"hex\");\n}\nfunction getCollabStateRoot() {\n  const configured = process.env.REMIX_COLLAB_STATE_ROOT?.trim();\n  return configured || path.join(os.homedir(), \".remix\", \"collab-state\");\n}\nfunction buildLaneStateKey(params) {\n  const fingerprint = params.repoFingerprint?.trim();\n  const laneId = params.laneId?.trim();\n  const repoRoot = params.repoRoot?.trim();\n  const stableSource = repoRoot || \"unknown-repo-root\";\n  const fingerprintSource = fingerprint || \"unknown-repo-fingerprint\";\n  const laneSource = laneId || \"unknown-lane\";\n  return sha256Hex(`${stableSource}::${fingerprintSource}::${laneSource}`);\n}\nfunction getSnapshotsRoot() {\n  return path.join(getCollabStateRoot(), \"snapshots\");\n}\nfunction getSnapshotRecordsRoot() {\n  return path.join(getSnapshotsRoot(), \"records\");\n}\nfunction getSnapshotBlobsRoot() {\n  return path.join(getSnapshotsRoot(), \"blobs\");\n}\nfunction getBaselinesRoot() {\n  return path.join(getCollabStateRoot(), \"baselines\");\n}\nfunction getFinalizeQueueRoot() {\n  return path.join(getCollabStateRoot(), \"finalize-queue\");\n}\nfunction getAsyncJobsRoot() {\n  return path.join(getCollabStateRoot(), \"jobs\");\n}\nfunction getAsyncJobDir(jobId) {\n  return path.join(getAsyncJobsRoot(), jobId);\n}\nfunction getAsyncJobFilePath(jobId) {\n  return path.join(getAsyncJobDir(jobId), \"job.json\");\n}\nfunction getAsyncJobBundlePath(jobId) {\n  return path.join(getAsyncJobDir(jobId), \"bundle.bundle\");\n}\nfunction getLogsRoot() {\n  return path.join(getCollabStateRoot(), \"logs\");\n}\nfunction getDrainerLogPath() {\n  return path.join(getLogsRoot(), \"drainer.log\");\n}\nfunction getDrainerPidPath() {\n  return path.join(getCollabStateRoot(), \"drainer.pid\");\n}\n\n// src/infrastructure/collab/asyncJobStore.ts\nvar ASYNC_JOB_LOCK_STALE_MS = 10 * 60 * 1e3;\nvar TERMINAL_ASYNC_JOB_RETENTION_MS = 24 * 60 * 60 * 1e3;\nvar REMOVED_ASYNC_JOB_KINDS = /* @__PURE__ */ new Set([[\"re\", \"anchor\"].join(\"_\")]);\nfunction getJobLockPath(id) {\n  return path2.join(getAsyncJobDir(id), \"lock\");\n}\nfunction isTerminalStatus(status) {\n  return status === \"completed\" || status === \"failed\";\n}\nfunction isProcessingStatus(status) {\n  return status === \"submitting\" || status === \"uploading\" || status === \"server_processing\";\n}\nfunction createEmptySummary() {\n  return {\n    state: \"idle\",\n    activeJobCount: 0,\n    queuedJobCount: 0,\n    processingJobCount: 0,\n    failedJobCount: 0,\n    oldestCreatedAt: null,\n    newestCreatedAt: null,\n    latestError: null,\n    kinds: []\n  };\n}\nfunction normalizeJob(input) {\n  const now = (/* @__PURE__ */ new Date()).toISOString();\n  const base = {\n    schemaVersion: 1,\n    id: input.id ?? randomUUID(),\n    kind: input.kind,\n    status: input.status,\n    repoRoot: input.repoRoot,\n    repoFingerprint: input.repoFingerprint ?? null,\n    branchName: input.branchName ?? null,\n    laneId: input.laneId ?? null,\n    createdAt: input.createdAt ?? now,\n    updatedAt: input.updatedAt ?? now,\n    retryCount: Number.isFinite(input.retryCount) ? Math.max(0, Number(input.retryCount)) : 0,\n    error: input.error ?? null,\n    idempotencyKey: input.idempotencyKey ?? null\n  };\n  if (input.kind === \"init\") {\n    return { ...base, kind: \"init\", payload: input.payload };\n  }\n  if (input.kind === \"init_post\") {\n    return { ...base, kind: \"init_post\", payload: input.payload };\n  }\n  throw new Error(`Unsupported async job kind: ${input.kind ?? \"unknown\"}`);\n}\nasync function enqueueAsyncJob(input) {\n  const job = normalizeJob(input);\n  await fs.mkdir(getAsyncJobDir(job.id), { recursive: true });\n  await writeJsonAtomic(getAsyncJobFilePath(job.id), job);\n  return job;\n}\nfunction parseAsyncJob(raw) {\n  if (!raw || typeof raw !== \"object\") return null;\n  const data = raw;\n  if (data.schemaVersion !== 1) return null;\n  if (typeof data.id !== \"string\") return null;\n  if (data.kind !== \"init\" && data.kind !== \"init_post\") return null;\n  if (!data.payload || typeof data.payload !== \"object\") return null;\n  return data;\n}\nasync function readAsyncJob(jobId) {\n  try {\n    const raw = await fs.readFile(getAsyncJobFilePath(jobId), \"utf8\");\n    const parsed = JSON.parse(raw);\n    return parseAsyncJob(parsed);\n  } catch {\n    return null;\n  }\n}\nasync function listAsyncJobs() {\n  const root = getAsyncJobsRoot();\n  let entries;\n  try {\n    entries = await fs.readdir(root, { withFileTypes: true });\n  } catch (error) {\n    if (error?.code === \"ENOENT\") return [];\n    throw error;\n  }\n  const jobs = await Promise.all(\n    entries.filter((entry) => entry.isDirectory()).map((entry) => readAsyncJob(entry.name))\n  );\n  return jobs.filter((job) => Boolean(job)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n}\nasync function pruneRemovedAsyncJobKinds() {\n  const root = getAsyncJobsRoot();\n  let entries;\n  try {\n    entries = await fs.readdir(root, { withFileTypes: true });\n  } catch (error) {\n    if (error?.code === \"ENOENT\") return;\n    throw error;\n  }\n  await Promise.all(\n    entries.filter((entry) => entry.isDirectory()).map(async (entry) => {\n      let parsed;\n      try {\n        const raw = await fs.readFile(getAsyncJobFilePath(entry.name), \"utf8\");\n        parsed = JSON.parse(raw);\n      } catch {\n        return;\n      }\n      if (parsed.schemaVersion === 1 && typeof parsed.id === \"string\" && typeof parsed.kind === \"string\" && REMOVED_ASYNC_JOB_KINDS.has(parsed.kind)) {\n        await deleteAsyncJob(entry.name);\n      }\n    })\n  );\n}\nasync function listAsyncJobsForRepo(params) {\n  const jobs = await listAsyncJobs();\n  return jobs.filter((job) => {\n    if (job.repoRoot !== params.repoRoot) return false;\n    if (params.branchName && job.branchName && job.branchName !== params.branchName) return false;\n    if (params.kind && job.kind !== params.kind) return false;\n    return true;\n  });\n}\nasync function findPendingAsyncJob(params) {\n  const jobs = await listAsyncJobsForRepo({\n    repoRoot: params.repoRoot,\n    branchName: params.branchName,\n    kind: params.kind\n  });\n  return jobs.find((job) => !isTerminalStatus(job.status)) ?? null;\n}\nasync function findFailedAsyncJob(params) {\n  const jobs = await listAsyncJobsForRepo({\n    repoRoot: params.repoRoot,\n    branchName: params.branchName,\n    kind: params.kind\n  });\n  return jobs.find((job) => job.status === \"failed\") ?? null;\n}\nasync function updateAsyncJob(jobId, update) {\n  const existing = await readAsyncJob(jobId);\n  if (!existing) return null;\n  const now = (/* @__PURE__ */ new Date()).toISOString();\n  if (existing.kind === \"init\") {\n    const nextPayload = update.payload ?? existing.payload;\n    const next = {\n      ...existing,\n      ...update,\n      schemaVersion: 1,\n      id: existing.id,\n      kind: \"init\",\n      createdAt: existing.createdAt,\n      updatedAt: now,\n      payload: nextPayload\n    };\n    await writeJsonAtomic(getAsyncJobFilePath(jobId), next);\n    return next;\n  }\n  if (existing.kind === \"init_post\") {\n    const nextPayload = update.payload ?? existing.payload;\n    const next = {\n      ...existing,\n      ...update,\n      schemaVersion: 1,\n      id: existing.id,\n      kind: \"init_post\",\n      createdAt: existing.createdAt,\n      updatedAt: now,\n      payload: nextPayload\n    };\n    await writeJsonAtomic(getAsyncJobFilePath(jobId), next);\n    return next;\n  }\n  throw new Error(`Unsupported async job kind: ${existing.kind ?? \"unknown\"}`);\n}\nasync function deleteAsyncJob(jobId) {\n  await fs.rm(getAsyncJobDir(jobId), { recursive: true, force: true });\n}\nasync function acquireJobLock(jobId) {\n  const lockPath = getJobLockPath(jobId);\n  await fs.mkdir(getAsyncJobDir(jobId), { recursive: true });\n  try {\n    await fs.mkdir(lockPath);\n    return true;\n  } catch (error) {\n    if (error?.code !== \"EEXIST\") throw error;\n  }\n  try {\n    const stat = await fs.stat(lockPath);\n    if (Date.now() - stat.mtimeMs < ASYNC_JOB_LOCK_STALE_MS) return false;\n    await fs.rm(lockPath, { recursive: true, force: true });\n  } catch (error) {\n    if (error?.code !== \"ENOENT\") throw error;\n  }\n  try {\n    await fs.mkdir(lockPath);\n    return true;\n  } catch (error) {\n    if (error?.code === \"EEXIST\") return false;\n    throw error;\n  }\n}\nasync function claimAsyncJob(jobId) {\n  const acquired = await acquireJobLock(jobId);\n  if (!acquired) return null;\n  const lockPath = getJobLockPath(jobId);\n  let released = false;\n  const release = async () => {\n    if (released) return;\n    released = true;\n    await fs.rm(lockPath, { recursive: true, force: true }).catch(() => void 0);\n  };\n  try {\n    const job = await readAsyncJob(jobId);\n    if (!job) {\n      await release();\n      return null;\n    }\n    if (isTerminalStatus(job.status)) {\n      await release();\n      return null;\n    }\n    return { job, release };\n  } catch (error) {\n    await release();\n    throw error;\n  }\n}\nasync function summarizeAsyncJobs(params) {\n  const jobs = await listAsyncJobsForRepo({ repoRoot: params.repoRoot, branchName: params.branchName ?? null });\n  const active = jobs.filter((job) => !isTerminalStatus(job.status) || job.status === \"failed\");\n  const summary = createEmptySummary();\n  if (active.length === 0) return summary;\n  const kinds = /* @__PURE__ */ new Set();\n  for (const job of active) {\n    kinds.add(job.kind);\n    if (job.error) summary.latestError = job.error;\n    if (job.status === \"failed\") {\n      summary.failedJobCount += 1;\n    } else if (isProcessingStatus(job.status)) {\n      summary.processingJobCount += 1;\n    } else {\n      summary.queuedJobCount += 1;\n    }\n  }\n  summary.activeJobCount = summary.queuedJobCount + summary.processingJobCount;\n  summary.kinds = Array.from(kinds);\n  summary.oldestCreatedAt = active[0].createdAt;\n  summary.newestCreatedAt = active[active.length - 1].createdAt;\n  if (summary.processingJobCount > 0) summary.state = \"processing\";\n  else if (summary.queuedJobCount > 0) summary.state = \"queued\";\n  else summary.state = \"failed\";\n  return summary;\n}\nasync function pruneTerminalAsyncJobs() {\n  await pruneRemovedAsyncJobKinds();\n  const jobs = await listAsyncJobs();\n  const now = Date.now();\n  await Promise.all(\n    jobs.filter((job) => {\n      if (!isTerminalStatus(job.status)) return false;\n      const updated = Date.parse(job.updatedAt);\n      if (!Number.isFinite(updated)) return true;\n      return now - updated >= TERMINAL_ASYNC_JOB_RETENTION_MS;\n    }).map((job) => deleteAsyncJob(job.id))\n  );\n}\nfunction getAsyncJobBundleFilePath(jobId) {\n  return getAsyncJobBundlePath(jobId);\n}\nasync function awaitAsyncJob(params) {\n  const pollIntervalMs = Math.max(50, params.pollIntervalMs ?? 500);\n  const deadline = Date.now() + params.timeoutMs;\n  let lastSeen = null;\n  while (Date.now() < deadline) {\n    const job = await readAsyncJob(params.jobId);\n    if (job) {\n      lastSeen = job;\n      if (job.status === \"completed\") return { status: \"completed\", job };\n      if (job.status === \"failed\") return { status: \"failed\", job };\n    } else if (lastSeen) {\n      return { status: \"timeout\", job: lastSeen };\n    } else {\n      return { status: \"timeout\", job: null };\n    }\n    const remaining = deadline - Date.now();\n    if (remaining <= 0) break;\n    await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, remaining)));\n  }\n  const final = await readAsyncJob(params.jobId);\n  if (final) {\n    if (final.status === \"completed\") return { status: \"completed\", job: final };\n    if (final.status === \"failed\") return { status: \"failed\", job: final };\n    return { status: \"timeout\", job: final };\n  }\n  return { status: \"timeout\", job: lastSeen };\n}\n\n// src/infrastructure/collab/localBaselineStore.ts\nimport fs2 from \"fs/promises\";\nimport path3 from \"path\";\nfunction getBaselinePath(params) {\n  return path3.join(getBaselinesRoot(), `${buildLaneStateKey(params)}.json`);\n}\nfunction normalizeNullableString(value) {\n  const normalized = String(value ?? \"\").trim();\n  return normalized || null;\n}\nfunction isSameBaselineIdentity(left, right) {\n  return left.repoRoot === right.repoRoot && (left.repoFingerprint ?? null) === (right.repoFingerprint ?? null) && (left.laneId ?? null) === (right.laneId ?? null) && left.currentAppId === right.currentAppId && (left.branchName ?? null) === (right.branchName ?? null);\n}\nasync function readLocalBaseline(params) {\n  try {\n    const raw = await fs2.readFile(getBaselinePath(params), \"utf8\");\n    const parsed = JSON.parse(raw);\n    if (!parsed || typeof parsed !== \"object\") return null;\n    if (![1, 2].includes(Number(parsed.schemaVersion)) || typeof parsed.key !== \"string\" || typeof parsed.repoRoot !== \"string\") {\n      return null;\n    }\n    return {\n      schemaVersion: Number(parsed.schemaVersion) === 2 ? 2 : 1,\n      key: parsed.key,\n      repoRoot: parsed.repoRoot,\n      repoFingerprint: parsed.repoFingerprint ?? null,\n      laneId: parsed.laneId ?? null,\n      currentAppId: String(parsed.currentAppId ?? \"\"),\n      branchName: parsed.branchName ?? null,\n      lastSnapshotId: parsed.lastSnapshotId ?? null,\n      lastSnapshotHash: parsed.lastSnapshotHash ?? null,\n      lastServerRevisionId: parsed.lastServerRevisionId ?? null,\n      lastServerTreeHash: parsed.lastServerTreeHash ?? null,\n      lastServerHeadHash: parsed.lastServerHeadHash ?? null,\n      lastSeenLocalCommitHash: parsed.lastSeenLocalCommitHash ?? null,\n      updatedAt: String(parsed.updatedAt ?? \"\")\n    };\n  } catch {\n    return null;\n  }\n}\nasync function writeLocalBaseline(baseline) {\n  const key = buildLaneStateKey(baseline);\n  const normalized = {\n    schemaVersion: 2,\n    key,\n    repoRoot: baseline.repoRoot,\n    repoFingerprint: baseline.repoFingerprint ?? null,\n    laneId: baseline.laneId ?? null,\n    currentAppId: baseline.currentAppId,\n    branchName: baseline.branchName ?? null,\n    lastSnapshotId: baseline.lastSnapshotId ?? null,\n    lastSnapshotHash: baseline.lastSnapshotHash ?? null,\n    lastServerRevisionId: baseline.lastServerRevisionId ?? null,\n    lastServerTreeHash: baseline.lastServerTreeHash ?? null,\n    lastServerHeadHash: baseline.lastServerHeadHash ?? null,\n    lastSeenLocalCommitHash: baseline.lastSeenLocalCommitHash ?? null,\n    updatedAt: baseline.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()\n  };\n  await writeJsonAtomic(getBaselinePath(baseline), normalized);\n  return normalized;\n}\nasync function readAllLocalBaselines() {\n  let entries;\n  try {\n    entries = await fs2.readdir(getBaselinesRoot());\n  } catch (error) {\n    if (error?.code === \"ENOENT\") return [];\n    throw error;\n  }\n  const baselines = [];\n  for (const entry of entries) {\n    if (!entry.endsWith(\".json\")) continue;\n    try {\n      const raw = await fs2.readFile(path3.join(getBaselinesRoot(), entry), \"utf8\");\n      const parsed = JSON.parse(raw);\n      if (!parsed || typeof parsed !== \"object\") continue;\n      if (![1, 2].includes(Number(parsed.schemaVersion)) || typeof parsed.key !== \"string\" || typeof parsed.repoRoot !== \"string\") {\n        continue;\n      }\n      baselines.push({\n        schemaVersion: Number(parsed.schemaVersion) === 2 ? 2 : 1,\n        key: parsed.key,\n        repoRoot: parsed.repoRoot,\n        repoFingerprint: parsed.repoFingerprint ?? null,\n        laneId: parsed.laneId ?? null,\n        currentAppId: String(parsed.currentAppId ?? \"\"),\n        branchName: parsed.branchName ?? null,\n        lastSnapshotId: parsed.lastSnapshotId ?? null,\n        lastSnapshotHash: parsed.lastSnapshotHash ?? null,\n        lastServerRevisionId: parsed.lastServerRevisionId ?? null,\n        lastServerTreeHash: parsed.lastServerTreeHash ?? null,\n        lastServerHeadHash: parsed.lastServerHeadHash ?? null,\n        lastSeenLocalCommitHash: parsed.lastSeenLocalCommitHash ?? null,\n        updatedAt: String(parsed.updatedAt ?? \"\")\n      });\n    } catch {\n      continue;\n    }\n  }\n  return baselines;\n}\nasync function migrateLocalBaselineForLaneChange(params) {\n  if ((params.fromLaneId ?? null) === (params.toLaneId ?? null)) {\n    return { status: \"same_lane\" };\n  }\n  const target = await readLocalBaseline({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.toLaneId\n  });\n  if (target) {\n    return { status: \"target_exists\" };\n  }\n  const source = await readLocalBaseline({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.fromLaneId\n  });\n  if (!source) {\n    return { status: \"source_missing\" };\n  }\n  const expectedSource = {\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.fromLaneId,\n    currentAppId: params.currentAppId,\n    branchName: params.branchName\n  };\n  const actualSource = {\n    repoRoot: source.repoRoot,\n    repoFingerprint: source.repoFingerprint,\n    laneId: source.laneId,\n    currentAppId: source.currentAppId,\n    branchName: source.branchName\n  };\n  if (!isSameBaselineIdentity(actualSource, expectedSource)) {\n    return { status: \"source_missing\" };\n  }\n  const baseline = await writeLocalBaseline({\n    ...source,\n    laneId: params.toLaneId\n  });\n  return { status: \"migrated\", baseline };\n}\nasync function findCompatibleLocalBaseline(params) {\n  const targetKey = buildLaneStateKey(params);\n  const branchName = normalizeNullableString(params.branchName);\n  const candidates = (await readAllLocalBaselines()).filter((baseline) => {\n    if (baseline.key === targetKey) return false;\n    if (baseline.repoRoot !== params.repoRoot) return false;\n    if ((baseline.repoFingerprint ?? null) !== (params.repoFingerprint ?? null)) return false;\n    if (baseline.currentAppId !== params.currentAppId) return false;\n    return true;\n  });\n  const branchMatches = candidates.filter((baseline) => normalizeNullableString(baseline.branchName) === branchName);\n  const compatible = branchMatches.length > 0 ? branchMatches : candidates.filter((baseline) => normalizeNullableString(baseline.branchName) === null);\n  if (compatible.length === 0) return { status: \"none\", candidateCount: 0 };\n  if (compatible.length > 1) return { status: \"ambiguous\", candidateCount: compatible.length };\n  return { status: \"found\", baseline: compatible[0] };\n}\nasync function clearLocalBaseline(params) {\n  try {\n    await fs2.unlink(getBaselinePath(params));\n  } catch (error) {\n    if (error?.code !== \"ENOENT\") {\n      throw error;\n    }\n  }\n}\n\n// src/infrastructure/collab/localSnapshotStore.ts\nimport { createHash as createHash2, randomUUID as randomUUID2 } from \"crypto\";\nimport fs3 from \"fs/promises\";\nimport os2 from \"os\";\nimport path4 from \"path\";\nimport { execa } from \"execa\";\nfunction sha256Hex2(value) {\n  return createHash2(\"sha256\").update(value).digest(\"hex\");\n}\nfunction getSnapshotRecordPath(snapshotId) {\n  return path4.join(getSnapshotRecordsRoot(), `${snapshotId}.json`);\n}\nfunction getBlobPath(blobHash) {\n  return path4.join(getSnapshotBlobsRoot(), blobHash.slice(0, 2), blobHash);\n}\nasync function runGitZ(args, cwd) {\n  const res = await execa(\"git\", args, {\n    cwd,\n    stderr: \"ignore\",\n    stripFinalNewline: false\n  });\n  return String(res.stdout || \"\");\n}\nasync function listWorkspaceFiles(repoRoot) {\n  const raw = await runGitZ([\"ls-files\", \"-z\", \"--cached\", \"--others\", \"--exclude-standard\", \"--deduplicate\"], repoRoot);\n  const seen = /* @__PURE__ */ new Set();\n  const result = [];\n  for (const entry of raw.split(\"\\0\")) {\n    const relativePath = entry.trim();\n    if (!relativePath || seen.has(relativePath)) continue;\n    const absolutePath = path4.join(repoRoot, relativePath);\n    try {\n      const stat = await fs3.lstat(absolutePath);\n      if (stat.isFile() || stat.isSymbolicLink()) {\n        seen.add(relativePath);\n        result.push(relativePath);\n      }\n    } catch {\n    }\n  }\n  return result.sort((a, b) => a.localeCompare(b));\n}\nasync function persistBlob(blobHash, content) {\n  const blobPath = getBlobPath(blobHash);\n  try {\n    await fs3.access(blobPath);\n  } catch {\n    await fs3.mkdir(path4.dirname(blobPath), { recursive: true });\n    if (typeof content === \"string\") {\n      await fs3.writeFile(blobPath, content, \"utf8\");\n    } else {\n      await fs3.writeFile(blobPath, content);\n    }\n  }\n}\nfunction buildSnapshotHash(files) {\n  const manifest = files.map((file) => `${file.path}\t${file.mode}\t${file.blobHash}\t${file.size}`).join(\"\\n\");\n  return sha256Hex2(manifest);\n}\nasync function inspectLocalSnapshot(params) {\n  const repoRoot = params.repoRoot;\n  const files = await listWorkspaceFiles(repoRoot);\n  const manifest = [];\n  for (const relativePath of files) {\n    const absolutePath = path4.join(repoRoot, relativePath);\n    const stat = await fs3.lstat(absolutePath);\n    if (stat.isSymbolicLink()) {\n      const linkTarget = await fs3.readlink(absolutePath);\n      const blobHash2 = sha256Hex2(`symlink:${linkTarget}`);\n      if (params.persistBlobs !== false) {\n        await persistBlob(blobHash2, linkTarget);\n      }\n      manifest.push({\n        path: relativePath,\n        mode: \"symlink\",\n        blobHash: blobHash2,\n        size: Buffer.byteLength(linkTarget)\n      });\n      continue;\n    }\n    const content = await fs3.readFile(absolutePath);\n    const blobHash = sha256Hex2(content);\n    if (params.persistBlobs !== false) {\n      await persistBlob(blobHash, content);\n    }\n    manifest.push({\n      path: relativePath,\n      mode: stat.mode & 73 ? \"executable\" : \"file\",\n      blobHash,\n      size: stat.size\n    });\n  }\n  const normalizedManifest = manifest.sort((a, b) => a.path.localeCompare(b.path));\n  return {\n    repoRoot,\n    repoFingerprint: params.repoFingerprint ?? null,\n    laneId: params.laneId ?? null,\n    /* v8 ignore next -- branch fallback only applies when git branch lookup races/fails. */\n    branchName: params.branchName ?? await getCurrentBranch(repoRoot).catch(() => null),\n    /* v8 ignore next -- commit fallback only applies when git HEAD lookup races/fails. */\n    localCommitHash: await getHeadCommitHash(repoRoot).catch(() => null),\n    snapshotHash: buildSnapshotHash(normalizedManifest),\n    createdAt: (/* @__PURE__ */ new Date()).toISOString(),\n    files: normalizedManifest\n  };\n}\nasync function captureLocalSnapshot(params) {\n  const inspection = await inspectLocalSnapshot({ ...params, persistBlobs: true });\n  const snapshot = {\n    schemaVersion: 1,\n    id: randomUUID2(),\n    ...inspection\n  };\n  await writeJsonAtomic(getSnapshotRecordPath(snapshot.id), snapshot);\n  return snapshot;\n}\nasync function readLocalSnapshot(snapshotId) {\n  if (!snapshotId) return null;\n  try {\n    const raw = await fs3.readFile(getSnapshotRecordPath(snapshotId), \"utf8\");\n    const parsed = JSON.parse(raw);\n    if (!parsed || parsed.schemaVersion !== 1) return null;\n    return parsed;\n  } catch {\n    return null;\n  }\n}\nasync function materializeLocalSnapshot(snapshotId, targetDir) {\n  const snapshot = await readLocalSnapshot(snapshotId);\n  await fs3.mkdir(targetDir, { recursive: true });\n  if (!snapshot) return;\n  for (const entry of snapshot.files) {\n    const destination = path4.join(targetDir, entry.path);\n    await fs3.mkdir(path4.dirname(destination), { recursive: true });\n    const blobPath = getBlobPath(entry.blobHash);\n    if (entry.mode === \"symlink\") {\n      const linkTarget = await fs3.readFile(blobPath, \"utf8\");\n      await fs3.symlink(linkTarget, destination);\n      continue;\n    }\n    await fs3.copyFile(blobPath, destination);\n    if (entry.mode === \"executable\") {\n      await fs3.chmod(destination, 493);\n    }\n  }\n}\nasync function pruneEmptyParentDirectories(repoRoot, filePath) {\n  let current = path4.dirname(filePath);\n  while (current !== repoRoot) {\n    const entries = await fs3.readdir(current).catch(() => null);\n    if (!entries || entries.length > 0) return;\n    await fs3.rmdir(current).catch(() => void 0);\n    current = path4.dirname(current);\n  }\n}\nasync function restoreLocalSnapshotToWorktree(snapshotId, repoRoot) {\n  const snapshot = await readLocalSnapshot(snapshotId);\n  await fs3.mkdir(repoRoot, { recursive: true });\n  const desiredPaths = new Set(snapshot?.files.map((entry) => entry.path) ?? []);\n  const currentPaths = await listWorkspaceFiles(repoRoot);\n  for (const relativePath of currentPaths) {\n    if (desiredPaths.has(relativePath)) continue;\n    const absolutePath = path4.join(repoRoot, relativePath);\n    await fs3.rm(absolutePath, { recursive: true, force: true }).catch(() => void 0);\n    await pruneEmptyParentDirectories(repoRoot, absolutePath);\n  }\n  if (!snapshot) return;\n  for (const entry of snapshot.files) {\n    const destination = path4.join(repoRoot, entry.path);\n    await fs3.mkdir(path4.dirname(destination), { recursive: true });\n    await fs3.rm(destination, { recursive: true, force: true }).catch(() => void 0);\n    const blobPath = getBlobPath(entry.blobHash);\n    if (entry.mode === \"symlink\") {\n      const linkTarget = await fs3.readFile(blobPath, \"utf8\");\n      await fs3.symlink(linkTarget, destination);\n      continue;\n    }\n    await fs3.copyFile(blobPath, destination);\n    if (entry.mode === \"executable\") {\n      await fs3.chmod(destination, 493);\n    }\n  }\n}\nasync function clearDirectoryExceptGit(targetDir) {\n  const entries = await fs3.readdir(targetDir, { withFileTypes: true });\n  for (const entry of entries) {\n    if (entry.name === \".git\") continue;\n    await fs3.rm(path4.join(targetDir, entry.name), { recursive: true, force: true });\n  }\n}\nasync function diffLocalSnapshots(params) {\n  const tempRoot = await fs3.mkdtemp(path4.join(os2.tmpdir(), \"remix-snapshot-diff-\"));\n  const repoDir = path4.join(tempRoot, \"repo\");\n  await fs3.mkdir(repoDir, { recursive: true });\n  try {\n    await materializeLocalSnapshot(params.baseSnapshotId, repoDir);\n    await execa(\"git\", [\"init\"], { cwd: repoDir, stderr: \"ignore\" });\n    await execa(\"git\", [\"add\", \"-A\"], { cwd: repoDir, stderr: \"ignore\" });\n    await execa(\n      \"git\",\n      [\"-c\", \"user.name=Remix\", \"-c\", \"user.email=remix@local\", \"commit\", \"--allow-empty\", \"-m\", \"baseline snapshot\"],\n      { cwd: repoDir, stderr: \"ignore\" }\n    );\n    await clearDirectoryExceptGit(repoDir);\n    await materializeLocalSnapshot(params.targetSnapshotId, repoDir);\n    await execa(\"git\", [\"add\", \"-A\"], { cwd: repoDir, stderr: \"ignore\" });\n    const diffRes = await execa(\"git\", [\"diff\", \"--binary\", \"--no-ext-diff\", \"--cached\", \"HEAD\"], {\n      cwd: repoDir,\n      reject: false,\n      stderr: \"ignore\",\n      stripFinalNewline: false\n    });\n    const pathsRes = await execa(\"git\", [\"diff\", \"--name-only\", \"--cached\", \"HEAD\", \"-z\"], {\n      cwd: repoDir,\n      reject: false,\n      stderr: \"ignore\",\n      stripFinalNewline: false\n    });\n    const diff = String(diffRes.stdout || \"\");\n    const changedPaths = String(pathsRes.stdout || \"\").split(\"\\0\").map((value) => value.trim()).filter(Boolean);\n    return {\n      baseSnapshotId: params.baseSnapshotId,\n      targetSnapshotId: params.targetSnapshotId,\n      diff,\n      diffSha256: diff ? sha256Hex2(diff) : null,\n      changedPaths,\n      stats: summarizeUnifiedDiff(diff)\n    };\n  } finally {\n    await fs3.rm(tempRoot, { recursive: true, force: true });\n  }\n}\n\n// src/infrastructure/collab/pendingFinalizeQueue.ts\nimport { randomUUID as randomUUID3 } from \"crypto\";\nimport fs4 from \"fs/promises\";\nimport path5 from \"path\";\nvar FINALIZE_JOB_LOCK_STALE_MS = 90 * 1e3;\nvar FINALIZE_ATTEMPT_STALE_MS = 10 * 60 * 1e3;\nvar TERMINAL_FINALIZE_JOB_RETENTION_MS = 24 * 60 * 60 * 1e3;\nfunction getJobPath(id) {\n  return path5.join(getFinalizeQueueRoot(), `${id}.json`);\n}\nfunction getJobLockPath2(id) {\n  return path5.join(getFinalizeQueueRoot(), `${id}.lock`);\n}\nfunction isPastDue(isoTimestamp) {\n  if (!isoTimestamp) return true;\n  const parsed = Date.parse(isoTimestamp);\n  return Number.isFinite(parsed) && parsed <= Date.now();\n}\nfunction isStaleAttempt(job) {\n  if (job.status !== \"processing\") return false;\n  if (!job.lastAttemptAt) return true;\n  const parsed = Date.parse(job.lastAttemptAt);\n  if (!Number.isFinite(parsed)) return true;\n  return Date.now() - parsed >= FINALIZE_ATTEMPT_STALE_MS;\n}\nfunction readMetadataDisposition(job) {\n  const value = job.metadata.failureDisposition;\n  return value === \"retryable\" || value === \"terminal\" ? value : null;\n}\nfunction isTerminalFailure(job) {\n  return job.status === \"failed\" && readMetadataDisposition(job) === \"terminal\";\n}\nfunction isTerminalFailureExpired(job) {\n  if (!isTerminalFailure(job)) return false;\n  const updatedAtMs = Date.parse(job.updatedAt);\n  if (!Number.isFinite(updatedAtMs)) return false;\n  return Date.now() - updatedAtMs >= TERMINAL_FINALIZE_JOB_RETENTION_MS;\n}\nfunction matchesJobScope(job, scope) {\n  if (job.repoRoot !== scope.repoRoot) return false;\n  if (scope.currentAppId && job.currentAppId !== scope.currentAppId) return false;\n  if (scope.laneId && job.laneId !== scope.laneId) return false;\n  if (scope.repoFingerprint && job.repoFingerprint && job.repoFingerprint !== scope.repoFingerprint) return false;\n  return true;\n}\nfunction isSameProcessingScope(left, right) {\n  return left.id !== right.id && left.repoRoot === right.repoRoot && left.currentAppId === right.currentAppId && (left.laneId ?? null) === (right.laneId ?? null) && (left.repoFingerprint ?? null) === (right.repoFingerprint ?? null);\n}\nasync function hasFreshJobLock(jobId) {\n  try {\n    const stat = await fs4.stat(getJobLockPath2(jobId));\n    return Date.now() - stat.mtimeMs < FINALIZE_JOB_LOCK_STALE_MS;\n  } catch (error) {\n    if (error?.code === \"ENOENT\") {\n      return false;\n    }\n    throw error;\n  }\n}\nasync function blocksFinalizeClaim(candidate, blocker) {\n  if (!isSameProcessingScope(candidate, blocker)) return false;\n  if (blocker.status === \"processing\") return hasFreshJobLock(blocker.id);\n  return blocker.status === \"queued\" && isPastDue(blocker.nextRetryAt) && blocker.capturedAt < candidate.capturedAt;\n}\nfunction createEmptyPendingFinalizeQueueSummary() {\n  return {\n    state: \"idle\",\n    activeJobCount: 0,\n    queuedJobCount: 0,\n    processingJobCount: 0,\n    retryScheduledJobCount: 0,\n    awaitingUsageJobCount: 0,\n    failedJobCount: 0,\n    oldestCapturedAt: null,\n    newestCapturedAt: null,\n    nextRetryAt: null,\n    latestError: null\n  };\n}\nasync function acquireJobLock2(jobId) {\n  const lockPath = getJobLockPath2(jobId);\n  try {\n    await fs4.mkdir(lockPath);\n    return true;\n  } catch (error) {\n    if (error?.code !== \"EEXIST\") {\n      throw error;\n    }\n  }\n  try {\n    const stat = await fs4.stat(lockPath);\n    if (Date.now() - stat.mtimeMs < FINALIZE_JOB_LOCK_STALE_MS) {\n      return false;\n    }\n    await fs4.rm(lockPath, { recursive: true, force: true });\n  } catch (error) {\n    if (error?.code !== \"ENOENT\") {\n      throw error;\n    }\n  }\n  try {\n    await fs4.mkdir(lockPath);\n    return true;\n  } catch (error) {\n    if (error?.code === \"EEXIST\") {\n      return false;\n    }\n    throw error;\n  }\n}\nasync function heartbeatJobLock(jobId) {\n  const lockPath = getJobLockPath2(jobId);\n  const now = /* @__PURE__ */ new Date();\n  try {\n    await fs4.utimes(lockPath, now, now);\n  } catch {\n  }\n}\nasync function cleanStaleFinalizeJobLocks() {\n  const removed = [];\n  const skipped = [];\n  const errors = [];\n  let entries;\n  try {\n    const dirents = await fs4.readdir(getFinalizeQueueRoot(), { withFileTypes: true });\n    entries = dirents.map((d) => ({ name: d.name, isDir: d.isDirectory() }));\n  } catch (error) {\n    if (error?.code === \"ENOENT\") {\n      return { removed, skipped, errors };\n    }\n    throw error;\n  }\n  for (const entry of entries) {\n    if (!entry.isDir || !entry.name.endsWith(\".lock\")) continue;\n    const jobId = entry.name.replace(/\\.lock$/, \"\");\n    const lockPath = path5.join(getFinalizeQueueRoot(), entry.name);\n    try {\n      const stat = await fs4.stat(lockPath);\n      const ageMs = Date.now() - stat.mtimeMs;\n      if (ageMs < FINALIZE_JOB_LOCK_STALE_MS) {\n        skipped.push({ jobId, reason: `fresh (age=${Math.round(ageMs / 1e3)}s)` });\n        continue;\n      }\n      await fs4.rm(lockPath, { recursive: true, force: true });\n      removed.push(jobId);\n    } catch (error) {\n      errors.push({ jobId, error: error instanceof Error ? error.message : String(error) });\n    }\n  }\n  return { removed, skipped, errors };\n}\nfunction normalizeJob2(input) {\n  const now = (/* @__PURE__ */ new Date()).toISOString();\n  const sourceConversation = SourceConversationSchema.safeParse(input.sourceConversation);\n  return {\n    schemaVersion: 1,\n    id: input.id ?? randomUUID3(),\n    status: input.status,\n    repoRoot: input.repoRoot,\n    repoFingerprint: input.repoFingerprint ?? null,\n    currentAppId: input.currentAppId,\n    laneId: input.laneId ?? null,\n    threadId: input.threadId ?? null,\n    sourceConversation: sourceConversation.success ? sourceConversation.data : null,\n    branchName: input.branchName ?? null,\n    prompt: input.prompt,\n    assistantResponse: input.assistantResponse,\n    baselineSnapshotId: input.baselineSnapshotId ?? null,\n    baselineServerRevisionId: input.baselineServerRevisionId ?? null,\n    baselineServerHeadHash: input.baselineServerHeadHash ?? null,\n    currentSnapshotId: input.currentSnapshotId,\n    capturedAt: input.capturedAt ?? now,\n    updatedAt: input.updatedAt ?? now,\n    idempotencyKey: input.idempotencyKey ?? null,\n    error: input.error ?? null,\n    retryCount: Number.isFinite(input.retryCount) ? Math.max(0, Number(input.retryCount)) : 0,\n    lastAttemptAt: input.lastAttemptAt ?? null,\n    nextRetryAt: input.nextRetryAt ?? null,\n    metadata: input.metadata ?? {}\n  };\n}\nasync function enqueuePendingFinalizeJob(input) {\n  const job = normalizeJob2(input);\n  await writeJsonAtomic(getJobPath(job.id), job);\n  return job;\n}\nasync function readPendingFinalizeJob(jobId) {\n  try {\n    const raw = await fs4.readFile(getJobPath(jobId), \"utf8\");\n    const parsed = JSON.parse(raw);\n    if (!parsed || parsed.schemaVersion !== 1 || typeof parsed.id !== \"string\") return null;\n    return normalizeJob2({\n      id: parsed.id,\n      status: parsed.status ?? \"queued\",\n      repoRoot: String(parsed.repoRoot ?? \"\"),\n      repoFingerprint: parsed.repoFingerprint ?? null,\n      currentAppId: String(parsed.currentAppId ?? \"\"),\n      laneId: parsed.laneId ?? null,\n      threadId: parsed.threadId ?? null,\n      sourceConversation: parsed.sourceConversation ?? null,\n      branchName: parsed.branchName ?? null,\n      prompt: String(parsed.prompt ?? \"\"),\n      assistantResponse: String(parsed.assistantResponse ?? \"\"),\n      baselineSnapshotId: parsed.baselineSnapshotId ?? null,\n      baselineServerRevisionId: parsed.baselineServerRevisionId ?? null,\n      baselineServerHeadHash: parsed.baselineServerHeadHash ?? null,\n      currentSnapshotId: String(parsed.currentSnapshotId ?? \"\"),\n      capturedAt: parsed.capturedAt,\n      updatedAt: parsed.updatedAt,\n      idempotencyKey: parsed.idempotencyKey ?? null,\n      error: parsed.error ?? null,\n      retryCount: parsed.retryCount ?? 0,\n      lastAttemptAt: parsed.lastAttemptAt ?? null,\n      nextRetryAt: parsed.nextRetryAt ?? null,\n      metadata: parsed.metadata ?? {}\n    });\n  } catch {\n    return null;\n  }\n}\nasync function listPendingFinalizeJobs() {\n  try {\n    const entries = await fs4.readdir(getFinalizeQueueRoot(), { withFileTypes: true });\n    const jobs = await Promise.all(\n      entries.filter((entry) => entry.isFile() && entry.name.endsWith(\".json\")).map((entry) => readPendingFinalizeJob(entry.name.replace(/\\.json$/, \"\")))\n    );\n    return jobs.filter((job) => Boolean(job)).sort((a, b) => a.capturedAt.localeCompare(b.capturedAt));\n  } catch (error) {\n    if (error?.code === \"ENOENT\") {\n      return [];\n    }\n    throw error;\n  }\n}\nasync function prunePendingFinalizeJobs() {\n  const jobs = await listPendingFinalizeJobs();\n  await Promise.all(\n    jobs.filter((job) => job.status === \"completed\" || isTerminalFailureExpired(job)).map((job) => removePendingFinalizeJob(job.id))\n  );\n}\nasync function summarizePendingFinalizeJobs(scope) {\n  const jobs = (await listPendingFinalizeJobs()).filter((job) => matchesJobScope(job, scope));\n  const summary = createEmptyPendingFinalizeQueueSummary();\n  const relevantJobs = jobs.filter((job) => job.status !== \"completed\");\n  if (relevantJobs.length === 0) return summary;\n  summary.oldestCapturedAt = relevantJobs[0]?.capturedAt ?? null;\n  summary.newestCapturedAt = relevantJobs[relevantJobs.length - 1]?.capturedAt ?? null;\n  for (const job of relevantJobs) {\n    if (job.error) {\n      summary.latestError = job.error;\n    }\n    if (job.nextRetryAt && (!summary.nextRetryAt || job.nextRetryAt < summary.nextRetryAt)) {\n      summary.nextRetryAt = job.nextRetryAt;\n    }\n    if (job.status === \"processing\") {\n      summary.processingJobCount += 1;\n      continue;\n    }\n    if (job.status === \"failed\") {\n      summary.failedJobCount += 1;\n      continue;\n    }\n    if (!isPastDue(job.nextRetryAt)) {\n      if (job.retryCount === 0 && !job.error) {\n        summary.awaitingUsageJobCount += 1;\n      } else {\n        summary.retryScheduledJobCount += 1;\n      }\n      continue;\n    }\n    summary.queuedJobCount += 1;\n  }\n  summary.activeJobCount = summary.queuedJobCount + summary.processingJobCount + summary.retryScheduledJobCount + summary.awaitingUsageJobCount;\n  if (summary.processingJobCount > 0) {\n    summary.state = \"processing\";\n  } else if (summary.queuedJobCount > 0) {\n    summary.state = \"queued\";\n  } else if (summary.retryScheduledJobCount > 0) {\n    summary.state = \"retry_scheduled\";\n  } else if (summary.awaitingUsageJobCount > 0) {\n    summary.state = \"awaiting_usage\";\n  } else {\n    summary.state = \"failed\";\n  }\n  return summary;\n}\nasync function updatePendingFinalizeJob(jobId, update) {\n  const existing = await readPendingFinalizeJob(jobId);\n  if (!existing) return null;\n  const next = {\n    ...existing,\n    ...update,\n    schemaVersion: 1,\n    id: existing.id,\n    capturedAt: existing.capturedAt,\n    updatedAt: (/* @__PURE__ */ new Date()).toISOString(),\n    metadata: update.metadata ? { ...existing.metadata, ...update.metadata } : existing.metadata\n  };\n  await writeJsonAtomic(getJobPath(jobId), next);\n  return next;\n}\nasync function claimPendingFinalizeJob(jobId) {\n  const lockPath = getJobLockPath2(jobId);\n  const lockAcquired = await acquireJobLock2(jobId);\n  if (!lockAcquired) return null;\n  let released = false;\n  const release = async () => {\n    if (released) return;\n    released = true;\n    await fs4.rm(lockPath, { recursive: true, force: true }).catch(() => void 0);\n  };\n  try {\n    let existing = await readPendingFinalizeJob(jobId);\n    if (!existing) {\n      await release();\n      return null;\n    }\n    if (isStaleAttempt(existing)) {\n      const recovered = await updatePendingFinalizeJob(jobId, {\n        status: \"queued\",\n        error: existing.error ?? \"Recovered a stale finalize processing lease.\",\n        nextRetryAt: null\n      });\n      existing = recovered ?? existing;\n    }\n    if (existing.status === \"failed\") {\n      if (isTerminalFailure(existing)) {\n        await release();\n        return null;\n      }\n      const recovered = await updatePendingFinalizeJob(jobId, {\n        status: \"queued\",\n        nextRetryAt: existing.nextRetryAt ?? null\n      });\n      existing = recovered ?? existing;\n    }\n    if (existing.status !== \"queued\" || !isPastDue(existing.nextRetryAt)) {\n      await release();\n      return null;\n    }\n    const jobs = await listPendingFinalizeJobs();\n    for (const job of jobs) {\n      if (await blocksFinalizeClaim(existing, job)) {\n        await release();\n        return null;\n      }\n    }\n    const now = (/* @__PURE__ */ new Date()).toISOString();\n    const claimed = await updatePendingFinalizeJob(jobId, {\n      status: \"processing\",\n      error: null,\n      retryCount: existing.retryCount + 1,\n      lastAttemptAt: now,\n      nextRetryAt: null\n    });\n    if (!claimed) {\n      await release();\n      return null;\n    }\n    return { job: claimed, release };\n  } catch (error) {\n    await release();\n    throw error;\n  }\n}\nasync function removePendingFinalizeJob(jobId) {\n  try {\n    await fs4.unlink(getJobPath(jobId));\n  } catch (error) {\n    if (error?.code !== \"ENOENT\") {\n      throw error;\n    }\n  }\n  await fs4.rm(getJobLockPath2(jobId), { recursive: true, force: true }).catch(() => void 0);\n}\nvar forgetPendingFinalizeJob = removePendingFinalizeJob;\nasync function requeuePendingFinalizeJob(jobId) {\n  const existing = await readPendingFinalizeJob(jobId);\n  if (!existing) return null;\n  await fs4.rm(getJobLockPath2(jobId), { recursive: true, force: true }).catch(() => void 0);\n  return updatePendingFinalizeJob(jobId, {\n    status: \"queued\",\n    error: null,\n    nextRetryAt: null,\n    metadata: {\n      // Reset the auto-terminal counter so an operator-initiated retry gets\n      // a fresh budget instead of being escalated to \"failed\" on the very\n      // next attempt.\n      consecutiveFailures: 0,\n      consecutiveFailureReason: null,\n      // Clear any previous terminal disposition so claim doesn't short-circuit.\n      failureDisposition: null,\n      failureReason: null,\n      requeuedAt: (/* @__PURE__ */ new Date()).toISOString()\n    }\n  });\n}\n\n// src/application/collab/shared.ts\nimport { createHash as createHash3 } from \"crypto\";\nfunction unwrapResponseObject(resp, label) {\n  const obj = resp?.responseObject;\n  if (obj === void 0 || obj === null) {\n    const message = typeof resp?.message === \"string\" && resp.message.trim().length > 0 ? resp.message : `Missing ${label} response`;\n    throw new RemixError(message, { exitCode: 1, hint: resp ? JSON.stringify(resp, null, 2) : null });\n  }\n  return obj;\n}\nvar DEFAULT_PAGINATION_LIMIT = 25;\nvar MAX_PAGINATION_LIMIT = 50;\nfunction normalizePagination(params) {\n  const rawLimit = typeof params?.limit === \"number\" && Number.isFinite(params.limit) ? Math.trunc(params.limit) : DEFAULT_PAGINATION_LIMIT;\n  const rawOffset = typeof params?.offset === \"number\" && Number.isFinite(params.offset) ? Math.trunc(params.offset) : 0;\n  return {\n    limit: Math.max(1, Math.min(MAX_PAGINATION_LIMIT, rawLimit)),\n    offset: Math.max(0, rawOffset)\n  };\n}\nfunction paginateOverfetchedItems(items, params) {\n  const pagination = normalizePagination(params);\n  return {\n    items: items.slice(0, pagination.limit),\n    pagination: {\n      ...pagination,\n      hasMore: items.length > pagination.limit\n    }\n  };\n}\nfunction unwrapMergeRequest(resp) {\n  return unwrapResponseObject(resp, \"merge request\");\n}\nfunction unwrapMergeRequestReview(resp) {\n  return unwrapResponseObject(resp, \"merge request review\");\n}\nfunction sleep(ms) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\nfunction buildDeterministicIdempotencyKey(parts) {\n  return createHash3(\"sha256\").update(JSON.stringify(parts)).digest(\"hex\");\n}\nfunction formatCliErrorDetail(err) {\n  if (err instanceof RemixError) {\n    return [err.message, err.hint].filter(Boolean).join(\"\\n\\n\") || null;\n  }\n  if (err instanceof Error) {\n    return err.message || null;\n  }\n  return typeof err === \"string\" && err.trim() ? err.trim() : null;\n}\nfunction sanitizeCheckoutDirName(value) {\n  const sanitized = value.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n  return sanitized || \"remix-remix\";\n}\nfunction buildDashboardAppUrl(appId) {\n  return `https://dashboard.remix.one/apps/${encodeURIComponent(appId)}`;\n}\nasync function resolveProjectLaneIfAuthoritative(api, params) {\n  const branchName = String(params.branchName ?? \"\").trim();\n  if (!branchName) return null;\n  if (!params.projectId && !params.repoFingerprint && !params.remoteUrl) return null;\n  const readLane = async () => {\n    const laneResp = await api.resolveProjectLaneBinding({\n      projectId: params.projectId ?? void 0,\n      repoFingerprint: params.repoFingerprint ?? void 0,\n      remoteUrl: params.remoteUrl ?? void 0,\n      defaultBranch: params.defaultBranch ?? void 0,\n      branchName,\n      currentAppId: params.currentAppId ?? void 0,\n      upstreamAppId: params.expectedUpstreamAppId ?? void 0\n    });\n    return unwrapResponseObject(laneResp, \"project lane binding\");\n  };\n  let lane = await readLane();\n  const shouldRepairResolvedLane = lane.status === \"resolved\" && Boolean(\n    params.expectedUpstreamAppId && (!lane.upstreamAppId || lane.upstreamAppId !== params.expectedUpstreamAppId)\n  );\n  if (shouldRepairResolvedLane && params.createIfMissing && params.seedAppId) {\n    const ensuredResp = await api.ensureProjectLaneBinding({\n      projectId: params.projectId ?? void 0,\n      repoFingerprint: params.repoFingerprint ?? void 0,\n      remoteUrl: params.remoteUrl ?? void 0,\n      defaultBranch: params.defaultBranch ?? void 0,\n      branchName,\n      currentAppId: params.currentAppId ?? void 0,\n      upstreamAppId: params.expectedUpstreamAppId ?? void 0,\n      seedAppId: params.seedAppId\n    });\n    lane = unwrapResponseObject(ensuredResp, \"project lane binding\");\n  }\n  if (lane.status !== \"resolved\" && params.createIfMissing && params.seedAppId) {\n    const ensuredResp = await api.ensureProjectLaneBinding({\n      projectId: params.projectId ?? void 0,\n      repoFingerprint: params.repoFingerprint ?? void 0,\n      remoteUrl: params.remoteUrl ?? void 0,\n      defaultBranch: params.defaultBranch ?? void 0,\n      branchName,\n      currentAppId: params.currentAppId ?? void 0,\n      upstreamAppId: params.expectedUpstreamAppId ?? void 0,\n      seedAppId: params.seedAppId\n    });\n    lane = unwrapResponseObject(ensuredResp, \"project lane binding\");\n  }\n  if (lane.status !== \"resolved\") return null;\n  if (params.projectId && lane.projectId && lane.projectId !== params.projectId) return null;\n  if (params.currentAppId && lane.currentAppId && lane.currentAppId !== params.currentAppId) return null;\n  if (params.expectedUpstreamAppId && lane.upstreamAppId && lane.upstreamAppId !== params.expectedUpstreamAppId) return null;\n  return lane;\n}\nasync function pollAppReady(api, appId, deps = {}) {\n  const now = deps.clock?.now ?? Date.now;\n  const sleepFn = deps.timers?.sleep ?? sleep;\n  const started = now();\n  let delay = 2e3;\n  while (now() - started < 20 * 60 * 1e3) {\n    const appResp = await api.getApp(appId);\n    const app = unwrapResponseObject(appResp, \"app\");\n    const status = typeof app.status === \"string\" ? app.status : \"\";\n    if (status === \"ready\") return app;\n    if (status === \"error\") {\n      throw new RemixError(\"App is in error state.\", {\n        exitCode: 1,\n        hint: typeof app.statusError === \"string\" ? app.statusError : null\n      });\n    }\n    await sleepFn(delay);\n    delay = Math.min(1e4, Math.floor(delay * 1.4));\n  }\n  throw new RemixError(\"Timed out waiting for app to become ready.\", { exitCode: 1 });\n}\nvar DEFAULT_APP_IMPORTED_TIMEOUT_MS = 6e4;\nvar APP_IMPORTED_SLOW_WARNING_MS = 3e4;\nfunction resolveImportedTimeoutMs(override) {\n  if (typeof override === \"number\" && Number.isFinite(override) && override > 0) return override;\n  const fromEnv = Number(process.env.REMIX_INIT_POLL_TIMEOUT_MS);\n  if (Number.isFinite(fromEnv) && fromEnv > 0) return fromEnv;\n  return DEFAULT_APP_IMPORTED_TIMEOUT_MS;\n}\nasync function pollAppImported(api, appId, opts) {\n  const timeoutMs = resolveImportedTimeoutMs(opts?.timeoutMs);\n  const slowWarningMs = opts?.slowWarningMs ?? APP_IMPORTED_SLOW_WARNING_MS;\n  const started = Date.now();\n  let delay = 500;\n  let warnedSlow = false;\n  while (Date.now() - started < timeoutMs) {\n    const appResp = await api.getApp(appId);\n    const app = unwrapResponseObject(appResp, \"app\");\n    const status = typeof app.status === \"string\" ? app.status : \"\";\n    if (status === \"error\") {\n      throw new RemixError(\"App is in error state.\", {\n        exitCode: 1,\n        hint: typeof app.statusError === \"string\" ? app.statusError : null\n      });\n    }\n    const headCommitId = typeof app.headCommitId === \"string\" ? app.headCommitId : null;\n    if (headCommitId) return app;\n    const elapsed = Date.now() - started;\n    if (!warnedSlow && elapsed >= slowWarningMs) {\n      warnedSlow = true;\n      const onSlow = opts?.onSlow;\n      if (onSlow) {\n        onSlow(elapsed);\n      } else {\n        console.warn(\n          `[remix collab init] still waiting for app import (>${Math.round(elapsed / 1e3)}s); will time out at ${Math.round(timeoutMs / 1e3)}s`\n        );\n      }\n    }\n    await sleep(delay);\n    delay = Math.min(2e3, Math.floor(delay * 1.4));\n  }\n  throw new RemixError(\"Timed out waiting for app to be imported.\", {\n    exitCode: 1,\n    hint: `head_commit_id was not set within ${Math.round(timeoutMs / 1e3)}s. The backend import worker may have hung; check the app's status in the dashboard, or set REMIX_INIT_POLL_TIMEOUT_MS to a higher value if the bundle is unusually large.`\n  });\n}\nasync function pollChangeStep(api, appId, changeStepId) {\n  const started = Date.now();\n  let delay = 1500;\n  while (Date.now() - started < 20 * 60 * 1e3) {\n    const resp = await api.getChangeStep(appId, changeStepId);\n    const step = unwrapResponseObject(resp, \"change step\");\n    const status = typeof step.status === \"string\" ? step.status : \"\";\n    if (status === \"succeeded\") return step;\n    if (status === \"failed\") {\n      throw new RemixError(\"Change step failed.\", {\n        exitCode: 1,\n        hint: typeof step.statusError === \"string\" ? step.statusError : null\n      });\n    }\n    await sleep(delay);\n    delay = Math.min(1e4, Math.floor(delay * 1.4));\n  }\n  throw new RemixError(\"Timed out waiting for change step.\", { exitCode: 1 });\n}\nasync function pollChangeStepReplay(api, appId, replayId) {\n  const started = Date.now();\n  let delay = 1500;\n  while (Date.now() - started < 30 * 60 * 1e3) {\n    const resp = await api.getChangeStepReplay(appId, replayId);\n    const replay = unwrapResponseObject(resp, \"change step replay\");\n    if (replay.status === \"succeeded\") return replay;\n    if (replay.status === \"manual_resolution_required\") {\n      throw new RemixError(\"AI-assisted replay requires manual intervention.\", {\n        exitCode: 2,\n        hint: replay.statusError || \"The server could not safely adapt the preserved local diff.\"\n      });\n    }\n    if (replay.status === \"failed\" || replay.status === \"cancelled\") {\n      throw new RemixError(\"AI-assisted replay failed.\", {\n        exitCode: 1,\n        hint: replay.statusError || null\n      });\n    }\n    await sleep(delay);\n    delay = Math.min(1e4, Math.floor(delay * 1.4));\n  }\n  throw new RemixError(\"Timed out waiting for AI-assisted replay.\", { exitCode: 1 });\n}\nasync function pollUpstreamSyncCompletion(api, appId, params) {\n  const started = Date.now();\n  let delay = 1500;\n  let sawNonReady = params.initialStatus !== \"ready\";\n  while (Date.now() - started < 30 * 60 * 1e3) {\n    const appResp = await api.getApp(appId);\n    const app = unwrapResponseObject(appResp, \"app\");\n    const status = typeof app.status === \"string\" ? app.status : \"\";\n    const headCommitId = typeof app.headCommitId === \"string\" ? app.headCommitId : null;\n    if (status === \"error\") {\n      throw new RemixError(\"App upstream sync failed.\", {\n        exitCode: 1,\n        hint: typeof app.statusError === \"string\" ? app.statusError : null\n      });\n    }\n    if (status !== \"ready\") sawNonReady = true;\n    if (status === \"ready\" && headCommitId && headCommitId !== params.initialHeadCommitId) {\n      return app;\n    }\n    if (status === \"ready\" && sawNonReady) {\n      return app;\n    }\n    await sleep(delay);\n    delay = Math.min(1e4, Math.floor(delay * 1.4));\n  }\n  throw new RemixError(\"Timed out waiting for upstream sync.\", { exitCode: 1 });\n}\nasync function pollMergeRequestCompletion(api, mrId, params) {\n  const started = Date.now();\n  let delay = 1500;\n  while (Date.now() - started < 30 * 60 * 1e3) {\n    const reviewResp = await api.getMergeRequestReview(mrId);\n    const review = unwrapMergeRequestReview(reviewResp);\n    const mergeRequest = review.mergeRequest;\n    if (mergeRequest.status === \"merged\") return mergeRequest;\n    if (mergeRequest.status === \"manual_resolution_required\") {\n      throw new RemixError(\"Merge approval requires manual conflict resolution.\", {\n        exitCode: 2,\n        hint: \"Merge request ended in status=manual_resolution_required.\"\n      });\n    }\n    if (mergeRequest.status === \"rejected\" || mergeRequest.status === \"closed\") {\n      throw new RemixError(\"Merge approval did not complete successfully.\", {\n        exitCode: 1,\n        hint: `Merge request ended in status=${mergeRequest.status}.`\n      });\n    }\n    if (params?.targetAppId) {\n      const appResp = await api.getApp(params.targetAppId);\n      const app = unwrapResponseObject(appResp, \"app\");\n      const status = typeof app.status === \"string\" ? app.status : \"\";\n      if (status === \"error\") {\n        throw new RemixError(\"Merge job failed.\", {\n          exitCode: 1,\n          hint: typeof app.statusError === \"string\" ? app.statusError : null\n        });\n      }\n    }\n    await sleep(delay);\n    delay = Math.min(1e4, Math.floor(delay * 1.4));\n  }\n  throw new RemixError(\"Timed out waiting for merge approval to complete.\", { exitCode: 1 });\n}\n\n// src/application/collab/laneBindingResolver.ts\nfunction normalizeBranchName(value) {\n  const normalized = String(value ?? \"\").trim();\n  return normalized || null;\n}\nfunction buildBindingFromLane(state, lane) {\n  if (!lane.currentAppId || !lane.upstreamAppId) return null;\n  const resolvedBranch = normalizeBranchName(lane.branchName) ?? state.currentBranch ?? null;\n  const resolvedDefaultBranch = normalizeBranchName(lane.defaultBranch) ?? normalizeBranchName(state.defaultBranch);\n  const explicitRootProjectId = state.explicitRootBinding?.projectId ?? null;\n  const bindingMode = explicitRootProjectId && lane.projectId === explicitRootProjectId && resolvedBranch && resolvedBranch === resolvedDefaultBranch ? \"explicit_root\" : \"lane\";\n  return {\n    schemaVersion: 3,\n    projectId: lane.projectId ?? state.projectId,\n    currentAppId: lane.currentAppId,\n    upstreamAppId: lane.upstreamAppId,\n    threadId: lane.threadId ?? null,\n    repoFingerprint: lane.repoFingerprint ?? state.repoFingerprint ?? null,\n    remoteUrl: lane.remoteUrl ?? state.remoteUrl ?? null,\n    defaultBranch: lane.defaultBranch ?? state.defaultBranch ?? null,\n    laneId: lane.laneId ?? null,\n    branchName: resolvedBranch,\n    bindingMode\n  };\n}\nfunction shouldPersistRemoteLaneMetadata(localBinding, lane) {\n  return Boolean(\n    !localBinding.laneId && lane.laneId || !localBinding.threadId && lane.threadId || !localBinding.repoFingerprint && lane.repoFingerprint || !localBinding.remoteUrl && lane.remoteUrl || !localBinding.defaultBranch && lane.defaultBranch || !localBinding.branchName && lane.branchName\n  );\n}\nfunction shouldRequireRemoteLaneForCurrentBranch(params) {\n  if (!params.currentBranch) return false;\n  const defaultBranch = normalizeBranchName(params.defaultBranch);\n  if (params.currentBranch === defaultBranch) return false;\n  return !params.binding.laneId || params.binding.currentAppId === params.binding.upstreamAppId;\n}\nfunction resolveLaneLookupProjectId(params) {\n  const currentBranch = normalizeBranchName(params.currentBranch);\n  const defaultBranch = normalizeBranchName(params.defaultBranch);\n  const localProjectId = params.localBinding.projectId ?? null;\n  if (currentBranch && currentBranch !== defaultBranch && localProjectId) {\n    return localProjectId;\n  }\n  return params.explicitRootProjectId ?? (params.requireRemoteLane ? void 0 : localProjectId ?? params.fallbackProjectId ?? void 0);\n}\nasync function persistResolvedLane(repoRoot, binding) {\n  const previousBinding = await readCollabBinding(repoRoot);\n  await writeCollabBinding(repoRoot, {\n    projectId: binding.projectId,\n    currentAppId: binding.currentAppId,\n    upstreamAppId: binding.upstreamAppId,\n    threadId: binding.threadId,\n    repoFingerprint: binding.repoFingerprint,\n    remoteUrl: binding.remoteUrl,\n    defaultBranch: binding.defaultBranch,\n    laneId: binding.laneId,\n    branchName: binding.branchName,\n    bindingMode: binding.bindingMode\n  });\n  if (previousBinding && (previousBinding.laneId ?? null) !== (binding.laneId ?? null)) {\n    await migrateLocalBaselineForLaneChange({\n      repoRoot,\n      repoFingerprint: binding.repoFingerprint,\n      currentAppId: binding.currentAppId,\n      branchName: binding.branchName,\n      fromLaneId: previousBinding.laneId,\n      toLaneId: binding.laneId\n    });\n  }\n  return readCollabBinding(repoRoot);\n}\nfunction buildAmbiguousResolution(params) {\n  return {\n    status: \"ambiguous_family_selection\",\n    currentBranch: params.currentBranch,\n    projectIds: Array.isArray(params.lane.projectIds) ? params.lane.projectIds.filter((value) => typeof value === \"string\" && value.trim().length > 0) : [],\n    repoFingerprint: params.lane.repoFingerprint ?? params.state.repoFingerprint,\n    remoteUrl: params.lane.remoteUrl ?? params.state.remoteUrl,\n    defaultBranch: params.lane.defaultBranch ?? params.state.defaultBranch\n  };\n}\nvar RESOLUTION_CACHE_TTL_MS = 5e3;\nvar resolutionCache = /* @__PURE__ */ new Map();\nvar cacheClock3 = () => Date.now();\nfunction buildResolutionCacheKey(params) {\n  return [\n    params.repoRoot,\n    params.currentBranch ?? \"\",\n    params.hasApi ? \"1\" : \"0\",\n    params.currentAppId ?? \"\",\n    params.upstreamAppId ?? \"\",\n    params.laneId ?? \"\"\n  ].join(\"|\");\n}\nfunction readResolutionCache(key) {\n  const entry = resolutionCache.get(key);\n  if (!entry) return null;\n  if (cacheClock3() - entry.cachedAt > RESOLUTION_CACHE_TTL_MS) {\n    resolutionCache.delete(key);\n    return null;\n  }\n  return entry.resolution;\n}\nfunction writeResolutionCache(key, resolution) {\n  if (resolution.status !== \"resolved\") return;\n  resolutionCache.set(key, { resolution, cachedAt: cacheClock3() });\n}\nasync function resolveActiveLaneBinding(params) {\n  const state = await readCollabBindingState(params.repoRoot);\n  const cacheKey = buildResolutionCacheKey({\n    repoRoot: params.repoRoot,\n    currentBranch: state ? normalizeBranchName(state.currentBranch) : null,\n    hasApi: Boolean(params.api),\n    currentAppId: state?.binding?.currentAppId ?? null,\n    upstreamAppId: state?.binding?.upstreamAppId ?? null,\n    laneId: state?.binding?.laneId ?? null\n  });\n  const cached = readResolutionCache(cacheKey);\n  if (cached) return cached;\n  const resolution = await resolveActiveLaneBindingUncached(params, state);\n  writeResolutionCache(cacheKey, resolution);\n  return resolution;\n}\nasync function resolveActiveLaneBindingUncached(params, state) {\n  if (!state) {\n    return { status: \"not_bound\", currentBranch: null };\n  }\n  const currentBranch = normalizeBranchName(state.currentBranch);\n  const localBinding = state.binding;\n  if (localBinding) {\n    const requireRemoteLane = shouldRequireRemoteLaneForCurrentBranch({\n      binding: localBinding,\n      currentBranch,\n      defaultBranch: state.defaultBranch\n    });\n    if (!params.api || !currentBranch) {\n      return {\n        status: \"resolved\",\n        source: \"local\",\n        binding: localBinding,\n        currentBranch\n      };\n    }\n    const laneResp2 = await params.api.resolveProjectLaneBinding({\n      projectId: resolveLaneLookupProjectId({\n        explicitRootProjectId: state.explicitRootBinding?.projectId,\n        localBinding,\n        currentBranch,\n        defaultBranch: state.defaultBranch,\n        requireRemoteLane,\n        fallbackProjectId: state.projectId\n      }),\n      repoFingerprint: state.repoFingerprint ?? void 0,\n      remoteUrl: state.remoteUrl ?? void 0,\n      defaultBranch: state.defaultBranch ?? void 0,\n      branchName: currentBranch,\n      currentAppId: localBinding.currentAppId,\n      upstreamAppId: localBinding.upstreamAppId\n    });\n    const lane2 = unwrapResponseObject(laneResp2, \"project lane binding\");\n    if (lane2.status === \"ambiguous_family_selection\") {\n      return buildAmbiguousResolution({ state, currentBranch, lane: lane2 });\n    }\n    if (lane2.status === \"resolved\") {\n      const resolvedBranch = normalizeBranchName(lane2.branchName);\n      const resolvedProjectId = lane2.projectId ?? state.projectId;\n      const branchConflict = Boolean(resolvedBranch && localBinding.branchName && resolvedBranch !== localBinding.branchName);\n      const appConflict = Boolean(lane2.currentAppId && lane2.currentAppId !== localBinding.currentAppId);\n      const upstreamConflict = Boolean(lane2.upstreamAppId && lane2.upstreamAppId !== localBinding.upstreamAppId);\n      const projectConflict = Boolean(resolvedProjectId && localBinding.projectId && resolvedProjectId !== localBinding.projectId);\n      if (branchConflict || appConflict || upstreamConflict || projectConflict) {\n        if (requireRemoteLane) {\n          const binding = buildBindingFromLane(state, lane2);\n          if (binding) {\n            return {\n              status: \"resolved\",\n              source: \"remote\",\n              binding,\n              currentBranch\n            };\n          }\n        }\n        return {\n          status: \"binding_conflict\",\n          binding: localBinding,\n          resolvedLane: lane2,\n          currentBranch\n        };\n      }\n      if (shouldPersistRemoteLaneMetadata(localBinding, lane2)) {\n        const binding = buildBindingFromLane(state, lane2);\n        if (binding) {\n          return {\n            status: \"resolved\",\n            source: \"remote\",\n            binding,\n            currentBranch\n          };\n        }\n      }\n    }\n    if (requireRemoteLane) {\n      return {\n        status: \"missing_branch_binding\",\n        currentBranch,\n        projectId: lane2.projectId ?? state.projectId,\n        repoFingerprint: lane2.repoFingerprint ?? state.repoFingerprint,\n        remoteUrl: lane2.remoteUrl ?? state.remoteUrl,\n        defaultBranch: lane2.defaultBranch ?? state.defaultBranch,\n        upstreamAppId: lane2.upstreamAppId ?? localBinding.upstreamAppId ?? null,\n        threadId: lane2.threadId ?? localBinding.threadId ?? null\n      };\n    }\n    return {\n      status: \"resolved\",\n      source: \"local\",\n      binding: localBinding,\n      currentBranch\n    };\n  }\n  if (!params.api || !currentBranch) {\n    return {\n      status: \"missing_branch_binding\",\n      currentBranch,\n      projectId: state.projectId,\n      repoFingerprint: state.repoFingerprint,\n      remoteUrl: state.remoteUrl,\n      defaultBranch: state.defaultBranch,\n      upstreamAppId: null,\n      threadId: null\n    };\n  }\n  const laneResp = await params.api.resolveProjectLaneBinding({\n    projectId: state.explicitRootBinding?.projectId ?? state.projectId ?? void 0,\n    repoFingerprint: state.repoFingerprint ?? void 0,\n    remoteUrl: state.remoteUrl ?? void 0,\n    defaultBranch: state.defaultBranch ?? void 0,\n    branchName: currentBranch,\n    currentAppId: state.binding?.currentAppId,\n    upstreamAppId: state.binding?.upstreamAppId\n  });\n  const lane = unwrapResponseObject(laneResp, \"project lane binding\");\n  if (lane.status === \"ambiguous_family_selection\") {\n    return buildAmbiguousResolution({ state, currentBranch, lane });\n  }\n  if (lane.status === \"resolved\") {\n    const binding = buildBindingFromLane(state, lane);\n    if (binding) {\n      return {\n        status: \"resolved\",\n        source: \"remote\",\n        binding,\n        currentBranch\n      };\n    }\n  }\n  return {\n    status: \"missing_branch_binding\",\n    currentBranch,\n    projectId: lane.projectId ?? state.explicitRootBinding?.projectId ?? state.projectId,\n    repoFingerprint: lane.repoFingerprint ?? state.repoFingerprint,\n    remoteUrl: lane.remoteUrl ?? state.remoteUrl,\n    defaultBranch: lane.defaultBranch ?? state.defaultBranch,\n    upstreamAppId: lane.upstreamAppId ?? state.explicitRootBinding?.upstreamAppId ?? null,\n    threadId: lane.threadId ?? state.explicitRootBinding?.threadId ?? null\n  };\n}\nasync function ensureActiveLaneBinding(params) {\n  const resolved = await resolveActiveLaneBinding({\n    repoRoot: params.repoRoot,\n    api: params.api\n  });\n  if (resolved.status === \"resolved\") {\n    if (resolved.source === \"local\") {\n      return resolved.binding;\n    }\n    return persistResolvedLane(params.repoRoot, resolved.binding);\n  }\n  if (resolved.status === \"binding_conflict\") {\n    const serverAppId = resolved.resolvedLane.currentAppId ?? \"(unknown)\";\n    const operation = params.operation ?? \"this command\";\n    throw new RemixError(\"Current branch binding conflicts with the server-resolved Remix lane.\", {\n      exitCode: 2,\n      hint: `Local app ${resolved.binding.currentAppId}; server app ${serverAppId}. Repair the branch binding before running ${operation}.`\n    });\n  }\n  if (resolved.status === \"ambiguous_family_selection\") {\n    throw new RemixError(\"Multiple canonical Remix families match this repository.\", {\n      exitCode: 2,\n      hint: \"This checkout is not specific enough to choose a single family for the current branch. Continue from a checkout already bound to the intended family, or run `remix collab init --force-new` to create a new canonical family.\"\n    });\n  }\n  if (resolved.status === \"not_bound\") {\n    return null;\n  }\n  if (!resolved.currentBranch) {\n    throw new RemixError(\"Current branch is not yet bound to a Remix lane.\", {\n      exitCode: 2,\n      hint: `Switch to a named branch before running ${params.operation ?? \"this command\"}.`\n    });\n  }\n  throw new RemixError(\"Current branch is not yet bound to a Remix lane.\", {\n    exitCode: 2,\n    hint: `Run \\`remix collab init\\` on branch ${resolved.currentBranch} before running ${params.operation ?? \"this command\"}.`\n  });\n}\n\n// src/application/collab/collabDetectRepoState.ts\nfunction buildBaseState() {\n  return {\n    status: \"ready\",\n    repoState: null,\n    repoRoot: null,\n    binding: null,\n    currentBranch: null,\n    branchName: null,\n    localCommitHash: null,\n    currentSnapshotHash: null,\n    currentServerRevisionId: null,\n    currentServerTreeHash: null,\n    currentServerHeadHash: null,\n    currentServerHeadCommitId: null,\n    worktreeClean: false,\n    pendingFinalize: {\n      state: \"idle\",\n      activeJobCount: 0,\n      queuedJobCount: 0,\n      processingJobCount: 0,\n      retryScheduledJobCount: 0,\n      awaitingUsageJobCount: 0,\n      failedJobCount: 0,\n      oldestCapturedAt: null,\n      newestCapturedAt: null,\n      nextRetryAt: null,\n      latestError: null\n    },\n    pendingAsyncJobs: {\n      state: \"idle\",\n      activeJobCount: 0,\n      queuedJobCount: 0,\n      processingJobCount: 0,\n      failedJobCount: 0,\n      oldestCreatedAt: null,\n      newestCreatedAt: null,\n      latestError: null,\n      kinds: []\n    },\n    warnings: [],\n    hint: null,\n    metadataWarnings: [],\n    baseline: {\n      lastSnapshotId: null,\n      lastSnapshotHash: null,\n      lastServerRevisionId: null,\n      lastServerTreeHash: null,\n      lastServerHeadHash: null,\n      lastSeenLocalCommitHash: null\n    }\n  };\n}\nasync function refreshEquivalentRevisionBaseline(params) {\n  return writeLocalBaseline({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.binding.repoFingerprint,\n    laneId: params.binding.laneId,\n    currentAppId: params.binding.currentAppId,\n    branchName: params.binding.branchName,\n    lastSnapshotId: params.baseline.lastSnapshotId,\n    lastSnapshotHash: params.baseline.lastSnapshotHash,\n    lastServerRevisionId: params.appHead.headRevisionId ?? null,\n    lastServerTreeHash: params.appHead.treeHash ?? params.baseline.lastServerTreeHash ?? null,\n    lastServerHeadHash: params.appHead.headCommitHash,\n    lastSeenLocalCommitHash: params.baseline.lastSeenLocalCommitHash\n  });\n}\nasync function collabDetectRepoState(params) {\n  const detected = buildBaseState();\n  let repoRoot;\n  try {\n    repoRoot = await findGitRoot(params.cwd);\n  } catch (error) {\n    detected.status = \"not_git_repo\";\n    detected.hint = formatCliErrorDetail(error) ?? \"Not inside a git repository.\";\n    return detected;\n  }\n  detected.repoRoot = repoRoot;\n  const bindingResolution = await resolveActiveLaneBinding({ repoRoot, api: params.api ?? void 0 });\n  if (bindingResolution.status === \"not_bound\") {\n    detected.status = \"not_bound\";\n    detected.repoState = \"binding_problem\";\n    detected.hint = \"Run `remix collab init` first.\";\n    return detected;\n  }\n  if (bindingResolution.status === \"missing_branch_binding\") {\n    detected.status = \"branch_binding_missing\";\n    detected.repoState = \"binding_problem\";\n    detected.currentBranch = bindingResolution.currentBranch;\n    detected.branchName = bindingResolution.currentBranch;\n    detected.hint = `Current branch ${bindingResolution.currentBranch ?? \"(detached)\"} is not yet bound to a Remix lane.`;\n    return detected;\n  }\n  if (bindingResolution.status === \"ambiguous_family_selection\") {\n    detected.status = \"family_ambiguous\";\n    detected.repoState = \"binding_problem\";\n    detected.currentBranch = bindingResolution.currentBranch;\n    detected.branchName = bindingResolution.currentBranch;\n    detected.hint = \"Multiple canonical Remix families match this repository. Continue from a checkout already bound to the intended family, or run `remix collab init --force-new`.\";\n    return detected;\n  }\n  if (bindingResolution.status === \"binding_conflict\") {\n    const conflictBranch = bindingResolution.currentBranch ?? \"(detached)\";\n    const conflictLaneId = bindingResolution.resolvedLane.laneId ?? \"(unknown)\";\n    const conflictAppId = bindingResolution.resolvedLane.currentAppId ?? \"(unknown)\";\n    detected.status = \"metadata_conflict\";\n    detected.repoState = \"metadata_conflict\";\n    detected.binding = bindingResolution.binding;\n    detected.currentBranch = bindingResolution.currentBranch;\n    detected.branchName = bindingResolution.binding.branchName;\n    detected.hint = `Local binding for ${conflictBranch} points to app ${bindingResolution.binding.currentAppId}, but the server resolved lane ${conflictLaneId} / app ${conflictAppId}.`;\n    return detected;\n  }\n  const binding = bindingResolution.binding;\n  detected.binding = binding;\n  const [currentBranch, localCommitHash, worktreeStatus] = await Promise.all([\n    getCurrentBranch(repoRoot),\n    getHeadCommitHash(repoRoot),\n    getWorktreeStatus(repoRoot)\n  ]);\n  detected.currentBranch = currentBranch;\n  detected.branchName = binding.branchName ?? null;\n  detected.localCommitHash = localCommitHash;\n  detected.worktreeClean = worktreeStatus.isClean;\n  if (!localCommitHash) {\n    detected.status = \"missing_head\";\n    detected.repoState = \"binding_problem\";\n    detected.hint = \"Failed to resolve local HEAD commit.\";\n    return detected;\n  }\n  if (!params.allowBranchMismatch && !isBoundBranchMatch(currentBranch, binding.branchName ?? null)) {\n    detected.status = \"branch_mismatch\";\n    detected.repoState = \"binding_problem\";\n    detected.hint = buildBranchMismatchHint({ currentBranch, branchName: binding.branchName ?? null });\n    return detected;\n  }\n  if (!params.api) {\n    const asyncSummaryBranchName = binding.branchName ?? null;\n    const [inspection, pendingFinalize, pendingAsyncJobs] = await Promise.all([\n      inspectLocalSnapshot({\n        repoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branchName: binding.branchName,\n        persistBlobs: false\n      }),\n      summarizePendingFinalizeJobs({\n        repoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        currentAppId: binding.currentAppId,\n        laneId: binding.laneId\n      }),\n      summarizeAsyncJobs({ repoRoot, branchName: asyncSummaryBranchName })\n    ]);\n    detected.currentSnapshotHash = inspection.snapshotHash;\n    detected.pendingFinalize = pendingFinalize;\n    detected.pendingAsyncJobs = pendingAsyncJobs;\n    return detected;\n  }\n  try {\n    let baseline = await readLocalBaseline({\n      repoFingerprint: binding.repoFingerprint,\n      laneId: binding.laneId,\n      repoRoot\n    });\n    let ambiguousBaselineCandidateCount = null;\n    if (!baseline) {\n      const compatibleBaseline = await findCompatibleLocalBaseline({\n        repoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        currentAppId: binding.currentAppId,\n        branchName: binding.branchName\n      });\n      if (compatibleBaseline.status === \"found\") {\n        baseline = await writeLocalBaseline({\n          ...compatibleBaseline.baseline,\n          repoRoot,\n          repoFingerprint: binding.repoFingerprint,\n          laneId: binding.laneId,\n          currentAppId: binding.currentAppId,\n          branchName: binding.branchName\n        });\n        detected.warnings.push(\n          `Recovered local Remix baseline after lane id changed from ${compatibleBaseline.baseline.laneId ?? \"null\"} to ${binding.laneId ?? \"null\"} for app ${binding.currentAppId} on branch ${binding.branchName ?? \"(unknown)\"}.`\n        );\n      } else if (compatibleBaseline.status === \"ambiguous\") {\n        ambiguousBaselineCandidateCount = compatibleBaseline.candidateCount;\n      }\n    }\n    const hasFullBaseline = Boolean(baseline?.lastSnapshotHash && baseline?.lastServerHeadHash);\n    const metadataIdentityPromise = hasFullBaseline ? getAppDeltaCached(params.api, binding.currentAppId, {\n      baseHeadHash: baseline.lastServerHeadHash,\n      targetHeadHash: baseline.lastServerHeadHash,\n      repoFingerprint: binding.repoFingerprint ?? void 0,\n      remoteUrl: binding.remoteUrl ?? void 0,\n      defaultBranch: binding.defaultBranch ?? void 0\n    }) : Promise.resolve(null);\n    const asyncSummaryBranchName = binding.branchName ?? null;\n    const [headResp, inspection, parallelMetadataResp, pendingFinalize, pendingAsyncJobs] = await Promise.all([\n      getAppHeadCached(params.api, binding.currentAppId),\n      inspectLocalSnapshot({\n        repoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branchName: binding.branchName,\n        persistBlobs: false\n      }),\n      metadataIdentityPromise,\n      summarizePendingFinalizeJobs({\n        repoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        currentAppId: binding.currentAppId,\n        laneId: binding.laneId\n      }),\n      summarizeAsyncJobs({ repoRoot, branchName: asyncSummaryBranchName })\n    ]);\n    const appHead = unwrapResponseObject(headResp, \"app head\");\n    detected.currentServerRevisionId = appHead.headRevisionId ?? null;\n    detected.currentServerTreeHash = appHead.treeHash ?? null;\n    detected.currentServerHeadHash = appHead.headCommitHash;\n    detected.currentServerHeadCommitId = appHead.headCommitId;\n    detected.currentSnapshotHash = inspection.snapshotHash;\n    detected.pendingFinalize = pendingFinalize;\n    detected.pendingAsyncJobs = pendingAsyncJobs;\n    detected.baseline = {\n      lastSnapshotId: baseline?.lastSnapshotId ?? null,\n      lastSnapshotHash: baseline?.lastSnapshotHash ?? null,\n      lastServerRevisionId: baseline?.lastServerRevisionId ?? null,\n      lastServerTreeHash: baseline?.lastServerTreeHash ?? null,\n      lastServerHeadHash: baseline?.lastServerHeadHash ?? null,\n      lastSeenLocalCommitHash: baseline?.lastSeenLocalCommitHash ?? null\n    };\n    if (!baseline?.lastSnapshotHash || !baseline.lastServerHeadHash) {\n      if (detected.worktreeClean && localCommitHash && localCommitHash !== appHead.headCommitHash) {\n        try {\n          const bootstrapResp = await params.api.getAppDelta(binding.currentAppId, {\n            baseHeadHash: localCommitHash,\n            targetHeadHash: appHead.headCommitHash,\n            targetRevisionId: appHead.headRevisionId,\n            repoFingerprint: binding.repoFingerprint ?? void 0,\n            remoteUrl: binding.remoteUrl ?? void 0,\n            defaultBranch: binding.defaultBranch ?? void 0\n          });\n          const bootstrapDelta = unwrapResponseObject(bootstrapResp, \"app delta\");\n          detected.metadataWarnings = Array.from(/* @__PURE__ */ new Set([...detected.metadataWarnings, ...bootstrapDelta.warnings]));\n          detected.warnings.push(...bootstrapDelta.warnings);\n          if (bootstrapDelta.status === \"conflict_risk\") {\n            detected.status = \"metadata_conflict\";\n            detected.repoState = \"metadata_conflict\";\n            detected.hint = bootstrapDelta.warnings.join(\"\\n\") || \"Run the command from the correct bound repository.\";\n            return detected;\n          }\n          if (bootstrapDelta.status === \"delta_ready\" || bootstrapDelta.status === \"up_to_date\") {\n            detected.repoState = \"server_only_changed\";\n            detected.hint = \"This checkout has not stored a local Remix baseline yet, but its current Git HEAD is already known to Remix. Pull the server delta locally to create the first baseline for this checkout.\";\n            return detected;\n          }\n        } catch {\n        }\n      }\n      detected.repoState = \"external_local_base_changed\";\n      detected.hint = ambiguousBaselineCandidateCount !== null ? `No local Remix revision baseline exists for this lane, and multiple compatible local baselines were found (${ambiguousBaselineCandidateCount}). Run \\`remix collab status\\` or sync this lane to seed an unambiguous baseline.` : \"No local Remix revision baseline exists for this lane yet. Run `remix collab init` or sync this lane to seed the baseline.\";\n      return detected;\n    }\n    const localHeadMovedSinceBaseline = Boolean(baseline.lastSeenLocalCommitHash) && localCommitHash !== baseline.lastSeenLocalCommitHash;\n    if (localHeadMovedSinceBaseline) {\n      detected.warnings.push(\n        \"Local Git HEAD changed since the last Remix baseline. Remix will use the current workspace snapshot to detect divergence.\"\n      );\n    }\n    const metadataCheck = unwrapResponseObject(parallelMetadataResp, \"app delta metadata\");\n    detected.metadataWarnings = metadataCheck.warnings;\n    detected.warnings.push(...metadataCheck.warnings);\n    if (metadataCheck.status === \"conflict_risk\") {\n      detected.status = \"metadata_conflict\";\n      detected.repoState = \"metadata_conflict\";\n      detected.hint = metadataCheck.warnings.join(\"\\n\") || \"Run the command from the correct bound repository.\";\n      return detected;\n    }\n    const localChanged = inspection.snapshotHash !== baseline.lastSnapshotHash;\n    const serverHeadChanged = appHead.headCommitHash !== baseline.lastServerHeadHash;\n    const revisionChanged = Boolean(\n      baseline.lastServerRevisionId && (appHead.headRevisionId ?? null) !== baseline.lastServerRevisionId\n    );\n    const equivalentRevisionDrift = revisionChanged && !serverHeadChanged;\n    if (equivalentRevisionDrift) {\n      const refreshedBaseline = await refreshEquivalentRevisionBaseline({\n        repoRoot,\n        binding,\n        baseline,\n        appHead\n      });\n      detected.baseline.lastServerRevisionId = refreshedBaseline.lastServerRevisionId;\n      detected.baseline.lastServerTreeHash = refreshedBaseline.lastServerTreeHash;\n      detected.baseline.lastServerHeadHash = refreshedBaseline.lastServerHeadHash;\n    }\n    const serverChanged = serverHeadChanged;\n    if (!localChanged && !serverChanged) {\n      detected.repoState = \"idle\";\n      return detected;\n    }\n    if (localChanged && !serverChanged) {\n      detected.repoState = \"local_only_changed\";\n      return detected;\n    }\n    if (!localChanged && serverChanged) {\n      detected.repoState = \"server_only_changed\";\n      detected.hint = \"The server lane advanced since the last agreed baseline. Pull the server delta locally before continuing.\";\n      return detected;\n    }\n    detected.repoState = \"both_changed\";\n    detected.hint = \"Both the local workspace and the server lane changed since the last agreed baseline. Replay or reconcile is required before normal recording continues.\";\n    return detected;\n  } catch (error) {\n    detected.status = \"remote_error\";\n    detected.hint = formatCliErrorDetail(error) ?? \"Failed to detect the current Remix repo state.\";\n    return detected;\n  }\n}\n\n// src/infrastructure/git/gitEventHarvester.ts\nvar GIT_TIMEOUT_MS = 1e4;\nvar GIT_MAX_BUFFER = 64 * 1024 * 1024;\nvar MAX_COMMITS = 100;\nvar RECORD_SEPARATOR = \"\u001e\";\nvar FIELD_SEPARATOR = \"\u001f\";\nvar LOG_FORMAT = `${RECORD_SEPARATOR}%H${FIELD_SEPARATOR}%P${FIELD_SEPARATOR}%an${FIELD_SEPARATOR}%ae${FIELD_SEPARATOR}%cn${FIELD_SEPARATOR}%ce${FIELD_SEPARATOR}%aI${FIELD_SEPARATOR}%cI${FIELD_SEPARATOR}%s`;\nfunction buildGitEventStatusArgs() {\n  return [\"status\", \"--porcelain=v1\"];\n}\nfunction buildGitEventDiffNumstatArgs(params) {\n  if (params.kind === \"uncommitted\") {\n    return [\"diff\", \"--numstat\", \"HEAD\"];\n  }\n  return [\"diff\", \"--numstat\", \"--no-renames\", params.fromCommit, params.toCommit];\n}\nfunction buildGitEventReachabilityArgs(fromCommit, toCommit) {\n  return [\"merge-base\", \"--is-ancestor\", fromCommit, toCommit];\n}\nfunction buildGitEventLogArgs(fromCommit, toCommit) {\n  return [\n    \"log\",\n    \"--first-parent\",\n    \"-m\",\n    \"--numstat\",\n    \"--no-renames\",\n    `--format=${LOG_FORMAT}`,\n    `${fromCommit}..${toCommit}`\n  ];\n}\nfunction buildGitEventNameRevArgs(secondParent) {\n  return [\"name-rev\", \"--name-only\", \"--no-undefined\", secondParent];\n}\nfunction sanitizedEnv() {\n  const env = { ...process.env };\n  delete env.GIT_DIR;\n  delete env.GIT_WORK_TREE;\n  delete env.GIT_COMMON_DIR;\n  delete env.GIT_INDEX_FILE;\n  return env;\n}\nasync function runGitEvent(args, cwd, adapter = createSystemGitAdapter()) {\n  return adapter.run(\n    createGitCommandPlan({\n      args,\n      cwd,\n      env: sanitizedEnv(),\n      timeoutMs: GIT_TIMEOUT_MS,\n      maxBuffer: GIT_MAX_BUFFER\n    })\n  );\n}\nfunction parseNumstatLine(line) {\n  const tab1 = line.indexOf(\"\t\");\n  if (tab1 < 0) return null;\n  const tab2 = line.indexOf(\"\t\", tab1 + 1);\n  if (tab2 < 0) return null;\n  const addedRaw = line.slice(0, tab1);\n  const removedRaw = line.slice(tab1 + 1, tab2);\n  const filePath = line.slice(tab2 + 1);\n  if (!filePath) return null;\n  const added = addedRaw === \"-\" ? 0 : Number.parseInt(addedRaw, 10);\n  const removed = removedRaw === \"-\" ? 0 : Number.parseInt(removedRaw, 10);\n  return {\n    added: Number.isFinite(added) ? added : 0,\n    removed: Number.isFinite(removed) ? removed : 0,\n    path: filePath\n  };\n}\nfunction parseLogOutput(stdout) {\n  const records = [];\n  const parts = stdout.split(RECORD_SEPARATOR);\n  for (const part of parts) {\n    if (!part) continue;\n    const newlineIdx = part.indexOf(\"\\n\");\n    const metadataLine = newlineIdx === -1 ? part : part.slice(0, newlineIdx);\n    const rest = newlineIdx === -1 ? \"\" : part.slice(newlineIdx + 1);\n    const fields = metadataLine.split(FIELD_SEPARATOR);\n    if (fields.length < 9) continue;\n    const [hash, parentsField, authorName, authorEmail, committerName, committerEmail, authorDateIso, committerDateIso, subject] = fields;\n    const parents = parentsField ? parentsField.split(\" \").filter(Boolean) : [];\n    const commit = {\n      hash,\n      parents,\n      authorName,\n      authorEmail,\n      committerName,\n      committerEmail,\n      authorDateIso,\n      committerDateIso,\n      subject,\n      filesChanged: 0,\n      linesAdded: 0,\n      linesRemoved: 0\n    };\n    const touchedPaths = /* @__PURE__ */ new Set();\n    for (const rawLine of rest.split(\"\\n\")) {\n      if (!rawLine) continue;\n      const parsed = parseNumstatLine(rawLine);\n      if (!parsed) continue;\n      commit.linesAdded += parsed.added;\n      commit.linesRemoved += parsed.removed;\n      touchedPaths.add(parsed.path);\n    }\n    commit.filesChanged = touchedPaths.size;\n    records.push(commit);\n  }\n  return records;\n}\nfunction buildCommitEvent(raw) {\n  return {\n    hash: raw.hash,\n    shortHash: raw.hash.slice(0, 7),\n    isMerge: raw.parents.length >= 2,\n    parents: raw.parents,\n    author: { name: raw.authorName, email: raw.authorEmail },\n    committer: { name: raw.committerName, email: raw.committerEmail },\n    message: raw.subject,\n    timestamp: raw.authorDateIso,\n    filesChanged: raw.filesChanged,\n    linesAdded: raw.linesAdded,\n    linesRemoved: raw.linesRemoved\n  };\n}\nvar MERGE_BRANCH_REGEXES = [\n  /^Merge branch '([^']+)'(?: into .+)?$/,\n  /^Merge remote-tracking branch '([^']+)'(?: into .+)?$/,\n  /^Merge pull request #\\d+ from (\\S+)$/\n];\nfunction parseBranchFromMergeMessage(subject) {\n  for (const re of MERGE_BRANCH_REGEXES) {\n    const match = re.exec(subject);\n    if (!match) continue;\n    const raw = match[1];\n    if (!raw) continue;\n    return raw.startsWith(\"origin/\") ? raw.slice(\"origin/\".length) : raw;\n  }\n  return null;\n}\nasync function resolveBranchFromNameRev(secondParent, repoRoot, adapter) {\n  const res = await runGitEvent(\n    buildGitEventNameRevArgs(secondParent),\n    repoRoot,\n    adapter\n  );\n  if (res.exitCode !== 0 || res.timedOut) return null;\n  let name = res.stdout.trim();\n  if (!name) return null;\n  if (name.startsWith(\"remotes/origin/\")) name = name.slice(\"remotes/origin/\".length);\n  else if (name.startsWith(\"origin/\")) name = name.slice(\"origin/\".length);\n  if (name.includes(\"~\") || name.includes(\"^\") || name.startsWith(\"tags/\") || name === \"undefined\") return null;\n  return name;\n}\nfunction summarizePorcelainStatus(stdout) {\n  const summary = {\n    filesChanged: 0,\n    staged: 0,\n    unstaged: 0,\n    untracked: 0\n  };\n  const uniquePaths = /* @__PURE__ */ new Set();\n  for (const rawLine of stdout.split(\"\\n\")) {\n    if (!rawLine) continue;\n    if (rawLine.startsWith(\"??\")) {\n      summary.untracked += 1;\n      uniquePaths.add(rawLine.slice(3));\n      continue;\n    }\n    if (rawLine.length < 3) continue;\n    const indexCode = rawLine.charCodeAt(0);\n    const worktreeCode = rawLine.charCodeAt(1);\n    const indexCh = rawLine[0];\n    const worktreeCh = rawLine[1];\n    const pathPart = rawLine.slice(3);\n    if (indexCh !== \" \" && indexCode !== 63) summary.staged += 1;\n    if ((worktreeCh === \"M\" || worktreeCh === \"D\") && worktreeCode !== 63) summary.unstaged += 1;\n    uniquePaths.add(pathPart);\n  }\n  summary.filesChanged = uniquePaths.size;\n  return summary;\n}\nasync function collectUncommittedSummary(repoRoot, adapter) {\n  const summary = {\n    filesChanged: 0,\n    linesAdded: 0,\n    linesRemoved: 0,\n    staged: 0,\n    unstaged: 0,\n    untracked: 0\n  };\n  const statusRes = await runGitEvent(buildGitEventStatusArgs(), repoRoot, adapter);\n  if (statusRes.exitCode === 0 && !statusRes.timedOut) {\n    Object.assign(summary, summarizePorcelainStatus(statusRes.stdout));\n  }\n  const diffRes = await runGitEvent(buildGitEventDiffNumstatArgs({ kind: \"uncommitted\" }), repoRoot, adapter);\n  if (diffRes.exitCode === 0 && !diffRes.timedOut) {\n    for (const rawLine of diffRes.stdout.split(\"\\n\")) {\n      if (!rawLine) continue;\n      const parsed = parseNumstatLine(rawLine);\n      if (!parsed) continue;\n      summary.linesAdded += parsed.added;\n      summary.linesRemoved += parsed.removed;\n    }\n  }\n  return summary;\n}\nfunction buildEmptyPreTurnEvents(params) {\n  return {\n    commits: [],\n    merges: [],\n    uncommittedAtFinalize: params.uncommitted,\n    summary: {\n      totalCommits: 0,\n      totalMerges: 0,\n      totalFilesChanged: 0,\n      totalLinesAdded: 0,\n      totalLinesRemoved: 0,\n      elapsedMs: null,\n      truncated: false,\n      rewritten: params.rewritten\n    },\n    range: { fromCommit: params.fromCommit, toCommit: params.toCommit },\n    schemaVersion: 1\n  };\n}\nasync function collectPreTurnGitEvents(params) {\n  try {\n    const git = params.git ?? createSystemGitAdapter();\n    const uncommitted = await collectUncommittedSummary(params.repoRoot, git);\n    if (!params.fromCommit || params.fromCommit === params.toCommit) {\n      return buildEmptyPreTurnEvents({\n        fromCommit: params.fromCommit,\n        toCommit: params.toCommit,\n        uncommitted,\n        rewritten: false\n      });\n    }\n    const reachabilityRes = await runGitEvent(\n      buildGitEventReachabilityArgs(params.fromCommit, params.toCommit),\n      params.repoRoot,\n      git\n    );\n    if (reachabilityRes.timedOut) return null;\n    if (reachabilityRes.exitCode === 1) {\n      return buildEmptyPreTurnEvents({\n        fromCommit: null,\n        toCommit: params.toCommit,\n        uncommitted,\n        rewritten: true\n      });\n    }\n    if (reachabilityRes.exitCode !== 0) return null;\n    const logRes = await runGitEvent(\n      buildGitEventLogArgs(params.fromCommit, params.toCommit),\n      params.repoRoot,\n      git\n    );\n    if (logRes.timedOut || logRes.exitCode !== 0) return null;\n    const rawCommits = parseLogOutput(logRes.stdout);\n    const totalCommits = rawCommits.length;\n    const totalMerges = rawCommits.reduce((n, c) => n + (c.parents.length >= 2 ? 1 : 0), 0);\n    const ordered = [...rawCommits].reverse();\n    const truncated = ordered.length > MAX_COMMITS;\n    const kept = truncated ? ordered.slice(ordered.length - MAX_COMMITS) : ordered;\n    const commits = kept.map(buildCommitEvent);\n    const merges = [];\n    for (const raw of rawCommits) {\n      if (raw.parents.length < 2) continue;\n      const secondParent = raw.parents[1];\n      const fromBranchFromMessage = parseBranchFromMergeMessage(raw.subject);\n      const fromBranchFromNameRev = await resolveBranchFromNameRev(secondParent, params.repoRoot, git);\n      merges.push({\n        hash: raw.hash,\n        shortHash: raw.hash.slice(0, 7),\n        fromBranchFromMessage,\n        fromBranchFromNameRev,\n        fromCommit: secondParent,\n        filesChanged: raw.filesChanged,\n        linesAdded: raw.linesAdded,\n        linesRemoved: raw.linesRemoved,\n        message: raw.subject\n      });\n    }\n    let totalFilesChanged = 0;\n    let totalLinesAdded = 0;\n    let totalLinesRemoved = 0;\n    const diffRes = await runGitEvent(\n      buildGitEventDiffNumstatArgs({ kind: \"range\", fromCommit: params.fromCommit, toCommit: params.toCommit }),\n      params.repoRoot,\n      git\n    );\n    if (diffRes.exitCode === 0 && !diffRes.timedOut) {\n      const uniquePaths = /* @__PURE__ */ new Set();\n      for (const rawLine of diffRes.stdout.split(\"\\n\")) {\n        if (!rawLine) continue;\n        const parsed = parseNumstatLine(rawLine);\n        if (!parsed) continue;\n        uniquePaths.add(parsed.path);\n        totalLinesAdded += parsed.added;\n        totalLinesRemoved += parsed.removed;\n      }\n      totalFilesChanged = uniquePaths.size;\n    }\n    let elapsedMs = null;\n    if (rawCommits.length > 0) {\n      const committerTimes = rawCommits.map((c) => Date.parse(c.committerDateIso)).filter((t) => Number.isFinite(t));\n      if (committerTimes.length > 0) {\n        const min = Math.min(...committerTimes);\n        const max = Math.max(...committerTimes);\n        elapsedMs = max - min;\n      }\n    }\n    return {\n      // commits[] is a first-parent view: it contains the commits on the\n      // receiving branch plus merges as single entries. Commits that entered\n      // via merges are represented by the MergeEvent, not listed individually.\n      commits,\n      merges,\n      uncommittedAtFinalize: uncommitted,\n      summary: {\n        totalCommits,\n        totalMerges,\n        totalFilesChanged,\n        totalLinesAdded,\n        totalLinesRemoved,\n        elapsedMs,\n        truncated,\n        rewritten: false\n      },\n      range: { fromCommit: params.fromCommit, toCommit: params.toCommit },\n      schemaVersion: 1\n    };\n  } catch (err) {\n    console.warn(\n      `[remix-core] preTurnEvents harvester failed: ${err instanceof Error ? err.message : String(err)}`\n    );\n    return null;\n  }\n}\n\n// src/application/collab/jobRunner.ts\nasync function drainClaimedJobs(params) {\n  await params.prune();\n  const jobs = await params.list();\n  const results = [];\n  for (const listedJob of jobs) {\n    if (params.isTerminal(listedJob)) continue;\n    const claimed = await params.claim(listedJob);\n    if (!claimed) continue;\n    try {\n      const result = await params.process(claimed);\n      results.push(result);\n      await params.afterSuccess?.({ listedJob, job: claimed.job, result });\n    } catch (error) {\n      await claimed.release();\n      if (params.onError === \"throw\") throw error;\n    }\n  }\n  return results;\n}\n\n// src/application/collab/workflowState.ts\nfunction asyncJobWorkflowState(status) {\n  if (status === \"completed\" || status === \"failed\" || status === \"queued\") return status;\n  return \"processing\";\n}\nfunction planAsyncJobDrainTransition(job) {\n  const state = asyncJobWorkflowState(job.status);\n  if (state === \"completed\" || state === \"failed\") {\n    return { workflow: \"async_job_drain\", state, action: \"skip_terminal\", terminal: true };\n  }\n  return {\n    workflow: \"async_job_drain\",\n    state,\n    action: job.kind === \"init\" ? \"process_init\" : \"process_init_post\",\n    terminal: false\n  };\n}\nfunction planFinalizeQueueTransition(job) {\n  if (job.status === \"completed\" || job.status === \"failed\" && job.metadata.failureDisposition === \"terminal\") {\n    return { workflow: \"finalize\", state: job.status, action: \"skip_terminal\", terminal: true };\n  }\n  if (job.status === \"failed\") {\n    return { workflow: \"finalize\", state: \"retryable_failed\", action: \"claim_and_process\", terminal: false };\n  }\n  return { workflow: \"finalize\", state: job.status, action: \"claim_and_process\", terminal: false };\n}\nfunction planCheckoutWorkflowTransition(params) {\n  if (!params.appId?.trim()) {\n    return { workflow: \"checkout\", state: \"failed\", action: \"require_app\", terminal: true };\n  }\n  return { workflow: \"checkout\", state: \"selected\", action: \"checkout\", terminal: false };\n}\nfunction planApproveWorkflowTransition(params) {\n  if (params.mode === \"sync-target-repo\") {\n    return params.hasCwd ? { workflow: \"approve\", state: \"sync_target_repo\", action: \"sync_target_repo\", terminal: false } : { workflow: \"approve\", state: \"failed\", action: \"require_cwd\", terminal: true };\n  }\n  return { workflow: \"approve\", state: \"remote_only\", action: \"approve_remote\", terminal: false };\n}\nfunction planRequestMergeWorkflowTransition(params) {\n  if (!params.hasBinding) {\n    return { workflow: \"request_merge\", state: \"failed\", action: \"require_binding\", terminal: true };\n  }\n  if (params.hasPendingFinalize) {\n    return { workflow: \"request_merge\", state: \"pending_finalize\", action: \"require_finalize_drain\", terminal: true };\n  }\n  return { workflow: \"request_merge\", state: \"bound\", action: \"open_merge_request\", terminal: false };\n}\n\n// src/application/collab/finalizeQueueRunner.ts\nasync function drainPendingFinalizeQueueJobs(params) {\n  return drainClaimedJobs({\n    prune: prunePendingFinalizeJobs,\n    list: listPendingFinalizeJobs,\n    isTerminal: (job) => planFinalizeQueueTransition(job).terminal,\n    claim: (job) => claimPendingFinalizeJob(job.id),\n    process: (claimed) => params.processClaimedJob({\n      api: params.api,\n      job: claimed.job,\n      release: claimed.release\n    }),\n    afterSuccess: async ({ listedJob }) => {\n      await removePendingFinalizeJob(listedJob.id);\n    }\n  });\n}\n\n// src/application/collab/finalizeWorkspaceMetadata.ts\nfunction buildWorkspaceMetadata(params) {\n  const metadata = {\n    branch: params.branchName,\n    repoRoot: params.repoRoot,\n    remoteUrl: params.remoteUrl,\n    defaultBranch: params.defaultBranch,\n    recordingMode: \"boundary_delta\",\n    baselineSnapshotId: params.baselineSnapshotId,\n    currentSnapshotId: params.currentSnapshotId,\n    baselineServerRevisionId: params.baselineServerRevisionId ?? null,\n    baselineServerHeadHash: params.baselineServerHeadHash,\n    currentSnapshotHash: params.currentSnapshotHash,\n    localCommitHash: params.localCommitHash,\n    repoStateAtCapture: params.repoState,\n    replayedFromBaseHash: params.replayedFromBaseHash ?? null,\n    previousLocalCommitHash: params.previousLocalCommitHash ?? null\n  };\n  if (params.preTurnEvents) {\n    metadata.preTurnEvents = params.preTurnEvents;\n  }\n  if (params.turnUsage) {\n    metadata.turnUsage = params.turnUsage;\n  }\n  if (typeof params.promptedAt === \"string\" && params.promptedAt.trim()) {\n    metadata.promptedAt = params.promptedAt.trim();\n  }\n  return metadata;\n}\n\n// src/application/collab/finalizeDecision.ts\nvar FINALIZE_AUTO_TERMINAL_THRESHOLD = 5;\nvar FINALIZE_AUTO_TERMINAL_TOTAL_RETRY_THRESHOLD = 8;\nfunction classifyFinalizeError(error) {\n  const tagged = error;\n  return {\n    disposition: tagged.finalizeDisposition ?? \"retryable\",\n    reason: tagged.finalizeReason ?? \"unknown\",\n    message: error instanceof Error ? error.message : String(error)\n  };\n}\nfunction computeFailureEscalation(job, reason) {\n  const previousReason = job.metadata.consecutiveFailureReason;\n  const previousCountRaw = job.metadata.consecutiveFailures;\n  const previousCount = typeof previousCountRaw === \"number\" && Number.isFinite(previousCountRaw) && previousCountRaw > 0 ? Math.floor(previousCountRaw) : 0;\n  const previousTotalRaw = job.metadata.totalFailures;\n  const previousTotal = typeof previousTotalRaw === \"number\" && Number.isFinite(previousTotalRaw) && previousTotalRaw > 0 ? Math.floor(previousTotalRaw) : 0;\n  const sameReason = previousReason === reason;\n  const next = sameReason ? previousCount + 1 : 1;\n  const totalFailures = previousTotal + 1;\n  const consecutiveTripped = next >= FINALIZE_AUTO_TERMINAL_THRESHOLD;\n  const totalTripped = totalFailures >= FINALIZE_AUTO_TERMINAL_TOTAL_RETRY_THRESHOLD;\n  const escalationTrigger = consecutiveTripped ? \"consecutive_same_reason\" : totalTripped ? \"total_retries\" : \"none\";\n  return {\n    consecutiveFailures: next,\n    consecutiveFailureReason: reason,\n    totalFailures,\n    shouldEscalateToTerminal: consecutiveTripped || totalTripped,\n    escalationTrigger\n  };\n}\nfunction hasFinalizeBaselineDrifted(params) {\n  return params.liveSnapshotId !== params.jobSnapshotId || (params.jobServerRevisionId ? params.liveServerRevisionId !== params.jobServerRevisionId : false) || params.liveServerHeadHash !== params.jobServerHeadHash;\n}\nfunction canSalvageNoDiffFinalize(params) {\n  if (params.baselineDrifted && params.currentSnapshotHash !== params.liveBaselineSnapshotHash) return false;\n  return params.serverStillAtBaseline;\n}\nfunction classifyChangedFinalizeDrift(params) {\n  if (!params.baselineDrifted) return \"no_drift\";\n  return params.localBaselineAdvanced && params.serverHeadAdvanced ? \"consistent_advance\" : \"inconsistent_drift\";\n}\nfunction shouldReplayChangedFinalize(params) {\n  return params.currentServerHeadHash !== params.submissionBaseHeadHash || params.baselineDrifted;\n}\nfunction shouldAdoptExistingChangeStepBeforeReplay(params) {\n  return params.replayNeeded && Boolean(params.idempotencyKey?.trim());\n}\nfunction validateSucceededChangeStepForBaseline(params) {\n  const nextServerHeadHash = typeof params.headCommitHash === \"string\" ? params.headCommitHash.trim() : \"\";\n  if (!nextServerHeadHash) {\n    throw new RemixError(\"Backend returned a succeeded change step without a head commit hash.\", {\n      exitCode: 1,\n      hint: \"This is a backend invariant violation; retry will not help. Run `remix collab status` before trying again.\"\n    });\n  }\n  const nextServerRevisionId = typeof params.resultRevisionId === \"string\" ? params.resultRevisionId.trim() : \"\";\n  return {\n    nextServerHeadHash,\n    nextServerRevisionId: nextServerRevisionId || null,\n    needsFreshHeadVerification: !nextServerRevisionId\n  };\n}\n\n// src/infrastructure/collab/checkoutIdentityStore.ts\nimport { randomUUID as randomUUID4 } from \"crypto\";\nimport fs5 from \"fs/promises\";\nimport path6 from \"path\";\nfunction getCheckoutIdentityPath(params) {\n  return path6.join(getCollabStateRoot(), \"checkouts\", `${buildLaneStateKey(params)}.json`);\n}\nasync function getCheckoutIdentity(params) {\n  const filePath = getCheckoutIdentityPath(params);\n  try {\n    const raw = await fs5.readFile(filePath, \"utf8\");\n    const parsed = JSON.parse(raw);\n    const checkoutId = typeof parsed?.checkoutId === \"string\" ? parsed.checkoutId.trim() : \"\";\n    if (checkoutId) return checkoutId;\n  } catch {\n  }\n  const next = {\n    schemaVersion: 1,\n    checkoutId: randomUUID4(),\n    updatedAt: (/* @__PURE__ */ new Date()).toISOString()\n  };\n  await writeJsonAtomic(filePath, next);\n  return next.checkoutId;\n}\n\n// src/application/collab/localAlignmentReporting.ts\nfunction toCheckoutAction(action) {\n  if (action === \"pull\" || action === \"reconcile\" || action === \"await_finalize\" || action === \"record\") return action;\n  return \"no_action\";\n}\nfunction actionForRepoState(repoState) {\n  if (repoState === \"server_only_changed\") return \"pull\";\n  if (repoState === \"both_changed\" || repoState === \"external_local_base_changed\" || repoState === \"baseline_missing\") {\n    return \"reconcile\";\n  }\n  if (repoState === \"local_only_changed\") return \"record\";\n  return \"no_action\";\n}\nfunction alignmentRequiredForAction(action) {\n  if (action === \"pull\") return \"sync\";\n  if (action === \"reconcile\") return \"reconcile\";\n  if (action === \"await_finalize\") return \"finalize\";\n  if (action === \"record\") return \"record\";\n  return void 0;\n}\nasync function reportCheckoutState(params) {\n  try {\n    const checkoutId = await getCheckoutIdentity({\n      repoRoot: params.repoRoot,\n      repoFingerprint: params.repoFingerprint ?? null,\n      laneId: params.laneId ?? null\n    });\n    await params.api.reportLocalCheckoutState(params.appId, {\n      checkoutId,\n      collabLaneId: params.laneId ?? void 0,\n      branch: params.branch ?? void 0,\n      repoFingerprint: params.repoFingerprint ?? void 0,\n      localState: params.localState ?? void 0,\n      recommendedAction: params.recommendedAction,\n      materializationStatus: params.materializationStatus ?? void 0,\n      alignmentRequired: params.alignmentRequired ?? alignmentRequiredForAction(params.recommendedAction),\n      baselineRevisionId: params.baselineRevisionId,\n      localRevisionId: params.localRevisionId,\n      serverRevisionId: params.serverRevisionId,\n      localHeadHash: params.localHeadHash ?? void 0,\n      serverHeadCommitId: params.serverHeadCommitId,\n      serverHeadHash: params.serverHeadHash ?? void 0,\n      hasLocalChanges: params.hasLocalChanges,\n      hasUnrecordedChanges: params.hasUnrecordedChanges,\n      pendingFinalizeCount: params.pendingFinalizeCount,\n      metadata: params.metadata\n    });\n    return { warnings: [] };\n  } catch (err) {\n    const message = err instanceof Error ? err.message : String(err ?? \"unknown error\");\n    return { warnings: [`Failed to report local checkout state: ${message}`] };\n  }\n}\nasync function reportCheckoutStateFromStatus(params) {\n  const { api, status } = params;\n  const repoRoot = status.repo.repoRoot;\n  const appId = status.binding.currentAppId;\n  if (!api || !repoRoot || !appId) return { warnings: [] };\n  return reportCheckoutState({\n    api,\n    appId,\n    repoRoot,\n    repoFingerprint: status.binding.repoFingerprint,\n    laneId: status.binding.laneId,\n    branch: status.repo.branch ?? status.binding.branchName,\n    localState: status.alignment.repoState,\n    recommendedAction: toCheckoutAction(status.recommendedAction),\n    materializationStatus: status.alignment.checked ? \"checked\" : void 0,\n    baselineRevisionId: status.alignment.baseline.lastServerRevisionId,\n    serverRevisionId: status.alignment.current.serverRevisionId,\n    localHeadHash: status.alignment.current.localCommitHash ?? status.repo.headCommitHash,\n    serverHeadCommitId: status.alignment.current.serverHeadCommitId,\n    serverHeadHash: status.alignment.current.serverHeadHash,\n    hasLocalChanges: status.alignment.repoState === \"local_only_changed\" || status.alignment.repoState === \"both_changed\",\n    hasUnrecordedChanges: status.alignment.repoState === \"local_only_changed\" || status.alignment.repoState === \"both_changed\",\n    pendingFinalizeCount: status.alignment.pendingFinalize.activeJobCount,\n    metadata: {\n      source: params.source,\n      branchMismatch: status.repo.branchMismatch\n    }\n  });\n}\nasync function reportAlignedCheckoutState(params) {\n  return reportCheckoutState({\n    api: params.api,\n    appId: params.appId,\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    branch: params.branch,\n    localState: \"idle\",\n    recommendedAction: \"no_action\",\n    materializationStatus: \"applied\",\n    baselineRevisionId: params.baselineRevisionId,\n    serverRevisionId: params.serverRevisionId,\n    localHeadHash: params.localHeadHash,\n    serverHeadCommitId: params.serverHeadCommitId,\n    serverHeadHash: params.serverHeadHash,\n    hasLocalChanges: false,\n    hasUnrecordedChanges: false,\n    pendingFinalizeCount: 0,\n    metadata: { source: params.source }\n  });\n}\nasync function reportCheckoutStateFromFinalize(params) {\n  const recommendedAction = params.materializationStatus.startsWith(\"queued\") ? \"await_finalize\" : actionForRepoState(params.repoState);\n  const hasLocalChanges = params.repoState === \"local_only_changed\" || params.repoState === \"both_changed\";\n  return reportCheckoutState({\n    api: params.api,\n    appId: params.appId,\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    branch: params.branch,\n    localState: params.repoState,\n    recommendedAction,\n    materializationStatus: params.materializationStatus,\n    alignmentRequired: params.alignmentRequired,\n    baselineRevisionId: params.baselineRevisionId,\n    serverRevisionId: params.serverRevisionId,\n    localHeadHash: params.localHeadHash,\n    serverHeadCommitId: params.serverHeadCommitId,\n    serverHeadHash: params.serverHeadHash,\n    hasLocalChanges,\n    hasUnrecordedChanges: recommendedAction === \"record\" || recommendedAction === \"reconcile\",\n    pendingFinalizeCount: params.pendingFinalizeCount,\n    metadata: { source: params.source }\n  });\n}\nasync function recordLocalAlignmentEvent(params) {\n  try {\n    await params.api.recordLocalAlignmentEvent(params.appId, {\n      eventKind: params.eventKind,\n      branch: params.branch,\n      collabLaneId: params.collabLaneId ?? void 0,\n      baseRevisionId: params.baseRevisionId,\n      targetRevisionId: params.targetRevisionId,\n      resultRevisionId: params.resultRevisionId,\n      baseHeadHash: params.baseHeadHash ?? void 0,\n      targetHeadCommitId: params.targetHeadCommitId,\n      targetHeadHash: params.targetHeadHash ?? void 0,\n      resultHeadHash: params.resultHeadHash ?? void 0,\n      changedFilesCount: params.changedFilesCount,\n      insertions: params.insertions,\n      deletions: params.deletions,\n      localCommitCount: params.localCommitCount,\n      summary: params.summary,\n      idempotencyKey: params.idempotencyKey,\n      metadata: { source: params.eventKind }\n    });\n    return { warnings: [] };\n  } catch (err) {\n    const message = err instanceof Error ? err.message : String(err ?? \"unknown error\");\n    return { warnings: [`Failed to record local alignment event: ${message}`] };\n  }\n}\n\n// src/application/collab/collabFinalizeProcessing.ts\nvar FINALIZE_RETRY_BASE_DELAY_MS = 15e3;\nvar FINALIZE_RETRY_MAX_DELAY_MS = 5 * 60 * 1e3;\nvar FINALIZE_JOB_PROCESSING_TIMEOUT_MS_DEFAULT = 90 * 1e3;\nvar finalizeJobProcessingTimeoutMs = FINALIZE_JOB_PROCESSING_TIMEOUT_MS_DEFAULT;\nvar FINALIZE_LOCK_HEARTBEAT_MS = Math.max(15e3, Math.floor(FINALIZE_JOB_LOCK_STALE_MS / 3));\nfunction readMetadataString(job, key) {\n  const value = job.metadata[key];\n  return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\nfunction readMetadataActor(job) {\n  const actor = job.metadata.actor;\n  return actor && typeof actor === \"object\" ? actor : void 0;\n}\nfunction readMetadataTurnUsage(job) {\n  const value = job.metadata.turnUsage;\n  return value && typeof value === \"object\" ? value : null;\n}\nfunction buildNextRetryAt(retryCount) {\n  const exponent = Math.max(0, retryCount - 1);\n  const delayMs = Math.min(FINALIZE_RETRY_BASE_DELAY_MS * 2 ** exponent, FINALIZE_RETRY_MAX_DELAY_MS);\n  return new Date(Date.now() + delayMs).toISOString();\n}\nfunction buildFinalizeCliError(params) {\n  const error = new RemixError(params.message, {\n    exitCode: params.exitCode,\n    hint: params.hint\n  });\n  error.finalizeDisposition = params.disposition;\n  error.finalizeReason = params.reason;\n  return error;\n}\nfunction runWithFinalizeTimeout(work, jobId) {\n  let timer;\n  const cap = finalizeJobProcessingTimeoutMs;\n  const timeout = new Promise((_, reject) => {\n    timer = setTimeout(() => {\n      reject(\n        buildFinalizeCliError({\n          message: `Finalize job ${jobId} exceeded the ${Math.round(\n            cap / 1e3\n          )}s drainer wall-clock timeout. The slow request will be retried by a future drainer pass.`,\n          exitCode: 1,\n          hint: \"If this keeps recurring, run `remix collab finalize-queue list` to inspect the job, then `remix collab finalize-queue forget <id>` to drop it manually.\",\n          disposition: \"retryable\",\n          reason: \"processing_timeout\"\n        })\n      );\n    }, cap);\n    timer.unref?.();\n  });\n  return Promise.race([work, timeout]).finally(() => {\n    if (timer) clearTimeout(timer);\n  });\n}\nfunction startLockHeartbeat(jobId) {\n  const handle = setInterval(() => {\n    void heartbeatJobLock(jobId);\n  }, FINALIZE_LOCK_HEARTBEAT_MS);\n  handle.unref?.();\n  return () => clearInterval(handle);\n}\nasync function findExistingChangeStepByIdempotency(params) {\n  const idempotencyKey = params.idempotencyKey?.trim();\n  if (!idempotencyKey) return null;\n  const resp = await params.api.listChangeSteps(params.appId, { limit: 1, idempotencyKey });\n  const responseObject = unwrapResponseObject(\n    resp,\n    \"change step list\"\n  );\n  const steps = Array.isArray(responseObject) ? responseObject : Array.isArray(responseObject.items) ? responseObject.items : [];\n  return steps.find((step) => step.idempotencyKey === idempotencyKey) ?? null;\n}\nasync function writeBaselineFromSucceededChangeStep(params) {\n  let baselineAdvance;\n  try {\n    baselineAdvance = validateSucceededChangeStepForBaseline({\n      headCommitHash: params.changeStep.headCommitHash,\n      resultRevisionId: params.changeStep.resultRevisionId\n    });\n  } catch (error) {\n    if (error instanceof RemixError) {\n      throw buildFinalizeCliError({\n        message: error.message,\n        exitCode: error.exitCode,\n        hint: error.hint ?? void 0,\n        disposition: \"terminal\",\n        reason: \"missing_head_commit_hash\"\n      });\n    }\n    throw error;\n  }\n  const nextServerHeadHash = baselineAdvance.nextServerHeadHash;\n  let nextServerRevisionId = baselineAdvance.nextServerRevisionId ?? \"\";\n  let nextServerTreeHash = null;\n  if (baselineAdvance.needsFreshHeadVerification) {\n    const freshHeadResp = await params.api.getAppHead(params.job.currentAppId);\n    const freshHead = unwrapResponseObject(freshHeadResp, \"app head\");\n    if (freshHead.headCommitHash !== nextServerHeadHash || !freshHead.headRevisionId) {\n      throw buildFinalizeCliError({\n        message: \"Backend returned a succeeded change step without a matching result revision.\",\n        exitCode: 1,\n        hint: \"The local baseline was not advanced because the post-step revision could not be verified. Restart the backend/CLI and retry after checking `remix collab status`.\",\n        disposition: \"terminal\",\n        reason: \"missing_result_revision_id\"\n      });\n    }\n    nextServerRevisionId = freshHead.headRevisionId;\n    nextServerTreeHash = freshHead.treeHash ?? null;\n  }\n  await writeLocalBaseline({\n    repoRoot: params.job.repoRoot,\n    repoFingerprint: params.job.repoFingerprint,\n    laneId: params.job.laneId,\n    currentAppId: params.job.currentAppId,\n    branchName: params.job.branchName,\n    lastSnapshotId: params.snapshot.id,\n    lastSnapshotHash: params.snapshot.snapshotHash,\n    lastServerRevisionId: nextServerRevisionId,\n    lastServerTreeHash: nextServerTreeHash,\n    lastServerHeadHash: nextServerHeadHash,\n    lastSeenLocalCommitHash: params.snapshot.localCommitHash\n  });\n}\nasync function reportCompletedFinalizeCheckoutState(params) {\n  const result = await reportAlignedCheckoutState({\n    api: params.api,\n    appId: params.job.currentAppId,\n    repoRoot: params.job.repoRoot,\n    repoFingerprint: params.job.repoFingerprint,\n    laneId: params.job.laneId,\n    branch: params.job.branchName,\n    baselineRevisionId: params.serverRevisionId,\n    serverRevisionId: params.serverRevisionId,\n    localHeadHash: params.snapshot.localCommitHash,\n    serverHeadCommitId: params.serverHeadCommitId,\n    serverHeadHash: params.serverHeadHash,\n    source: params.source\n  });\n  return result.warnings;\n}\nasync function harvestPreTurnEvents(repoRoot, fromCommit, toCommit) {\n  if (!toCommit) return null;\n  try {\n    return await collectPreTurnGitEvents({ repoRoot, fromCommit, toCommit });\n  } catch (err) {\n    console.warn(\n      `[remix-core] preTurnEvents harvester threw: ${err instanceof Error ? err.message : String(err)}`\n    );\n    return null;\n  }\n}\nasync function processClaimedPendingFinalizeJob(params) {\n  const job = params.job;\n  const stopHeartbeat = startLockHeartbeat(job.id);\n  try {\n    return await runWithFinalizeTimeout(processClaimedPendingFinalizeJobInner(params), job.id);\n  } catch (error) {\n    const classified = classifyFinalizeError(error);\n    const escalation = computeFailureEscalation(job, classified.reason);\n    const finalDisposition = classified.disposition === \"terminal\" || escalation.shouldEscalateToTerminal ? \"terminal\" : \"retryable\";\n    const autoEscalated = finalDisposition === \"terminal\" && escalation.shouldEscalateToTerminal && classified.disposition !== \"terminal\";\n    let escalationSuffix = \"\";\n    if (autoEscalated) {\n      if (escalation.escalationTrigger === \"consecutive_same_reason\") {\n        escalationSuffix = ` (auto-escalated to terminal after ${escalation.consecutiveFailures} consecutive ${classified.reason} failures)`;\n      } else if (escalation.escalationTrigger === \"total_retries\") {\n        escalationSuffix = ` (auto-escalated to terminal after ${escalation.totalFailures} total retries with mixed failure reasons; latest=${classified.reason})`;\n      }\n    }\n    await updatePendingFinalizeJob(job.id, {\n      status: finalDisposition === \"terminal\" ? \"failed\" : \"queued\",\n      error: `${classified.message}${escalationSuffix}`,\n      nextRetryAt: finalDisposition === \"terminal\" ? null : buildNextRetryAt(job.retryCount),\n      metadata: {\n        failureDisposition: finalDisposition,\n        failureReason: classified.reason,\n        consecutiveFailures: escalation.consecutiveFailures,\n        consecutiveFailureReason: escalation.consecutiveFailureReason,\n        totalFailures: escalation.totalFailures\n      }\n    });\n    throw error;\n  } finally {\n    stopHeartbeat();\n    await params.release();\n  }\n}\nasync function processClaimedPendingFinalizeJobInner(params) {\n  const job = params.job;\n  const [snapshot, baseline, appHeadResp] = await Promise.all([\n    readLocalSnapshot(job.currentSnapshotId),\n    readLocalBaseline({\n      repoFingerprint: job.repoFingerprint,\n      laneId: job.laneId,\n      repoRoot: job.repoRoot\n    }),\n    getAppHeadCached(params.api, job.currentAppId)\n  ]);\n  if (!snapshot) {\n    throw buildFinalizeCliError({\n      message: \"Captured snapshot is missing from the local snapshot store.\",\n      exitCode: 1,\n      disposition: \"terminal\",\n      reason: \"snapshot_missing\"\n    });\n  }\n  if (!baseline) {\n    throw buildFinalizeCliError({\n      message: \"Local baseline is missing for this queued finalize job.\",\n      exitCode: 2,\n      hint: \"Run `remix collab init` to seed this checkout's revision baseline.\",\n      disposition: \"terminal\",\n      reason: \"baseline_missing\"\n    });\n  }\n  const baselineDrifted = hasFinalizeBaselineDrifted({\n    liveSnapshotId: baseline.lastSnapshotId,\n    jobSnapshotId: job.baselineSnapshotId,\n    liveServerRevisionId: baseline.lastServerRevisionId,\n    jobServerRevisionId: job.baselineServerRevisionId,\n    liveServerHeadHash: baseline.lastServerHeadHash,\n    jobServerHeadHash: job.baselineServerHeadHash\n  });\n  const appHead = unwrapResponseObject(appHeadResp, \"app head\");\n  const remoteUrl = readMetadataString(job, \"remoteUrl\");\n  const defaultBranch = readMetadataString(job, \"defaultBranch\");\n  const repoState = readMetadataString(job, \"repoState\");\n  const actor = readMetadataActor(job);\n  const turnUsage = readMetadataTurnUsage(job);\n  const promptedAt = readMetadataString(job, \"promptedAt\");\n  const previousLocalCommitHash = baseline.lastSeenLocalCommitHash ?? null;\n  const preTurnEvents = await harvestPreTurnEvents(\n    job.repoRoot,\n    previousLocalCommitHash,\n    snapshot.localCommitHash\n  );\n  const diffResult = await diffLocalSnapshots({\n    baseSnapshotId: job.baselineSnapshotId,\n    targetSnapshotId: job.currentSnapshotId\n  });\n  if (!diffResult.diff.trim()) {\n    const serverStillAtBaseline = job.baselineServerRevisionId ? appHead.headRevisionId === job.baselineServerRevisionId : appHead.headCommitHash === job.baselineServerHeadHash;\n    if (baselineDrifted && !canSalvageNoDiffFinalize({\n      baselineDrifted,\n      currentSnapshotHash: snapshot.snapshotHash,\n      liveBaselineSnapshotHash: baseline.lastSnapshotHash,\n      serverStillAtBaseline: true\n    })) {\n      throw buildFinalizeCliError({\n        message: \"Finalize queue baseline drifted before this job was processed.\",\n        exitCode: 1,\n        hint: \"Process queued finalize jobs in capture order, or run `remix collab init` to refresh the revision baseline before retrying.\",\n        disposition: \"terminal\",\n        reason: \"baseline_drifted\"\n      });\n    }\n    if (!canSalvageNoDiffFinalize({ baselineDrifted: false, currentSnapshotHash: \"\", liveBaselineSnapshotHash: \"\", serverStillAtBaseline })) {\n      throw buildFinalizeCliError({\n        message: \"Server lane changed before a no-diff turn could be recorded.\",\n        exitCode: 2,\n        hint: \"Pull the server changes locally before recording another no-diff turn.\",\n        disposition: \"terminal\",\n        reason: \"server_lane_changed\"\n      });\n    }\n    const collabTurnResp = await params.api.createCollabTurn(job.currentAppId, {\n      threadId: job.threadId ?? void 0,\n      collabLaneId: job.laneId ?? void 0,\n      prompt: job.prompt,\n      assistantResponse: job.assistantResponse,\n      actor,\n      sourceConversation: job.sourceConversation ?? void 0,\n      workspaceMetadata: buildWorkspaceMetadata({\n        repoRoot: job.repoRoot,\n        branchName: job.branchName,\n        remoteUrl,\n        defaultBranch,\n        baselineSnapshotId: job.baselineSnapshotId,\n        currentSnapshotId: job.currentSnapshotId,\n        baselineServerRevisionId: job.baselineServerRevisionId,\n        baselineServerHeadHash: job.baselineServerHeadHash,\n        currentSnapshotHash: snapshot.snapshotHash,\n        localCommitHash: snapshot.localCommitHash,\n        repoState,\n        previousLocalCommitHash,\n        preTurnEvents,\n        turnUsage,\n        promptedAt\n      }),\n      idempotencyKey: job.idempotencyKey ?? void 0\n    });\n    const collabTurn = unwrapResponseObject(collabTurnResp, \"collab turn\");\n    await writeLocalBaseline({\n      repoRoot: job.repoRoot,\n      repoFingerprint: job.repoFingerprint,\n      laneId: job.laneId,\n      currentAppId: job.currentAppId,\n      branchName: job.branchName,\n      lastSnapshotId: snapshot.id,\n      lastSnapshotHash: snapshot.snapshotHash,\n      lastServerRevisionId: appHead.headRevisionId ?? null,\n      lastServerTreeHash: appHead.treeHash ?? null,\n      lastServerHeadHash: appHead.headCommitHash,\n      lastSeenLocalCommitHash: snapshot.localCommitHash\n    });\n    await updatePendingFinalizeJob(job.id, {\n      status: \"completed\",\n      metadata: { collabTurnId: collabTurn.id }\n    });\n    const reportWarnings2 = await reportCompletedFinalizeCheckoutState({\n      api: params.api,\n      job,\n      snapshot,\n      serverRevisionId: appHead.headRevisionId ?? null,\n      serverHeadCommitId: appHead.headCommitId,\n      serverHeadHash: appHead.headCommitHash,\n      source: \"finalize_no_diff_turn\"\n    });\n    return {\n      mode: \"no_diff_turn\",\n      idempotencyKey: job.idempotencyKey ?? \"\",\n      queued: false,\n      jobId: job.id,\n      repoState,\n      changeStep: null,\n      collabTurn,\n      autoSync: null,\n      warnings: reportWarnings2\n    };\n  }\n  const localBaselineAdvanced = baseline.lastSnapshotId !== job.baselineSnapshotId;\n  const serverHeadAdvanced = job.baselineServerRevisionId ? appHead.headRevisionId !== job.baselineServerRevisionId : appHead.headCommitHash !== job.baselineServerHeadHash;\n  const changedDrift = classifyChangedFinalizeDrift({ baselineDrifted, localBaselineAdvanced, serverHeadAdvanced });\n  if (changedDrift !== \"no_drift\") {\n    if (changedDrift === \"inconsistent_drift\") {\n      throw buildFinalizeCliError({\n        message: `Finalize queue baseline advanced inconsistently before this job was processed (localBaselineAdvanced=${localBaselineAdvanced}, serverHeadAdvanced=${serverHeadAdvanced}, jobBaselineSnapshotId=${job.baselineSnapshotId ?? \"null\"}, liveBaselineSnapshotId=${baseline.lastSnapshotId ?? \"null\"}, jobBaselineServerHeadHash=${job.baselineServerHeadHash ?? \"null\"}, liveBaselineServerHeadHash=${baseline.lastServerHeadHash ?? \"null\"}, currentAppHeadHash=${appHead.headCommitHash}). This indicates local Remix state diverged from the backend in a way that should not be reachable in normal operation; please report this as a bug.`,\n        exitCode: 1,\n        hint: \"Run `remix collab status` to inspect, then sync or reconcile before retrying.\",\n        disposition: \"terminal\",\n        reason: \"baseline_drifted\"\n      });\n    }\n  }\n  let submissionDiff = diffResult.diff;\n  let submissionBaseHeadHash = job.baselineServerHeadHash;\n  let submissionBaseRevisionId = job.baselineServerRevisionId;\n  let replayedFromBaseHash = null;\n  if (!submissionBaseHeadHash) {\n    throw buildFinalizeCliError({\n      message: \"Baseline server head is missing for this finalize job.\",\n      exitCode: 1,\n      disposition: \"terminal\",\n      reason: \"baseline_server_head_missing\"\n    });\n  }\n  const replayNeeded = shouldReplayChangedFinalize({\n    currentServerHeadHash: appHead.headCommitHash,\n    submissionBaseHeadHash,\n    baselineDrifted\n  });\n  if (shouldAdoptExistingChangeStepBeforeReplay({ replayNeeded, idempotencyKey: job.idempotencyKey })) {\n    const existingChangeStep = await findExistingChangeStepByIdempotency({\n      api: params.api,\n      appId: job.currentAppId,\n      idempotencyKey: job.idempotencyKey\n    });\n    if (existingChangeStep) {\n      const changeStep2 = existingChangeStep.status === \"succeeded\" ? existingChangeStep : await pollChangeStep(params.api, job.currentAppId, existingChangeStep.id);\n      invalidateAppHeadCache(job.currentAppId);\n      invalidateAppDeltaCacheForApp(job.currentAppId);\n      await writeBaselineFromSucceededChangeStep({ api: params.api, job, snapshot, changeStep: changeStep2 });\n      await updatePendingFinalizeJob(job.id, {\n        status: \"completed\",\n        metadata: {\n          changeStepId: String(changeStep2.id ?? \"\")\n        }\n      });\n      const reportWarnings2 = await reportCompletedFinalizeCheckoutState({\n        api: params.api,\n        job,\n        snapshot,\n        serverRevisionId: String(changeStep2.resultRevisionId ?? \"\") || null,\n        serverHeadCommitId: String(changeStep2.commitId ?? \"\") || null,\n        serverHeadHash: String(changeStep2.headCommitHash ?? \"\") || null,\n        source: \"finalize_changed_turn\"\n      });\n      return {\n        mode: \"changed_turn\",\n        idempotencyKey: job.idempotencyKey ?? \"\",\n        queued: false,\n        jobId: job.id,\n        repoState,\n        changeStep: changeStep2,\n        collabTurn: null,\n        autoSync: null,\n        warnings: reportWarnings2\n      };\n    }\n  }\n  if (replayNeeded) {\n    try {\n      const replayResp = await params.api.startChangeStepReplay(job.currentAppId, {\n        prompt: job.prompt,\n        assistantResponse: job.assistantResponse,\n        diff: diffResult.diff,\n        baseCommitHash: submissionBaseHeadHash,\n        baseRevisionId: job.baselineServerRevisionId,\n        targetHeadCommitHash: appHead.headCommitHash,\n        targetRevisionId: appHead.headRevisionId,\n        expectedPaths: diffResult.changedPaths,\n        actor,\n        workspaceMetadata: buildWorkspaceMetadata({\n          repoRoot: job.repoRoot,\n          branchName: job.branchName,\n          remoteUrl,\n          defaultBranch,\n          baselineSnapshotId: job.baselineSnapshotId,\n          currentSnapshotId: job.currentSnapshotId,\n          baselineServerRevisionId: job.baselineServerRevisionId,\n          baselineServerHeadHash: job.baselineServerHeadHash,\n          currentSnapshotHash: snapshot.snapshotHash,\n          localCommitHash: snapshot.localCommitHash,\n          repoState,\n          previousLocalCommitHash,\n          preTurnEvents,\n          turnUsage,\n          promptedAt\n        }),\n        idempotencyKey: buildDeterministicIdempotencyKey({\n          kind: \"collab_finalize_turn_replay_v1\",\n          appId: job.currentAppId,\n          baseCommitHash: submissionBaseHeadHash,\n          targetHeadCommitHash: appHead.headCommitHash,\n          currentSnapshotId: job.currentSnapshotId,\n          diffSha256: diffResult.diffSha256\n        })\n      });\n      const replayStart = unwrapResponseObject(replayResp, \"change step replay\");\n      const replay = await pollChangeStepReplay(params.api, job.currentAppId, String(replayStart.id));\n      const replayDiffResp = await params.api.getChangeStepReplayDiff(job.currentAppId, replay.id);\n      const replayDiff = unwrapResponseObject(replayDiffResp, \"change step replay diff\");\n      submissionDiff = replayDiff.diff;\n      replayedFromBaseHash = submissionBaseHeadHash;\n      submissionBaseHeadHash = appHead.headCommitHash;\n      submissionBaseRevisionId = appHead.headRevisionId;\n    } catch (error) {\n      if (error instanceof RemixError && error.finalizeDisposition === void 0) {\n        const detail = error.hint ? `${error.message} (${error.hint})` : error.message;\n        throw buildFinalizeCliError({\n          message: \"Server-side replay could not adapt the captured diff to the current server head: \" + detail,\n          exitCode: 1,\n          hint: error.hint ?? void 0,\n          disposition: \"terminal\",\n          reason: \"replay_unrecoverable\"\n        });\n      }\n      throw error;\n    }\n  }\n  const changeStepResp = await params.api.createChangeStep(job.currentAppId, {\n    threadId: job.threadId ?? void 0,\n    collabLaneId: job.laneId ?? void 0,\n    prompt: job.prompt,\n    assistantResponse: job.assistantResponse,\n    diff: submissionDiff,\n    baseCommitHash: submissionBaseHeadHash,\n    baseRevisionId: submissionBaseRevisionId,\n    headCommitHash: submissionBaseHeadHash,\n    changedFilesCount: diffResult.stats.changedFilesCount,\n    insertions: diffResult.stats.insertions,\n    deletions: diffResult.stats.deletions,\n    actor,\n    sourceConversation: job.sourceConversation ?? void 0,\n    workspaceMetadata: buildWorkspaceMetadata({\n      repoRoot: job.repoRoot,\n      branchName: job.branchName,\n      remoteUrl,\n      defaultBranch,\n      baselineSnapshotId: job.baselineSnapshotId,\n      currentSnapshotId: job.currentSnapshotId,\n      baselineServerRevisionId: job.baselineServerRevisionId,\n      baselineServerHeadHash: job.baselineServerHeadHash,\n      currentSnapshotHash: snapshot.snapshotHash,\n      localCommitHash: snapshot.localCommitHash,\n      repoState,\n      replayedFromBaseHash,\n      previousLocalCommitHash,\n      preTurnEvents,\n      turnUsage,\n      promptedAt\n    }),\n    idempotencyKey: job.idempotencyKey ?? void 0\n  });\n  const createdStep = unwrapResponseObject(changeStepResp, \"change step\");\n  const changeStep = await pollChangeStep(params.api, job.currentAppId, String(createdStep.id));\n  invalidateAppHeadCache(job.currentAppId);\n  invalidateAppDeltaCacheForApp(job.currentAppId);\n  await writeBaselineFromSucceededChangeStep({ api: params.api, job, snapshot, changeStep });\n  await updatePendingFinalizeJob(job.id, {\n    status: \"completed\",\n    metadata: {\n      changeStepId: String(changeStep.id ?? \"\")\n    }\n  });\n  const reportWarnings = await reportCompletedFinalizeCheckoutState({\n    api: params.api,\n    job,\n    snapshot,\n    serverRevisionId: String(changeStep.resultRevisionId ?? \"\") || null,\n    serverHeadCommitId: String(changeStep.commitId ?? \"\") || null,\n    serverHeadHash: String(changeStep.headCommitHash ?? \"\") || null,\n    source: \"finalize_changed_turn\"\n  });\n  return {\n    mode: \"changed_turn\",\n    idempotencyKey: job.idempotencyKey ?? \"\",\n    queued: false,\n    jobId: job.id,\n    repoState,\n    changeStep,\n    collabTurn: null,\n    autoSync: null,\n    warnings: reportWarnings\n  };\n}\nasync function processPendingFinalizeJob(params) {\n  const claimed = await claimPendingFinalizeJob(params.jobId);\n  if (!claimed) {\n    const job = await readPendingFinalizeJob(params.jobId);\n    if (job?.status === \"processing\") {\n      throw new RemixError(\"Finalize job is already being processed.\", { exitCode: 1 });\n    }\n    if (job?.status === \"failed\") {\n      throw new RemixError(\"Finalize job failed permanently and will not retry automatically.\", {\n        exitCode: 1,\n        hint: job.error ?? \"Review the local finalize queue and record a fresh Remix turn if needed.\"\n      });\n    }\n    throw new RemixError(\"Finalize job was not found.\", { exitCode: 1 });\n  }\n  return processClaimedPendingFinalizeJob({ api: params.api, job: claimed.job, release: claimed.release });\n}\nasync function enqueueCapturedFinalizeTurn(params) {\n  return enqueuePendingFinalizeJob({\n    status: \"queued\",\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    currentAppId: params.currentAppId,\n    laneId: params.laneId,\n    threadId: params.threadId,\n    sourceConversation: params.sourceConversation ?? null,\n    branchName: params.branchName,\n    prompt: params.prompt,\n    assistantResponse: params.assistantResponse,\n    baselineSnapshotId: params.baselineSnapshotId,\n    baselineServerRevisionId: params.baselineServerRevisionId ?? null,\n    baselineServerHeadHash: params.baselineServerHeadHash,\n    currentSnapshotId: params.currentSnapshotId,\n    idempotencyKey: params.idempotencyKey,\n    error: null,\n    retryCount: 0,\n    lastAttemptAt: null,\n    nextRetryAt: params.nextRetryAt ?? null,\n    metadata: params.metadata ?? {}\n  });\n}\nasync function drainPendingFinalizeQueue(params) {\n  return drainPendingFinalizeQueueJobs({\n    api: params.api,\n    processClaimedJob: processClaimedPendingFinalizeJob\n  });\n}\n\n// src/application/collab/collabFinalizeTurn.ts\nvar FINALIZE_AWAIT_INIT_POST_TIMEOUT_MS = 6e4;\nvar FINALIZE_UNALIGNED_DRAIN_TIMEOUT_MS = 1e4;\nfunction collectWarnings(value) {\n  if (!Array.isArray(value)) return [];\n  return value.filter((entry) => typeof entry === \"string\" && entry.trim().length > 0);\n}\nfunction throwBlockingDetectedStatus(detected) {\n  if (detected.status === \"not_bound\") {\n    throw new RemixError(\"Repository is not bound to Remix.\", {\n      code: \"not_bound\",\n      exitCode: 2,\n      hint: detected.hint\n    });\n  }\n  if (detected.status === \"branch_binding_missing\") {\n    throw new RemixError(detected.hint || \"Current branch is not ready for Remix recording.\", {\n      code: detected.status,\n      exitCode: 2,\n      hint: detected.hint\n    });\n  }\n  if (detected.status === \"family_ambiguous\") {\n    throw new RemixError(detected.hint || \"Current branch is not ready for Remix recording.\", {\n      code: detected.status,\n      exitCode: 2,\n      hint: detected.hint\n    });\n  }\n  if (detected.status === \"metadata_conflict\" || detected.status === \"branch_mismatch\") {\n    throw new RemixError(\"Repository must be realigned before finalizing the turn.\", {\n      code: detected.status,\n      exitCode: 2,\n      hint: detected.hint\n    });\n  }\n  if (detected.status === \"remote_error\") {\n    const message = detected.hint || \"Failed to determine the current repo state.\";\n    throw new RemixError(message, {\n      code: detected.status,\n      exitCode: 1,\n      hint: detected.hint\n    });\n  }\n}\nfunction withTimeout(work, timeoutMs, message) {\n  let timer;\n  const timeout = new Promise((_, reject) => {\n    timer = setTimeout(() => reject(new Error(message)), timeoutMs);\n    timer.unref?.();\n  });\n  return Promise.race([work, timeout]).finally(() => {\n    if (timer) clearTimeout(timer);\n  });\n}\nasync function drainPendingFinalizeBeforeUnalignedFallback(params) {\n  const summary = await summarizePendingFinalizeJobs({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    currentAppId: params.currentAppId,\n    laneId: params.laneId\n  });\n  if (summary.activeJobCount <= 0) {\n    return { attempted: false, warnings: [] };\n  }\n  const warnings = [];\n  try {\n    await withTimeout(\n      drainPendingFinalizeQueue({ api: params.api }),\n      FINALIZE_UNALIGNED_DRAIN_TIMEOUT_MS,\n      `Timed out waiting ${Math.round(\n        FINALIZE_UNALIGNED_DRAIN_TIMEOUT_MS / 1e3\n      )}s for pending Remix turn recording to advance the local baseline.`\n    );\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    warnings.push(`Pending Remix turn recording could not be drained before this turn was captured: ${message}`);\n  } finally {\n    invalidateAppHeadCache(params.currentAppId);\n    invalidateAppDeltaCacheForApp(params.currentAppId);\n  }\n  return { attempted: true, warnings };\n}\nvar FINALIZE_QUEUED_WARNING = \"Queued only: the local Remix turn was captured, but no remote change step or collab turn exists yet. Drain or await finalize before merge-related flows.\";\nvar CONVERSATION_ONLY_WARNING = \"Recorded conversation only: this turn was not materialized into a change step.\";\nfunction buildConversationOnlyWorkspaceMetadata(params) {\n  const metadata = {\n    branch: params.branchName,\n    repoRoot: params.repoRoot,\n    remoteUrl: params.remoteUrl,\n    defaultBranch: params.defaultBranch,\n    recordingMode: \"conversation_only\",\n    materializationStatus: params.materializationStatus,\n    alignmentRequired: params.alignmentRequired,\n    baselineSnapshotId: params.baselineSnapshotId,\n    baselineServerRevisionId: params.baselineServerRevisionId,\n    baselineServerHeadHash: params.baselineServerHeadHash,\n    currentServerRevisionId: params.currentServerRevisionId,\n    currentServerHeadHash: params.currentServerHeadHash,\n    currentServerHeadCommitId: params.currentServerHeadCommitId,\n    localCommitHash: params.localCommitHash,\n    repoStateAtCapture: params.repoState,\n    actor: params.actor ?? null\n  };\n  if (params.turnUsage) {\n    metadata.turnUsage = params.turnUsage;\n  }\n  if (typeof params.promptedAt === \"string\" && params.promptedAt.trim()) {\n    metadata.promptedAt = params.promptedAt.trim();\n  }\n  return metadata;\n}\nasync function recordConversationOnlyTurn(params) {\n  const idempotencyKey = params.explicitIdempotencyKey?.trim() || buildDeterministicIdempotencyKey({\n    kind: \"collab_finalize_turn_conversation_only_v1\",\n    appId: params.binding.currentAppId,\n    laneId: params.binding.laneId,\n    materializationStatus: params.materializationStatus,\n    alignmentRequired: params.alignmentRequired,\n    baselineSnapshotId: params.baselineSnapshotId ?? null,\n    baselineServerRevisionId: params.baselineServerRevisionId ?? null,\n    baselineServerHeadHash: params.baselineServerHeadHash ?? null,\n    currentServerRevisionId: params.currentServerRevisionId ?? null,\n    currentServerHeadHash: params.currentServerHeadHash ?? null,\n    currentServerHeadCommitId: params.currentServerHeadCommitId ?? null,\n    localCommitHash: params.localCommitHash ?? null,\n    repoState: params.repoState,\n    prompt: params.prompt,\n    assistantResponse: params.assistantResponse,\n    sourceConversation: params.sourceConversation ?? null\n  });\n  const collabTurnResp = await params.api.createCollabTurn(params.binding.currentAppId, {\n    threadId: params.binding.threadId ?? void 0,\n    collabLaneId: params.binding.laneId ?? void 0,\n    prompt: params.prompt,\n    assistantResponse: params.assistantResponse,\n    actor: params.actor,\n    sourceConversation: params.sourceConversation ?? void 0,\n    workspaceMetadata: buildConversationOnlyWorkspaceMetadata({\n      repoRoot: params.repoRoot,\n      branchName: params.binding.branchName,\n      remoteUrl: params.binding.remoteUrl,\n      defaultBranch: params.binding.defaultBranch,\n      baselineSnapshotId: params.baselineSnapshotId ?? null,\n      baselineServerRevisionId: params.baselineServerRevisionId ?? null,\n      baselineServerHeadHash: params.baselineServerHeadHash ?? null,\n      currentServerRevisionId: params.currentServerRevisionId ?? null,\n      currentServerHeadHash: params.currentServerHeadHash ?? null,\n      currentServerHeadCommitId: params.currentServerHeadCommitId ?? null,\n      localCommitHash: params.localCommitHash ?? null,\n      repoState: params.repoState,\n      materializationStatus: params.materializationStatus,\n      alignmentRequired: params.alignmentRequired,\n      actor: params.actor ?? null,\n      turnUsage: params.turnUsage ?? null,\n      promptedAt: params.promptedAt\n    }),\n    idempotencyKey\n  });\n  const collabTurn = unwrapResponseObject(collabTurnResp, \"collab turn\");\n  const reportResult = await reportCheckoutStateFromFinalize({\n    api: params.api,\n    appId: params.binding.currentAppId,\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.binding.repoFingerprint,\n    laneId: params.binding.laneId,\n    branch: params.binding.branchName,\n    repoState: params.repoState,\n    materializationStatus: params.materializationStatus,\n    alignmentRequired: params.alignmentRequired,\n    baselineRevisionId: params.baselineServerRevisionId,\n    serverRevisionId: params.currentServerRevisionId,\n    localHeadHash: params.localCommitHash,\n    serverHeadCommitId: params.currentServerHeadCommitId,\n    serverHeadHash: params.currentServerHeadHash,\n    source: \"finalize_conversation_only\"\n  });\n  return {\n    mode: \"conversation_only\",\n    idempotencyKey,\n    queued: false,\n    jobId: null,\n    repoState: params.repoState,\n    changeStep: null,\n    collabTurn,\n    autoSync: null,\n    warnings: [CONVERSATION_ONLY_WARNING, ...collectWarnings(params.warnings ?? []), ...reportResult.warnings]\n  };\n}\nasync function collabFinalizeTurn(params) {\n  const repoRoot = await findGitRoot(params.cwd);\n  const binding = await ensureActiveLaneBinding({\n    repoRoot,\n    api: params.api,\n    operation: \"`remix collab finalize-turn`\"\n  });\n  if (!binding) {\n    throw new RemixError(\"Repository is not bound to Remix.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab init` first.\"\n    });\n  }\n  const prompt = params.prompt.trim();\n  const assistantResponse = params.assistantResponse.trim();\n  const sourceConversation = params.sourceConversation ? SourceConversationSchema.parse(params.sourceConversation) : null;\n  if (!prompt) throw new RemixError(\"Prompt is required.\", { exitCode: 2 });\n  if (!assistantResponse) throw new RemixError(\"Assistant response is required.\", { exitCode: 2 });\n  if (params.diff?.trim()) {\n    throw new RemixError(\"External diff submission is no longer supported for `finalize_turn`.\", {\n      exitCode: 2,\n      hint: \"Finalize turns now capture the real workspace boundary from the local snapshot store.\"\n    });\n  }\n  const pendingInit = await findPendingAsyncJob({\n    repoRoot,\n    branchName: binding.branchName ?? null,\n    kind: \"init\"\n  });\n  if (pendingInit) {\n    throw new RemixError(\"Cannot finalize a turn while the initial Remix import is still processing.\", {\n      exitCode: 2,\n      hint: `Init job ${pendingInit.id} is still in the background queue. Run \\`remix collab status\\` to check progress.`\n    });\n  }\n  const failedInitPost = await findFailedAsyncJob({\n    repoRoot,\n    branchName: binding.branchName ?? null,\n    kind: \"init_post\"\n  });\n  if (failedInitPost) {\n    throw new RemixError(\"The initial Remix import failed; this turn cannot be recorded.\", {\n      exitCode: 2,\n      hint: (failedInitPost.error ? `Last error: ${failedInitPost.error}\n\n` : \"\") + \"Run `remix collab init` again to retry \\u2014 the post-init drainer cleared the local binding so this is safe.\"\n    });\n  }\n  const pendingInitPost = await findPendingAsyncJob({\n    repoRoot,\n    branchName: binding.branchName ?? null,\n    kind: \"init_post\"\n  });\n  if (pendingInitPost) {\n    const initPostTimeoutMs = params.initPostAwaitTimeoutMs ?? FINALIZE_AWAIT_INIT_POST_TIMEOUT_MS;\n    const result = await awaitAsyncJob({\n      jobId: pendingInitPost.id,\n      timeoutMs: initPostTimeoutMs,\n      pollIntervalMs: 500\n    });\n    if (result.status !== \"completed\") {\n      if (result.status === \"failed\") {\n        throw new RemixError(\"The initial Remix import failed; this turn cannot be recorded.\", {\n          exitCode: 2,\n          hint: (result.job?.error ? `Last error: ${result.job.error}\n\n` : \"\") + \"Run `remix collab init` again to retry \\u2014 the post-init drainer cleared the local binding so this is safe.\"\n        });\n      }\n      try {\n        return await recordConversationOnlyTurn({\n          api: params.api,\n          binding,\n          repoRoot,\n          prompt,\n          assistantResponse,\n          explicitIdempotencyKey: params.idempotencyKey,\n          actor: params.actor,\n          sourceConversation,\n          turnUsage: params.turnUsage,\n          promptedAt: params.promptedAt,\n          repoState: \"init_post_pending\",\n          materializationStatus: \"skipped_init_post_pending\",\n          alignmentRequired: \"init_post\",\n          warnings: [`Init post job ${pendingInitPost.id} is still pending; recorded conversation only.`]\n        });\n      } catch {\n      }\n      throw new RemixError(\"Timed out waiting for the initial Remix import to finish provisioning.\", {\n        exitCode: 2,\n        hint: `Init post job ${pendingInitPost.id} did not complete within ${Math.round(\n          initPostTimeoutMs / 1e3\n        )}s. Run \\`remix collab status\\` to check progress, then retry once it reports ready.`\n      });\n    }\n  }\n  let detected = await collabDetectRepoState({\n    api: params.api,\n    cwd: repoRoot,\n    allowBranchMismatch: params.allowBranchMismatch\n  });\n  throwBlockingDetectedStatus(detected);\n  let pendingFinalizeDrainWarnings = [];\n  if (detected.repoState === \"server_only_changed\" || detected.repoState === \"both_changed\") {\n    const recovery = await drainPendingFinalizeBeforeUnalignedFallback({\n      api: params.api,\n      repoRoot,\n      repoFingerprint: binding.repoFingerprint,\n      currentAppId: binding.currentAppId,\n      laneId: binding.laneId\n    });\n    if (recovery.attempted) {\n      pendingFinalizeDrainWarnings = recovery.warnings;\n      detected = await collabDetectRepoState({\n        api: params.api,\n        cwd: repoRoot,\n        allowBranchMismatch: params.allowBranchMismatch\n      });\n      throwBlockingDetectedStatus(detected);\n    }\n  }\n  if (detected.status === \"missing_head\") {\n    return recordConversationOnlyTurn({\n      api: params.api,\n      binding,\n      repoRoot,\n      prompt,\n      assistantResponse,\n      explicitIdempotencyKey: params.idempotencyKey,\n      actor: params.actor,\n      sourceConversation,\n      turnUsage: params.turnUsage,\n      promptedAt: params.promptedAt,\n      repoState: \"missing_head\",\n      materializationStatus: \"skipped_missing_head\",\n      alignmentRequired: \"head\",\n      localCommitHash: null,\n      warnings: [...pendingFinalizeDrainWarnings, ...detected.warnings]\n    });\n  }\n  if (detected.repoState === \"server_only_changed\" || detected.repoState === \"both_changed\") {\n    return recordConversationOnlyTurn({\n      api: params.api,\n      binding,\n      repoRoot,\n      prompt,\n      assistantResponse,\n      explicitIdempotencyKey: params.idempotencyKey,\n      actor: params.actor,\n      sourceConversation,\n      turnUsage: params.turnUsage,\n      promptedAt: params.promptedAt,\n      repoState: detected.repoState,\n      materializationStatus: \"skipped_unaligned\",\n      alignmentRequired: detected.repoState === \"both_changed\" ? \"reconcile\" : \"sync\",\n      baselineSnapshotId: detected.baseline.lastSnapshotId,\n      baselineServerRevisionId: detected.baseline.lastServerRevisionId,\n      baselineServerHeadHash: detected.baseline.lastServerHeadHash,\n      currentServerRevisionId: detected.currentServerRevisionId,\n      currentServerHeadHash: detected.currentServerHeadHash,\n      currentServerHeadCommitId: detected.currentServerHeadCommitId,\n      localCommitHash: detected.localCommitHash,\n      warnings: [...pendingFinalizeDrainWarnings, ...detected.warnings]\n    });\n  }\n  if (detected.repoState === \"external_local_base_changed\") {\n    return recordConversationOnlyTurn({\n      api: params.api,\n      binding,\n      repoRoot,\n      prompt,\n      assistantResponse,\n      explicitIdempotencyKey: params.idempotencyKey,\n      actor: params.actor,\n      sourceConversation,\n      turnUsage: params.turnUsage,\n      promptedAt: params.promptedAt,\n      repoState: \"external_local_base_changed\",\n      materializationStatus: \"skipped_baseline_missing\",\n      alignmentRequired: \"baseline\",\n      baselineSnapshotId: detected.baseline.lastSnapshotId,\n      baselineServerRevisionId: detected.baseline.lastServerRevisionId,\n      baselineServerHeadHash: detected.baseline.lastServerHeadHash,\n      currentServerRevisionId: detected.currentServerRevisionId,\n      currentServerHeadHash: detected.currentServerHeadHash,\n      currentServerHeadCommitId: detected.currentServerHeadCommitId,\n      localCommitHash: detected.localCommitHash,\n      warnings: [...pendingFinalizeDrainWarnings, ...detected.warnings]\n    });\n  }\n  const baseline = await readLocalBaseline({\n    repoFingerprint: binding.repoFingerprint,\n    laneId: binding.laneId,\n    repoRoot\n  });\n  if (!baseline) {\n    return recordConversationOnlyTurn({\n      api: params.api,\n      binding,\n      repoRoot,\n      prompt,\n      assistantResponse,\n      explicitIdempotencyKey: params.idempotencyKey,\n      actor: params.actor,\n      sourceConversation,\n      turnUsage: params.turnUsage,\n      promptedAt: params.promptedAt,\n      repoState: \"baseline_missing\",\n      materializationStatus: \"skipped_baseline_missing\",\n      alignmentRequired: \"baseline\",\n      baselineSnapshotId: detected.baseline.lastSnapshotId,\n      baselineServerRevisionId: detected.baseline.lastServerRevisionId,\n      baselineServerHeadHash: detected.baseline.lastServerHeadHash,\n      currentServerRevisionId: detected.currentServerRevisionId,\n      currentServerHeadHash: detected.currentServerHeadHash,\n      currentServerHeadCommitId: detected.currentServerHeadCommitId,\n      localCommitHash: detected.localCommitHash,\n      warnings: [...pendingFinalizeDrainWarnings, ...detected.warnings]\n    });\n  }\n  const snapshot = await captureLocalSnapshot({\n    repoRoot,\n    repoFingerprint: binding.repoFingerprint,\n    laneId: binding.laneId,\n    branchName: binding.branchName\n  });\n  const mode = snapshot.snapshotHash === baseline.lastSnapshotHash ? \"no_diff_turn\" : \"changed_turn\";\n  const idempotencyKey = params.idempotencyKey?.trim() || buildDeterministicIdempotencyKey({\n    kind: \"collab_finalize_turn_boundary_v2\",\n    appId: binding.currentAppId,\n    laneId: binding.laneId,\n    baselineSnapshotId: baseline.lastSnapshotId,\n    baselineServerRevisionId: baseline.lastServerRevisionId,\n    baselineServerHeadHash: baseline.lastServerHeadHash,\n    currentSnapshotId: snapshot.id,\n    currentSnapshotHash: snapshot.snapshotHash,\n    repoState: detected.repoState,\n    prompt,\n    assistantResponse,\n    sourceConversation\n  });\n  const awaitingDeadlineMs = typeof params.awaitingUsageDeadlineMs === \"number\" && params.awaitingUsageDeadlineMs > 0 ? params.awaitingUsageDeadlineMs : null;\n  const nextRetryAt = awaitingDeadlineMs === null ? null : new Date(Date.now() + awaitingDeadlineMs).toISOString();\n  const job = await enqueueCapturedFinalizeTurn({\n    repoRoot,\n    repoFingerprint: binding.repoFingerprint,\n    currentAppId: binding.currentAppId,\n    laneId: binding.laneId,\n    threadId: binding.threadId,\n    sourceConversation,\n    branchName: binding.branchName,\n    prompt,\n    assistantResponse,\n    baselineSnapshotId: baseline.lastSnapshotId,\n    baselineServerRevisionId: baseline.lastServerRevisionId,\n    baselineServerHeadHash: baseline.lastServerHeadHash,\n    currentSnapshotId: snapshot.id,\n    idempotencyKey,\n    metadata: {\n      remoteUrl: binding.remoteUrl,\n      defaultBranch: binding.defaultBranch,\n      actor: params.actor ?? null,\n      sourceConversation,\n      repoState: detected.repoState,\n      turnUsage: params.turnUsage ?? null,\n      promptedAt: typeof params.promptedAt === \"string\" && params.promptedAt.trim() ? params.promptedAt.trim() : null\n    },\n    nextRetryAt\n  });\n  const reportResult = await reportCheckoutStateFromFinalize({\n    api: params.api,\n    appId: binding.currentAppId,\n    repoRoot,\n    repoFingerprint: binding.repoFingerprint,\n    laneId: binding.laneId,\n    branch: binding.branchName,\n    repoState: detected.repoState,\n    materializationStatus: \"queued_finalize\",\n    alignmentRequired: \"finalize\",\n    baselineRevisionId: baseline.lastServerRevisionId,\n    serverRevisionId: detected.currentServerRevisionId,\n    localHeadHash: snapshot.localCommitHash,\n    serverHeadCommitId: detected.currentServerHeadCommitId,\n    serverHeadHash: detected.currentServerHeadHash,\n    pendingFinalizeCount: 1,\n    source: \"finalize_queue\"\n  });\n  return {\n    mode,\n    idempotencyKey,\n    queued: true,\n    jobId: job.id,\n    repoState: detected.repoState,\n    changeStep: null,\n    collabTurn: null,\n    autoSync: null,\n    warnings: [FINALIZE_QUEUED_WARNING, ...collectWarnings([...pendingFinalizeDrainWarnings, ...detected.warnings]), ...reportResult.warnings]\n  };\n}\n\n// src/application/collab/finalizePreflightCodes.ts\nvar FINALIZE_PREFLIGHT_FAILURE_CODES = [\n  // Repo has no .remix/ binding at all. Fix: `remix collab init`.\n  \"not_bound\",\n  // Binding file exists but the current branch has no entry. Fix: same as\n  // not_bound — `remix collab init` records this branch into the binding.\n  \"branch_binding_missing\",\n  // Branch matches multiple lane families (very rare race). Fix: human\n  // investigation; auto-fixers should treat as warn-only.\n  \"family_ambiguous\",\n  // Local-vs-server metadata diverged on app id / lane id. Fix: human\n  // investigation; auto-fixers should treat as warn-only.\n  \"metadata_conflict\",\n  // Currently checked-out branch differs from the one in the binding.\n  // Fix: human (either checkout the recorded branch or update binding).\n  \"branch_mismatch\",\n  // HEAD ref unreadable / git reports an error. Fix: human investigation.\n  \"missing_head\",\n  \"remote_error\",\n  // Server has commits we don't. Fix: `remix collab sync` (safe to\n  // auto-run for fast-forward; non-FF refused by the command itself).\n  \"pull_required\",\n  // Both local and server changed. Fix: inspect and apply reconcile.\n  \"reconcile_required\",\n  // Local revision baseline is missing. Fix: `remix collab init` or sync.\n  \"baseline_missing\"\n];\nvar CODE_SET = new Set(FINALIZE_PREFLIGHT_FAILURE_CODES);\nfunction isFinalizePreflightFailureCode(value) {\n  return typeof value === \"string\" && CODE_SET.has(value);\n}\n\n// src/application/collab/recordingPreflight.ts\nfunction mapDetectedRepoStateToRecordingPreflight(detected) {\n  if (detected.status === \"not_git_repo\") {\n    return {\n      status: \"not_git_repo\",\n      repoState: detected.repoState,\n      repoRoot: null,\n      appId: null,\n      currentBranch: null,\n      branchName: null,\n      headCommitHash: null,\n      worktreeClean: false,\n      syncStatus: null,\n      syncTargetCommitHash: null,\n      syncTargetCommitId: null,\n      reconcileTargetHeadCommitHash: null,\n      reconcileTargetHeadCommitId: null,\n      warnings: detected.warnings,\n      hint: detected.hint\n    };\n  }\n  const syncTargetCommitHash = detected.currentServerHeadHash;\n  const syncTargetCommitId = detected.currentServerHeadCommitId;\n  const base = {\n    repoState: detected.repoState,\n    repoRoot: detected.repoRoot,\n    appId: detected.binding?.currentAppId ?? null,\n    currentBranch: detected.currentBranch,\n    branchName: detected.branchName,\n    headCommitHash: detected.localCommitHash,\n    worktreeClean: detected.worktreeClean,\n    syncStatus: detected.repoState === \"server_only_changed\" ? \"delta_ready\" : detected.status === \"metadata_conflict\" ? \"conflict_risk\" : null,\n    syncTargetCommitHash,\n    syncTargetCommitId,\n    reconcileTargetHeadCommitHash: detected.currentServerHeadHash,\n    reconcileTargetHeadCommitId: detected.currentServerHeadCommitId,\n    warnings: detected.warnings,\n    hint: detected.hint\n  };\n  if (detected.status === \"not_bound\") return { status: \"not_bound\", ...base };\n  if (detected.status === \"branch_binding_missing\") return { status: \"branch_binding_missing\", ...base };\n  if (detected.status === \"family_ambiguous\") return { status: \"family_ambiguous\", ...base };\n  if (detected.status === \"metadata_conflict\") return { status: \"metadata_conflict\", ...base };\n  if (detected.status === \"missing_head\") return { status: \"missing_head\", ...base };\n  if (detected.status === \"branch_mismatch\") return { status: \"branch_mismatch\", ...base };\n  if (detected.repoState === \"server_only_changed\") return { status: \"pull_required\", ...base };\n  if (detected.repoState === \"both_changed\") return { status: \"reconcile_required\", ...base };\n  if (detected.repoState === \"external_local_base_changed\") return { status: \"baseline_missing\", ...base };\n  return { status: \"ready\", ...base };\n}\nasync function collabRecordingPreflight(params) {\n  const detected = await collabDetectRepoState({\n    api: params.api,\n    cwd: params.cwd,\n    allowBranchMismatch: params.allowBranchMismatch\n  });\n  return mapDetectedRepoStateToRecordingPreflight(detected);\n}\n\n// src/infrastructure/locking/repoMutationLock.ts\nimport fs6 from \"fs/promises\";\nimport os3 from \"os\";\nimport path7 from \"path\";\nvar DEFAULT_ACQUIRE_TIMEOUT_MS = 15e3;\nvar DEFAULT_STALE_MS = 45e3;\nvar DEFAULT_HEARTBEAT_MS = 5e3;\nvar RETRY_DELAY_MS = 250;\nvar heldLocks = /* @__PURE__ */ new Map();\nfunction sleep2(ms) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\nfunction createOwner(params) {\n  const now = (/* @__PURE__ */ new Date()).toISOString();\n  return {\n    operation: params.operation,\n    repoRoot: params.repoRoot,\n    pid: process.pid,\n    hostname: os3.hostname(),\n    startedAt: now,\n    heartbeatAt: now,\n    version: process.version,\n    requestId: params.requestId?.trim() || null\n  };\n}\nasync function writeOwnerMetadata(ownerPath, owner) {\n  await fs6.writeFile(ownerPath, `${JSON.stringify(owner, null, 2)}\n`, \"utf8\");\n}\nasync function readOwnerMetadata(ownerPath) {\n  try {\n    const raw = await fs6.readFile(ownerPath, \"utf8\");\n    const parsed = JSON.parse(raw);\n    if (!parsed || typeof parsed !== \"object\") return null;\n    if (!parsed.operation || !parsed.repoRoot || typeof parsed.pid !== \"number\" || !parsed.startedAt || !parsed.heartbeatAt) {\n      return null;\n    }\n    return {\n      operation: parsed.operation,\n      repoRoot: parsed.repoRoot,\n      pid: parsed.pid,\n      hostname: typeof parsed.hostname === \"string\" ? parsed.hostname : \"unknown\",\n      startedAt: parsed.startedAt,\n      heartbeatAt: parsed.heartbeatAt,\n      version: typeof parsed.version === \"string\" ? parsed.version : \"unknown\",\n      requestId: typeof parsed.requestId === \"string\" ? parsed.requestId : null\n    };\n  } catch {\n    return null;\n  }\n}\nasync function isProcessAlive(owner) {\n  if (!owner) return null;\n  if (owner.hostname !== os3.hostname()) return null;\n  try {\n    process.kill(owner.pid, 0);\n    return true;\n  } catch (error) {\n    if (error?.code === \"EPERM\") return true;\n    if (error?.code === \"ESRCH\") return false;\n    return null;\n  }\n}\nasync function getLastKnownUpdateMs(lockDir, ownerPath, owner) {\n  const heartbeatMs = owner ? Date.parse(owner.heartbeatAt) : Number.NaN;\n  if (Number.isFinite(heartbeatMs)) return heartbeatMs;\n  const startedMs = owner ? Date.parse(owner.startedAt) : Number.NaN;\n  if (Number.isFinite(startedMs)) return startedMs;\n  const stat = await fs6.stat(ownerPath).catch(() => null);\n  if (stat) return stat.mtimeMs;\n  const dirStat = await fs6.stat(lockDir).catch(() => null);\n  if (dirStat) return dirStat.mtimeMs;\n  return 0;\n}\nasync function ensureLockDir(lockDir) {\n  await fs6.mkdir(path7.dirname(lockDir), { recursive: true });\n}\nasync function tryAcquireLock(lockDir, ownerPath, owner) {\n  try {\n    await ensureLockDir(lockDir);\n    await fs6.mkdir(lockDir);\n    try {\n      await writeOwnerMetadata(ownerPath, owner);\n    } catch (error) {\n      await fs6.rm(lockDir, { recursive: true, force: true }).catch(() => void 0);\n      throw error;\n    }\n    return true;\n  } catch (error) {\n    if (error?.code === \"EEXIST\") return false;\n    throw error;\n  }\n}\nfunction formatLockHint(params) {\n  const lines = [\n    /* v8 ignore next -- observed-held diagnostic only appears after a timed wait. */\n    params.observedHeldLock ? `Observed lock state: ${REMIX_ERROR_CODES.REPO_LOCK_HELD}.` : null,\n    params.owner ? `Active operation: ${params.owner.operation}` : \"Active operation: unknown\",\n    params.owner ? `Repo root: ${params.owner.repoRoot}` : null,\n    params.owner ? `Owner: pid=${params.owner.pid} host=${params.owner.hostname}` : null,\n    params.owner ? `Started at: ${params.owner.startedAt}` : null,\n    params.owner ? `Heartbeat at: ${params.owner.heartbeatAt}` : null,\n    `Waited ${params.waitedMs}ms for the repo mutation lock.`,\n    `Stale lock threshold: ${params.staleMs}ms.`,\n    \"Retry after the active operation finishes. If the process crashed, wait for stale lock recovery or remove the stale lock manually if necessary.\"\n  ];\n  return lines.filter(Boolean).join(\"\\n\");\n}\nfunction formatOwnerSummary(owner) {\n  if (!owner) {\n    return \"unknown owner\";\n  }\n  return `operation=${owner.operation} pid=${owner.pid} host=${owner.hostname} startedAt=${owner.startedAt} heartbeatAt=${owner.heartbeatAt}`;\n}\nfunction buildStaleRecoveryNotice(owner) {\n  return {\n    code: REMIX_ERROR_CODES.REPO_LOCK_STALE_RECOVERED,\n    owner,\n    message: `[${REMIX_ERROR_CODES.REPO_LOCK_STALE_RECOVERED}] Recovered a stale Remix repo mutation lock (${formatOwnerSummary(owner)}).`\n  };\n}\nasync function acquirePhysicalLock(lockDir, ownerPath, owner, options) {\n  const startedAt = Date.now();\n  const notices = [];\n  let observedHeldLock = false;\n  while (Date.now() - startedAt < options.acquireTimeoutMs) {\n    if (await tryAcquireLock(lockDir, ownerPath, owner)) return notices;\n    const currentOwner2 = await readOwnerMetadata(ownerPath);\n    observedHeldLock = true;\n    const lastUpdateMs = await getLastKnownUpdateMs(lockDir, ownerPath, currentOwner2);\n    const ageMs = Math.max(0, Date.now() - lastUpdateMs);\n    const alive = await isProcessAlive(currentOwner2);\n    if (ageMs >= options.staleMs && alive !== true) {\n      notices.push(buildStaleRecoveryNotice(currentOwner2));\n      await fs6.rm(lockDir, { recursive: true, force: true }).catch(() => void 0);\n      continue;\n    }\n    await sleep2(RETRY_DELAY_MS);\n  }\n  const currentOwner = await readOwnerMetadata(ownerPath);\n  throw new RemixError(\"Repository is busy with another Remix mutation.\", {\n    code: REMIX_ERROR_CODES.REPO_LOCK_TIMEOUT,\n    exitCode: 2,\n    hint: formatLockHint({\n      owner: currentOwner,\n      waitedMs: Date.now() - startedAt,\n      staleMs: options.staleMs,\n      observedHeldLock\n    })\n  });\n}\nfunction startHeartbeat(lockDir, ownerPath, owner, heartbeatMs) {\n  return setInterval(() => {\n    const nextOwner = {\n      ...owner,\n      heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()\n    };\n    owner.heartbeatAt = nextOwner.heartbeatAt;\n    void writeOwnerMetadata(ownerPath, nextOwner).catch(() => void 0);\n    void fs6.utimes(lockDir, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date()).catch(() => void 0);\n  }, heartbeatMs);\n}\nasync function releaseReentrantLock(lockDir) {\n  const held = heldLocks.get(lockDir);\n  if (!held) return;\n  held.count -= 1;\n  if (held.count > 0) return;\n  clearInterval(held.heartbeatTimer);\n  heldLocks.delete(lockDir);\n  await fs6.rm(lockDir, { recursive: true, force: true }).catch(() => void 0);\n}\nasync function withRepoMutationLock(options, fn) {\n  const repoRoot = await findGitRoot(options.cwd);\n  const gitCommonDir = await getGitCommonDir(repoRoot);\n  const lockDir = path7.join(gitCommonDir, \"remix\", \"locks\", \"repo-mutation.lock\");\n  const owner = createOwner({\n    operation: options.operation,\n    repoRoot,\n    requestId: options.requestId\n  });\n  const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;\n  const acquireTimeoutMs = options.acquireTimeoutMs ?? DEFAULT_ACQUIRE_TIMEOUT_MS;\n  const staleMs = options.staleMs ?? DEFAULT_STALE_MS;\n  const existing = heldLocks.get(lockDir);\n  let notices = [];\n  if (!existing) {\n    notices = await acquirePhysicalLock(lockDir, path7.join(lockDir, \"owner.json\"), owner, {\n      acquireTimeoutMs,\n      staleMs\n    });\n    const ownerPath = path7.join(lockDir, \"owner.json\");\n    heldLocks.set(lockDir, {\n      count: 1,\n      lockDir,\n      ownerPath,\n      owner,\n      heartbeatTimer: startHeartbeat(lockDir, ownerPath, owner, heartbeatMs)\n    });\n  } else {\n    existing.count += 1;\n  }\n  try {\n    return await fn({\n      repoRoot,\n      gitCommonDir,\n      lockDir,\n      notices,\n      warnings: notices.map((notice) => notice.message)\n    });\n  } finally {\n    await releaseReentrantLock(lockDir);\n  }\n}\n\n// src/application/collab/workspaceBaseline.ts\nasync function ensureWorkspaceMatchesBaseline(params) {\n  const baseline = await readLocalBaseline({\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    repoRoot: params.repoRoot\n  });\n  if (!baseline?.lastSnapshotHash || !baseline.lastServerHeadHash) {\n    throw new RemixError(\"Local Remix baseline is missing for this lane.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab init` or sync from a checkout with a valid revision baseline before applying server changes.\"\n    });\n  }\n  const inspection = await inspectLocalSnapshot({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    branchName: params.branchName,\n    persistBlobs: false\n  });\n  if (inspection.snapshotHash !== baseline.lastSnapshotHash) {\n    throw new RemixError(`Local boundary changes must be recorded or discarded before running ${params.operation}.`, {\n      exitCode: 2,\n      hint: \"This checkout contains workspace changes that are not part of the current Remix baseline. Record them first, or restore the workspace back to the last agreed baseline before retrying.\"\n    });\n  }\n  return { baseline, inspection };\n}\n\n// src/application/collab/collabSync.ts\nasync function collabSync(params) {\n  const repoRoot = await findGitRoot(params.cwd);\n  const binding = await ensureActiveLaneBinding({\n    repoRoot,\n    api: params.api,\n    operation: \"`remix collab sync`\"\n  });\n  if (!binding) {\n    throw new RemixError(\"Repository is not bound to Remix.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab init` first.\"\n    });\n  }\n  const detected = await collabDetectRepoState({\n    api: params.api,\n    cwd: repoRoot,\n    allowBranchMismatch: params.allowBranchMismatch\n  });\n  if (!detected.binding) {\n    throw new RemixError(\"Repository is not bound to Remix.\", { exitCode: 2, hint: detected.hint });\n  }\n  if (detected.repoState === \"idle\") {\n    const headCommitHash2 = await getHeadCommitHash(repoRoot);\n    const branch2 = await requireCurrentBranch(repoRoot);\n    if (!detected.currentServerHeadHash || !detected.currentServerHeadCommitId) {\n      throw new RemixError(\"Failed to resolve the current Remix server head for this lane.\", {\n        exitCode: 1,\n        hint: \"Run `remix collab status` and retry after the repository is fully connected to Remix.\"\n      });\n    }\n    return {\n      status: \"up_to_date\",\n      branch: branch2,\n      repoRoot,\n      baseCommitHash: detected.currentServerHeadHash,\n      targetCommitHash: detected.currentServerHeadHash,\n      targetCommitId: detected.currentServerHeadCommitId,\n      stats: { changedFilesCount: 0, insertions: 0, deletions: 0 },\n      localCommitHash: headCommitHash2,\n      applied: false,\n      dryRun: params.dryRun\n    };\n  }\n  if (detected.repoState !== \"server_only_changed\") {\n    throw new RemixError(\"A direct pull is only available when the server changed and the local workspace did not.\", {\n      exitCode: 2,\n      hint: detected.hint\n    });\n  }\n  const branch = await requireCurrentBranch(repoRoot);\n  const headCommitHash = await getHeadCommitHash(repoRoot);\n  const repoSnapshot = await captureRepoSnapshot(repoRoot, { includeWorkspaceDiffHash: true });\n  const bootstrapFromLocalHead = !detected.baseline.lastSnapshotHash || !detected.baseline.lastServerHeadHash;\n  let baselineServerHeadHash;\n  let baselineServerRevisionId = null;\n  if (bootstrapFromLocalHead) {\n    if (!headCommitHash) {\n      throw new RemixError(\"Failed to resolve local HEAD commit for the initial sync bootstrap.\", {\n        exitCode: 1,\n        hint: \"Retry after Git HEAD is available, or run `remix collab init` to seed this checkout's revision baseline.\"\n      });\n    }\n    baselineServerHeadHash = headCommitHash;\n  } else {\n    const { baseline } = await ensureWorkspaceMatchesBaseline({\n      repoRoot,\n      repoFingerprint: binding.repoFingerprint,\n      laneId: binding.laneId,\n      branchName: binding.branchName,\n      operation: \"`remix collab sync`\"\n    });\n    if (!baseline.lastServerHeadHash) {\n      throw new RemixError(\"Local Remix baseline is missing the last acknowledged server head.\", {\n        exitCode: 2,\n        hint: \"Run `remix collab init` or sync from a checkout with a valid revision baseline before pulling server changes.\"\n      });\n    }\n    baselineServerHeadHash = baseline.lastServerHeadHash;\n    baselineServerRevisionId = baseline.lastServerRevisionId;\n  }\n  const deltaResp = await params.api.getAppDelta(binding.currentAppId, {\n    baseHeadHash: baselineServerHeadHash,\n    baseRevisionId: baselineServerRevisionId,\n    repoFingerprint: binding.repoFingerprint ?? void 0,\n    remoteUrl: binding.remoteUrl ?? void 0,\n    defaultBranch: binding.defaultBranch ?? void 0\n  });\n  const delta = unwrapResponseObject(deltaResp, \"app delta\");\n  if (delta.status === \"conflict_risk\") {\n    throw new RemixError(\"Local repository metadata conflicts with the bound Remix app.\", {\n      exitCode: 2,\n      hint: delta.warnings.join(\"\\n\") || \"Run the command from the correct bound repository.\"\n    });\n  }\n  const previewResult = {\n    status: delta.status === \"content_equivalent\" ? \"base_unknown\" : delta.status,\n    branch,\n    repoRoot,\n    baseCommitHash: baselineServerHeadHash,\n    targetCommitHash: delta.targetHeadHash,\n    targetCommitId: delta.targetHeadCommitId,\n    stats: delta.stats,\n    localCommitHash: headCommitHash,\n    applied: false,\n    dryRun: params.dryRun\n  };\n  if (params.dryRun) {\n    return previewResult;\n  }\n  if (delta.status === \"up_to_date\") {\n    if (!bootstrapFromLocalHead) {\n      return previewResult;\n    }\n    return withRepoMutationLock(\n      {\n        cwd: repoRoot,\n        operation: \"collabSync\"\n      },\n      async ({ repoRoot: lockedRepoRoot, warnings }) => {\n        await assertRepoSnapshotUnchanged(lockedRepoRoot, repoSnapshot, {\n          operation: \"`remix collab sync`\",\n          recoveryHint: \"The repository changed before the first local Remix baseline could be created. Review the local changes and rerun `remix collab sync`.\"\n        });\n        const snapshot = await captureLocalSnapshot({\n          repoRoot: lockedRepoRoot,\n          repoFingerprint: binding.repoFingerprint,\n          laneId: binding.laneId,\n          branchName: binding.branchName\n        });\n        await writeLocalBaseline({\n          repoRoot: lockedRepoRoot,\n          repoFingerprint: binding.repoFingerprint,\n          laneId: binding.laneId,\n          currentAppId: binding.currentAppId,\n          branchName: binding.branchName,\n          lastSnapshotId: snapshot.id,\n          lastSnapshotHash: snapshot.snapshotHash,\n          lastServerRevisionId: delta.targetRevisionId ?? null,\n          lastServerTreeHash: delta.targetTreeHash ?? null,\n          lastServerHeadHash: delta.targetHeadHash,\n          lastSeenLocalCommitHash: snapshot.localCommitHash\n        });\n        const reportResult = await reportAlignedCheckoutState({\n          api: params.api,\n          appId: binding.currentAppId,\n          repoRoot: lockedRepoRoot,\n          repoFingerprint: binding.repoFingerprint,\n          laneId: binding.laneId,\n          branch,\n          baselineRevisionId: delta.targetRevisionId ?? null,\n          serverRevisionId: delta.targetRevisionId ?? null,\n          localHeadHash: snapshot.localCommitHash,\n          serverHeadCommitId: delta.targetHeadCommitId,\n          serverHeadHash: delta.targetHeadHash,\n          source: \"sync_apply\"\n        });\n        return {\n          ...previewResult,\n          localCommitHash: snapshot.localCommitHash,\n          ...[...warnings, ...reportResult.warnings].length > 0 ? { warnings: [...warnings, ...reportResult.warnings] } : {}\n        };\n      }\n    );\n  }\n  if (delta.status === \"base_unknown\") {\n    throw new RemixError(\"Direct pull is unavailable because Remix can no longer diff from the last acknowledged server head.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab reconcile --dry-run` to inspect recovery options before retrying. If this checkout has no local Remix baseline yet for this lane, run `remix collab init` to seed one.\"\n    });\n  }\n  if (delta.status !== \"delta_ready\") {\n    throw new RemixError(\"Direct pull is not available for the current repository state.\", {\n      exitCode: 2,\n      hint: delta.warnings.join(\"\\n\") || \"Run `remix collab status` to inspect the current alignment state.\"\n    });\n  }\n  return withRepoMutationLock(\n    {\n      cwd: repoRoot,\n      operation: \"collabSync\"\n    },\n    async ({ repoRoot: lockedRepoRoot, warnings }) => {\n      if (bootstrapFromLocalHead) {\n        await assertRepoSnapshotUnchanged(lockedRepoRoot, repoSnapshot, {\n          operation: \"`remix collab sync`\",\n          recoveryHint: \"The repository changed before the first local Remix baseline could be created. Review the local changes and rerun `remix collab sync`.\"\n        });\n      } else {\n        await ensureWorkspaceMatchesBaseline({\n          repoRoot: lockedRepoRoot,\n          repoFingerprint: binding.repoFingerprint,\n          laneId: binding.laneId,\n          branchName: binding.branchName,\n          operation: \"`remix collab sync`\"\n        });\n      }\n      await applyUnifiedDiffToWorktree(lockedRepoRoot, delta.diff, \"`remix collab pull`\");\n      const snapshot = await captureLocalSnapshot({\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branchName: binding.branchName\n      });\n      await writeLocalBaseline({\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        currentAppId: binding.currentAppId,\n        branchName: binding.branchName,\n        lastSnapshotId: snapshot.id,\n        lastSnapshotHash: snapshot.snapshotHash,\n        lastServerRevisionId: delta.targetRevisionId ?? null,\n        lastServerTreeHash: delta.targetTreeHash ?? null,\n        lastServerHeadHash: delta.targetHeadHash,\n        lastSeenLocalCommitHash: snapshot.localCommitHash\n      });\n      const reportResult = await reportAlignedCheckoutState({\n        api: params.api,\n        appId: binding.currentAppId,\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branch,\n        baselineRevisionId: delta.targetRevisionId ?? null,\n        serverRevisionId: delta.targetRevisionId ?? null,\n        localHeadHash: snapshot.localCommitHash,\n        serverHeadCommitId: delta.targetHeadCommitId,\n        serverHeadHash: delta.targetHeadHash,\n        source: \"sync_apply\"\n      });\n      const eventResult = await recordLocalAlignmentEvent({\n        api: params.api,\n        appId: binding.currentAppId,\n        eventKind: \"sync_local\",\n        branch,\n        collabLaneId: binding.laneId,\n        baseRevisionId: baselineServerRevisionId,\n        targetRevisionId: delta.targetRevisionId ?? null,\n        resultRevisionId: delta.targetRevisionId ?? null,\n        baseHeadHash: baselineServerHeadHash,\n        targetHeadCommitId: delta.targetHeadCommitId,\n        targetHeadHash: delta.targetHeadHash,\n        resultHeadHash: delta.targetHeadHash,\n        changedFilesCount: delta.stats.changedFilesCount,\n        insertions: delta.stats.insertions,\n        deletions: delta.stats.deletions,\n        localCommitCount: 0,\n        summary: \"Synced local checkout with Remix.\",\n        idempotencyKey: buildDeterministicIdempotencyKey({\n          kind: \"collab_sync_local_alignment_v1\",\n          appId: binding.currentAppId,\n          laneId: binding.laneId,\n          baseRevisionId: baselineServerRevisionId,\n          targetRevisionId: delta.targetRevisionId ?? null,\n          baseHeadHash: baselineServerHeadHash,\n          targetHeadHash: delta.targetHeadHash,\n          diffSha256: delta.diffSha256\n        })\n      });\n      return {\n        ...previewResult,\n        status: \"delta_ready\",\n        localCommitHash: snapshot.localCommitHash,\n        applied: true,\n        dryRun: false,\n        ...[...warnings, ...reportResult.warnings, ...eventResult.warnings].length > 0 ? { warnings: [...warnings, ...reportResult.warnings, ...eventResult.warnings] } : {}\n      };\n    }\n  );\n}\n\n// src/application/collab/collabApprove.ts\nasync function collabApprove(params) {\n  const approvePayload = {\n    status: \"approved\",\n    ...params.approvalStrategy ? { approvalStrategy: params.approvalStrategy } : {}\n  };\n  const transition = planApproveWorkflowTransition({\n    mode: params.mode,\n    hasCwd: Boolean(params.cwd?.trim())\n  });\n  if (transition.action === \"sync_target_repo\") {\n    return withRepoMutationLock(\n      {\n        cwd: params.cwd ?? \"\",\n        operation: \"collabApproveSyncTarget\"\n      },\n      async ({ repoRoot, warnings }) => {\n        const binding = await ensureActiveLaneBinding({\n          repoRoot,\n          api: params.api,\n          operation: \"`remix collab approve --sync-target-repo`\"\n        });\n        if (!binding) {\n          throw new RemixError(\"Repository is not bound to Remix.\", {\n            exitCode: 2,\n            hint: \"Run `remix collab init` first, or use `--remote-only`.\"\n          });\n        }\n        await ensureCleanWorktree(repoRoot, \"`remix collab approve --sync-target-repo`\");\n        const branch = await requireCurrentBranch(repoRoot);\n        assertBoundBranchMatch({\n          currentBranch: branch,\n          branchName: binding.branchName,\n          allowBranchMismatch: params.allowBranchMismatch,\n          operation: \"`remix collab approve --sync-target-repo`\"\n        });\n        const mrResp = await params.api.getMergeRequest(params.mrId);\n        const mergeRequest = unwrapMergeRequest(mrResp);\n        const targetAppId = mergeRequest.targetAppId;\n        if (binding.currentAppId !== targetAppId) {\n          throw new RemixError(\"Current repository is not the merge target for this merge request.\", {\n            exitCode: 2,\n            hint: `Run the command from the repository bound to app ${targetAppId}, or use --remote-only.`\n          });\n        }\n        const resp2 = await params.api.updateMergeRequest(params.mrId, approvePayload);\n        const approvedMergeRequest2 = unwrapMergeRequest(resp2);\n        const completedMergeRequest2 = await pollMergeRequestCompletion(params.api, params.mrId, {\n          targetAppId: targetAppId ?? approvedMergeRequest2.targetAppId\n        });\n        const localSync = await collabSync({\n          api: params.api,\n          cwd: repoRoot,\n          dryRun: false,\n          allowBranchMismatch: params.allowBranchMismatch\n        });\n        const localSyncWarnings = Array.isArray(localSync.warnings) ? localSync.warnings ?? [] : [];\n        return {\n          mode: params.mode,\n          mergeRequestId: completedMergeRequest2.id,\n          terminalStatus: completedMergeRequest2.status,\n          targetAppId: completedMergeRequest2.targetAppId,\n          mergeRequest: completedMergeRequest2,\n          repoRoot,\n          localSync,\n          ...warnings.length > 0 || localSyncWarnings.length > 0 ? {\n            warnings: Array.from(/* @__PURE__ */ new Set([...warnings, ...localSyncWarnings]))\n          } : {}\n        };\n      }\n    );\n  }\n  if (transition.action === \"require_cwd\") {\n    throw new RemixError(\"Working directory is required for `--sync-target-repo`.\", {\n      exitCode: 2\n    });\n  }\n  const resp = await params.api.updateMergeRequest(params.mrId, approvePayload);\n  const approvedMergeRequest = unwrapMergeRequest(resp);\n  const completedMergeRequest = await pollMergeRequestCompletion(params.api, params.mrId, {\n    targetAppId: approvedMergeRequest.targetAppId\n  });\n  return {\n    mode: params.mode,\n    mergeRequestId: completedMergeRequest.id,\n    terminalStatus: completedMergeRequest.status,\n    targetAppId: completedMergeRequest.targetAppId,\n    mergeRequest: completedMergeRequest\n  };\n}\n\n// src/application/collab/checkoutWorkspace.ts\nimport fs7 from \"fs/promises\";\nimport os4 from \"os\";\nimport path8 from \"path\";\nasync function pathExists(targetPath) {\n  try {\n    await fs7.access(targetPath);\n    return true;\n  } catch {\n    return false;\n  }\n}\nasync function statIsDirectory(targetPath) {\n  const stats = await fs7.stat(targetPath).catch(() => null);\n  return Boolean(stats?.isDirectory());\n}\nasync function findContainingGitRoot(startPath) {\n  let current = path8.resolve(startPath);\n  while (true) {\n    if (await pathExists(path8.join(current, \".git\"))) return current;\n    const parent = path8.dirname(current);\n    if (parent === current) return null;\n    current = parent;\n  }\n}\nfunction isSubpath(parentPath, candidatePath) {\n  const relative = path8.relative(parentPath, candidatePath);\n  return relative === \"\" || !relative.startsWith(\"..\") && !path8.isAbsolute(relative);\n}\nasync function resolveCheckoutDestination(params) {\n  if (params.outputDir?.trim()) {\n    const preferredRepoRoot = path8.resolve(params.outputDir.trim());\n    const parentDir2 = path8.dirname(preferredRepoRoot);\n    if (!await statIsDirectory(parentDir2)) {\n      throw new RemixError(\"Remix output parent directory does not exist.\", {\n        exitCode: 2,\n        hint: `Create the directory first: ${parentDir2}`\n      });\n    }\n    return {\n      preferredRepoRoot,\n      parentDir: parentDir2,\n      explicitOutputDir: true\n    };\n  }\n  const parentDir = path8.resolve(params.cwd);\n  if (!await statIsDirectory(parentDir)) {\n    throw new RemixError(\"Remix output parent directory does not exist.\", {\n      exitCode: 2,\n      hint: `Create the directory first: ${parentDir}`\n    });\n  }\n  return {\n    preferredRepoRoot: path8.join(parentDir, params.defaultDirName),\n    parentDir,\n    explicitOutputDir: false\n  };\n}\nasync function assertSafeCheckoutDestination(params) {\n  const callerGitRoot = await findContainingGitRoot(params.cwd);\n  if (callerGitRoot && isSubpath(callerGitRoot, params.repoRoot)) {\n    throw new RemixError(\"Refusing to create a remix checkout inside an existing git repository.\", {\n      exitCode: 2,\n      hint: params.explicitOutputDir ? `Choose a destination outside ${callerGitRoot}.` : `Pass --output-dir outside ${callerGitRoot}.`\n    });\n  }\n  const parentGitRoot = await findContainingGitRoot(params.parentDir);\n  if (parentGitRoot && isSubpath(parentGitRoot, params.repoRoot)) {\n    throw new RemixError(\"Refusing to create a remix checkout inside an existing git repository.\", {\n      exitCode: 2,\n      hint: params.explicitOutputDir ? `Choose a destination outside ${parentGitRoot}.` : `Pass --output-dir outside ${parentGitRoot}.`\n    });\n  }\n}\nasync function materializeAppCheckout(params) {\n  const destination = await resolveCheckoutDestination({\n    cwd: params.cwd,\n    outputDir: params.outputDir ?? null,\n    defaultDirName: params.defaultDirName\n  });\n  await assertSafeCheckoutDestination({\n    cwd: params.cwd,\n    repoRoot: destination.preferredRepoRoot,\n    parentDir: destination.parentDir,\n    explicitOutputDir: destination.explicitOutputDir\n  });\n  const repoRoot = destination.explicitOutputDir ? await reserveDirectory(destination.preferredRepoRoot) : await reserveAvailableDirPath(destination.preferredRepoRoot);\n  const bundleTempDir = await fs7.mkdtemp(path8.join(os4.tmpdir(), \"remix-checkout-\"));\n  const bundlePath = path8.join(bundleTempDir, \"repository.bundle\");\n  const phase = (next) => {\n    try {\n      params.onPhase?.(next);\n    } catch {\n    }\n  };\n  try {\n    phase(\"downloading\");\n    const bundle = await params.api.downloadAppBundle(params.appId);\n    phase(\"unpacking\");\n    await fs7.writeFile(bundlePath, bundle.data);\n    await cloneGitBundleToDirectory(bundlePath, repoRoot);\n    phase(\"finalizing\");\n    if (params.expectedBranchName?.trim()) {\n      await checkoutLocalBranch(repoRoot, params.expectedBranchName.trim());\n    }\n    if (params.expectedRemoteUrl?.trim()) {\n      await setRemoteOriginUrl(repoRoot, params.expectedRemoteUrl);\n    }\n    await ensureGitInfoExcludeEntries(repoRoot, [\".remix/\"]);\n  } catch (err) {\n    await fs7.rm(repoRoot, { recursive: true, force: true }).catch(() => {\n    });\n    throw err;\n  } finally {\n    await fs7.rm(bundleTempDir, { recursive: true, force: true });\n  }\n  const branchName = await getCurrentBranch(repoRoot) ?? params.expectedBranchName?.trim() ?? null;\n  const remoteUrl = normalizeGitRemote(params.expectedRemoteUrl ?? await getRemoteOriginUrl(repoRoot));\n  const defaultBranch = params.expectedDefaultBranch?.trim() ?? await getDefaultBranch(repoRoot) ?? branchName ?? null;\n  const repoFingerprint = remoteUrl ? await buildRepoFingerprint({ gitRoot: repoRoot, remoteUrl, defaultBranch }) : null;\n  return {\n    repoRoot,\n    remoteUrl,\n    defaultBranch,\n    branchName,\n    repoFingerprint\n  };\n}\n\n// src/application/collab/collabCheckout.ts\nasync function collabCheckout(params) {\n  const transition = planCheckoutWorkflowTransition({ appId: params.appId });\n  if (transition.action === \"require_app\") {\n    throw new RemixError(\"No app selected.\", {\n      exitCode: 2,\n      hint: \"Pass the app id to checkout.\"\n    });\n  }\n  const appId = params.appId?.trim() ?? \"\";\n  const app = await pollAppReady(params.api, appId);\n  const collab = app.collab && typeof app.collab === \"object\" ? app.collab : null;\n  const source = app.source && typeof app.source === \"object\" ? app.source : null;\n  const authoritativeBranchName = typeof collab?.branchName === \"string\" && collab.branchName.trim() || typeof source?.branch === \"string\" && source.branch.trim() || typeof source?.defaultBranch === \"string\" && source.defaultBranch.trim() || null;\n  const authoritativeRemoteUrl = typeof source?.remoteUrl === \"string\" && source.remoteUrl.trim() || null;\n  const authoritativeDefaultBranch = typeof source?.defaultBranch === \"string\" && source.defaultBranch.trim() || null;\n  const checkout = await materializeAppCheckout({\n    api: params.api,\n    cwd: params.cwd,\n    appId: String(app.id),\n    outputDir: params.outputDir ?? null,\n    defaultDirName: sanitizeCheckoutDirName(String(app.name || app.id)),\n    expectedBranchName: authoritativeBranchName,\n    expectedRemoteUrl: authoritativeRemoteUrl,\n    expectedDefaultBranch: authoritativeDefaultBranch,\n    onPhase: params.onPhase\n  });\n  const upstreamAppId = String(app.forkedFromAppId ?? app.id);\n  const laneId = typeof collab?.laneId === \"string\" ? collab.laneId : null;\n  const repoFingerprint = typeof source?.repoFingerprint === \"string\" ? source.repoFingerprint : checkout.repoFingerprint;\n  const remoteUrl = typeof source?.remoteUrl === \"string\" ? source.remoteUrl : checkout.remoteUrl;\n  const defaultBranch = typeof source?.defaultBranch === \"string\" ? source.defaultBranch : checkout.defaultBranch;\n  const branchName = authoritativeBranchName ?? checkout.branchName;\n  const authoritativeLane = await resolveProjectLaneIfAuthoritative(params.api, {\n    projectId: String(app.projectId),\n    repoFingerprint,\n    remoteUrl,\n    defaultBranch,\n    branchName,\n    currentAppId: String(app.id),\n    expectedUpstreamAppId: upstreamAppId,\n    createIfMissing: !params.skipLaneMaterialization,\n    seedAppId: params.skipLaneMaterialization ? null : String(app.id)\n  });\n  const bindingPath = await writeCollabBinding(checkout.repoRoot, {\n    projectId: authoritativeLane?.projectId ?? String(app.projectId),\n    currentAppId: authoritativeLane?.currentAppId ?? String(app.id),\n    upstreamAppId: authoritativeLane?.upstreamAppId ?? upstreamAppId,\n    threadId: authoritativeLane?.threadId ?? (app.threadId ? String(app.threadId) : null),\n    repoFingerprint: authoritativeLane?.repoFingerprint ?? repoFingerprint,\n    remoteUrl: authoritativeLane?.remoteUrl ?? remoteUrl,\n    defaultBranch: authoritativeLane?.defaultBranch ?? defaultBranch,\n    laneId: authoritativeLane?.laneId ?? laneId,\n    branchName: authoritativeLane?.branchName ?? branchName,\n    bindingMode: \"lane\"\n  });\n  const currentAppId = authoritativeLane?.currentAppId ?? String(app.id);\n  const repoFingerprintForBaseline = authoritativeLane?.repoFingerprint ?? repoFingerprint;\n  const laneIdForBaseline = authoritativeLane?.laneId ?? laneId;\n  const branchNameForBaseline = authoritativeLane?.branchName ?? branchName;\n  const appHead = unwrapResponseObject(\n    await params.api.getAppHead(currentAppId),\n    \"app head\"\n  );\n  const snapshot = await captureLocalSnapshot({\n    repoRoot: checkout.repoRoot,\n    repoFingerprint: repoFingerprintForBaseline,\n    laneId: laneIdForBaseline,\n    branchName: branchNameForBaseline\n  });\n  await writeLocalBaseline({\n    repoRoot: checkout.repoRoot,\n    repoFingerprint: repoFingerprintForBaseline,\n    laneId: laneIdForBaseline,\n    currentAppId,\n    branchName: branchNameForBaseline,\n    lastSnapshotId: snapshot.id,\n    lastSnapshotHash: snapshot.snapshotHash,\n    lastServerRevisionId: appHead.headRevisionId ?? null,\n    lastServerTreeHash: appHead.treeHash ?? null,\n    lastServerHeadHash: appHead.headCommitHash,\n    lastSeenLocalCommitHash: snapshot.localCommitHash\n  });\n  return {\n    appId: currentAppId,\n    dashboardUrl: buildDashboardAppUrl(currentAppId),\n    projectId: authoritativeLane?.projectId ?? String(app.projectId),\n    upstreamAppId: authoritativeLane?.upstreamAppId ?? upstreamAppId,\n    bindingPath,\n    repoRoot: checkout.repoRoot\n  };\n}\n\n// src/application/collab/collabListMergeRequests.ts\nvar APP_SCOPED_QUEUES = /* @__PURE__ */ new Set([\"app_reviewable\", \"app_outgoing\", \"app_related_visible\"]);\nasync function resolveQueueAppId(params) {\n  if (!APP_SCOPED_QUEUES.has(params.queue)) {\n    return params.appId ?? void 0;\n  }\n  if (params.appId?.trim()) {\n    return params.appId.trim();\n  }\n  if (!params.cwd?.trim()) {\n    throw new RemixError(\"An app-scoped merge-request queue requires either `appId` or `cwd`.\", {\n      exitCode: 2,\n      hint: \"Pass `appId` explicitly, or run the request from a Remix-bound checkout with `cwd` set.\"\n    });\n  }\n  const repoRoot = await findGitRoot(params.cwd);\n  const bindingResolution = await resolveActiveLaneBinding({ repoRoot });\n  if (bindingResolution.status === \"not_bound\") {\n    throw new RemixError(\"Repository is not bound to Remix.\", {\n      exitCode: 2,\n      hint: \"Bind the repository first or pass `appId` explicitly for the app-scoped merge-request queue.\"\n    });\n  }\n  if (bindingResolution.status === \"missing_branch_binding\") {\n    throw new RemixError(\"Current branch is not yet bound to a Remix lane.\", {\n      exitCode: 2,\n      hint: `Switch back to a bound branch, or run \\`remix collab init\\` on ${bindingResolution.currentBranch ?? \"this branch\"} before listing merge requests.`\n    });\n  }\n  if (bindingResolution.status === \"binding_conflict\") {\n    throw new RemixError(\"Current branch binding conflicts with the server-resolved Remix lane.\", {\n      exitCode: 2,\n      hint: `Local app ${bindingResolution.binding.currentAppId}; server app ${bindingResolution.resolvedLane.currentAppId ?? \"(unknown)\"}.`\n    });\n  }\n  if (bindingResolution.status === \"ambiguous_family_selection\") {\n    throw new RemixError(\"Multiple canonical Remix families match this repository.\", {\n      exitCode: 2,\n      hint: \"This checkout does not identify a single canonical family. Continue from a checkout already bound to the intended family, or pass `appId` explicitly for the queue request.\"\n    });\n  }\n  return bindingResolution.binding.currentAppId;\n}\nasync function collabListMergeRequests(params) {\n  const appId = await resolveQueueAppId({\n    cwd: params.cwd,\n    appId: params.appId,\n    queue: params.queue\n  });\n  const pageRequest = normalizePagination(params);\n  const resp = await params.api.listMergeRequests({\n    queue: params.queue,\n    appId,\n    status: params.status,\n    kind: params.kind ?? \"merge\",\n    limit: pageRequest.limit + 1,\n    offset: pageRequest.offset\n  });\n  const mergeRequests = unwrapResponseObject(resp, \"merge requests\");\n  const page = paginateOverfetchedItems(mergeRequests, params);\n  return {\n    queue: params.queue,\n    appId: appId ?? null,\n    mergeRequests: page.items,\n    pagination: page.pagination\n  };\n}\n\n// src/application/collab/resolveScopeTarget.ts\nasync function resolveScopeTarget(params) {\n  if (params.targetId?.trim()) return params.targetId.trim();\n  const repoRoot = await findGitRoot(params.cwd);\n  const bindingResolution = await resolveActiveLaneBinding({ repoRoot, api: params.api });\n  if (bindingResolution.status === \"not_bound\") {\n    throw new RemixError(\"Repository is not bound to Remix and no explicit target id was provided.\", { exitCode: 2 });\n  }\n  if (bindingResolution.status === \"missing_branch_binding\") {\n    throw new RemixError(\"Current branch is not yet bound to a Remix lane and no explicit target id was provided.\", {\n      exitCode: 2\n    });\n  }\n  if (bindingResolution.status === \"binding_conflict\") {\n    throw new RemixError(\"Current branch binding conflicts with the server-resolved Remix lane.\", {\n      exitCode: 2,\n      hint: `Local app ${bindingResolution.binding.currentAppId}; server app ${bindingResolution.resolvedLane.currentAppId ?? \"(unknown)\"}.`\n    });\n  }\n  if (bindingResolution.status === \"ambiguous_family_selection\") {\n    throw new RemixError(\"Multiple canonical Remix families match this repository and no explicit target id was provided.\", {\n      exitCode: 2,\n      hint: \"This checkout does not identify a single canonical family. Continue from a checkout already bound to the intended family, or pass `targetId` explicitly.\"\n    });\n  }\n  const binding = bindingResolution.binding;\n  if (params.scope === \"project\") {\n    if (!binding.projectId) {\n      throw new RemixError(\"Could not resolve the project for the current repository binding.\", { exitCode: 2 });\n    }\n    return binding.projectId;\n  }\n  if (params.scope === \"app\") return binding.currentAppId;\n  if (!binding.projectId) {\n    throw new RemixError(\"Could not resolve the project for the current repository binding.\", { exitCode: 2 });\n  }\n  const project = unwrapResponseObject(await params.api.getProject(binding.projectId), \"project\");\n  const organizationId = typeof project.organizationId === \"string\" ? project.organizationId : null;\n  if (!organizationId) {\n    throw new RemixError(\"Could not resolve the organization for the current repository binding.\", { exitCode: 2 });\n  }\n  return organizationId;\n}\n\n// src/application/collab/collabMembers.ts\nvar ORGANIZATION_MEMBER_ROLES = [\"owner\", \"admin\", \"member\", \"viewer\"];\nvar WORKFLOW_MEMBER_ROLES = [\"owner\", \"maintainer\", \"editor\", \"viewer\"];\nfunction getMemberRolesForScope(scope) {\n  return scope === \"organization\" ? ORGANIZATION_MEMBER_ROLES : WORKFLOW_MEMBER_ROLES;\n}\nfunction validateMemberRole(scope, role) {\n  const normalized = role.trim().toLowerCase();\n  if (getMemberRolesForScope(scope).includes(normalized)) return normalized;\n  throw new RemixError(`Invalid ${scope} member role.`, {\n    exitCode: 2,\n    hint: `Allowed roles: ${getMemberRolesForScope(scope).join(\", \")}`\n  });\n}\nasync function collabListMembers(params) {\n  const targetId = await resolveScopeTarget({\n    api: params.api,\n    cwd: params.cwd,\n    scope: params.scope,\n    targetId: params.targetId\n  });\n  const pageRequest = normalizePagination(params);\n  const resp = params.scope === \"organization\" ? await params.api.listOrganizationMembers(targetId, {\n    limit: pageRequest.limit + 1,\n    offset: pageRequest.offset\n  }) : params.scope === \"project\" ? await params.api.listProjectMembers(targetId, {\n    limit: pageRequest.limit + 1,\n    offset: pageRequest.offset\n  }) : await params.api.listAppMembers(targetId, {\n    limit: pageRequest.limit + 1,\n    offset: pageRequest.offset\n  });\n  const members = params.scope === \"organization\" ? unwrapResponseObject(resp, \"members\") : params.scope === \"project\" ? unwrapResponseObject(resp, \"members\") : unwrapResponseObject(resp, \"members\");\n  const page = paginateOverfetchedItems(members, params);\n  return {\n    scopeType: params.scope,\n    targetId,\n    members: page.items,\n    pagination: page.pagination\n  };\n}\nasync function collabUpdateMemberRole(params) {\n  const targetId = await resolveScopeTarget({\n    api: params.api,\n    cwd: params.cwd,\n    scope: params.scope,\n    targetId: params.targetId\n  });\n  const role = validateMemberRole(params.scope, params.role);\n  const resp = params.scope === \"organization\" ? await params.api.updateOrganizationMember(targetId, params.userId, { role }) : params.scope === \"project\" ? await params.api.updateProjectMember(targetId, params.userId, { role }) : await params.api.updateAppMember(targetId, params.userId, { role });\n  const member = params.scope === \"organization\" ? unwrapResponseObject(resp, \"member\") : params.scope === \"project\" ? unwrapResponseObject(resp, \"member\") : unwrapResponseObject(resp, \"member\");\n  return {\n    scopeType: params.scope,\n    targetId,\n    member\n  };\n}\n\n// src/application/collab/collabInit.ts\nimport fs12 from \"fs/promises\";\nimport path11 from \"path\";\n\n// src/shared/hash.ts\nimport crypto from \"crypto\";\nimport fs8 from \"fs\";\nasync function sha256FileHex(filePath) {\n  const hash = crypto.createHash(\"sha256\");\n  await new Promise((resolve, reject) => {\n    const stream = fs8.createReadStream(filePath);\n    stream.on(\"data\", (chunk) => hash.update(chunk));\n    stream.on(\"error\", reject);\n    stream.on(\"end\", () => resolve());\n  });\n  return hash.digest(\"hex\");\n}\n\n// src/application/collab/collabInitDecision.ts\nfunction shouldRequireCleanWorktreeForInit(params) {\n  return Boolean(params.forceNew) || !params.hasExistingBinding;\n}\nfunction classifyExistingInitBaseline(baseline) {\n  return baseline?.lastSnapshotHash && (baseline.lastServerRevisionId || baseline.lastServerHeadHash) ? \"existing\" : null;\n}\nfunction classifyInitBaselineDelta(params) {\n  if (params.equivalentBaselineStatus) return params.equivalentBaselineStatus;\n  if (params.deltaStatus === \"content_equivalent\") return \"seeded\";\n  if (params.deltaStatus === \"up_to_date\" || params.deltaStatus === \"delta_ready\") return \"requires_sync\";\n  return null;\n}\nfunction canSeedEquivalentBranchBaseline(params) {\n  if (!params.branchName || !params.defaultBranch || params.branchName === params.defaultBranch) return false;\n  if (!params.defaultBranchCurrentAppId) return false;\n  if (params.upstreamAppId && params.defaultBranchCurrentAppId !== params.upstreamAppId) return false;\n  if (!params.defaultBaselineSnapshotHash || !params.defaultBaselineServerHeadHash) return false;\n  if (params.defaultBaselineServerHeadHash !== params.appHeadHash) return false;\n  return params.localSnapshotHash === params.defaultBaselineSnapshotHash || params.localCommitHash === params.defaultBaselineLocalCommitHash;\n}\nfunction resolveStoredBindingAnchor(params) {\n  const currentBranchBinding = params.currentBranch ? params.state.branchBindings[params.currentBranch] ?? null : null;\n  if (currentBranchBinding?.currentAppId) {\n    return { binding: currentBranchBinding, branchName: params.currentBranch };\n  }\n  const defaultBranchBinding = params.defaultBranch ? params.state.branchBindings[params.defaultBranch] ?? null : null;\n  if (defaultBranchBinding?.currentAppId) {\n    return { binding: defaultBranchBinding, branchName: params.defaultBranch };\n  }\n  return null;\n}\nfunction shouldReplaceAsyncInitJobs(params) {\n  return Boolean(params.forceNew);\n}\nfunction shouldReturnPendingAsyncInit(params) {\n  return !params.forceNew && params.pendingJobFound;\n}\n\n// src/application/collab/collabInitBaseline.ts\nasync function trySeedEquivalentBranchBaseline(params) {\n  if (!params.branchName || !params.defaultBranch || params.branchName === params.defaultBranch) {\n    return null;\n  }\n  const bindingState = await readCollabBindingState(params.repoRoot);\n  const defaultBranchBinding = params.defaultBranch ? bindingState?.branchBindings[params.defaultBranch] ?? null : null;\n  if (!defaultBranchBinding?.currentAppId) {\n    return null;\n  }\n  if (params.upstreamAppId && defaultBranchBinding.currentAppId !== params.upstreamAppId) {\n    return null;\n  }\n  const defaultBaseline = await readLocalBaseline({\n    repoFingerprint: params.repoFingerprint,\n    laneId: defaultBranchBinding.laneId,\n    repoRoot: params.repoRoot\n  });\n  if (!defaultBaseline?.lastSnapshotHash || !defaultBaseline.lastServerHeadHash) {\n    return null;\n  }\n  if (defaultBaseline.lastServerHeadHash !== params.appHeadHash) {\n    return null;\n  }\n  const inspection = await inspectLocalSnapshot({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    branchName: params.branchName,\n    persistBlobs: false\n  });\n  if (!canSeedEquivalentBranchBaseline({\n    branchName: params.branchName,\n    defaultBranch: params.defaultBranch,\n    upstreamAppId: params.upstreamAppId,\n    defaultBranchCurrentAppId: defaultBranchBinding?.currentAppId ?? null,\n    defaultBaselineSnapshotHash: defaultBaseline?.lastSnapshotHash ?? null,\n    defaultBaselineServerHeadHash: defaultBaseline?.lastServerHeadHash ?? null,\n    defaultBaselineLocalCommitHash: defaultBaseline?.lastSeenLocalCommitHash ?? null,\n    appHeadHash: params.appHeadHash,\n    localSnapshotHash: inspection.snapshotHash,\n    localCommitHash: inspection.localCommitHash\n  })) {\n    return null;\n  }\n  await writeLocalBaseline({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    currentAppId: params.currentAppId,\n    branchName: params.branchName,\n    lastSnapshotId: defaultBaseline.lastSnapshotId,\n    lastSnapshotHash: defaultBaseline.lastSnapshotHash,\n    lastServerRevisionId: params.appHeadRevisionId,\n    lastServerTreeHash: params.appTreeHash,\n    lastServerHeadHash: params.appHeadHash,\n    lastSeenLocalCommitHash: inspection.localCommitHash\n  });\n  return \"seeded\";\n}\nasync function resolveInitBaselineStatus(params) {\n  const baseline = await readLocalBaseline({\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    repoRoot: params.repoRoot\n  });\n  const existingBaselineStatus = classifyExistingInitBaseline(baseline);\n  if (existingBaselineStatus) return existingBaselineStatus;\n  const localHeadCommitHash = await getHeadCommitHash(params.repoRoot);\n  if (!localHeadCommitHash) return \"baseline_missing\";\n  const appHead = unwrapResponseObject(\n    await params.api.getAppHead(params.currentAppId),\n    \"app head\"\n  );\n  if (localHeadCommitHash === appHead.headCommitHash) {\n    await seedImportedInitBaseline({\n      api: params.api,\n      repoRoot: params.repoRoot,\n      repoFingerprint: params.repoFingerprint,\n      laneId: params.laneId,\n      currentAppId: params.currentAppId,\n      branchName: params.branchName\n    });\n    return \"seeded\";\n  }\n  const localSnapshotHash = params.branchName && params.defaultBranch && params.branchName !== params.defaultBranch ? (await inspectLocalSnapshot({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    branchName: params.branchName,\n    persistBlobs: false\n  })).snapshotHash : void 0;\n  try {\n    const deltaResp = await params.api.getAppDelta(params.currentAppId, {\n      baseHeadHash: localHeadCommitHash,\n      targetHeadHash: appHead.headCommitHash,\n      targetRevisionId: appHead.headRevisionId,\n      localSnapshotHash,\n      repoFingerprint: params.repoFingerprint,\n      remoteUrl: params.remoteUrl ?? void 0,\n      defaultBranch: params.defaultBranch ?? void 0\n    });\n    const delta = unwrapResponseObject(deltaResp, \"app delta\");\n    if (delta.status === \"up_to_date\" || delta.status === \"delta_ready\") {\n      const equivalentBaseline = await trySeedEquivalentBranchBaseline({\n        repoRoot: params.repoRoot,\n        repoFingerprint: params.repoFingerprint,\n        laneId: params.laneId,\n        currentAppId: params.currentAppId,\n        upstreamAppId: params.upstreamAppId ?? null,\n        branchName: params.branchName,\n        defaultBranch: params.defaultBranch,\n        appHeadHash: appHead.headCommitHash,\n        appHeadRevisionId: appHead.headRevisionId ?? null,\n        appTreeHash: appHead.treeHash ?? null\n      });\n      if (equivalentBaseline) {\n        return equivalentBaseline;\n      }\n      return classifyInitBaselineDelta({ deltaStatus: delta.status }) ?? \"baseline_missing\";\n    }\n    if (delta.status === \"content_equivalent\") {\n      await seedImportedInitBaseline({\n        api: params.api,\n        repoRoot: params.repoRoot,\n        repoFingerprint: params.repoFingerprint,\n        laneId: params.laneId,\n        currentAppId: params.currentAppId,\n        branchName: params.branchName\n      });\n      return classifyInitBaselineDelta({ deltaStatus: delta.status }) ?? \"baseline_missing\";\n    }\n    if (delta.status === \"base_unknown\") {\n      const equivalentBaseline = await trySeedEquivalentBranchBaseline({\n        repoRoot: params.repoRoot,\n        repoFingerprint: params.repoFingerprint,\n        laneId: params.laneId,\n        currentAppId: params.currentAppId,\n        upstreamAppId: params.upstreamAppId ?? null,\n        branchName: params.branchName,\n        defaultBranch: params.defaultBranch,\n        appHeadHash: appHead.headCommitHash,\n        appHeadRevisionId: appHead.headRevisionId ?? null,\n        appTreeHash: appHead.treeHash ?? null\n      });\n      if (equivalentBaseline) {\n        return equivalentBaseline;\n      }\n    }\n  } catch {\n  }\n  return \"baseline_missing\";\n}\nasync function seedImportedInitBaseline(params) {\n  const appHead = unwrapResponseObject(\n    await params.api.getAppHead(params.currentAppId),\n    \"app head\"\n  );\n  const snapshot = await captureLocalSnapshot({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    branchName: params.branchName\n  });\n  await writeLocalBaseline({\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    laneId: params.laneId,\n    currentAppId: params.currentAppId,\n    branchName: params.branchName,\n    lastSnapshotId: snapshot.id,\n    lastSnapshotHash: snapshot.snapshotHash,\n    lastServerRevisionId: appHead.headRevisionId ?? null,\n    lastServerTreeHash: appHead.treeHash ?? null,\n    lastServerHeadHash: appHead.headCommitHash,\n    lastSeenLocalCommitHash: snapshot.localCommitHash\n  });\n  return \"seeded\";\n}\n\n// src/application/collab/collabInitBinding.ts\nfunction requireResolvedLaneBinding(lane, params) {\n  if (lane.status === \"resolved\" && lane.currentAppId && lane.upstreamAppId) {\n    return lane;\n  }\n  const branchLabel = params.branchName ?? \"the current branch\";\n  const laneStatus = String(lane.status ?? \"\");\n  throw new RemixError(`Failed to resolve a Remix lane for ${branchLabel}.`, {\n    exitCode: 1,\n    hint: laneStatus === \"binding_not_found\" ? `Run ${params.operation} again after the repository has been initialized.` : laneStatus === \"ambiguous_family_selection\" ? \"Multiple canonical Remix families match this repository. Continue from a checkout already bound to the intended family, or rerun with `--force-new` to create a new family.\" : `Remix did not return complete lane metadata for ${branchLabel}.`\n  });\n}\nfunction resolveProjectBindingResult(response) {\n  const payload = response?.responseObject;\n  if (!payload || typeof payload !== \"object\") {\n    return { status: \"not_found\" };\n  }\n  if (payload.status === \"ambiguous_family_selection\") {\n    const projectIds = Array.isArray(payload.projectIds) ? payload.projectIds.filter((value) => typeof value === \"string\" && value.trim().length > 0) : [];\n    return {\n      status: \"ambiguous_family_selection\",\n      candidateCount: typeof payload.candidateCount === \"number\" && Number.isFinite(payload.candidateCount) ? payload.candidateCount : projectIds.length,\n      projectIds\n    };\n  }\n  if (payload.projectId && payload.appId) {\n    return {\n      status: \"resolved\",\n      projectId: String(payload.projectId),\n      appId: String(payload.appId),\n      upstreamAppId: String(payload.upstreamAppId ?? payload.appId),\n      threadId: payload.threadId ? String(payload.threadId) : null\n    };\n  }\n  return { status: \"not_found\" };\n}\nfunction throwAmbiguousFamilyError(params) {\n  const familyCount = params.candidateCount || params.projectIds.length;\n  const projectHint = params.projectIds.length > 0 ? ` Matching project ids: ${params.projectIds.join(\", \")}.` : \"\";\n  const remoteHint = params.remoteUrl ? ` (${params.remoteUrl})` : \"\";\n  throw new RemixError(\"Multiple canonical Remix families already match this repository.\", {\n    exitCode: 2,\n    hint: `Plain \\`remix collab init\\` cannot safely choose among ${familyCount} matching canonical families for repo fingerprint ${params.repoFingerprint}${remoteHint}.${projectHint} Run \\`remix collab init --force-new\\` to create a new canonical family, or continue from a checkout already bound to the intended family.`\n  });\n}\nasync function resolveOrEnsureLaneBinding(params) {\n  const resolvePayload = {\n    projectId: params.projectId ?? void 0,\n    repoFingerprint: params.repoFingerprint,\n    remoteUrl: params.remoteUrl ?? void 0,\n    defaultBranch: params.defaultBranch ?? void 0,\n    branchName: params.branchName\n  };\n  let lane = unwrapResponseObject(\n    await params.api.resolveProjectLaneBinding(resolvePayload),\n    \"project lane binding\"\n  );\n  if (lane.status !== \"resolved\") {\n    lane = unwrapResponseObject(\n      await params.api.ensureProjectLaneBinding({\n        ...resolvePayload,\n        seedAppId: params.seedAppId ?? void 0,\n        seedHeadCommitHash: params.seedHeadCommitHash ?? void 0\n      }),\n      \"project lane binding\"\n    );\n  }\n  return requireResolvedLaneBinding(lane, {\n    branchName: params.branchName,\n    operation: params.operation\n  });\n}\nfunction branchBindingFromLane(lane, mode, fallback) {\n  return {\n    projectId: lane.projectId ?? fallback.projectId,\n    currentAppId: lane.currentAppId ?? fallback.currentAppId,\n    upstreamAppId: lane.upstreamAppId ?? fallback.upstreamAppId,\n    threadId: lane.threadId ?? fallback.threadId,\n    laneId: lane.laneId ?? null,\n    bindingMode: mode\n  };\n}\n\n// src/application/collab/collabInitAsync.ts\nimport { randomUUID as randomUUID5 } from \"crypto\";\n\n// src/infrastructure/collab/drainerLog.ts\nimport fs9 from \"fs/promises\";\nimport path9 from \"path\";\nasync function logDrainerEvent(jobId, event, fields = {}) {\n  const entry = {\n    ts: (/* @__PURE__ */ new Date()).toISOString(),\n    jobId,\n    event,\n    ...fields\n  };\n  try {\n    await fs9.mkdir(getLogsRoot(), { recursive: true });\n    await fs9.appendFile(getDrainerLogPath(), `${JSON.stringify(entry)}\n`, \"utf8\");\n  } catch {\n  }\n}\nfunction drainerLogPath() {\n  return getDrainerLogPath();\n}\n\n// src/application/collab/collabInitAsync.ts\nasync function resolvePendingAsyncInitResult(params) {\n  if (shouldReplaceAsyncInitJobs({ forceNew: params.forceNew })) {\n    for (const kind of [\"init\", \"init_post\"]) {\n      const existing = await listAsyncJobsForRepo({ repoRoot: params.repoRoot, branchName: params.branchName, kind });\n      for (const job of existing) {\n        await deleteAsyncJob(job.id);\n        await logDrainerEvent(job.id, \"replaced\", {\n          kind,\n          reason: \"force_new\",\n          previousStatus: job.status,\n          previousError: job.error\n        });\n      }\n    }\n    return null;\n  }\n  const pendingPost = await findPendingAsyncJob({ repoRoot: params.repoRoot, branchName: params.branchName, kind: \"init_post\" });\n  const pending = pendingPost ?? await findPendingAsyncJob({ repoRoot: params.repoRoot, branchName: params.branchName, kind: \"init\" });\n  if (!shouldReturnPendingAsyncInit({ forceNew: params.forceNew, pendingJobFound: Boolean(pending) }) || !pending) {\n    return null;\n  }\n  const existingBinding = await readCollabBinding(params.repoRoot);\n  if (existingBinding && existingBinding.currentAppId) {\n    return {\n      queued: true,\n      jobId: pending.id,\n      repoRoot: params.repoRoot,\n      projectId: existingBinding.projectId ?? \"\",\n      appId: existingBinding.currentAppId,\n      upstreamAppId: existingBinding.upstreamAppId ?? existingBinding.currentAppId,\n      dashboardUrl: buildDashboardAppUrl(existingBinding.currentAppId),\n      bindingPath: getCollabBindingPath(params.repoRoot),\n      repoFingerprint: existingBinding.repoFingerprint ?? params.repoFingerprint,\n      bindingMode: existingBinding.bindingMode,\n      createdCanonicalFamily: false,\n      remoteUrl: existingBinding.remoteUrl ?? params.remoteUrl,\n      defaultBranch: existingBinding.defaultBranch ?? params.defaultBranch ?? null,\n      ...params.warnings.length > 0 ? { warnings: params.warnings } : {}\n    };\n  }\n  return {\n    queued: true,\n    jobId: pending.id,\n    repoRoot: params.repoRoot,\n    projectId: \"\",\n    appId: \"\",\n    upstreamAppId: \"\",\n    dashboardUrl: \"\",\n    bindingPath: getCollabBindingPath(params.repoRoot),\n    repoFingerprint: params.repoFingerprint,\n    bindingMode: \"lane\",\n    createdCanonicalFamily: false,\n    remoteUrl: params.remoteUrl,\n    defaultBranch: params.defaultBranch ?? null,\n    ...params.warnings.length > 0 ? { warnings: params.warnings } : {}\n  };\n}\nasync function clearFailedAsyncInitJobs(params) {\n  if (params.forceNew) return;\n  const failed = await findFailedAsyncJob({ repoRoot: params.repoRoot, branchName: params.branchName, kind: \"init\" });\n  if (failed) {\n    await deleteAsyncJob(failed.id);\n  }\n  const failedPost = await findFailedAsyncJob({ repoRoot: params.repoRoot, branchName: params.branchName, kind: \"init_post\" });\n  if (failedPost) {\n    await deleteAsyncJob(failedPost.id);\n  }\n}\nasync function enqueueInitPostJob(params) {\n  const job = await enqueueAsyncJob({\n    id: randomUUID5(),\n    kind: \"init_post\",\n    status: \"queued\",\n    repoRoot: params.repoRoot,\n    repoFingerprint: params.repoFingerprint,\n    branchName: params.branchName,\n    laneId: params.laneId,\n    retryCount: 0,\n    error: null,\n    idempotencyKey: null,\n    payload: {\n      appId: params.appId,\n      syncPhaseStartedAt: params.syncPhaseStartedAt,\n      syncPhaseFinishedAt: params.syncPhaseFinishedAt\n    }\n  });\n  await logDrainerEvent(job.id, \"submitted\", {\n    kind: \"init_post\",\n    appId: params.appId,\n    [\"init.sync_phase_ms\"]: params.syncPhaseFinishedAt - params.syncPhaseStartedAt\n  });\n  return job;\n}\n\n// src/application/collab/collabInitImport.ts\nimport fs11 from \"fs/promises\";\nimport path10 from \"path\";\n\n// src/shared/upload.ts\nimport fs10 from \"fs\";\nimport { PassThrough } from \"stream\";\nasync function uploadPresigned(params) {\n  const stats = await fs10.promises.stat(params.filePath).catch(() => null);\n  if (!stats || !stats.isFile()) {\n    throw new RemixError(\"Upload file not found.\", { exitCode: 2 });\n  }\n  const totalBytes = stats.size;\n  const fileStream = fs10.createReadStream(params.filePath);\n  const pass = new PassThrough();\n  let sentBytes = 0;\n  fileStream.on(\"data\", (chunk) => {\n    sentBytes += chunk.length;\n    params.onProgress?.({ sentBytes, totalBytes });\n  });\n  fileStream.on(\"error\", (err) => pass.destroy(err));\n  fileStream.pipe(pass);\n  const response = await fetch(params.uploadUrl, {\n    method: \"PUT\",\n    headers: params.headers,\n    body: pass,\n    duplex: \"half\"\n  });\n  if (!response.ok) {\n    const text = await response.text().catch(() => \"\");\n    throw new RemixError(\"Upload failed.\", {\n      exitCode: 1,\n      hint: `Status: ${response.status}\n${text}`.trim() || null\n    });\n  }\n}\n\n// src/application/collab/collabInitImport.ts\nasync function uploadInitBundle(params) {\n  const bundleName = params.bundleName ?? path10.basename(params.bundlePath);\n  const bundleSize = (await fs11.stat(params.bundlePath)).size;\n  const presignResp = await params.api.presignImportUploadFirstParty({\n    file: {\n      name: bundleName,\n      mimeType: \"application/x-git-bundle\",\n      size: bundleSize,\n      checksumSha256: params.bundleSha\n    }\n  });\n  const presign = unwrapResponseObject(presignResp, \"upload\");\n  await uploadPresigned({\n    uploadUrl: String(presign.uploadUrl),\n    headers: presign.headers ?? {},\n    filePath: params.bundlePath\n  });\n  return String(presign.uploadId);\n}\nasync function importUploadedInitBundle(params) {\n  const importPayload = {\n    uploadId: params.uploadId,\n    appName: params.appName,\n    platform: \"generic\",\n    profile: params.profile ?? void 0,\n    isPublic: false,\n    branch: params.branch ?? void 0,\n    remoteUrl: params.remoteUrl ?? void 0,\n    defaultBranch: params.defaultBranch ?? void 0,\n    repoFingerprint: params.repoFingerprint,\n    headCommitHash: params.headCommitHash,\n    forceNew: params.forceNew\n  };\n  if (\"path\" in params) {\n    importPayload.path = params.path?.trim() || void 0;\n  }\n  const importResp = await params.api.importFromUploadFirstParty(importPayload);\n  return unwrapResponseObject(importResp, \"import\");\n}\n\n// src/application/collab/collabInit.ts\nasync function collabInit(params) {\n  return withRepoMutationLock(\n    {\n      cwd: params.cwd,\n      operation: \"collabInit\"\n    },\n    async ({ repoRoot, warnings }) => {\n      await ensureGitInfoExcludeEntries(repoRoot, [\".remix/\"]);\n      if (params.path?.trim()) {\n        throw new RemixError(\"`remix collab init --path` is not supported.\", {\n          exitCode: 2,\n          hint: \"History-preserving init imports the full git repository. Run the command from the repository root without --path.\"\n        });\n      }\n      const localBindingState = await readCollabBindingState(repoRoot, { persist: true });\n      const hasExistingBinding = localBindingState != null && Object.keys(localBindingState.branchBindings ?? {}).length > 0;\n      if (shouldRequireCleanWorktreeForInit({ forceNew: params.forceNew, hasExistingBinding })) {\n        await ensureCleanWorktree(repoRoot, \"`remix collab init`\");\n      }\n      const persistedRemoteUrl = normalizeGitRemote(localBindingState?.remoteUrl ?? null);\n      const currentBranch = await getCurrentBranch(repoRoot);\n      const defaultBranch = localBindingState?.defaultBranch ?? await getDefaultBranch(repoRoot) ?? currentBranch;\n      const branchName = currentBranch ?? defaultBranch ?? null;\n      const localHeadCommitHash = await getHeadCommitHash(repoRoot);\n      const remoteUrl = persistedRemoteUrl ?? normalizeGitRemote(await getRemoteOriginUrl(repoRoot));\n      const repoFingerprint = localBindingState?.repoFingerprint ?? await buildRepoFingerprint({ gitRoot: repoRoot, remoteUrl, defaultBranch });\n      const repoSnapshot = await captureRepoSnapshot(repoRoot);\n      if (params.asyncSubmit) {\n        const pendingResult = await resolvePendingAsyncInitResult({\n          forceNew: params.forceNew,\n          repoRoot,\n          branchName,\n          repoFingerprint,\n          remoteUrl,\n          defaultBranch: defaultBranch ?? null,\n          warnings\n        });\n        if (pendingResult) {\n          return pendingResult;\n        }\n      }\n      if (!params.forceNew && localBindingState?.explicitRootBinding && branchName) {\n        const explicitRoot = localBindingState.explicitRootBinding;\n        const explicitProjectId = explicitRoot.projectId ?? localBindingState.projectId;\n        let canonicalLane2 = null;\n        let boundProjectId2 = explicitProjectId;\n        let boundCurrentAppId2 = explicitRoot.currentAppId;\n        let boundUpstreamAppId2 = explicitRoot.upstreamAppId;\n        let boundThreadId2 = explicitRoot.threadId;\n        let boundLaneId2 = explicitRoot.laneId;\n        if (defaultBranch && branchName !== defaultBranch) {\n          canonicalLane2 = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: explicitProjectId ?? void 0,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName: defaultBranch,\n            operation: \"`remix collab init`\"\n          });\n          const lane = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: canonicalLane2.projectId ?? explicitProjectId ?? void 0,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName,\n            seedHeadCommitHash: localHeadCommitHash,\n            operation: \"`remix collab init`\"\n          });\n          boundProjectId2 = lane.projectId ?? boundProjectId2;\n          boundCurrentAppId2 = lane.currentAppId ?? boundCurrentAppId2;\n          boundUpstreamAppId2 = lane.upstreamAppId ?? boundUpstreamAppId2;\n          boundThreadId2 = lane.threadId ?? boundThreadId2;\n          boundLaneId2 = lane.laneId ?? null;\n        } else {\n          canonicalLane2 = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: explicitProjectId ?? void 0,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName,\n            operation: \"`remix collab init`\"\n          });\n          boundProjectId2 = canonicalLane2.projectId ?? boundProjectId2;\n          boundCurrentAppId2 = canonicalLane2.currentAppId ?? boundCurrentAppId2;\n          boundUpstreamAppId2 = canonicalLane2.upstreamAppId ?? boundUpstreamAppId2;\n          boundThreadId2 = canonicalLane2.threadId ?? boundThreadId2;\n          boundLaneId2 = canonicalLane2.laneId ?? null;\n        }\n        const readyApp = await pollAppImported(params.api, boundCurrentAppId2);\n        boundProjectId2 = String(readyApp.projectId ?? boundProjectId2);\n        boundThreadId2 = readyApp.threadId ? String(readyApp.threadId) : boundThreadId2;\n        await assertRepoSnapshotUnchanged(repoRoot, repoSnapshot, {\n          operation: \"`remix collab init`\",\n          recoveryHint: \"The repository changed while the local binding was being initialized. Review the local changes and rerun `remix collab init`.\"\n        });\n        await writeCollabBinding(repoRoot, {\n          projectId: canonicalLane2?.projectId ?? explicitProjectId ?? null,\n          currentAppId: canonicalLane2?.currentAppId ?? explicitRoot.currentAppId,\n          upstreamAppId: canonicalLane2?.upstreamAppId ?? canonicalLane2?.currentAppId ?? explicitRoot.upstreamAppId ?? explicitRoot.currentAppId,\n          threadId: canonicalLane2?.threadId ?? explicitRoot.threadId,\n          repoFingerprint: canonicalLane2?.repoFingerprint ?? explicitRoot.repoFingerprint ?? repoFingerprint,\n          remoteUrl: canonicalLane2?.remoteUrl ?? explicitRoot.remoteUrl ?? remoteUrl,\n          defaultBranch: canonicalLane2?.defaultBranch ?? explicitRoot.defaultBranch ?? defaultBranch ?? null,\n          laneId: canonicalLane2?.laneId ?? explicitRoot.laneId,\n          branchName: defaultBranch,\n          bindingMode: \"explicit_root\"\n        });\n        if (defaultBranch && branchName !== defaultBranch) {\n          await writeCollabBinding(repoRoot, {\n            projectId: boundProjectId2,\n            currentAppId: boundCurrentAppId2,\n            upstreamAppId: boundUpstreamAppId2,\n            threadId: boundThreadId2,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch: defaultBranch ?? null,\n            laneId: boundLaneId2,\n            branchName,\n            bindingMode: \"lane\"\n          });\n        }\n        return {\n          reused: true,\n          projectId: boundProjectId2 ?? explicitProjectId ?? \"\",\n          appId: boundCurrentAppId2,\n          dashboardUrl: buildDashboardAppUrl(boundCurrentAppId2),\n          upstreamAppId: boundUpstreamAppId2,\n          bindingPath: path11.join(repoRoot, \".remix\", \"config.json\"),\n          repoRoot,\n          repoFingerprint,\n          bindingMode: defaultBranch && branchName !== defaultBranch ? \"lane\" : \"explicit_root\",\n          createdCanonicalFamily: false,\n          baselineStatus: await resolveInitBaselineStatus({\n            api: params.api,\n            repoRoot,\n            repoFingerprint,\n            laneId: boundLaneId2,\n            currentAppId: boundCurrentAppId2,\n            upstreamAppId: boundUpstreamAppId2,\n            branchName,\n            remoteUrl,\n            defaultBranch\n          }),\n          ...warnings.length > 0 ? { warnings } : {}\n        };\n      }\n      const storedBindingAnchor = localBindingState && branchName ? resolveStoredBindingAnchor({\n        state: localBindingState,\n        currentBranch,\n        defaultBranch\n      }) : null;\n      if (!params.forceNew && localBindingState && storedBindingAnchor && branchName) {\n        const existingBinding = storedBindingAnchor.binding;\n        const existingProjectId = existingBinding.projectId ?? localBindingState.projectId;\n        let canonicalLane2 = null;\n        let boundProjectId2 = existingProjectId;\n        let boundCurrentAppId2 = existingBinding.currentAppId;\n        let boundUpstreamAppId2 = existingBinding.upstreamAppId;\n        let boundThreadId2 = existingBinding.threadId;\n        let boundLaneId2 = existingBinding.laneId;\n        if (defaultBranch && branchName !== defaultBranch) {\n          canonicalLane2 = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: existingProjectId ?? void 0,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName: defaultBranch,\n            operation: \"`remix collab init`\"\n          });\n          const lane = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: canonicalLane2.projectId ?? existingProjectId ?? void 0,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName,\n            seedHeadCommitHash: localHeadCommitHash,\n            operation: \"`remix collab init`\"\n          });\n          boundProjectId2 = lane.projectId ?? boundProjectId2;\n          boundCurrentAppId2 = lane.currentAppId ?? boundCurrentAppId2;\n          boundUpstreamAppId2 = lane.upstreamAppId ?? boundUpstreamAppId2;\n          boundThreadId2 = lane.threadId ?? boundThreadId2;\n          boundLaneId2 = lane.laneId ?? null;\n        } else {\n          canonicalLane2 = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: existingProjectId ?? void 0,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName,\n            operation: \"`remix collab init`\"\n          });\n          boundProjectId2 = canonicalLane2.projectId ?? boundProjectId2;\n          boundCurrentAppId2 = canonicalLane2.currentAppId ?? boundCurrentAppId2;\n          boundUpstreamAppId2 = canonicalLane2.upstreamAppId ?? boundUpstreamAppId2;\n          boundThreadId2 = canonicalLane2.threadId ?? boundThreadId2;\n          boundLaneId2 = canonicalLane2.laneId ?? null;\n        }\n        const readyApp = await pollAppImported(params.api, boundCurrentAppId2);\n        boundProjectId2 = String(readyApp.projectId ?? boundProjectId2);\n        boundThreadId2 = readyApp.threadId ? String(readyApp.threadId) : boundThreadId2;\n        await assertRepoSnapshotUnchanged(repoRoot, repoSnapshot, {\n          operation: \"`remix collab init`\",\n          recoveryHint: \"The repository changed while the local binding was being initialized. Review the local changes and rerun `remix collab init`.\"\n        });\n        if (canonicalLane2 && defaultBranch && branchName !== defaultBranch) {\n          await writeCollabBinding(repoRoot, {\n            projectId: canonicalLane2.projectId ?? existingProjectId ?? null,\n            currentAppId: canonicalLane2.currentAppId ?? existingBinding.currentAppId,\n            upstreamAppId: canonicalLane2.upstreamAppId ?? canonicalLane2.currentAppId ?? existingBinding.upstreamAppId ?? existingBinding.currentAppId,\n            threadId: canonicalLane2.threadId ?? existingBinding.threadId,\n            repoFingerprint: canonicalLane2.repoFingerprint ?? localBindingState.repoFingerprint ?? repoFingerprint,\n            remoteUrl: canonicalLane2.remoteUrl ?? localBindingState.remoteUrl ?? remoteUrl,\n            defaultBranch: canonicalLane2.defaultBranch ?? localBindingState.defaultBranch ?? defaultBranch ?? null,\n            laneId: canonicalLane2.laneId ?? null,\n            branchName: defaultBranch,\n            bindingMode: \"lane\"\n          });\n        }\n        const bindingPath2 = await writeCollabBinding(repoRoot, {\n          projectId: boundProjectId2,\n          currentAppId: boundCurrentAppId2,\n          upstreamAppId: boundUpstreamAppId2,\n          threadId: boundThreadId2,\n          repoFingerprint,\n          remoteUrl,\n          defaultBranch: defaultBranch ?? null,\n          laneId: boundLaneId2,\n          branchName,\n          bindingMode: \"lane\"\n        });\n        return {\n          reused: true,\n          projectId: boundProjectId2 ?? existingProjectId ?? \"\",\n          appId: boundCurrentAppId2,\n          dashboardUrl: buildDashboardAppUrl(boundCurrentAppId2),\n          upstreamAppId: boundUpstreamAppId2,\n          bindingPath: bindingPath2,\n          repoRoot,\n          repoFingerprint,\n          bindingMode: \"lane\",\n          createdCanonicalFamily: false,\n          baselineStatus: await resolveInitBaselineStatus({\n            api: params.api,\n            repoRoot,\n            repoFingerprint,\n            laneId: boundLaneId2,\n            currentAppId: boundCurrentAppId2,\n            upstreamAppId: boundUpstreamAppId2,\n            branchName,\n            remoteUrl,\n            defaultBranch\n          }),\n          ...warnings.length > 0 ? { warnings } : {}\n        };\n      }\n      if (!params.forceNew) {\n        const bindingResolution = resolveProjectBindingResult(\n          await params.api.resolveProjectBinding({\n            repoFingerprint,\n            remoteUrl: remoteUrl ?? void 0,\n            branchName: branchName ?? void 0\n          })\n        );\n        if (bindingResolution.status === \"ambiguous_family_selection\") {\n          throwAmbiguousFamilyError({\n            repoFingerprint,\n            remoteUrl,\n            projectIds: bindingResolution.projectIds,\n            candidateCount: bindingResolution.candidateCount\n          });\n        }\n        if (bindingResolution.status === \"resolved\") {\n          const initialProjectId = bindingResolution.projectId;\n          const initialCurrentAppId = bindingResolution.appId;\n          const initialUpstreamAppId = bindingResolution.upstreamAppId;\n          const initialThreadId = bindingResolution.threadId;\n          let boundProjectId2 = initialProjectId;\n          let boundCurrentAppId2 = initialCurrentAppId;\n          let boundUpstreamAppId2 = initialUpstreamAppId;\n          let boundThreadId2 = initialThreadId;\n          let boundLaneId2 = null;\n          let canonicalLane2 = null;\n          if (branchName) {\n            if (defaultBranch && branchName !== defaultBranch) {\n              canonicalLane2 = await resolveOrEnsureLaneBinding({\n                api: params.api,\n                repoFingerprint,\n                remoteUrl,\n                defaultBranch,\n                branchName: defaultBranch,\n                seedAppId: initialCurrentAppId,\n                operation: \"`remix collab init`\"\n              });\n              const lane = await resolveOrEnsureLaneBinding({\n                api: params.api,\n                projectId: canonicalLane2.projectId ?? void 0,\n                repoFingerprint,\n                remoteUrl,\n                defaultBranch,\n                branchName,\n                seedHeadCommitHash: localHeadCommitHash,\n                operation: \"`remix collab init`\"\n              });\n              boundProjectId2 = lane.projectId ?? boundProjectId2;\n              boundCurrentAppId2 = lane.currentAppId ?? boundCurrentAppId2;\n              boundUpstreamAppId2 = lane.upstreamAppId ?? boundUpstreamAppId2;\n              boundThreadId2 = lane.threadId ?? boundThreadId2;\n              boundLaneId2 = lane.laneId ?? null;\n            } else {\n              const lane = await resolveOrEnsureLaneBinding({\n                api: params.api,\n                repoFingerprint,\n                remoteUrl,\n                defaultBranch,\n                branchName,\n                seedAppId: initialCurrentAppId,\n                operation: \"`remix collab init`\"\n              });\n              canonicalLane2 = lane;\n              boundProjectId2 = lane.projectId ?? boundProjectId2;\n              boundCurrentAppId2 = lane.currentAppId ?? boundCurrentAppId2;\n              boundUpstreamAppId2 = lane.upstreamAppId ?? boundUpstreamAppId2;\n              boundThreadId2 = lane.threadId ?? boundThreadId2;\n              boundLaneId2 = lane.laneId ?? null;\n            }\n          }\n          if (boundCurrentAppId2) {\n            const readyApp = await pollAppImported(params.api, boundCurrentAppId2);\n            boundProjectId2 = String(readyApp.projectId ?? boundProjectId2);\n            boundThreadId2 = readyApp.threadId ? String(readyApp.threadId) : boundThreadId2;\n          }\n          await assertRepoSnapshotUnchanged(repoRoot, repoSnapshot, {\n            operation: \"`remix collab init`\",\n            recoveryHint: \"The repository changed while the local binding was being initialized. Review the local changes and rerun `remix collab init`.\"\n          });\n          if (canonicalLane2 && defaultBranch && branchName && branchName !== defaultBranch) {\n            await writeCollabBinding(repoRoot, {\n              projectId: canonicalLane2.projectId ?? null,\n              currentAppId: canonicalLane2.currentAppId ?? boundCurrentAppId2,\n              upstreamAppId: canonicalLane2.upstreamAppId ?? canonicalLane2.currentAppId ?? boundCurrentAppId2,\n              threadId: canonicalLane2.threadId ?? null,\n              repoFingerprint: canonicalLane2.repoFingerprint ?? repoFingerprint,\n              remoteUrl: canonicalLane2.remoteUrl ?? remoteUrl,\n              defaultBranch: canonicalLane2.defaultBranch ?? defaultBranch,\n              laneId: canonicalLane2.laneId ?? null,\n              branchName: defaultBranch,\n              bindingMode: \"lane\"\n            });\n          }\n          const bindingPath2 = await writeCollabBinding(repoRoot, {\n            projectId: boundProjectId2,\n            currentAppId: boundCurrentAppId2,\n            upstreamAppId: boundUpstreamAppId2,\n            threadId: boundThreadId2,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch: defaultBranch ?? null,\n            laneId: boundLaneId2,\n            branchName,\n            bindingMode: \"lane\"\n          });\n          return {\n            reused: true,\n            projectId: boundProjectId2,\n            appId: boundCurrentAppId2,\n            dashboardUrl: buildDashboardAppUrl(boundCurrentAppId2),\n            upstreamAppId: boundUpstreamAppId2,\n            bindingPath: bindingPath2,\n            repoRoot,\n            repoFingerprint,\n            bindingMode: \"lane\",\n            createdCanonicalFamily: false,\n            baselineStatus: await resolveInitBaselineStatus({\n              api: params.api,\n              repoRoot,\n              repoFingerprint,\n              laneId: boundLaneId2,\n              currentAppId: boundCurrentAppId2,\n              upstreamAppId: boundUpstreamAppId2,\n              branchName,\n              remoteUrl,\n              defaultBranch\n            }),\n            ...warnings.length > 0 ? { warnings } : {}\n          };\n        }\n      }\n      if (params.asyncSubmit) {\n        await clearFailedAsyncInitJobs({ forceNew: params.forceNew, repoRoot, branchName });\n        const syncPhaseStartedAt = Date.now();\n        const { bundlePath: bundleFilePath, headCommitHash: bundledHeadCommitHash } = await createGitBundle(\n          repoRoot,\n          \"repository.bundle\"\n        );\n        const tmpBundleDir = path11.dirname(bundleFilePath);\n        try {\n          const bundleSha2 = await sha256FileHex(bundleFilePath);\n          const uploadId2 = await uploadInitBundle({\n            api: params.api,\n            bundlePath: bundleFilePath,\n            bundleSha: bundleSha2,\n            bundleName: \"repository.bundle\"\n          });\n          const imported2 = await importUploadedInitBundle({\n            api: params.api,\n            uploadId: uploadId2,\n            appName: params.appName?.trim() || path11.basename(repoRoot),\n            profile: params.profile ?? void 0,\n            branch: defaultBranch && branchName && branchName !== defaultBranch ? defaultBranch : currentBranch ?? void 0,\n            remoteUrl,\n            defaultBranch: defaultBranch ?? null,\n            repoFingerprint,\n            headCommitHash: bundledHeadCommitHash,\n            forceNew: params.forceNew\n          });\n          const importedAppId = String(imported2.appId);\n          let boundProjectId2 = String(imported2.projectId ?? \"\");\n          let boundCurrentAppId2 = importedAppId;\n          let boundUpstreamAppId2 = importedAppId;\n          let boundThreadId2 = imported2.threadId ? String(imported2.threadId) : null;\n          let boundLaneId2 = null;\n          let canonicalLane2 = null;\n          if (branchName) {\n            if (defaultBranch && branchName !== defaultBranch) {\n              canonicalLane2 = await resolveOrEnsureLaneBinding({\n                api: params.api,\n                projectId: boundProjectId2 || void 0,\n                repoFingerprint,\n                remoteUrl,\n                defaultBranch,\n                branchName: defaultBranch,\n                seedAppId: importedAppId,\n                operation: \"`remix collab init`\"\n              });\n              const lane = await resolveOrEnsureLaneBinding({\n                api: params.api,\n                projectId: canonicalLane2.projectId ?? boundProjectId2 ?? void 0,\n                repoFingerprint,\n                remoteUrl,\n                defaultBranch,\n                branchName,\n                seedHeadCommitHash: bundledHeadCommitHash,\n                operation: \"`remix collab init`\"\n              });\n              boundProjectId2 = lane.projectId ?? boundProjectId2;\n              boundCurrentAppId2 = lane.currentAppId ?? boundCurrentAppId2;\n              boundUpstreamAppId2 = lane.upstreamAppId ?? boundUpstreamAppId2;\n              boundThreadId2 = lane.threadId ?? boundThreadId2;\n              boundLaneId2 = lane.laneId ?? null;\n            } else {\n              const lane = await resolveOrEnsureLaneBinding({\n                api: params.api,\n                projectId: boundProjectId2 || void 0,\n                repoFingerprint,\n                remoteUrl,\n                defaultBranch,\n                branchName,\n                seedAppId: importedAppId,\n                operation: \"`remix collab init`\"\n              });\n              canonicalLane2 = lane;\n              boundProjectId2 = lane.projectId ?? boundProjectId2;\n              boundCurrentAppId2 = lane.currentAppId ?? boundCurrentAppId2;\n              boundUpstreamAppId2 = lane.upstreamAppId ?? boundUpstreamAppId2;\n              boundThreadId2 = lane.threadId ?? boundThreadId2;\n              boundLaneId2 = lane.laneId ?? null;\n            }\n          }\n          await assertRepoSnapshotUnchanged(repoRoot, repoSnapshot, {\n            operation: \"`remix collab init`\",\n            recoveryHint: \"The repository changed before the Remix binding was written. Review the local changes and rerun `remix collab init`.\"\n          });\n          const bindingMode2 = defaultBranch && branchName !== defaultBranch ? \"lane\" : \"explicit_root\";\n          let bindingPath2;\n          if (params.forceNew && defaultBranch && canonicalLane2) {\n            const canonicalBinding = branchBindingFromLane(canonicalLane2, \"explicit_root\", {\n              projectId: canonicalLane2.projectId ?? boundProjectId2,\n              currentAppId: canonicalLane2.currentAppId ?? boundCurrentAppId2,\n              upstreamAppId: canonicalLane2.upstreamAppId ?? canonicalLane2.currentAppId ?? boundCurrentAppId2,\n              threadId: canonicalLane2.threadId ?? boundThreadId2\n            });\n            const branchBindings = {\n              [defaultBranch]: canonicalBinding\n            };\n            if (branchName && branchName !== defaultBranch) {\n              branchBindings[branchName] = {\n                projectId: boundProjectId2,\n                currentAppId: boundCurrentAppId2,\n                upstreamAppId: boundUpstreamAppId2,\n                threadId: boundThreadId2,\n                laneId: boundLaneId2,\n                bindingMode: \"lane\"\n              };\n            }\n            bindingPath2 = await writeCollabBindingSnapshot({\n              repoRoot,\n              repoFingerprint,\n              remoteUrl,\n              defaultBranch,\n              branchBindings,\n              explicitRootBinding: canonicalBinding\n            });\n          } else {\n            if (canonicalLane2 && defaultBranch && branchName && branchName !== defaultBranch) {\n              await writeCollabBinding(repoRoot, {\n                projectId: canonicalLane2.projectId ?? null,\n                currentAppId: canonicalLane2.currentAppId ?? boundCurrentAppId2,\n                upstreamAppId: canonicalLane2.upstreamAppId ?? canonicalLane2.currentAppId ?? boundCurrentAppId2,\n                threadId: canonicalLane2.threadId ?? null,\n                repoFingerprint: canonicalLane2.repoFingerprint ?? repoFingerprint,\n                remoteUrl: canonicalLane2.remoteUrl ?? remoteUrl,\n                defaultBranch: canonicalLane2.defaultBranch ?? defaultBranch,\n                laneId: canonicalLane2.laneId ?? null,\n                branchName: defaultBranch,\n                // This branch is reached only when the CURRENT branch is\n                // not the default branch — so the binding being written\n                // here is for the DEFAULT branch (the canonical/main app).\n                // It must always be `explicit_root` regardless of\n                // `forceNew`; the previous `forceNew ? ... : \"lane\"`\n                // produced a `lane`-marked default-branch binding for\n                // every plain init, which silently disabled the\n                // history-import auto-spawn.\n                bindingMode: \"explicit_root\"\n              });\n            }\n            bindingPath2 = await writeCollabBinding(repoRoot, {\n              projectId: boundProjectId2,\n              currentAppId: boundCurrentAppId2,\n              upstreamAppId: boundUpstreamAppId2,\n              threadId: boundThreadId2,\n              repoFingerprint,\n              remoteUrl,\n              defaultBranch: defaultBranch ?? null,\n              laneId: boundLaneId2,\n              branchName,\n              bindingMode: bindingMode2\n            });\n          }\n          const syncPhaseFinishedAt = Date.now();\n          const job = await enqueueInitPostJob({\n            repoRoot,\n            repoFingerprint,\n            branchName,\n            laneId: boundLaneId2,\n            appId: boundCurrentAppId2,\n            syncPhaseStartedAt,\n            syncPhaseFinishedAt\n          });\n          return {\n            queued: true,\n            jobId: job.id,\n            repoRoot,\n            projectId: boundProjectId2,\n            appId: boundCurrentAppId2,\n            upstreamAppId: boundUpstreamAppId2,\n            dashboardUrl: buildDashboardAppUrl(boundCurrentAppId2),\n            bindingPath: bindingPath2,\n            repoFingerprint,\n            bindingMode: bindingMode2,\n            createdCanonicalFamily: Boolean(params.forceNew),\n            remoteUrl,\n            defaultBranch,\n            ...warnings.length > 0 ? { warnings } : {}\n          };\n        } finally {\n          await fs12.rm(tmpBundleDir, { recursive: true, force: true }).catch(() => void 0);\n        }\n      }\n      const { bundlePath, headCommitHash } = await createGitBundle(repoRoot, \"repository.bundle\");\n      const bundleSha = await sha256FileHex(bundlePath);\n      const uploadId = await uploadInitBundle({\n        api: params.api,\n        bundlePath,\n        bundleSha,\n        bundleName: \"repository.bundle\"\n      });\n      const imported = await importUploadedInitBundle({\n        api: params.api,\n        uploadId,\n        appName: params.appName?.trim() || path11.basename(repoRoot),\n        path: params.path?.trim() || void 0,\n        profile: params.profile ?? void 0,\n        branch: defaultBranch && branchName && branchName !== defaultBranch ? defaultBranch : currentBranch ?? void 0,\n        remoteUrl,\n        defaultBranch: defaultBranch ?? null,\n        repoFingerprint,\n        headCommitHash,\n        forceNew: params.forceNew\n      });\n      const app = await pollAppImported(params.api, String(imported.appId));\n      let boundProjectId = String(app.projectId);\n      let boundCurrentAppId = String(app.id);\n      let boundUpstreamAppId = String(app.id);\n      let boundThreadId = app.threadId ? String(app.threadId) : null;\n      let boundLaneId = null;\n      let canonicalLane = null;\n      if (branchName) {\n        if (defaultBranch && branchName !== defaultBranch) {\n          canonicalLane = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: boundProjectId,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName: defaultBranch,\n            seedAppId: String(app.id),\n            operation: \"`remix collab init`\"\n          });\n          const lane = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: canonicalLane.projectId ?? boundProjectId,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName,\n            seedHeadCommitHash: headCommitHash,\n            operation: \"`remix collab init`\"\n          });\n          boundProjectId = lane.projectId ?? boundProjectId;\n          boundCurrentAppId = lane.currentAppId ?? boundCurrentAppId;\n          boundUpstreamAppId = lane.upstreamAppId ?? boundUpstreamAppId;\n          boundThreadId = lane.threadId ?? boundThreadId;\n          boundLaneId = lane.laneId ?? null;\n        } else {\n          const lane = await resolveOrEnsureLaneBinding({\n            api: params.api,\n            projectId: boundProjectId,\n            repoFingerprint,\n            remoteUrl,\n            defaultBranch,\n            branchName,\n            seedAppId: String(app.id),\n            operation: \"`remix collab init`\"\n          });\n          canonicalLane = lane;\n          boundProjectId = lane.projectId ?? boundProjectId;\n          boundCurrentAppId = lane.currentAppId ?? boundCurrentAppId;\n          boundUpstreamAppId = lane.upstreamAppId ?? boundUpstreamAppId;\n          boundThreadId = lane.threadId ?? boundThreadId;\n          boundLaneId = lane.laneId ?? null;\n        }\n      }\n      if (boundCurrentAppId) {\n        const readyApp = await pollAppImported(params.api, boundCurrentAppId);\n        boundProjectId = String(readyApp.projectId ?? boundProjectId);\n        boundThreadId = readyApp.threadId ? String(readyApp.threadId) : boundThreadId;\n      }\n      await assertRepoSnapshotUnchanged(repoRoot, repoSnapshot, {\n        operation: \"`remix collab init`\",\n        recoveryHint: \"The repository changed before the Remix binding was written. Review the local changes and rerun `remix collab init`.\"\n      });\n      const bindingMode = defaultBranch && branchName !== defaultBranch ? \"lane\" : \"explicit_root\";\n      let bindingPath;\n      if (params.forceNew && defaultBranch && canonicalLane) {\n        const canonicalBinding = branchBindingFromLane(canonicalLane, \"explicit_root\", {\n          projectId: canonicalLane.projectId ?? boundProjectId,\n          currentAppId: canonicalLane.currentAppId ?? boundCurrentAppId,\n          upstreamAppId: canonicalLane.upstreamAppId ?? canonicalLane.currentAppId ?? boundCurrentAppId,\n          threadId: canonicalLane.threadId ?? boundThreadId\n        });\n        const branchBindings = {\n          [defaultBranch]: canonicalBinding\n        };\n        if (branchName && branchName !== defaultBranch) {\n          branchBindings[branchName] = {\n            projectId: boundProjectId,\n            currentAppId: boundCurrentAppId,\n            upstreamAppId: boundUpstreamAppId,\n            threadId: boundThreadId,\n            laneId: boundLaneId,\n            bindingMode: \"lane\"\n          };\n        }\n        bindingPath = await writeCollabBindingSnapshot({\n          repoRoot,\n          repoFingerprint,\n          remoteUrl,\n          defaultBranch,\n          branchBindings,\n          explicitRootBinding: canonicalBinding\n        });\n      } else {\n        if (canonicalLane && defaultBranch && branchName && branchName !== defaultBranch) {\n          await writeCollabBinding(repoRoot, {\n            projectId: canonicalLane.projectId ?? null,\n            currentAppId: canonicalLane.currentAppId ?? boundCurrentAppId,\n            upstreamAppId: canonicalLane.upstreamAppId ?? canonicalLane.currentAppId ?? boundCurrentAppId,\n            threadId: canonicalLane.threadId ?? null,\n            repoFingerprint: canonicalLane.repoFingerprint ?? repoFingerprint,\n            remoteUrl: canonicalLane.remoteUrl ?? remoteUrl,\n            defaultBranch: canonicalLane.defaultBranch ?? defaultBranch,\n            laneId: canonicalLane.laneId ?? null,\n            branchName: defaultBranch,\n            // Same reasoning as the queued-path default-branch write\n            // above: this is the canonical/main-app binding for the\n            // default branch and must be `explicit_root`, otherwise the\n            // history-import auto-spawn (gated on explicit_root) will\n            // silently no-op for every plain init.\n            bindingMode: \"explicit_root\"\n          });\n        }\n        bindingPath = await writeCollabBinding(repoRoot, {\n          projectId: boundProjectId,\n          currentAppId: boundCurrentAppId,\n          upstreamAppId: boundUpstreamAppId,\n          threadId: boundThreadId,\n          repoFingerprint,\n          remoteUrl,\n          defaultBranch: defaultBranch ?? null,\n          laneId: boundLaneId,\n          branchName,\n          bindingMode\n        });\n      }\n      const baselineStatus = await seedImportedInitBaseline({\n        api: params.api,\n        repoRoot,\n        repoFingerprint,\n        laneId: boundLaneId,\n        currentAppId: boundCurrentAppId,\n        branchName\n      });\n      return {\n        reused: false,\n        projectId: boundProjectId,\n        appId: boundCurrentAppId,\n        dashboardUrl: buildDashboardAppUrl(boundCurrentAppId),\n        upstreamAppId: boundUpstreamAppId,\n        bindingPath,\n        repoRoot,\n        repoFingerprint,\n        bindingMode,\n        createdCanonicalFamily: Boolean(params.forceNew),\n        baselineStatus,\n        remoteUrl,\n        defaultBranch,\n        ...warnings.length > 0 ? { warnings } : {}\n      };\n    }\n  );\n}\nasync function collabInitSubmit(params) {\n  return collabInit({ ...params, asyncSubmit: true });\n}\n\n// src/application/collab/collabInvite.ts\nasync function collabInvite(params) {\n  const scope = params.scope ?? \"project\";\n  const targetId = await resolveScopeTarget({\n    api: params.api,\n    cwd: params.cwd,\n    scope,\n    targetId: params.targetId\n  });\n  const payload = {\n    email: params.email,\n    role: params.role?.trim() || (scope === \"organization\" ? \"member\" : \"viewer\"),\n    ttlDays: params.ttlDays\n  };\n  const resp = scope === \"organization\" ? await params.api.createOrganizationInvite(targetId, payload) : scope === \"project\" ? await params.api.createProjectInvite(targetId, payload) : await params.api.createAppInvite(targetId, payload);\n  const invite = unwrapResponseObject(resp, \"invite\");\n  return {\n    ...invite,\n    scopeType: scope,\n    targetId\n  };\n}\n\n// src/application/collab/collabList.ts\nasync function collabList(params) {\n  const pageRequest = normalizePagination(params);\n  const resp = await params.api.listApps({\n    ownership: params.ownership ?? \"all\",\n    accessScope: params.accessScope ?? \"explicit_member\",\n    createdBy: params.createdBy,\n    forked: params.forked ?? \"all\",\n    limit: pageRequest.limit + 1,\n    offset: pageRequest.offset\n  });\n  const apps = unwrapResponseObject(resp, \"apps\");\n  const page = paginateOverfetchedItems(apps, params);\n  return {\n    apps: page.items,\n    pagination: page.pagination\n  };\n}\n\n// src/application/collab/collabReconcile.ts\nimport fs13 from \"fs/promises\";\nimport os5 from \"os\";\nimport path12 from \"path\";\nimport { execa as execa2 } from \"execa\";\n\n// src/application/collab/pendingFinalize.ts\nfunction hasPendingFinalize(summary) {\n  return Boolean(summary && summary.state !== \"idle\" && summary.activeJobCount > 0);\n}\nfunction buildPendingFinalizeHint() {\n  return \"Drain or await the local finalize queue first, then retry after the queued Remix turn finishes recording remotely.\";\n}\n\n// src/application/collab/reconcileDecision.ts\nfunction classifyReconcileDelta(delta) {\n  if (delta.status === \"conflict_risk\") {\n    return {\n      action: \"metadata_conflict\",\n      message: \"Local repository metadata conflicts with the bound Remix app.\",\n      exitCode: 2,\n      hint: delta.warnings.join(\"\\n\") || \"Run the command from the correct bound repository.\"\n    };\n  }\n  if (delta.status === \"base_unknown\") {\n    return {\n      action: \"base_unknown\",\n      message: \"Reconcile cannot pull the newer server state from the last acknowledged baseline.\",\n      exitCode: 2,\n      hint: \"Run `remix collab init` to seed a fresh revision baseline for this checkout before retrying.\"\n    };\n  }\n  if (delta.status !== \"delta_ready\" && delta.status !== \"up_to_date\") {\n    return {\n      action: \"unsupported_delta\",\n      message: \"Reconcile could not determine the server delta for this lane.\",\n      exitCode: 1,\n      hint: delta.warnings.join(\"\\n\") || \"Run `remix collab status` and retry once the lane is healthy.\"\n    };\n  }\n  return { action: \"ready\" };\n}\nfunction classifyReconcileDetectedState(detected) {\n  if (detected.status === \"metadata_conflict\" || detected.status === \"branch_mismatch\") {\n    return { action: \"realign\", hint: detected.hint };\n  }\n  if (detected.repoState === \"server_only_changed\" || detected.repoState === \"idle\") return { action: \"sync_instead\" };\n  if (detected.repoState === \"both_changed\") return { action: \"reconcile\" };\n  if (detected.repoState === \"external_local_base_changed\") {\n    return { action: \"external_local_base_changed\", hint: detected.hint };\n  }\n  if (detected.repoState === \"local_only_changed\") return { action: \"local_only_finalize\" };\n  return { action: \"not_reconcilable\", hint: detected.hint };\n}\nfunction shouldApplyServerDeltaBeforeReplay(params) {\n  return params.deltaStatus === \"delta_ready\" && params.diff.trim().length > 0;\n}\n\n// src/application/collab/collabReconcile.ts\nasync function reconcileBothChanged(params) {\n  const repoRoot = await findGitRoot(params.cwd);\n  const binding = await ensureActiveLaneBinding({\n    repoRoot,\n    api: params.api,\n    operation: \"`remix collab reconcile`\"\n  });\n  if (!binding) {\n    throw new RemixError(\"Repository is not bound to Remix.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab init` first.\"\n    });\n  }\n  const branch = await requireCurrentBranch(repoRoot);\n  const baseline = await readLocalBaseline({\n    repoFingerprint: binding.repoFingerprint,\n    laneId: binding.laneId,\n    repoRoot\n  });\n  if (!baseline?.lastSnapshotId || !baseline.lastServerHeadHash) {\n    throw new RemixError(\"Local Remix baseline is missing for this lane.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab init` or sync from a checkout with a valid revision baseline first.\"\n    });\n  }\n  const currentSnapshot = await captureLocalSnapshot({\n    repoRoot,\n    repoFingerprint: binding.repoFingerprint,\n    laneId: binding.laneId,\n    branchName: binding.branchName\n  });\n  const diffResult = await diffLocalSnapshots({\n    baseSnapshotId: baseline.lastSnapshotId,\n    targetSnapshotId: currentSnapshot.id\n  });\n  if (!diffResult.diff.trim()) {\n    throw new RemixError(\"No local boundary delta was found to reconcile.\", {\n      exitCode: 2,\n      hint: \"Pull the server delta locally, or make local changes before running `remix collab reconcile`.\"\n    });\n  }\n  const [appHeadResp, deltaResp, repoSnapshot] = await Promise.all([\n    params.api.getAppHead(binding.currentAppId),\n    params.api.getAppDelta(binding.currentAppId, {\n      baseHeadHash: baseline.lastServerHeadHash,\n      baseRevisionId: baseline.lastServerRevisionId,\n      repoFingerprint: binding.repoFingerprint ?? void 0,\n      remoteUrl: binding.remoteUrl ?? void 0,\n      defaultBranch: binding.defaultBranch ?? void 0\n    }),\n    captureRepoSnapshot(repoRoot, { includeWorkspaceDiffHash: true })\n  ]);\n  const appHead = unwrapResponseObject(appHeadResp, \"app head\");\n  const delta = unwrapResponseObject(deltaResp, \"app delta\");\n  const deltaDecision = classifyReconcileDelta(delta);\n  if (deltaDecision.action !== \"ready\") {\n    throw new RemixError(deltaDecision.message, {\n      exitCode: deltaDecision.exitCode,\n      hint: deltaDecision.hint\n    });\n  }\n  const preview = {\n    status: \"ready_to_reconcile\",\n    repoRoot,\n    branch,\n    currentAppId: binding.currentAppId,\n    localHeadCommitHash: currentSnapshot.localCommitHash,\n    baseHeadCommitHash: baseline.lastServerHeadHash,\n    targetHeadCommitHash: appHead.headCommitHash,\n    targetHeadCommitId: appHead.headCommitId,\n    stats: diffResult.stats,\n    warnings: delta.warnings,\n    applied: false,\n    dryRun: params.dryRun\n  };\n  if (params.dryRun) {\n    return preview;\n  }\n  const replayResp = await params.api.startChangeStepReplay(binding.currentAppId, {\n    prompt: \"Reconcile local boundary delta onto the latest server head.\",\n    assistantResponse: \"Replay the local boundary delta onto the latest server head without recording a new change step.\",\n    diff: diffResult.diff,\n    baseCommitHash: baseline.lastServerHeadHash,\n    baseRevisionId: baseline.lastServerRevisionId,\n    targetHeadCommitHash: appHead.headCommitHash,\n    targetRevisionId: appHead.headRevisionId,\n    expectedPaths: diffResult.changedPaths,\n    workspaceMetadata: {\n      recordingMode: \"boundary_delta\",\n      repoRoot,\n      branch,\n      baselineSnapshotId: baseline.lastSnapshotId,\n      currentSnapshotId: currentSnapshot.id,\n      baselineServerRevisionId: baseline.lastServerRevisionId,\n      baselineServerHeadHash: baseline.lastServerHeadHash,\n      currentSnapshotHash: currentSnapshot.snapshotHash,\n      localCommitHash: currentSnapshot.localCommitHash,\n      repoStateAtCapture: \"both_changed\"\n    },\n    idempotencyKey: buildDeterministicIdempotencyKey({\n      kind: \"collab_reconcile_replay_v1\",\n      appId: binding.currentAppId,\n      baseCommitHash: baseline.lastServerHeadHash,\n      targetHeadCommitHash: appHead.headCommitHash,\n      currentSnapshotId: currentSnapshot.id,\n      diffSha256: diffResult.diffSha256\n    })\n  });\n  const replayStart = unwrapResponseObject(replayResp, \"change step replay\");\n  const replay = await pollChangeStepReplay(params.api, binding.currentAppId, String(replayStart.id));\n  const replayDiffResp = await params.api.getChangeStepReplayDiff(binding.currentAppId, replay.id);\n  const replayDiff = unwrapResponseObject(replayDiffResp, \"change step replay diff\");\n  const tempRoot = await fs13.mkdtemp(path12.join(os5.tmpdir(), \"remix-reconcile-\"));\n  let serverHeadSnapshot = null;\n  let mergedSnapshot = null;\n  try {\n    const tempRepoRoot = path12.join(tempRoot, \"repo\");\n    await fs13.mkdir(tempRepoRoot, { recursive: true });\n    await execa2(\"git\", [\"init\"], { cwd: tempRepoRoot, stderr: \"ignore\" });\n    await materializeLocalSnapshot(baseline.lastSnapshotId, tempRepoRoot);\n    if (shouldApplyServerDeltaBeforeReplay({ deltaStatus: delta.status, diff: delta.diff })) {\n      await applyUnifiedDiffToWorktree(tempRepoRoot, delta.diff, \"`remix collab reconcile`\");\n    }\n    serverHeadSnapshot = await captureLocalSnapshot({\n      repoRoot: tempRepoRoot,\n      repoFingerprint: binding.repoFingerprint,\n      laneId: binding.laneId,\n      branchName: binding.branchName\n    });\n    if (replayDiff.diff.trim()) {\n      await applyUnifiedDiffToWorktree(tempRepoRoot, replayDiff.diff, \"`remix collab reconcile`\");\n    }\n    mergedSnapshot = await captureLocalSnapshot({\n      repoRoot: tempRepoRoot,\n      repoFingerprint: binding.repoFingerprint,\n      laneId: binding.laneId,\n      branchName: binding.branchName\n    });\n  } finally {\n    await fs13.rm(tempRoot, { recursive: true, force: true }).catch(() => void 0);\n  }\n  if (!serverHeadSnapshot || !mergedSnapshot) {\n    throw new RemixError(\"Failed to materialize the reconciled local workspace.\", { exitCode: 1 });\n  }\n  const workspaceChanged = currentSnapshot.snapshotHash !== mergedSnapshot.snapshotHash;\n  return withRepoMutationLock(\n    {\n      cwd: repoRoot,\n      operation: \"collabReconcile\"\n    },\n    async ({ repoRoot: lockedRepoRoot, warnings }) => {\n      await assertRepoSnapshotUnchanged(lockedRepoRoot, repoSnapshot, {\n        operation: \"`remix collab reconcile`\",\n        recoveryHint: \"The repository changed while reconcile was preparing the replay. Review the local changes and rerun `remix collab reconcile`.\"\n      });\n      await restoreLocalSnapshotToWorktree(mergedSnapshot.id, lockedRepoRoot);\n      const restoredSnapshot = await captureLocalSnapshot({\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branchName: binding.branchName\n      });\n      if (restoredSnapshot.snapshotHash !== mergedSnapshot.snapshotHash) {\n        throw new RemixError(\"Failed to restore the reconciled workspace into the local checkout.\", {\n          exitCode: 1,\n          hint: \"The local worktree did not match the reconciled snapshot after restore.\"\n        });\n      }\n      await writeLocalBaseline({\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        currentAppId: binding.currentAppId,\n        branchName: binding.branchName,\n        lastSnapshotId: serverHeadSnapshot.id,\n        lastSnapshotHash: serverHeadSnapshot.snapshotHash,\n        lastServerRevisionId: appHead.headRevisionId ?? null,\n        lastServerTreeHash: appHead.treeHash ?? null,\n        lastServerHeadHash: appHead.headCommitHash,\n        lastSeenLocalCommitHash: restoredSnapshot.localCommitHash\n      });\n      const reportResult = await reportAlignedCheckoutState({\n        api: params.api,\n        appId: binding.currentAppId,\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branch,\n        baselineRevisionId: appHead.headRevisionId ?? null,\n        serverRevisionId: appHead.headRevisionId ?? null,\n        localHeadHash: restoredSnapshot.localCommitHash,\n        serverHeadCommitId: appHead.headCommitId,\n        serverHeadHash: appHead.headCommitHash,\n        source: \"reconcile_apply\"\n      });\n      const eventResult = await recordLocalAlignmentEvent({\n        api: params.api,\n        appId: binding.currentAppId,\n        eventKind: \"reconcile_local\",\n        branch,\n        collabLaneId: binding.laneId,\n        baseRevisionId: baseline.lastServerRevisionId,\n        targetRevisionId: appHead.headRevisionId ?? null,\n        resultRevisionId: appHead.headRevisionId ?? null,\n        baseHeadHash: baseline.lastServerHeadHash,\n        targetHeadCommitId: appHead.headCommitId,\n        targetHeadHash: appHead.headCommitHash,\n        resultHeadHash: appHead.headCommitHash,\n        changedFilesCount: diffResult.stats.changedFilesCount,\n        insertions: diffResult.stats.insertions,\n        deletions: diffResult.stats.deletions,\n        localCommitCount: 0,\n        summary: \"Reconciled local checkout with Remix.\",\n        idempotencyKey: buildDeterministicIdempotencyKey({\n          kind: \"collab_reconcile_local_alignment_v1\",\n          appId: binding.currentAppId,\n          laneId: binding.laneId,\n          baseRevisionId: baseline.lastServerRevisionId,\n          targetRevisionId: appHead.headRevisionId ?? null,\n          baseHeadHash: baseline.lastServerHeadHash,\n          targetHeadHash: appHead.headCommitHash,\n          localDiffSha256: diffResult.diffSha256,\n          replayId: replay.id\n        })\n      });\n      const mergedWarnings = Array.from(/* @__PURE__ */ new Set([...delta.warnings, ...warnings, ...reportResult.warnings, ...eventResult.warnings]));\n      return {\n        ...preview,\n        status: \"reconciled\",\n        localHeadCommitHash: restoredSnapshot.localCommitHash,\n        applied: workspaceChanged,\n        dryRun: false,\n        ...mergedWarnings.length > 0 ? { warnings: mergedWarnings } : {}\n      };\n    }\n  );\n}\nasync function collabReconcile(params) {\n  const detected = await collabDetectRepoState({\n    api: params.api,\n    cwd: params.cwd,\n    allowBranchMismatch: params.allowBranchMismatch\n  });\n  const detectedDecision = classifyReconcileDetectedState({\n    status: detected.status,\n    repoState: detected.repoState,\n    hint: detected.hint\n  });\n  if (detectedDecision.action === \"realign\") {\n    throw new RemixError(\"Repository must be realigned before reconciliation.\", {\n      exitCode: 2,\n      hint: detectedDecision.hint\n    });\n  }\n  if (detectedDecision.action === \"sync_instead\") {\n    return collabSync(params);\n  }\n  if (detectedDecision.action === \"reconcile\") {\n    return reconcileBothChanged(params);\n  }\n  if (detectedDecision.action === \"external_local_base_changed\") {\n    throw new RemixError(\"This checkout needs a local Remix revision baseline before reconciliation.\", {\n      exitCode: 2,\n      hint: detectedDecision.hint || \"Run `remix collab init` or `remix collab sync` to seed the baseline.\"\n    });\n  }\n  if (detectedDecision.action === \"local_only_finalize\") {\n    if (hasPendingFinalize(detected.pendingFinalize)) {\n      throw new RemixError(\"Reconcile is not needed while queued Remix turn recording is still processing.\", {\n        exitCode: 2,\n        hint: buildPendingFinalizeHint()\n      });\n    }\n    throw new RemixError(\"Reconcile is not needed while only local boundary changes are pending.\", {\n      exitCode: 2,\n      hint: \"Record the local work with `remix collab finalize-turn` instead.\"\n    });\n  }\n  throw new RemixError(detected.hint || \"Repository is not ready for reconciliation.\", {\n    exitCode: 2,\n    hint: detected.hint\n  });\n}\n\n// src/application/collab/collabReject.ts\nasync function collabReject(params) {\n  const resp = await params.api.updateMergeRequest(params.mrId, { status: \"rejected\" });\n  return unwrapResponseObject(resp, \"merge request\");\n}\n\n// src/application/collab/collabRemix.ts\nasync function collabRemix(params) {\n  const sourceAppId = params.appId?.trim() || null;\n  if (!sourceAppId) {\n    throw new RemixError(\"No source app selected.\", {\n      exitCode: 2,\n      hint: \"Pass the source app id to remix.\"\n    });\n  }\n  const sourceApp = await pollAppReady(params.api, sourceAppId);\n  const sourceCollab = sourceApp.collab && typeof sourceApp.collab === \"object\" ? sourceApp.collab : null;\n  const sourceSource = sourceApp.source && typeof sourceApp.source === \"object\" ? sourceApp.source : null;\n  const sourceBranchName = typeof sourceCollab?.branchName === \"string\" && sourceCollab.branchName.trim() || typeof sourceSource?.branch === \"string\" && sourceSource.branch.trim() || typeof sourceSource?.defaultBranch === \"string\" && sourceSource.defaultBranch.trim() || void 0;\n  const forkResp = await params.api.forkApp(sourceAppId, {\n    name: params.name?.trim() || void 0,\n    platform: \"generic\",\n    branchName: sourceBranchName\n  });\n  const forked = unwrapResponseObject(forkResp, \"fork\");\n  const app = await pollAppReady(params.api, String(forked.id));\n  const collab = app.collab && typeof app.collab === \"object\" ? app.collab : null;\n  const source = app.source && typeof app.source === \"object\" ? app.source : null;\n  const authoritativeBranchName = typeof collab?.branchName === \"string\" && collab.branchName.trim() || typeof source?.branch === \"string\" && source.branch.trim() || typeof source?.defaultBranch === \"string\" && source.defaultBranch.trim() || sourceBranchName || null;\n  const authoritativeRemoteUrl = typeof source?.remoteUrl === \"string\" && source.remoteUrl.trim() || null;\n  const authoritativeDefaultBranch = typeof source?.defaultBranch === \"string\" && source.defaultBranch.trim() || null;\n  const checkout = await materializeAppCheckout({\n    api: params.api,\n    cwd: params.cwd,\n    appId: String(app.id),\n    outputDir: params.outputDir ?? null,\n    defaultDirName: sanitizeCheckoutDirName(String(params.name?.trim() || app.name || app.id)),\n    expectedBranchName: authoritativeBranchName,\n    expectedRemoteUrl: authoritativeRemoteUrl,\n    expectedDefaultBranch: authoritativeDefaultBranch,\n    onPhase: params.onPhase\n  });\n  const laneId = typeof collab?.laneId === \"string\" ? collab.laneId : null;\n  const repoFingerprint = typeof source?.repoFingerprint === \"string\" ? source.repoFingerprint : checkout.repoFingerprint;\n  const remoteUrl = typeof source?.remoteUrl === \"string\" ? source.remoteUrl : checkout.remoteUrl;\n  const defaultBranch = typeof source?.defaultBranch === \"string\" ? source.defaultBranch : checkout.defaultBranch;\n  const branchName = authoritativeBranchName ?? checkout.branchName;\n  const authoritativeLane = await resolveProjectLaneIfAuthoritative(params.api, {\n    projectId: String(app.projectId),\n    repoFingerprint,\n    remoteUrl,\n    defaultBranch,\n    branchName,\n    currentAppId: String(app.id),\n    expectedUpstreamAppId: String(app.forkedFromAppId ?? sourceAppId),\n    createIfMissing: true,\n    seedAppId: String(app.id)\n  });\n  const bindingPath = await writeCollabBinding(checkout.repoRoot, {\n    projectId: authoritativeLane?.projectId ?? String(app.projectId),\n    currentAppId: authoritativeLane?.currentAppId ?? String(app.id),\n    upstreamAppId: authoritativeLane?.upstreamAppId ?? String(app.forkedFromAppId ?? sourceAppId),\n    threadId: authoritativeLane?.threadId ?? (app.threadId ? String(app.threadId) : null),\n    repoFingerprint: authoritativeLane?.repoFingerprint ?? repoFingerprint,\n    remoteUrl: authoritativeLane?.remoteUrl ?? remoteUrl,\n    defaultBranch: authoritativeLane?.defaultBranch ?? defaultBranch,\n    laneId: authoritativeLane?.laneId ?? laneId,\n    branchName: authoritativeLane?.branchName ?? branchName,\n    bindingMode: \"lane\"\n  });\n  const currentAppId = authoritativeLane?.currentAppId ?? String(app.id);\n  const repoFingerprintForBaseline = authoritativeLane?.repoFingerprint ?? repoFingerprint;\n  const laneIdForBaseline = authoritativeLane?.laneId ?? laneId;\n  const branchNameForBaseline = authoritativeLane?.branchName ?? branchName;\n  const appHead = unwrapResponseObject(\n    await params.api.getAppHead(currentAppId),\n    \"app head\"\n  );\n  const snapshot = await captureLocalSnapshot({\n    repoRoot: checkout.repoRoot,\n    repoFingerprint: repoFingerprintForBaseline,\n    laneId: laneIdForBaseline,\n    branchName: branchNameForBaseline\n  });\n  await writeLocalBaseline({\n    repoRoot: checkout.repoRoot,\n    repoFingerprint: repoFingerprintForBaseline,\n    laneId: laneIdForBaseline,\n    currentAppId,\n    branchName: branchNameForBaseline,\n    lastSnapshotId: snapshot.id,\n    lastSnapshotHash: snapshot.snapshotHash,\n    lastServerRevisionId: appHead.headRevisionId ?? null,\n    lastServerTreeHash: appHead.treeHash ?? null,\n    lastServerHeadHash: appHead.headCommitHash,\n    lastSeenLocalCommitHash: snapshot.localCommitHash\n  });\n  return {\n    appId: currentAppId,\n    dashboardUrl: buildDashboardAppUrl(currentAppId),\n    projectId: authoritativeLane?.projectId ?? String(app.projectId),\n    upstreamAppId: authoritativeLane?.upstreamAppId ?? String(app.forkedFromAppId ?? sourceAppId),\n    bindingPath,\n    repoRoot: checkout.repoRoot\n  };\n}\n\n// src/infrastructure/collab/localStateRepository.ts\nvar defaultLocalStateRepository = {\n  baselines: {\n    read: readLocalBaseline,\n    write: writeLocalBaseline,\n    clear: clearLocalBaseline\n  },\n  snapshots: {\n    inspect: inspectLocalSnapshot,\n    capture: captureLocalSnapshot,\n    read: readLocalSnapshot,\n    materialize: materializeLocalSnapshot,\n    restoreToWorktree: restoreLocalSnapshotToWorktree,\n    diff: diffLocalSnapshots\n  },\n  asyncJobs: {\n    enqueue: enqueueAsyncJob,\n    read: readAsyncJob,\n    list: listAsyncJobs,\n    listForRepo: listAsyncJobsForRepo,\n    findPending: findPendingAsyncJob,\n    findFailed: findFailedAsyncJob,\n    update: updateAsyncJob,\n    delete: deleteAsyncJob,\n    claim: claimAsyncJob,\n    summarize: summarizeAsyncJobs,\n    pruneTerminal: pruneTerminalAsyncJobs,\n    getBundleFilePath: getAsyncJobBundleFilePath,\n    await: awaitAsyncJob\n  },\n  finalizeJobs: {\n    enqueue: enqueuePendingFinalizeJob,\n    read: readPendingFinalizeJob,\n    list: listPendingFinalizeJobs,\n    update: updatePendingFinalizeJob,\n    claim: claimPendingFinalizeJob,\n    remove: removePendingFinalizeJob,\n    forget: forgetPendingFinalizeJob,\n    requeue: requeuePendingFinalizeJob,\n    heartbeatLock: heartbeatJobLock,\n    cleanStaleLocks: cleanStaleFinalizeJobLocks,\n    prune: prunePendingFinalizeJobs,\n    summarize: summarizePendingFinalizeJobs\n  },\n  bindings: {\n    getPath: getCollabBindingPath,\n    read: readCollabBinding,\n    readState: readCollabBindingState,\n    write: writeCollabBinding,\n    writeSnapshot: writeCollabBindingSnapshot\n  }\n};\nfunction createLocalStateRepository(overrides = {}) {\n  return {\n    baselines: {\n      ...defaultLocalStateRepository.baselines,\n      ...overrides.baselines\n    },\n    snapshots: {\n      ...defaultLocalStateRepository.snapshots,\n      ...overrides.snapshots\n    },\n    asyncJobs: {\n      ...defaultLocalStateRepository.asyncJobs,\n      ...overrides.asyncJobs\n    },\n    finalizeJobs: {\n      ...defaultLocalStateRepository.finalizeJobs,\n      ...overrides.finalizeJobs\n    },\n    bindings: {\n      ...defaultLocalStateRepository.bindings,\n      ...overrides.bindings\n    }\n  };\n}\n\n// src/application/collab/collabRequestMerge.ts\nvar localState = createLocalStateRepository();\nasync function collabRequestMerge(params) {\n  const repoRoot = await findGitRoot(params.cwd);\n  const binding = await ensureActiveLaneBinding({\n    repoRoot,\n    api: params.api,\n    operation: \"`remix collab request-merge`\"\n  });\n  if (!binding) {\n    const transition2 = planRequestMergeWorkflowTransition({ hasBinding: false, hasPendingFinalize: false });\n    if (transition2.action === \"require_binding\") {\n      throw new RemixError(\"Repository is not bound to Remix.\", { exitCode: 2 });\n    }\n    throw new RemixError(\"Repository is not bound to Remix.\", { exitCode: 2 });\n  }\n  const pendingFinalize = await localState.finalizeJobs.summarize({\n    repoRoot,\n    repoFingerprint: binding.repoFingerprint,\n    currentAppId: binding.currentAppId,\n    laneId: binding.laneId\n  });\n  const transition = planRequestMergeWorkflowTransition({\n    hasBinding: true,\n    hasPendingFinalize: hasPendingFinalize(pendingFinalize)\n  });\n  if (transition.action === \"require_finalize_drain\") {\n    throw new RemixError(\"Pending Remix turn recording still processing.\", {\n      exitCode: 2,\n      hint: buildPendingFinalizeHint()\n    });\n  }\n  const resp = await params.api.openMergeRequest(binding.currentAppId);\n  return unwrapResponseObject(resp, \"merge request\");\n}\n\n// src/application/collab/collabStatus.ts\nfunction isFinalizeQueueBlocking(state) {\n  return state === \"queued\" || state === \"processing\" || state === \"retry_scheduled\" || state === \"awaiting_usage\";\n}\nfunction createBaseStatus() {\n  return {\n    schemaVersion: 1,\n    repo: {\n      isGitRepo: false,\n      repoRoot: null,\n      branch: null,\n      branchMismatch: false,\n      headCommitHash: null,\n      worktree: {\n        isClean: true,\n        entryCount: 0,\n        hasTrackedChanges: false,\n        hasUntrackedFiles: false,\n        preview: []\n      }\n    },\n    binding: {\n      isBound: false,\n      path: null,\n      projectId: null,\n      currentAppId: null,\n      upstreamAppId: null,\n      isRemix: null,\n      threadId: null,\n      repoFingerprint: null,\n      remoteUrl: null,\n      dashboardUrl: null,\n      defaultBranch: null,\n      laneId: null,\n      branchName: null,\n      bindingMode: null\n    },\n    remote: {\n      checked: false,\n      error: null,\n      appStatus: null,\n      incomingOpenMergeRequestCount: null,\n      outgoingOpenMergeRequestCount: null\n    },\n    sync: {\n      checked: false,\n      error: null,\n      canApply: false,\n      status: \"not_available\",\n      blockedReasons: [],\n      warnings: [],\n      targetCommitHash: null,\n      targetCommitId: null,\n      stats: null\n    },\n    reconcile: {\n      checked: false,\n      error: null,\n      canApply: false,\n      status: \"not_available\",\n      blockedReasons: [],\n      warnings: [],\n      targetHeadCommitHash: null,\n      targetHeadCommitId: null\n    },\n    alignment: {\n      checked: false,\n      error: null,\n      repoState: null,\n      canRecordTurn: false,\n      pendingFinalize: {\n        state: \"idle\",\n        activeJobCount: 0,\n        queuedJobCount: 0,\n        processingJobCount: 0,\n        retryScheduledJobCount: 0,\n        awaitingUsageJobCount: 0,\n        failedJobCount: 0,\n        oldestCapturedAt: null,\n        newestCapturedAt: null,\n        nextRetryAt: null,\n        latestError: null\n      },\n      baseline: {\n        lastSnapshotId: null,\n        lastSnapshotHash: null,\n        lastServerRevisionId: null,\n        lastServerTreeHash: null,\n        lastServerHeadHash: null,\n        lastSeenLocalCommitHash: null\n      },\n      current: {\n        snapshotHash: null,\n        serverRevisionId: null,\n        serverTreeHash: null,\n        serverHeadHash: null,\n        serverHeadCommitId: null,\n        localCommitHash: null\n      }\n    },\n    recommendedAction: \"no_action\",\n    warnings: []\n  };\n}\nfunction addWarning(status, message) {\n  const value = String(message ?? \"\").trim();\n  if (!value || status.warnings.includes(value)) return;\n  status.warnings.push(value);\n}\nfunction addBlockedReason(target, reason) {\n  if (!target.blockedReasons.includes(reason)) target.blockedReasons.push(reason);\n}\nfunction countMergeRequests(payload) {\n  if (Array.isArray(payload)) return payload.length;\n  if (!payload || typeof payload !== \"object\") return 0;\n  let total = 0;\n  for (const value of Object.values(payload)) {\n    if (Array.isArray(value)) total += value.length;\n  }\n  return total;\n}\nasync function collabStatus(params) {\n  const status = createBaseStatus();\n  let repoRoot;\n  try {\n    repoRoot = await findGitRoot(params.cwd);\n  } catch (err) {\n    addBlockedReason(status.sync, \"not_git_repo\");\n    addBlockedReason(status.reconcile, \"not_git_repo\");\n    addWarning(status, formatCliErrorDetail(err));\n    return status;\n  }\n  status.repo.isGitRepo = true;\n  status.repo.repoRoot = repoRoot;\n  const [branch, headCommitHash, worktreeStatus, detected] = await Promise.all([\n    getCurrentBranch(repoRoot),\n    getHeadCommitHash(repoRoot),\n    getWorktreeStatus(repoRoot),\n    collabDetectRepoState({ api: params.api ?? void 0, cwd: repoRoot })\n  ]);\n  status.repo.branch = branch;\n  status.repo.headCommitHash = headCommitHash;\n  status.repo.worktree = {\n    isClean: worktreeStatus.isClean,\n    entryCount: worktreeStatus.entries.length,\n    hasTrackedChanges: worktreeStatus.entries.some((entry) => !entry.startsWith(\"??\")),\n    hasUntrackedFiles: worktreeStatus.entries.some((entry) => entry.startsWith(\"??\")),\n    preview: worktreeStatus.entries.slice(0, 10)\n  };\n  if (!status.repo.worktree.isClean) addWarning(status, \"Working tree has local changes.\");\n  if (!branch) addWarning(status, \"Repository is in a detached HEAD state.\");\n  if (!headCommitHash) addWarning(status, \"Failed to resolve local HEAD commit.\");\n  if (detected.binding) {\n    status.binding = {\n      isBound: true,\n      path: getCollabBindingPath(repoRoot),\n      projectId: detected.binding.projectId,\n      currentAppId: detected.binding.currentAppId,\n      upstreamAppId: detected.binding.upstreamAppId,\n      isRemix: detected.binding.currentAppId !== detected.binding.upstreamAppId,\n      threadId: detected.binding.threadId,\n      repoFingerprint: detected.binding.repoFingerprint,\n      remoteUrl: detected.binding.remoteUrl,\n      // Dashboard URL is derived (not stored on the binding) — compute it\n      // here so every status caller, including MCP/agent tools, gets it\n      // alongside `remoteUrl` without having to know the URL convention.\n      dashboardUrl: detected.binding.currentAppId ? buildDashboardAppUrl(detected.binding.currentAppId) : null,\n      defaultBranch: detected.binding.defaultBranch,\n      laneId: detected.binding.laneId,\n      branchName: detected.binding.branchName,\n      bindingMode: detected.binding.bindingMode\n    };\n    status.repo.branchMismatch = branch !== detected.binding.branchName;\n  }\n  status.alignment.checked = Boolean(params.api);\n  status.alignment.repoState = detected.repoState;\n  status.alignment.error = detected.status === \"remote_error\" ? detected.hint : null;\n  status.alignment.pendingFinalize = detected.pendingFinalize;\n  status.alignment.baseline = detected.baseline;\n  status.alignment.current = {\n    snapshotHash: detected.currentSnapshotHash,\n    serverRevisionId: detected.currentServerRevisionId,\n    serverTreeHash: detected.currentServerTreeHash,\n    serverHeadHash: detected.currentServerHeadHash,\n    serverHeadCommitId: detected.currentServerHeadCommitId,\n    localCommitHash: detected.localCommitHash\n  };\n  status.alignment.canRecordTurn = !isFinalizeQueueBlocking(detected.pendingFinalize.state) && (detected.repoState === \"idle\" || detected.repoState === \"local_only_changed\");\n  switch (detected.status) {\n    case \"not_bound\":\n      addBlockedReason(status.sync, \"not_bound\");\n      addBlockedReason(status.reconcile, \"not_bound\");\n      status.recommendedAction = \"init\";\n      break;\n    case \"branch_binding_missing\":\n      addBlockedReason(status.sync, \"branch_binding_missing\");\n      addBlockedReason(status.reconcile, \"branch_binding_missing\");\n      status.recommendedAction = \"init\";\n      break;\n    case \"family_ambiguous\":\n      addBlockedReason(status.sync, \"family_ambiguous\");\n      addBlockedReason(status.reconcile, \"family_ambiguous\");\n      status.recommendedAction = \"choose_family\";\n      break;\n    case \"missing_head\":\n      addBlockedReason(status.sync, \"missing_head\");\n      addBlockedReason(status.reconcile, \"missing_head\");\n      break;\n    case \"branch_mismatch\":\n      addBlockedReason(status.sync, \"branch_mismatch\");\n      addBlockedReason(status.reconcile, \"branch_mismatch\");\n      break;\n    case \"metadata_conflict\":\n      addBlockedReason(status.sync, \"metadata_conflict\");\n      addBlockedReason(status.reconcile, \"metadata_conflict\");\n      status.sync.checked = true;\n      status.sync.status = \"conflict_risk\";\n      status.sync.warnings = detected.metadataWarnings;\n      status.reconcile.checked = true;\n      status.reconcile.status = \"metadata_conflict\";\n      status.reconcile.warnings = detected.metadataWarnings;\n      break;\n    case \"remote_error\":\n      addBlockedReason(status.sync, \"remote_error\");\n      addBlockedReason(status.reconcile, \"remote_error\");\n      status.sync.error = detected.hint;\n      status.reconcile.error = detected.hint;\n      break;\n    default:\n      break;\n  }\n  if (detected.repoState === \"server_only_changed\") {\n    status.sync.checked = true;\n    status.sync.status = \"delta_ready\";\n    status.sync.targetCommitHash = detected.currentServerHeadHash;\n    status.sync.targetCommitId = detected.currentServerHeadCommitId;\n    status.sync.canApply = !status.repo.branchMismatch;\n    status.recommendedAction = \"pull\";\n  } else if (detected.repoState === \"both_changed\") {\n    status.reconcile.checked = true;\n    status.reconcile.status = \"ready_to_reconcile\";\n    status.reconcile.targetHeadCommitHash = detected.currentServerHeadHash;\n    status.reconcile.targetHeadCommitId = detected.currentServerHeadCommitId;\n    status.reconcile.canApply = !status.repo.branchMismatch;\n    status.recommendedAction = \"reconcile\";\n  } else if (detected.repoState === \"external_local_base_changed\") {\n    status.recommendedAction = \"init\";\n    addBlockedReason(status.sync, \"baseline_missing\");\n    addBlockedReason(status.reconcile, \"baseline_missing\");\n  } else if (detected.repoState === \"local_only_changed\") {\n    status.recommendedAction = isFinalizeQueueBlocking(detected.pendingFinalize.state) ? \"await_finalize\" : \"record\";\n  } else if (detected.repoState === \"idle\") {\n    status.recommendedAction = isFinalizeQueueBlocking(detected.pendingFinalize.state) ? \"await_finalize\" : \"no_action\";\n  }\n  if (isFinalizeQueueBlocking(detected.pendingFinalize.state) && detected.status === \"ready\" && status.recommendedAction !== \"init\" && status.recommendedAction !== \"choose_family\") {\n    status.recommendedAction = \"await_finalize\";\n    addWarning(\n      status,\n      \"A captured Remix turn is still pending locally. Drain or await finalize before opening a merge request or starting another recovery flow.\"\n    );\n    addWarning(status, detected.pendingFinalize.latestError);\n  }\n  if (detected.pendingFinalize.failedJobCount > 0) {\n    addWarning(\n      status,\n      \"One or more queued finalize jobs failed permanently and will not retry automatically. Review the local finalize queue state before relying on those older captured turns.\"\n    );\n    addWarning(status, detected.pendingFinalize.latestError);\n  }\n  if (params.api && status.binding.currentAppId) {\n    const [appResult, incomingResult, outgoingResult] = await Promise.allSettled([\n      params.api.getApp(status.binding.currentAppId),\n      params.api.listMergeRequests({ queue: \"app_reviewable\", appId: status.binding.currentAppId, status: \"open\", kind: \"merge\" }),\n      params.api.listMergeRequests({ queue: \"app_outgoing\", appId: status.binding.currentAppId, status: \"open\", kind: \"merge\" })\n    ]);\n    const remoteErrors = [];\n    if (appResult.status === \"fulfilled\") {\n      const app = unwrapResponseObject(appResult.value, \"app\");\n      status.remote.appStatus = typeof app.status === \"string\" ? app.status : null;\n    } else {\n      remoteErrors.push(formatCliErrorDetail(appResult.reason) ?? \"Failed to fetch app status.\");\n    }\n    if (incomingResult.status === \"fulfilled\") {\n      status.remote.incomingOpenMergeRequestCount = countMergeRequests(\n        unwrapResponseObject(incomingResult.value, \"merge requests\")\n      );\n    } else {\n      remoteErrors.push(formatCliErrorDetail(incomingResult.reason) ?? \"Failed to fetch incoming merge requests.\");\n    }\n    if (outgoingResult.status === \"fulfilled\") {\n      status.remote.outgoingOpenMergeRequestCount = countMergeRequests(\n        unwrapResponseObject(outgoingResult.value, \"merge requests\")\n      );\n    } else {\n      remoteErrors.push(formatCliErrorDetail(outgoingResult.reason) ?? \"Failed to fetch outgoing merge requests.\");\n    }\n    status.remote.checked = remoteErrors.length === 0;\n    status.remote.error = remoteErrors.length > 0 ? remoteErrors.join(\"\\n\\n\") : null;\n  }\n  addWarning(status, detected.hint);\n  addWarning(status, status.remote.error);\n  for (const warning of detected.warnings) addWarning(status, warning);\n  for (const warning of status.sync.warnings) addWarning(status, warning);\n  for (const warning of status.reconcile.warnings) addWarning(status, warning);\n  if ((status.remote.incomingOpenMergeRequestCount ?? 0) > 0 && status.recommendedAction === \"no_action\") {\n    status.recommendedAction = \"review_queue\";\n  }\n  const reportResult = await reportCheckoutStateFromStatus({ api: params.api, status, source: \"status\" });\n  for (const warning of reportResult.warnings) addWarning(status, warning);\n  return status;\n}\n\n// src/application/collab/collabSyncUpstream.ts\nasync function collabSyncUpstream(params) {\n  const repoRoot = await findGitRoot(params.cwd);\n  const binding = await ensureActiveLaneBinding({\n    repoRoot,\n    api: params.api,\n    operation: \"`remix collab sync-upstream`\"\n  });\n  if (!binding) {\n    throw new RemixError(\"Repository is not bound to Remix.\", {\n      exitCode: 2,\n      hint: \"Run `remix collab init` first.\"\n    });\n  }\n  await ensureWorkspaceMatchesBaseline({\n    repoRoot,\n    repoFingerprint: binding.repoFingerprint,\n    laneId: binding.laneId,\n    branchName: binding.branchName,\n    operation: \"`remix collab sync-upstream`\"\n  });\n  await requireCurrentBranch(repoRoot);\n  const repoSnapshot = await captureRepoSnapshot(repoRoot);\n  if (binding.currentAppId === binding.upstreamAppId) {\n    throw new RemixError(\"Current repository is not bound to a remix/fork app.\", {\n      exitCode: 2,\n      hint: \"`remix collab sync-upstream` only applies to remixes/forks that have an upstream app.\"\n    });\n  }\n  const currentAppResp = await params.api.getApp(binding.currentAppId);\n  const currentApp = unwrapResponseObject(currentAppResp, \"app\");\n  const initialHeadCommitId = typeof currentApp.headCommitId === \"string\" ? currentApp.headCommitId : null;\n  const initialStatus = typeof currentApp.status === \"string\" ? currentApp.status : null;\n  const resp = await params.api.syncUpstreamApp(binding.currentAppId);\n  const syncUpstream = unwrapResponseObject(resp, \"upstream sync\");\n  if (syncUpstream.status === \"up-to-date\") {\n    return {\n      status: syncUpstream.status,\n      repoRoot,\n      appId: binding.currentAppId,\n      upstreamAppId: binding.upstreamAppId,\n      localUpdated: false\n    };\n  }\n  const completedApp = await pollUpstreamSyncCompletion(params.api, binding.currentAppId, {\n    initialHeadCommitId,\n    initialStatus\n  });\n  const localSyncResult = await withRepoMutationLock(\n    {\n      cwd: repoRoot,\n      operation: \"collabSyncUpstream\"\n    },\n    async ({ repoRoot: lockedRepoRoot, warnings }) => {\n      await assertRepoSnapshotUnchanged(lockedRepoRoot, repoSnapshot, {\n        operation: \"`remix collab sync-upstream`\",\n        recoveryHint: \"The repository changed while upstream sync was in progress. Review the local changes and rerun `remix collab sync-upstream`.\"\n      });\n      await ensureWorkspaceMatchesBaseline({\n        repoRoot: lockedRepoRoot,\n        repoFingerprint: binding.repoFingerprint,\n        laneId: binding.laneId,\n        branchName: binding.branchName,\n        operation: \"`remix collab sync-upstream`\"\n      });\n      await requireCurrentBranch(lockedRepoRoot);\n      const localSync = await collabSync({\n        api: params.api,\n        cwd: lockedRepoRoot,\n        dryRun: false\n      });\n      const localSyncWarnings = Array.isArray(localSync.warnings) ? localSync.warnings ?? [] : [];\n      return {\n        ...localSync,\n        ...warnings.length > 0 || localSyncWarnings.length > 0 ? {\n          warnings: Array.from(/* @__PURE__ */ new Set([...warnings, ...localSyncWarnings]))\n        } : {}\n      };\n    }\n  );\n  return {\n    status: syncUpstream.status,\n    mergeRequestId: syncUpstream.mergeRequestId ?? null,\n    repoRoot,\n    appId: binding.currentAppId,\n    upstreamAppId: binding.upstreamAppId,\n    remoteHeadCommitId: typeof completedApp.headCommitId === \"string\" ? completedApp.headCommitId : null,\n    localSync: localSyncResult,\n    localUpdated: true,\n    ...Array.isArray(localSyncResult.warnings) && (localSyncResult.warnings?.length ?? 0) > 0 ? { warnings: localSyncResult.warnings } : {}\n  };\n}\n\n// src/application/collab/collabView.ts\nasync function collabView(params) {\n  const resp = await params.api.getMergeRequestReview(params.mrId);\n  return unwrapMergeRequestReview(resp);\n}\n\n// src/application/collab/collabAsyncProcessing.ts\nimport fs14 from \"fs/promises\";\nimport path13 from \"path\";\n\n// src/application/collab/collabDependencies.ts\nimport { randomUUID as randomUUID6 } from \"crypto\";\nfunction isFullLocalStateRepository(value) {\n  return typeof value.bindings?.getPath === \"function\" && typeof value.bindings.read === \"function\" && typeof value.bindings.readState === \"function\" && typeof value.bindings.write === \"function\" && typeof value.bindings.writeSnapshot === \"function\" && typeof value.baselines?.read === \"function\" && typeof value.baselines.write === \"function\" && typeof value.baselines.clear === \"function\" && typeof value.snapshots?.inspect === \"function\" && typeof value.snapshots.capture === \"function\" && typeof value.snapshots.read === \"function\" && typeof value.snapshots.materialize === \"function\" && typeof value.snapshots.restoreToWorktree === \"function\" && typeof value.snapshots.diff === \"function\" && typeof value.asyncJobs?.enqueue === \"function\" && typeof value.asyncJobs.read === \"function\" && typeof value.asyncJobs.list === \"function\" && typeof value.asyncJobs.listForRepo === \"function\" && typeof value.asyncJobs.findPending === \"function\" && typeof value.asyncJobs.findFailed === \"function\" && typeof value.asyncJobs.update === \"function\" && typeof value.asyncJobs.delete === \"function\" && typeof value.asyncJobs.claim === \"function\" && typeof value.asyncJobs.summarize === \"function\" && typeof value.asyncJobs.pruneTerminal === \"function\" && typeof value.asyncJobs.getBundleFilePath === \"function\" && typeof value.asyncJobs.await === \"function\" && typeof value.finalizeJobs?.enqueue === \"function\" && typeof value.finalizeJobs.read === \"function\" && typeof value.finalizeJobs.list === \"function\" && typeof value.finalizeJobs.update === \"function\" && typeof value.finalizeJobs.claim === \"function\" && typeof value.finalizeJobs.remove === \"function\" && typeof value.finalizeJobs.forget === \"function\" && typeof value.finalizeJobs.requeue === \"function\" && typeof value.finalizeJobs.heartbeatLock === \"function\" && typeof value.finalizeJobs.cleanStaleLocks === \"function\" && typeof value.finalizeJobs.prune === \"function\" && typeof value.finalizeJobs.summarize === \"function\";\n}\nfunction createCollabDependencies(overrides = {}) {\n  const defaultClock = {\n    now: () => Date.now(),\n    isoNow: () => (/* @__PURE__ */ new Date()).toISOString()\n  };\n  const defaultTimers = {\n    sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n  };\n  const localState3 = overrides.localState ? isFullLocalStateRepository(overrides.localState) ? overrides.localState : createLocalStateRepository(overrides.localState) : createLocalStateRepository();\n  return {\n    clock: { ...defaultClock, ...overrides.clock },\n    ids: { randomUUID: randomUUID6, ...overrides.ids },\n    timers: { ...defaultTimers, ...overrides.timers },\n    git: overrides.git ?? createSystemGitAdapter(),\n    localState: localState3,\n    uploadPresigned: overrides.uploadPresigned ?? uploadPresigned\n  };\n}\n\n// src/application/collab/errorTaxonomy.ts\nvar TRANSIENT_NETWORK_CODES = /* @__PURE__ */ new Set([\n  \"ECONNREFUSED\",\n  \"ECONNRESET\",\n  \"ETIMEDOUT\",\n  \"EAI_AGAIN\",\n  \"ENOTFOUND\",\n  \"ENETUNREACH\",\n  \"EHOSTUNREACH\",\n  \"EPIPE\",\n  \"UND_ERR_SOCKET\",\n  \"UND_ERR_CONNECT_TIMEOUT\",\n  \"UND_ERR_HEADERS_TIMEOUT\",\n  \"UND_ERR_BODY_TIMEOUT\"\n]);\nfunction formatWorkflowError(error) {\n  if (error instanceof RemixError) {\n    return [error.message, error.hint].filter(Boolean).join(\"\\n\\n\") || error.message || \"Unknown error.\";\n  }\n  if (error instanceof Error) {\n    return error.message || \"Unknown error.\";\n  }\n  if (typeof error === \"string\") return error;\n  try {\n    return JSON.stringify(error);\n  } catch {\n    return \"Unknown error.\";\n  }\n}\nfunction readNumberCandidate(error, key) {\n  if (!error || typeof error !== \"object\") return null;\n  const value = error[key];\n  if (typeof value === \"number\" && Number.isFinite(value)) return value;\n  return null;\n}\nfunction readStringCandidate(error, key) {\n  if (!error || typeof error !== \"object\") return null;\n  const value = error[key];\n  if (typeof value === \"string\" && value.length > 0) return value;\n  return null;\n}\nfunction buildClassification(category, retryable) {\n  return {\n    category,\n    retryable,\n    terminal: !retryable,\n    disposition: retryable ? \"transient\" : \"jobSpecific\"\n  };\n}\nfunction classifyWorkflowError(error) {\n  const candidates = [error];\n  if (error && typeof error === \"object\" && \"cause\" in error) {\n    candidates.push(error.cause);\n  }\n  for (const candidate of candidates) {\n    const status = readNumberCandidate(candidate, \"status\") ?? readNumberCandidate(candidate, \"statusCode\");\n    if (status !== null) {\n      if (status === 401 || status === 403) return buildClassification(\"transient_backend\", true);\n      if (status >= 500 && status < 600) return buildClassification(\"transient_backend\", true);\n      if (status >= 400 && status < 500) return buildClassification(\"backend_contract_failure\", false);\n    }\n    const code = readStringCandidate(candidate, \"code\");\n    if (code && TRANSIENT_NETWORK_CODES.has(code)) return buildClassification(\"transient_network\", true);\n    if (code === \"ENOENT\" || code === \"EACCES\") return buildClassification(\"persisted_state_corruption\", false);\n    const name = readStringCandidate(candidate, \"name\");\n    if (name === \"AbortError\" || name === \"TimeoutError\") return buildClassification(\"transient_network\", true);\n    if (name === \"SyntaxError\") return buildClassification(\"backend_contract_failure\", false);\n  }\n  if (error instanceof RemixError) return buildClassification(\"user_action_needed\", false);\n  return buildClassification(\"backend_contract_failure\", false);\n}\n\n// src/application/collab/workflowEvents.ts\nasync function logDrainerWorkflowEvent(jobId, event, fields = {}) {\n  await logDrainerEvent(jobId, event, fields);\n}\n\n// src/application/collab/collabAsyncProcessing.ts\nvar MAX_TRANSIENT_RETRIES = 5;\nvar collabDependencies = createCollabDependencies();\nvar localState2 = collabDependencies.localState;\nasync function handleProcessError(job, error) {\n  const message = formatWorkflowError(error);\n  const { disposition: kind } = classifyWorkflowError(error);\n  if (kind === \"transient\") {\n    const nextRetry = (job.retryCount ?? 0) + 1;\n    if (nextRetry < MAX_TRANSIENT_RETRIES) {\n      await localState2.asyncJobs.update(job.id, {\n        status: \"queued\",\n        retryCount: nextRetry,\n        error: message\n      });\n      await logDrainerWorkflowEvent(job.id, \"retrying\", {\n        kind: job.kind,\n        retryCount: nextRetry,\n        error: message\n      });\n      return { status: \"retry_scheduled\", jobId: job.id, error: message, retryCount: nextRetry };\n    }\n    const finalMessage = `exceeded retry limit (${MAX_TRANSIENT_RETRIES} attempts). Last error: ${message}`;\n    await localState2.asyncJobs.update(job.id, { status: \"failed\", error: finalMessage, retryCount: nextRetry });\n    await logDrainerWorkflowEvent(job.id, \"failed\", { kind: job.kind, error: finalMessage, retryCount: nextRetry });\n    return { status: \"failed\", jobId: job.id, error: finalMessage };\n  }\n  await localState2.asyncJobs.update(job.id, { status: \"failed\", error: message });\n  await logDrainerWorkflowEvent(job.id, \"failed\", { kind: job.kind, error: message });\n  return { status: \"failed\", jobId: job.id, error: message };\n}\nasync function processInitJob(job, api) {\n  if (job.kind !== \"init\") return { status: \"skipped\", jobId: job.id };\n  const startedAt = collabDependencies.clock.now();\n  try {\n    await localState2.asyncJobs.update(job.id, { status: \"submitting\", error: null });\n    await logDrainerWorkflowEvent(job.id, \"claimed\", { kind: \"init\" });\n    const bundleStat = await fs14.stat(job.payload.bundlePath);\n    const presignResp = await api.presignImportUploadFirstParty({\n      file: {\n        name: path13.basename(job.payload.bundlePath),\n        mimeType: \"application/x-git-bundle\",\n        size: bundleStat.size,\n        checksumSha256: job.payload.bundleSha256\n      }\n    });\n    const presign = unwrapResponseObject(presignResp, \"upload\");\n    await localState2.asyncJobs.update(job.id, { status: \"uploading\" });\n    await logDrainerWorkflowEvent(job.id, \"uploading\", { kind: \"init\" });\n    await collabDependencies.uploadPresigned({\n      uploadUrl: String(presign.uploadUrl),\n      headers: presign.headers ?? {},\n      filePath: job.payload.bundlePath\n    });\n    await localState2.asyncJobs.update(job.id, { status: \"server_processing\" });\n    const importResp = await api.importFromUploadFirstParty({\n      uploadId: String(presign.uploadId),\n      appName: job.payload.appName?.trim() || path13.basename(job.repoRoot),\n      platform: \"generic\",\n      isPublic: false,\n      branch: job.payload.defaultBranch && job.branchName && job.branchName !== job.payload.defaultBranch ? job.payload.defaultBranch : job.branchName ?? void 0,\n      remoteUrl: job.payload.remoteUrl ?? void 0,\n      defaultBranch: job.payload.defaultBranch ?? void 0,\n      repoFingerprint: job.repoFingerprint ?? void 0,\n      headCommitHash: job.payload.headCommitHash\n    });\n    const imported = unwrapResponseObject(importResp, \"import\");\n    await logDrainerWorkflowEvent(job.id, \"server_accepted\", {\n      kind: \"init\",\n      appId: String(imported.appId ?? \"\")\n    });\n    const app = await pollAppReady(api, String(imported.appId), {\n      clock: collabDependencies.clock,\n      timers: collabDependencies.timers\n    });\n    let boundProjectId = String(app.projectId);\n    let boundCurrentAppId = String(app.id);\n    let boundUpstreamAppId = String(app.id);\n    let boundThreadId = app.threadId ? String(app.threadId) : null;\n    let boundLaneId = null;\n    let canonicalLane = null;\n    const branchName = job.branchName;\n    const defaultBranch = job.payload.defaultBranch;\n    const repoRoot = job.repoRoot;\n    const repoFingerprint = job.repoFingerprint;\n    const remoteUrl = job.payload.remoteUrl;\n    const headCommitHash = job.payload.headCommitHash;\n    if (branchName) {\n      if (defaultBranch && branchName !== defaultBranch) {\n        canonicalLane = await resolveOrEnsureLaneBinding({\n          api,\n          projectId: boundProjectId,\n          repoFingerprint: repoFingerprint ?? \"\",\n          remoteUrl,\n          defaultBranch,\n          branchName: defaultBranch,\n          seedAppId: String(app.id),\n          operation: \"`remix collab init` (background)\"\n        });\n        const lane = await resolveOrEnsureLaneBinding({\n          api,\n          projectId: canonicalLane.projectId ?? boundProjectId,\n          repoFingerprint: repoFingerprint ?? \"\",\n          remoteUrl,\n          defaultBranch,\n          branchName,\n          seedHeadCommitHash: headCommitHash,\n          operation: \"`remix collab init` (background)\"\n        });\n        boundProjectId = lane.projectId ?? boundProjectId;\n        boundCurrentAppId = lane.currentAppId ?? boundCurrentAppId;\n        boundUpstreamAppId = lane.upstreamAppId ?? boundUpstreamAppId;\n        boundThreadId = lane.threadId ?? boundThreadId;\n        boundLaneId = lane.laneId ?? null;\n      } else {\n        const lane = await resolveOrEnsureLaneBinding({\n          api,\n          projectId: boundProjectId,\n          repoFingerprint: repoFingerprint ?? \"\",\n          remoteUrl,\n          defaultBranch,\n          branchName,\n          seedAppId: String(app.id),\n          operation: \"`remix collab init` (background)\"\n        });\n        canonicalLane = lane;\n        boundProjectId = lane.projectId ?? boundProjectId;\n        boundCurrentAppId = lane.currentAppId ?? boundCurrentAppId;\n        boundUpstreamAppId = lane.upstreamAppId ?? boundUpstreamAppId;\n        boundThreadId = lane.threadId ?? boundThreadId;\n        boundLaneId = lane.laneId ?? null;\n      }\n    }\n    if (boundCurrentAppId) {\n      const readyApp = await pollAppReady(api, boundCurrentAppId, {\n        clock: collabDependencies.clock,\n        timers: collabDependencies.timers\n      });\n      boundProjectId = String(readyApp.projectId ?? boundProjectId);\n      boundThreadId = readyApp.threadId ? String(readyApp.threadId) : boundThreadId;\n    }\n    const bindingMode = defaultBranch && branchName !== defaultBranch ? \"lane\" : \"explicit_root\";\n    if (job.payload.forceNew && defaultBranch && canonicalLane) {\n      const canonicalBinding = branchBindingFromLane(canonicalLane, \"explicit_root\", {\n        projectId: canonicalLane.projectId ?? boundProjectId,\n        currentAppId: canonicalLane.currentAppId ?? boundCurrentAppId,\n        upstreamAppId: canonicalLane.upstreamAppId ?? canonicalLane.currentAppId ?? boundCurrentAppId,\n        threadId: canonicalLane.threadId ?? boundThreadId\n      });\n      const branchBindings = { [defaultBranch]: canonicalBinding };\n      if (branchName && branchName !== defaultBranch) {\n        branchBindings[branchName] = {\n          projectId: boundProjectId,\n          currentAppId: boundCurrentAppId,\n          upstreamAppId: boundUpstreamAppId,\n          threadId: boundThreadId,\n          laneId: boundLaneId,\n          bindingMode: \"lane\"\n        };\n      }\n      await localState2.bindings.writeSnapshot({\n        repoRoot,\n        repoFingerprint: repoFingerprint ?? \"\",\n        remoteUrl,\n        defaultBranch,\n        branchBindings,\n        explicitRootBinding: canonicalBinding\n      });\n    } else {\n      if (canonicalLane && defaultBranch && branchName && branchName !== defaultBranch) {\n        await localState2.bindings.write(repoRoot, {\n          projectId: canonicalLane.projectId ?? null,\n          currentAppId: canonicalLane.currentAppId ?? boundCurrentAppId,\n          upstreamAppId: canonicalLane.upstreamAppId ?? canonicalLane.currentAppId ?? boundCurrentAppId,\n          threadId: canonicalLane.threadId ?? null,\n          repoFingerprint: canonicalLane.repoFingerprint ?? repoFingerprint ?? \"\",\n          remoteUrl: canonicalLane.remoteUrl ?? remoteUrl,\n          defaultBranch: canonicalLane.defaultBranch ?? defaultBranch,\n          laneId: canonicalLane.laneId ?? null,\n          branchName: defaultBranch,\n          // This branch is reached only when the current branch is NOT\n          // the default branch — so the binding being written here is\n          // for the DEFAULT branch (the canonical/main app). It must\n          // always be `explicit_root` so the history-import auto-spawn\n          // can fire on first-ever inits (see autoSpawnHistoryImport.ts).\n          bindingMode: \"explicit_root\"\n        });\n      }\n      await localState2.bindings.write(repoRoot, {\n        projectId: boundProjectId,\n        currentAppId: boundCurrentAppId,\n        upstreamAppId: boundUpstreamAppId,\n        threadId: boundThreadId,\n        repoFingerprint: repoFingerprint ?? \"\",\n        remoteUrl,\n        defaultBranch: defaultBranch ?? null,\n        laneId: boundLaneId,\n        branchName,\n        bindingMode\n      });\n    }\n    await seedImportedInitBaseline({\n      api,\n      repoRoot,\n      repoFingerprint: repoFingerprint ?? \"\",\n      laneId: boundLaneId,\n      currentAppId: boundCurrentAppId,\n      branchName\n    });\n    await logDrainerWorkflowEvent(job.id, \"server_completed\", {\n      kind: \"init\",\n      appId: boundCurrentAppId,\n      dashboardUrl: buildDashboardAppUrl(boundCurrentAppId),\n      durationMs: collabDependencies.clock.now() - startedAt\n    });\n    await localState2.asyncJobs.update(job.id, { status: \"completed\", error: null });\n    await logDrainerWorkflowEvent(job.id, \"completed\", { kind: \"init\", durationMs: collabDependencies.clock.now() - startedAt });\n    return { status: \"completed\", jobId: job.id };\n  } catch (error) {\n    return await handleProcessError(job, error);\n  }\n}\nasync function processInitPostJob(job, api) {\n  if (job.kind !== \"init_post\") return { status: \"skipped\", jobId: job.id };\n  const startedAt = collabDependencies.clock.now();\n  const syncPhaseMs = Math.max(0, job.payload.syncPhaseFinishedAt - job.payload.syncPhaseStartedAt);\n  try {\n    await localState2.asyncJobs.update(job.id, { status: \"server_processing\", error: null });\n    await logDrainerWorkflowEvent(job.id, \"claimed\", {\n      kind: \"init_post\",\n      appId: job.payload.appId,\n      syncPhaseMs\n    });\n    await pollAppReady(api, job.payload.appId, {\n      clock: collabDependencies.clock,\n      timers: collabDependencies.timers\n    });\n    await seedImportedInitBaseline({\n      api,\n      repoRoot: job.repoRoot,\n      repoFingerprint: job.repoFingerprint ?? \"\",\n      laneId: job.laneId,\n      currentAppId: job.payload.appId,\n      branchName: job.branchName\n    });\n    const asyncPhaseMs = collabDependencies.clock.now() - startedAt;\n    await localState2.asyncJobs.update(job.id, { status: \"completed\", error: null });\n    await logDrainerWorkflowEvent(job.id, \"completed\", {\n      kind: \"init_post\",\n      appId: job.payload.appId,\n      durationMs: asyncPhaseMs,\n      // Top-level metrics requested in the rollout PR description so the\n      // sync vs async timing breakdown is grep-able in one place.\n      [\"init.sync_phase_ms\"]: syncPhaseMs,\n      [\"init.async_phase_ms\"]: asyncPhaseMs,\n      [\"init.total_ms\"]: syncPhaseMs + asyncPhaseMs\n    });\n    return { status: \"completed\", jobId: job.id };\n  } catch (error) {\n    const outcome = await handleProcessError(job, error);\n    if (outcome.status === \"failed\") {\n      const bindingPath = localState2.bindings.getPath(job.repoRoot);\n      try {\n        await fs14.unlink(bindingPath);\n        await logDrainerWorkflowEvent(job.id, \"binding_cleared\", {\n          kind: \"init_post\",\n          appId: job.payload.appId,\n          repoRoot: job.repoRoot,\n          bindingPath,\n          reason: \"init_post_terminal_failure\"\n        });\n      } catch (cleanupError) {\n        await logDrainerWorkflowEvent(job.id, \"binding_cleared\", {\n          kind: \"init_post\",\n          appId: job.payload.appId,\n          repoRoot: job.repoRoot,\n          bindingPath,\n          reason: \"init_post_terminal_failure\",\n          cleanupError: formatWorkflowError(cleanupError)\n        });\n      }\n    }\n    return outcome;\n  }\n}\nasync function collabInitProcess(jobId, opts) {\n  const claim = await localState2.asyncJobs.claim(jobId);\n  if (!claim) {\n    const job = await localState2.asyncJobs.read(jobId);\n    if (!job) return { status: \"skipped\", jobId };\n    return { status: \"skipped\", jobId };\n  }\n  try {\n    if (claim.job.kind !== \"init\") return { status: \"skipped\", jobId };\n    return await processInitJob(claim.job, opts.api);\n  } finally {\n    await claim.release();\n  }\n}\nasync function collabInitPostProcess(jobId, opts) {\n  const claim = await localState2.asyncJobs.claim(jobId);\n  if (!claim) {\n    const job = await localState2.asyncJobs.read(jobId);\n    if (!job) return { status: \"skipped\", jobId };\n    return { status: \"skipped\", jobId };\n  }\n  try {\n    if (claim.job.kind !== \"init_post\") return { status: \"skipped\", jobId };\n    return await processInitPostJob(claim.job, opts.api);\n  } finally {\n    await claim.release();\n  }\n}\nasync function acquireDrainerPidLock() {\n  const pidPath = getDrainerPidPath();\n  await fs14.mkdir(path13.dirname(pidPath), { recursive: true });\n  try {\n    const existing = await fs14.readFile(pidPath, \"utf8\").catch(() => \"\");\n    const existingPid = parseInt(existing.trim(), 10);\n    if (Number.isFinite(existingPid) && existingPid > 0 && existingPid !== process.pid) {\n      try {\n        process.kill(existingPid, 0);\n        return null;\n      } catch (error) {\n        if (error?.code !== \"ESRCH\") return null;\n      }\n    }\n    await fs14.writeFile(pidPath, String(process.pid), \"utf8\");\n    return {\n      release: async () => {\n        try {\n          const current = (await fs14.readFile(pidPath, \"utf8\")).trim();\n          if (current === String(process.pid)) {\n            await fs14.unlink(pidPath).catch(() => void 0);\n          }\n        } catch {\n        }\n      }\n    };\n  } catch {\n    return null;\n  }\n}\nasync function drainAsyncJobs(opts) {\n  const lockHandle = opts.respectPidLock === false ? null : await acquireDrainerPidLock();\n  if (opts.respectPidLock !== false && !lockHandle) return [];\n  try {\n    return await drainClaimedJobs({\n      prune: async () => {\n        try {\n          await localState2.asyncJobs.pruneTerminal();\n        } catch {\n        }\n      },\n      list: () => localState2.asyncJobs.list(),\n      isTerminal: (job) => planAsyncJobDrainTransition(job).terminal,\n      claim: async (job) => ({\n        job,\n        /* v8 ignore next -- async job processors perform their own claim/release cycle. */\n        release: async () => void 0\n      }),\n      process: async ({ job }) => {\n        const transition = planAsyncJobDrainTransition(job);\n        return transition.action === \"process_init\" ? collabInitProcess(job.id, { api: opts.api }) : collabInitPostProcess(job.id, { api: opts.api });\n      },\n      onError: \"throw\"\n    });\n  } finally {\n    if (lockHandle) await lockHandle.release();\n  }\n}\nexport {\n  FINALIZE_JOB_LOCK_STALE_MS,\n  FINALIZE_PREFLIGHT_FAILURE_CODES,\n  SourceConversationSchema,\n  awaitAsyncJob,\n  cleanStaleFinalizeJobLocks,\n  collabApprove,\n  collabCheckout,\n  collabFinalizeTurn,\n  collabInit,\n  collabInitProcess,\n  collabInitSubmit,\n  collabInvite,\n  collabList,\n  collabListMembers,\n  collabListMergeRequests,\n  collabReconcile,\n  collabRecordingPreflight,\n  collabReject,\n  collabRemix,\n  collabRequestMerge,\n  collabStatus,\n  collabSync,\n  collabSyncUpstream,\n  collabUpdateMemberRole,\n  collabView,\n  deleteAsyncJob,\n  drainAsyncJobs,\n  drainPendingFinalizeQueue,\n  drainerLogPath,\n  findFailedAsyncJob,\n  findPendingAsyncJob,\n  forgetPendingFinalizeJob,\n  getDrainerLogPath,\n  getDrainerPidPath,\n  getMemberRolesForScope,\n  isFinalizePreflightFailureCode,\n  listAsyncJobs,\n  listAsyncJobsForRepo,\n  listPendingFinalizeJobs,\n  processPendingFinalizeJob,\n  pruneTerminalAsyncJobs,\n  readAsyncJob,\n  readLocalSnapshot,\n  readPendingFinalizeJob,\n  requeuePendingFinalizeJob,\n  summarizeAsyncJobs,\n  updatePendingFinalizeJob,\n  validateMemberRole\n};\n","// Auto-fix dispatcher.\n//\n// Decides what to do with a structured collabFinalizeTurn preflight failure:\n//   * Some failure codes are SAFE to auto-fix without user input (binding\n//     missing → init; local baseline missing → init; pull needed → sync).\n//     For these, we spawn the fix command detached and update the failure\n//     marker so the next prompt's UserPromptSubmit knows the fix is in\n//     flight.\n//   * The rest (reconcile, branch_mismatch, metadata_conflict, missing_head,\n//     remote_error, family_ambiguous) are warn-only — we leave the marker\n//     alone (status=not_attempted) and let UserPromptSubmit nag the user\n//     until they manually fix it.\n//\n// Why detached and not synchronous: hooks should return fast. The fix\n// typically takes 5-25s; the user finds out it's running via the next\n// prompt's UserPromptSubmit warning surfacing the marker.\n//\n// Per-repo throttle: each spawned fix has its own local runtime\n// lock that prevents back-to-back duplicate spawns from the same hook\n// firing twice. The authoritative single-instance guard is the per-repo\n// withRepoMutationLock inside remix-core; the throttle just suppresses\n// pointless spawn churn.\n//\n// Baseline recovery is auto-applied because asking the user to approve a\n// low-level recording repair just causes silent recording loss. The server\n// keeps recorded turns durable; this local recovery only repairs the lane\n// baseline needed for future recordings.\nimport { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, statSync, utimesSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { FinalizePreflightFailureCode } from \"@remixhq/core/collab\";\n\nimport {\n  buildFreshFailureMarker,\n  writeFinalizeFailureMarker,\n  type FinalizeFailureMarker,\n} from \"./finalize-failure-marker.js\";\nimport { collabInitSpawnLockPath } from \"./collab-init-spawn-lock.js\";\nimport { appendHookDiagnosticsEvent } from \"./hook-diagnostics.js\";\nimport { resolveRemixCliForHook } from \"./remix-cli-path.js\";\nimport { getHookStateRoot } from \"./runtime.js\";\n\n// Mapping from preflight code → CLI subcommand that fixes it. Codes\n// absent from this map are warn-only (no auto-fix attempted).\nconst AUTO_FIX_COMMAND: Partial<Record<FinalizePreflightFailureCode, readonly string[]>> = {\n  // Already auto-spawned by hook-user-prompt's branch-init path, but we\n  // include it here too so a finalize-time failure (e.g. binding got\n  // deleted between init and the next finalize) also self-heals.\n  branch_binding_missing: [\"collab\", \"init\"],\n  // Local revision baseline is missing. Init seeds the branch/lane baseline\n  // without requiring the user to know about the recording internals.\n  baseline_missing: [\"collab\", \"init\"],\n  // Server moved ahead. `collab sync` is fast-forward-safe by default;\n  // it refuses non-FF on its own, so we don't need to gate here.\n  pull_required: [\"collab\", \"sync\"],\n};\n\nexport function isAutoFixableFinalizeFailureCode(\n  code: FinalizePreflightFailureCode | null,\n): code is keyof typeof AUTO_FIX_COMMAND {\n  return Boolean(code && AUTO_FIX_COMMAND[code]);\n}\n\n// Mapping from preflight code → human-readable command string the user\n// would run manually. Used to phrase the user_message when no auto-fix\n// is attempted.\nconst RECOMMENDED_USER_COMMAND: Partial<Record<FinalizePreflightFailureCode, string>> = {\n  not_bound: \"remix collab init\",\n  branch_binding_missing: \"remix collab init\",\n  family_ambiguous: \"remix collab status\",\n  metadata_conflict: \"remix collab status\",\n  branch_mismatch: \"remix collab status\",\n  missing_head: \"remix collab status\",\n  remote_error: \"remix collab status\",\n  pull_required: \"remix collab sync\",\n  baseline_missing: \"remix collab init\",\n};\n\n// Same window as the init throttle in hook-user-prompt.ts: long enough\n// to cover a slow fix (typically 10-25s) and short enough that a crashed\n// prior spawn doesn't permanently block re-tries.\nconst SPAWN_THROTTLE_MS = 5 * 60 * 1000;\n\nfunction commandSlug(args: readonly string[]): string {\n  // [\"collab\", \"init\"] → \"collab-init\"; safe filename component.\n  return args.join(\"-\").replace(/[^a-zA-Z0-9_-]/g, \"_\");\n}\n\nfunction stateRoot(): string {\n  return getHookStateRoot();\n}\n\nfunction sha256Hex(value: string): string {\n  return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction spawnLockPath(repoRoot: string, cmdSlug: string): string {\n  if (cmdSlug === \"collab-init\") {\n    return collabInitSpawnLockPath(repoRoot);\n  }\n  return path.join(stateRoot(), \"auto-fix-spawn-locks\", sha256Hex(repoRoot), `${cmdSlug}.lock`);\n}\n\nexport type AutoFixOutcome =\n  | {\n      kind: \"spawned\";\n      command: string;\n      pid: number | undefined;\n    }\n  | {\n      kind: \"warn_only\";\n      reason: \"no_auto_fix_for_code\" | \"unknown_code\";\n    }\n  | {\n      kind: \"spawn_throttled\";\n      command: string;\n      reason: \"spawn_lock_held\";\n    }\n  | {\n      kind: \"spawn_failed\";\n      command: string;\n      reason: \"spawn_failed\";\n      message: string;\n    };\n\nfunction spawnFixDetached(repoRoot: string, args: readonly string[]): AutoFixOutcome {\n  const slug = commandSlug(args);\n  const command = `remix ${args.join(\" \")}`;\n  const lockPath = spawnLockPath(repoRoot, slug);\n\n  try {\n    if (existsSync(lockPath)) {\n      const ageMs = Date.now() - statSync(lockPath).mtimeMs;\n      if (ageMs < SPAWN_THROTTLE_MS) {\n        return { kind: \"spawn_throttled\", command, reason: \"spawn_lock_held\" };\n      }\n    }\n  } catch {\n    // ignore — fall through and try to spawn anyway\n  }\n\n  try {\n    mkdirSync(path.dirname(lockPath), { recursive: true });\n  } catch {\n    // ignore — lock is best-effort\n  }\n\n  try {\n    const cli = resolveRemixCliForHook();\n    if (!cli.ok) {\n      return {\n        kind: \"spawn_failed\",\n        command,\n        reason: \"spawn_failed\",\n        message: cli.message,\n      };\n    }\n    const child = spawn(cli.path, [...args], {\n      cwd: repoRoot,\n      detached: true,\n      stdio: \"ignore\",\n      env: { ...process.env, REMIX_CLI_PATH: cli.path, REMIX_AUTO_FIX_SPAWN: \"1\" },\n    });\n    child.unref();\n    try {\n      writeFileSync(lockPath, String(child.pid ?? \"\"), \"utf8\");\n      utimesSync(lockPath, new Date(), new Date());\n    } catch {\n      // ignore — lock is best-effort\n    }\n    return { kind: \"spawned\", command, pid: child.pid };\n  } catch (spawnErr) {\n    return {\n      kind: \"spawn_failed\",\n      command,\n      reason: \"spawn_failed\",\n      message: spawnErr instanceof Error ? spawnErr.message : String(spawnErr),\n    };\n  }\n}\n\nexport type DispatchInput = {\n  hook: \"UserPromptSubmit\" | \"Stop\";\n  sessionId: string;\n  turnId: string | null;\n  repoRoot: string;\n  preflightCode: FinalizePreflightFailureCode | null;\n  message: string;\n  hint: string | null;\n};\n\n// Main entry point. Always writes/updates the failure marker (so the\n// next prompt has something to surface) and returns what was done so the\n// caller can log it. Never throws — best-effort is the right semantics\n// for a recovery dispatcher; if it can't write the marker, the worst\n// case is \"next prompt has no warning\" which is no worse than today.\nexport async function dispatchFinalizeFailure(input: DispatchInput): Promise<AutoFixOutcome> {\n  const recommendedCommand = input.preflightCode ? RECOMMENDED_USER_COMMAND[input.preflightCode] ?? null : null;\n  const marker = buildFreshFailureMarker({\n    repoRoot: input.repoRoot,\n    preflightCode: input.preflightCode,\n    message: input.message,\n    hint: input.hint,\n    recommendedCommand,\n  });\n\n  let outcome: AutoFixOutcome;\n  const autoFixArgs = input.preflightCode ? AUTO_FIX_COMMAND[input.preflightCode] : undefined;\n  if (!autoFixArgs) {\n    outcome = {\n      kind: \"warn_only\",\n      reason: input.preflightCode ? \"no_auto_fix_for_code\" : \"unknown_code\",\n    };\n  } else {\n    outcome = spawnFixDetached(input.repoRoot, autoFixArgs);\n    marker.autoFix = mergeOutcomeIntoMarker(marker.autoFix, outcome);\n  }\n\n  try {\n    await writeFinalizeFailureMarker(marker);\n  } catch (writeErr) {\n    await appendHookDiagnosticsEvent({\n      hook: input.hook,\n      sessionId: input.sessionId,\n      turnId: input.turnId ?? undefined,\n      stage: \"finalize_failure_marker_write_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot: input.repoRoot,\n      message: writeErr instanceof Error ? writeErr.message : String(writeErr),\n    });\n  }\n\n  await appendHookDiagnosticsEvent({\n    hook: input.hook,\n    sessionId: input.sessionId,\n    turnId: input.turnId ?? undefined,\n    stage: \"auto_fix_dispatched\",\n    result: outcome.kind === \"spawned\" ? \"success\" : outcome.kind === \"warn_only\" ? \"info\" : \"error\",\n    reason: outcome.kind,\n    repoRoot: input.repoRoot,\n    fields: {\n      preflightCode: input.preflightCode,\n      command: \"command\" in outcome ? outcome.command : null,\n      pid: outcome.kind === \"spawned\" ? outcome.pid ?? null : null,\n      recommendedCommand,\n    },\n    message: outcome.kind === \"spawn_failed\" ? outcome.message : null,\n  });\n\n  return outcome;\n}\n\nfunction mergeOutcomeIntoMarker(\n  existing: FinalizeFailureMarker[\"autoFix\"],\n  outcome: AutoFixOutcome,\n): FinalizeFailureMarker[\"autoFix\"] {\n  if (outcome.kind === \"spawned\") {\n    return {\n      status: \"in_progress\",\n      command: outcome.command,\n      pid: outcome.pid ?? null,\n      logPath: null,\n      attemptedAt: new Date().toISOString(),\n      failureMessage: null,\n    };\n  }\n  if (outcome.kind === \"spawn_throttled\") {\n    return {\n      status: \"in_progress\",\n      command: outcome.command,\n      pid: existing.pid,\n      logPath: existing.logPath,\n      attemptedAt: existing.attemptedAt,\n      failureMessage: null,\n    };\n  }\n  if (outcome.kind === \"spawn_failed\") {\n    return {\n      status: \"spawn_failed\",\n      command: outcome.command,\n      pid: null,\n      logPath: null,\n      attemptedAt: new Date().toISOString(),\n      failureMessage: outcome.message,\n    };\n  }\n  return existing;\n}\n","// `.remix/.last-finalize-failure.json` — the single source of truth for\n// \"the most recent collabFinalizeTurn failed for a structured reason.\"\n//\n// Writers:\n//   * hook-stop-collab.ts (Stop hook records turns; failures dispatch here)\n//   * auto-fix-dispatcher.ts (records auto-fix progress / outcome)\n// Readers:\n//   * hook-user-prompt.ts (re-surfaces the warning on the next prompt)\n//\n// Marker lifecycle:\n//   1. Finalize fails with a known FinalizePreflightFailureCode → marker\n//      written, optional auto-fix spawned.\n//   2. Each subsequent prompt's UserPromptSubmit re-surfaces the warning\n//      (with an updated message reflecting whether the auto-fix is still\n//      in progress, succeeded, or failed).\n//   3. The next successful finalize on the same repo deletes the marker.\n//   4. If the user manually runs the recommended fix command, the next\n//      finalize succeeds and the marker is deleted as in (3).\n//\n// Atomicity: writes go through a per-pid tmp file + rename, so a crash\n// mid-write can never leave the marker file in a half-parsed state.\n//\n// One marker per repo (not per session). The failure is a property of\n// the repo state, not of any single turn — if the user opens a second\n// Claude Code session in the same repo, both should see the same\n// warning.\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { FinalizePreflightFailureCode } from \"@remixhq/core/collab\";\n\nexport const FINALIZE_FAILURE_MARKER_REL = path.join(\".remix\", \".last-finalize-failure.json\");\n\nexport type AutoFixStatus =\n  // No auto-fix attempted (warn-only failure code, or auto-fix disabled).\n  | \"not_attempted\"\n  // Auto-fix command spawned, no result yet (still running or never reported).\n  | \"in_progress\"\n  // Auto-fix process completed with exit code 0 — but a follow-up finalize\n  // hasn't happened yet to confirm the underlying state is actually fixed.\n  | \"spawn_succeeded\"\n  // Auto-fix process exited non-zero or our spawn itself failed.\n  | \"spawn_failed\";\n\nexport type FinalizeFailureMarker = {\n  schemaVersion: 1;\n  // ISO timestamp of the original failure.\n  failedAt: string;\n  // Repo this marker is about. Markers live per-repo, but we record the\n  // root explicitly so a single hook that walks multiple touched repos\n  // can pick the right one.\n  repoRoot: string;\n  // Structured failure code from collabFinalizeTurn. May be null when the\n  // failure was something else (e.g. network blip, missing assistant\n  // response) — in that case the marker exists so UserPromptSubmit can\n  // still show a generic \"previous turn didn't record\" warning.\n  preflightCode: FinalizePreflightFailureCode | null;\n  // Free-text message + hint copied off the original error. Surfaced to\n  // the user verbatim.\n  message: string;\n  hint: string | null;\n  // Recommended CLI command for the user to run (e.g. \"remix collab init\").\n  // null when the failure isn't user-actionable (network, etc.).\n  recommendedCommand: string | null;\n  // Auto-fix bookkeeping. Updated by auto-fix-dispatcher when it spawns\n  // / completes the fix. Read by UserPromptSubmit to phrase the warning.\n  autoFix: {\n    status: AutoFixStatus;\n    // Command that was spawned, e.g. \"remix collab init\". null if\n    // status is \"not_attempted\".\n    command: string | null;\n    // PID of the spawned process. null when not spawned.\n    pid: number | null;\n    // Legacy field. New auto-fix spawns do not write repo-local logs.\n    logPath: string | null;\n    // ISO timestamp the spawn was attempted.\n    attemptedAt: string | null;\n    // Optional human-readable reason for spawn_failed.\n    failureMessage: string | null;\n  };\n};\n\nfunction markerPath(repoRoot: string): string {\n  return path.join(repoRoot, FINALIZE_FAILURE_MARKER_REL);\n}\n\nexport async function readFinalizeFailureMarker(repoRoot: string): Promise<FinalizeFailureMarker | null> {\n  const raw = await fs.readFile(markerPath(repoRoot), \"utf8\").catch(() => null);\n  if (!raw) return null;\n  try {\n    const parsed = JSON.parse(raw) as Partial<FinalizeFailureMarker>;\n    if (parsed.schemaVersion !== 1) return null;\n    if (typeof parsed.repoRoot !== \"string\" || typeof parsed.failedAt !== \"string\") return null;\n    if (typeof parsed.message !== \"string\") return null;\n    return parsed as FinalizeFailureMarker;\n  } catch {\n    return null;\n  }\n}\n\nexport async function writeFinalizeFailureMarker(marker: FinalizeFailureMarker): Promise<void> {\n  const filePath = markerPath(marker.repoRoot);\n  await fs.mkdir(path.dirname(filePath), { recursive: true });\n  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;\n  await fs.writeFile(tmpPath, JSON.stringify(marker, null, 2), \"utf8\");\n  await fs.rename(tmpPath, filePath);\n}\n\nexport async function clearFinalizeFailureMarker(repoRoot: string): Promise<void> {\n  await fs.rm(markerPath(repoRoot), { force: true }).catch(() => undefined);\n}\n\n// Build a marker initial state from a fresh finalize failure. Auto-fix\n// fields default to \"not_attempted\"; the dispatcher updates them after\n// it decides whether to spawn.\nexport function buildFreshFailureMarker(params: {\n  repoRoot: string;\n  preflightCode: FinalizePreflightFailureCode | null;\n  message: string;\n  hint: string | null;\n  recommendedCommand: string | null;\n}): FinalizeFailureMarker {\n  return {\n    schemaVersion: 1,\n    failedAt: new Date().toISOString(),\n    repoRoot: params.repoRoot,\n    preflightCode: params.preflightCode,\n    message: params.message,\n    hint: params.hint,\n    recommendedCommand: params.recommendedCommand,\n    autoFix: {\n      status: \"not_attempted\",\n      command: null,\n      pid: null,\n      logPath: null,\n      attemptedAt: null,\n      failureMessage: null,\n    },\n  };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { getHookStateRoot } from \"./runtime.js\";\n\nfunction stateRoot(): string {\n  return getHookStateRoot();\n}\n\nfunction sha256Hex(value: string): string {\n  return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function collabInitSpawnLockPath(repoRoot: string): string {\n  return path.join(stateRoot(), \"collab-init-spawn-locks\", `${sha256Hex(repoRoot)}.json`);\n}\n","import { readFileSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type PluginRuntime = \"claude\" | \"codex\";\n\nexport const CODEX_RUNTIME_MARKER = \"codex\";\nconst RUNTIME_MARKER_FILE = \".remix-plugin-runtime\";\n\nexport function getPluginRuntime(): PluginRuntime {\n  const configured = process.env.REMIX_PLUGIN_RUNTIME?.trim().toLowerCase();\n  if (configured === \"codex\" || configured === \"claude\") return configured;\n\n  const entrypoint = process.argv[1]?.trim();\n  if (entrypoint) {\n    try {\n      const marker = readFileSync(\n        path.resolve(path.dirname(entrypoint), \"..\", RUNTIME_MARKER_FILE),\n        \"utf8\",\n      )\n        .trim()\n        .toLowerCase();\n      if (marker === CODEX_RUNTIME_MARKER) return \"codex\";\n    } catch {\n      // Claude installs do not carry a runtime marker.\n    }\n  }\n  return \"claude\";\n}\n\nexport function getHookStateRoot(): string {\n  if (getPluginRuntime() === \"codex\") {\n    return (\n      process.env.REMIX_CODEX_PLUGIN_HOOK_STATE_ROOT?.trim() ||\n      path.join(os.tmpdir(), \"remix-codex-plugin-hooks\")\n    );\n  }\n  return (\n    process.env.REMIX_CLAUDE_PLUGIN_HOOK_STATE_ROOT?.trim() ||\n    path.join(os.tmpdir(), \"remix-claude-plugin-hooks\")\n  );\n}\n\nexport function getHookActor(version: string): {\n  type: \"agent\";\n  name: \"claude-code\" | \"codex\";\n  version: string;\n  provider: \"anthropic\" | \"openai\";\n} {\n  return getPluginRuntime() === \"codex\"\n    ? { type: \"agent\", name: \"codex\", version, provider: \"openai\" }\n    : { type: \"agent\", name: \"claude-code\", version, provider: \"anthropic\" };\n}\n\nexport function getRuntimeScopedTurnId(turnId: string): string {\n  // Preserve Claude's historical key shape so queued work remains idempotent\n  // across plugin upgrades. Codex gets an explicit namespace because it can\n  // reuse the same hook payload session/turn identifiers.\n  return getPluginRuntime() === \"codex\" ? `codex:${turnId}` : turnId;\n}\n","import { createHash } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport { getPendingTurnStateRootPath, listPendingTurnStateSummaries, type PendingTurnStateSummary } from \"./hook-state.js\";\nimport { pluginMetadata } from \"./metadata.js\";\nimport { getPluginRuntime } from \"./runtime.js\";\n\ntype HookDiagnosticsResult = \"start\" | \"info\" | \"skip\" | \"success\" | \"error\";\ntype HookDiagnosticsFieldValue = string | number | boolean | null;\n\nexport type HookDiagnosticsEvent = {\n  ts: string;\n  hook: string;\n  pluginVersion: string;\n  pid: number;\n  sessionId: string | null;\n  turnId: string | null;\n  stage: string;\n  result: HookDiagnosticsResult;\n  reason: string | null;\n  toolName: string | null;\n  repoRoot: string | null;\n  message: string | null;\n  fields: Record<string, HookDiagnosticsFieldValue>;\n};\n\nexport type HookDiagnosticsReport = {\n  logPath: string;\n  stateRoot: string;\n  recentEvents: HookDiagnosticsEvent[];\n  pendingStates: PendingTurnStateSummary[];\n};\n\nconst DEFAULT_EVENT_LIMIT = 50;\nconst MAX_EVENT_LIMIT = 200;\nconst MAX_LOG_BYTES = 512 * 1024;\n\nfunction resolveClaudeRoot(): string {\n  const configured = process.env.CLAUDE_CONFIG_DIR?.trim();\n  return configured || path.join(os.homedir(), \".claude\");\n}\n\nfunction resolvePluginDataDirName(): string {\n  return `${pluginMetadata.pluginId}-${pluginMetadata.pluginId}`;\n}\n\nexport function getHookDiagnosticsDirPath(): string {\n  const runtime = getPluginRuntime();\n  const configured =\n    runtime === \"codex\"\n      ? process.env.REMIX_CODEX_PLUGIN_HOOK_DIAGNOSTICS_DIR?.trim()\n      : process.env.REMIX_CLAUDE_PLUGIN_HOOK_DIAGNOSTICS_DIR?.trim();\n  if (runtime === \"codex\") {\n    return configured || path.join(os.homedir(), \".codex\", \"plugins\", \"data\", \"remix-codex\");\n  }\n  return configured || path.join(resolveClaudeRoot(), \"plugins\", \"data\", resolvePluginDataDirName());\n}\n\nexport function getHookDiagnosticsLogPath(): string {\n  return path.join(getHookDiagnosticsDirPath(), \"hooks.ndjson\");\n}\n\nfunction clampEventLimit(limit?: number): number {\n  if (typeof limit !== \"number\" || !Number.isFinite(limit)) return DEFAULT_EVENT_LIMIT;\n  return Math.max(1, Math.min(MAX_EVENT_LIMIT, Math.trunc(limit)));\n}\n\nfunction toFieldValue(value: unknown): HookDiagnosticsFieldValue | undefined {\n  if (value === null) return null;\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\" && Number.isFinite(value)) return value;\n  if (typeof value === \"boolean\") return value;\n  return undefined;\n}\n\nfunction normalizeFields(fields?: Record<string, unknown>): Record<string, HookDiagnosticsFieldValue> {\n  if (!fields) return {};\n  const normalizedEntries = Object.entries(fields)\n    .map(([key, value]) => {\n      const normalized = toFieldValue(value);\n      return normalized === undefined ? null : ([key, normalized] as const);\n    })\n    .filter((entry): entry is readonly [string, HookDiagnosticsFieldValue] => entry !== null);\n  return Object.fromEntries(normalizedEntries);\n}\n\nasync function rotateLogIfNeeded(logPath: string): Promise<void> {\n  const stat = await fs.stat(logPath).catch(() => null);\n  if (!stat || stat.size < MAX_LOG_BYTES) {\n    return;\n  }\n\n  const rotatedPath = `${logPath}.1`;\n  await fs.rm(rotatedPath, { force: true }).catch(() => undefined);\n  await fs.rename(logPath, rotatedPath).catch(() => undefined);\n}\n\nexport function summarizeText(value: string | null | undefined): {\n  present: boolean;\n  length: number;\n  sha256Prefix: string | null;\n} {\n  if (typeof value !== \"string\" || !value.trim()) {\n    return {\n      present: false,\n      length: 0,\n      sha256Prefix: null,\n    };\n  }\n\n  const trimmed = value.trim();\n  return {\n    present: true,\n    length: trimmed.length,\n    sha256Prefix: createHash(\"sha256\").update(trimmed).digest(\"hex\").slice(0, 12),\n  };\n}\n\nexport async function appendHookDiagnosticsEvent(params: {\n  hook: string;\n  sessionId?: string | null;\n  turnId?: string | null;\n  stage: string;\n  result: HookDiagnosticsResult;\n  reason?: string | null;\n  toolName?: string | null;\n  repoRoot?: string | null;\n  message?: string | null;\n  fields?: Record<string, unknown>;\n}): Promise<void> {\n  try {\n    const logPath = getHookDiagnosticsLogPath();\n    await fs.mkdir(path.dirname(logPath), { recursive: true });\n    await rotateLogIfNeeded(logPath);\n    const event: HookDiagnosticsEvent = {\n      ts: new Date().toISOString(),\n      hook: params.hook,\n      pluginVersion: pluginMetadata.version,\n      pid: process.pid,\n      sessionId: params.sessionId?.trim() || null,\n      turnId: params.turnId?.trim() || null,\n      stage: params.stage.trim(),\n      result: params.result,\n      reason: params.reason?.trim() || null,\n      toolName: params.toolName?.trim() || null,\n      repoRoot: params.repoRoot?.trim() || null,\n      message: params.message?.trim() || null,\n      fields: normalizeFields(params.fields),\n    };\n    await fs.appendFile(logPath, `${JSON.stringify(event)}\\n`, \"utf8\");\n  } catch {\n    // Diagnostics are best-effort and must never break hook execution.\n  }\n}\n\nasync function readEventsFromFile(filePath: string): Promise<HookDiagnosticsEvent[]> {\n  const raw = await fs.readFile(filePath, \"utf8\").catch(() => null);\n  if (!raw) return [];\n  return raw\n    .split(\"\\n\")\n    .map((line) => line.trim())\n    .filter(Boolean)\n    .flatMap((line) => {\n      try {\n        const parsed = JSON.parse(line) as HookDiagnosticsEvent;\n        return parsed && typeof parsed === \"object\" ? [parsed] : [];\n      } catch {\n        return [];\n      }\n    });\n}\n\nexport async function readRecentHookDiagnosticsEvents(limit?: number): Promise<HookDiagnosticsEvent[]> {\n  const eventLimit = clampEventLimit(limit);\n  const logPath = getHookDiagnosticsLogPath();\n  const [rotated, current] = await Promise.all([readEventsFromFile(`${logPath}.1`), readEventsFromFile(logPath)]);\n  return [...rotated, ...current].slice(-eventLimit);\n}\n\nexport async function readHookDiagnosticsReport(limit?: number): Promise<HookDiagnosticsReport> {\n  const [recentEvents, pendingStates] = await Promise.all([\n    readRecentHookDiagnosticsEvents(limit),\n    listPendingTurnStateSummaries(),\n  ]);\n\n  return {\n    logPath: getHookDiagnosticsLogPath(),\n    stateRoot: getPendingTurnStateRootPath(),\n    recentEvents,\n    pendingStates,\n  };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\n\nimport type { TurnIntent } from \"./history-routing.js\";\nimport { getHookStateRoot } from \"./runtime.js\";\nimport {\n  createClaudeSourceConversation,\n  normalizeClaudeSourceConversation,\n  type ClaudeSourceConversation,\n} from \"./source-conversation.js\";\n\nexport type RepoRecordMode = \"changed_turn\" | \"no_diff_turn\" | \"conversation_only\";\nexport type ManualRecordingScope = \"full_turn\";\n\nexport type TouchedRepoState = {\n  repoRoot: string;\n  projectId: string | null;\n  currentAppId: string | null;\n  upstreamAppId: string | null;\n  firstTouchedAt: string;\n  lastTouchedAt: string;\n  lastObservedWriteAt: string | null;\n  touchedBy: string[];\n  hasObservedWrite: boolean;\n  manuallyRecorded: boolean;\n  manuallyRecordedAt: string | null;\n  manuallyRecordedByTool: string | null;\n  manualRecordingScope: ManualRecordingScope | null;\n  manualRemoteChangeRecordedAt: string | null;\n  stopAttempted: boolean;\n  stopRecorded: boolean;\n  stopRecordedAt: string | null;\n  stopRecordedMode: RepoRecordMode | null;\n  recordingFailureMessage: string | null;\n  recordingFailureHint: string | null;\n  recordingFailedAt: string | null;\n};\n\nexport type PendingTurnState = {\n  sessionId: string;\n  turnId: string;\n  sourceConversation: ClaudeSourceConversation | null;\n  prompt: string;\n  initialCwd: string | null;\n  intent: TurnIntent;\n  submittedAt: string;\n  consultedMemory: boolean;\n  touchedRepos: Record<string, TouchedRepoState>;\n  turnFailureMessage: string | null;\n  turnFailureHint: string | null;\n  turnFailedAt: string | null;\n};\n\nexport type LastFinalizedTurnRecord = {\n  sessionId: string;\n  turnId: string;\n  sourceConversation: ClaudeSourceConversation | null;\n  prompt: string;\n  finalizedAt: string;\n};\n\nexport type PendingTouchedRepoSummary = {\n  repoRoot: string;\n  projectId: string | null;\n  currentAppId: string | null;\n  upstreamAppId: string | null;\n  lastTouchedAt: string;\n  lastObservedWriteAt: string | null;\n  touchedBy: string[];\n  hasObservedWrite: boolean;\n  manuallyRecorded: boolean;\n  manualRecordingScope: ManualRecordingScope | null;\n  stopAttempted: boolean;\n  stopRecorded: boolean;\n  stopRecordedMode: RepoRecordMode | null;\n  recordingFailureMessage: string | null;\n  recordingFailureHint: string | null;\n  recordingFailedAt: string | null;\n};\n\nexport type PendingTurnStateSummary = {\n  sessionId: string;\n  turnId: string;\n  initialCwd: string | null;\n  submittedAt: string;\n  consultedMemory: boolean;\n  promptLength: number;\n  touchedRepoCount: number;\n  turnFailureMessage: string | null;\n  turnFailureHint: string | null;\n  turnFailedAt: string | null;\n  touchedRepos: PendingTouchedRepoSummary[];\n};\n\nfunction stateRoot(): string {\n  return getHookStateRoot();\n}\n\nfunction statePath(sessionId: string): string {\n  return path.join(stateRoot(), `${sessionId}.json`);\n}\n\nfunction stateLockPath(sessionId: string): string {\n  return path.join(stateRoot(), `${sessionId}.lock`);\n}\n\nfunction stateLockMetaPath(sessionId: string): string {\n  return path.join(stateLockPath(sessionId), \"owner.json\");\n}\n\nasync function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n  await fs.mkdir(path.dirname(filePath), { recursive: true });\n  const tmpPath = `${filePath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n  await fs.writeFile(tmpPath, JSON.stringify(value, null, 2) + \"\\n\", \"utf8\");\n  await fs.rename(tmpPath, filePath);\n}\n\nconst STATE_LOCK_WAIT_MS = 2_000;\nconst STATE_LOCK_POLL_MS = 25;\nconst STATE_LOCK_STALE_MS = 30_000;\nconst STATE_LOCK_HEARTBEAT_MS = 5_000;\n\ntype StateLockMetadata = {\n  ownerId: string;\n  pid: number;\n  createdAt: string;\n  heartbeatAt: string;\n};\n\nasync function sleep(ms: number): Promise<void> {\n  await new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function readStateLockMetadata(sessionId: string): Promise<StateLockMetadata | null> {\n  const raw = await fs.readFile(stateLockMetaPath(sessionId), \"utf8\").catch(() => null);\n  if (!raw) return null;\n  try {\n    const parsed = JSON.parse(raw) as Partial<StateLockMetadata>;\n    if (\n      typeof parsed.ownerId !== \"string\" ||\n      typeof parsed.pid !== \"number\" ||\n      typeof parsed.createdAt !== \"string\" ||\n      typeof parsed.heartbeatAt !== \"string\"\n    ) {\n      return null;\n    }\n    return {\n      ownerId: parsed.ownerId,\n      pid: parsed.pid,\n      createdAt: parsed.createdAt,\n      heartbeatAt: parsed.heartbeatAt,\n    };\n  } catch {\n    return null;\n  }\n}\n\nasync function writeStateLockMetadata(sessionId: string, metadata: StateLockMetadata): Promise<void> {\n  await writeJsonAtomic(stateLockMetaPath(sessionId), metadata);\n}\n\nasync function tryRemoveStaleStateLock(sessionId: string): Promise<boolean> {\n  const lockPath = stateLockPath(sessionId);\n  const metadata = await readStateLockMetadata(sessionId);\n  const staleByHeartbeat =\n    metadata && Date.now() - new Date(metadata.heartbeatAt).getTime() > STATE_LOCK_STALE_MS;\n  if (staleByHeartbeat) {\n    await fs.rm(lockPath, { recursive: true, force: true }).catch(() => undefined);\n    return true;\n  }\n\n  if (!metadata) {\n    const lockStat = await fs.stat(lockPath).catch(() => null);\n    if (lockStat && Date.now() - lockStat.mtimeMs > STATE_LOCK_STALE_MS) {\n      await fs.rm(lockPath, { recursive: true, force: true }).catch(() => undefined);\n      return true;\n    }\n  }\n\n  return false;\n}\n\nasync function acquireStateLock(sessionId: string): Promise<() => Promise<void>> {\n  const lockPath = stateLockPath(sessionId);\n  const deadline = Date.now() + STATE_LOCK_WAIT_MS;\n  await fs.mkdir(stateRoot(), { recursive: true });\n\n  while (true) {\n    try {\n      await fs.mkdir(lockPath);\n      const ownerId = randomUUID();\n      const createdAt = new Date().toISOString();\n      const metadata: StateLockMetadata = {\n        ownerId,\n        pid: process.pid,\n        createdAt,\n        heartbeatAt: createdAt,\n      };\n      await writeStateLockMetadata(sessionId, metadata);\n      let released = false;\n      const heartbeat = setInterval(() => {\n        if (released) return;\n        void writeStateLockMetadata(sessionId, {\n          ...metadata,\n          heartbeatAt: new Date().toISOString(),\n        }).catch(() => undefined);\n      }, STATE_LOCK_HEARTBEAT_MS);\n      heartbeat.unref?.();\n\n      return async () => {\n        if (released) return;\n        released = true;\n        clearInterval(heartbeat);\n        const currentMetadata = await readStateLockMetadata(sessionId);\n        if (currentMetadata?.ownerId === ownerId) {\n          await fs.rm(lockPath, { recursive: true, force: true }).catch(() => undefined);\n        }\n      };\n    } catch (error) {\n      const code = error && typeof error === \"object\" && \"code\" in error ? (error as { code?: unknown }).code : null;\n      if (code !== \"EEXIST\") {\n        throw error;\n      }\n\n      if (await tryRemoveStaleStateLock(sessionId)) {\n        continue;\n      }\n\n      if (Date.now() >= deadline) {\n        throw new Error(`Timed out acquiring hook state lock for session ${sessionId}.`);\n      }\n      await sleep(STATE_LOCK_POLL_MS);\n    }\n  }\n}\n\nasync function withStateLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {\n  const release = await acquireStateLock(sessionId);\n  try {\n    return await fn();\n  } finally {\n    await release();\n  }\n}\n\nfunction normalizeIntent(value: unknown): TurnIntent {\n  return value === \"memory_first\" || value === \"collab_state\" || value === \"git_facts\" ? value : \"neutral\";\n}\n\nfunction normalizeString(value: unknown): string | null {\n  return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nfunction normalizeStringArray(value: unknown): string[] {\n  if (!Array.isArray(value)) return [];\n  return Array.from(\n    new Set(\n      value\n        .filter((entry): entry is string => typeof entry === \"string\" && entry.trim().length > 0)\n        .map((entry) => entry.trim()),\n    ),\n  );\n}\n\nfunction normalizeManualRecordingScope(value: unknown): ManualRecordingScope | null {\n  if (value === \"full_turn\") {\n    return \"full_turn\";\n  }\n  // Legacy pending-state files may still contain the retired \"change_step\" scope.\n  // Drop it instead of re-emitting a state that the current plugin no longer produces.\n  return null;\n}\n\nfunction normalizeTouchedRepo(value: unknown, repoRoot: string): TouchedRepoState | null {\n  if (!value || typeof value !== \"object\") return null;\n  const parsed = value as Partial<TouchedRepoState>;\n  const normalizedRepoRoot = normalizeString(parsed.repoRoot) ?? repoRoot.trim();\n  if (!normalizedRepoRoot) return null;\n\n  return {\n    repoRoot: normalizedRepoRoot,\n    projectId: normalizeString(parsed.projectId),\n    currentAppId: normalizeString(parsed.currentAppId),\n    upstreamAppId: normalizeString(parsed.upstreamAppId),\n    firstTouchedAt: normalizeString(parsed.firstTouchedAt) ?? new Date().toISOString(),\n    lastTouchedAt: normalizeString(parsed.lastTouchedAt) ?? new Date().toISOString(),\n    lastObservedWriteAt: normalizeString(parsed.lastObservedWriteAt),\n    touchedBy: normalizeStringArray(parsed.touchedBy),\n    hasObservedWrite: Boolean(parsed.hasObservedWrite),\n    manuallyRecorded: Boolean(parsed.manuallyRecorded),\n    manuallyRecordedAt: normalizeString(parsed.manuallyRecordedAt),\n    manuallyRecordedByTool: normalizeString(parsed.manuallyRecordedByTool),\n    manualRecordingScope: normalizeManualRecordingScope(parsed.manualRecordingScope),\n    manualRemoteChangeRecordedAt: normalizeString(parsed.manualRemoteChangeRecordedAt),\n    stopAttempted: Boolean(parsed.stopAttempted),\n    stopRecorded: Boolean(parsed.stopRecorded),\n    stopRecordedAt: normalizeString(parsed.stopRecordedAt),\n    stopRecordedMode:\n      parsed.stopRecordedMode === \"changed_turn\" ||\n      parsed.stopRecordedMode === \"no_diff_turn\" ||\n      parsed.stopRecordedMode === \"conversation_only\"\n        ? parsed.stopRecordedMode\n        : null,\n    recordingFailureMessage: normalizeString(parsed.recordingFailureMessage),\n    recordingFailureHint: normalizeString(parsed.recordingFailureHint),\n    recordingFailedAt: normalizeString(parsed.recordingFailedAt),\n  };\n}\n\nfunction normalizeTouchedRepos(value: unknown): Record<string, TouchedRepoState> {\n  if (!value || typeof value !== \"object\") return {};\n  const entries = Object.entries(value as Record<string, unknown>)\n    .map(([repoRoot, repo]) => normalizeTouchedRepo(repo, repoRoot))\n    .filter((repo): repo is TouchedRepoState => repo !== null)\n    .sort((a, b) => a.repoRoot.localeCompare(b.repoRoot));\n  return Object.fromEntries(entries.map((repo) => [repo.repoRoot, repo]));\n}\n\nfunction createTouchedRepo(params: {\n  repoRoot: string;\n  projectId?: string | null;\n  currentAppId?: string | null;\n  upstreamAppId?: string | null;\n  touchedBy?: string | null;\n  hasObservedWrite?: boolean;\n}): TouchedRepoState {\n  const now = new Date().toISOString();\n  const touchedBy = params.touchedBy?.trim() ? [params.touchedBy.trim()] : [];\n  return {\n    repoRoot: params.repoRoot,\n    projectId: normalizeString(params.projectId),\n    currentAppId: normalizeString(params.currentAppId),\n    upstreamAppId: normalizeString(params.upstreamAppId),\n    firstTouchedAt: now,\n    lastTouchedAt: now,\n    lastObservedWriteAt: params.hasObservedWrite ? now : null,\n    touchedBy,\n    hasObservedWrite: Boolean(params.hasObservedWrite),\n    manuallyRecorded: false,\n    manuallyRecordedAt: null,\n    manuallyRecordedByTool: null,\n    manualRecordingScope: null,\n    manualRemoteChangeRecordedAt: null,\n    stopAttempted: false,\n    stopRecorded: false,\n    stopRecordedAt: null,\n    stopRecordedMode: null,\n    recordingFailureMessage: null,\n    recordingFailureHint: null,\n    recordingFailedAt: null,\n  };\n}\n\nasync function updatePendingTurnState(\n  sessionId: string,\n  updater: (state: PendingTurnState) => void | boolean,\n): Promise<PendingTurnState | null> {\n  return withStateLock(sessionId, async () => {\n    const existing = await loadPendingTurnState(sessionId);\n    if (!existing) return null;\n    const result = updater(existing);\n    if (result === false) return existing;\n    await savePendingTurnState(existing);\n    return existing;\n  });\n}\n\nfunction summarizeTouchedRepo(repo: TouchedRepoState): PendingTouchedRepoSummary {\n  return {\n    repoRoot: repo.repoRoot,\n    projectId: repo.projectId,\n    currentAppId: repo.currentAppId,\n    upstreamAppId: repo.upstreamAppId,\n    lastTouchedAt: repo.lastTouchedAt,\n    lastObservedWriteAt: repo.lastObservedWriteAt,\n    touchedBy: [...repo.touchedBy],\n    hasObservedWrite: repo.hasObservedWrite,\n    manuallyRecorded: repo.manuallyRecorded,\n    manualRecordingScope: repo.manualRecordingScope,\n    stopAttempted: repo.stopAttempted,\n    stopRecorded: repo.stopRecorded,\n    stopRecordedMode: repo.stopRecordedMode,\n    recordingFailureMessage: repo.recordingFailureMessage,\n    recordingFailureHint: repo.recordingFailureHint,\n    recordingFailedAt: repo.recordingFailedAt,\n  };\n}\n\nfunction summarizePendingTurnState(state: PendingTurnState): PendingTurnStateSummary {\n  const touchedRepos = Object.values(state.touchedRepos)\n    .sort((a, b) => a.repoRoot.localeCompare(b.repoRoot))\n    .map((repo) => summarizeTouchedRepo(repo));\n  return {\n    sessionId: state.sessionId,\n    turnId: state.turnId,\n    initialCwd: state.initialCwd,\n    submittedAt: state.submittedAt,\n    consultedMemory: state.consultedMemory,\n    promptLength: state.prompt.length,\n    touchedRepoCount: touchedRepos.length,\n    turnFailureMessage: state.turnFailureMessage,\n    turnFailureHint: state.turnFailureHint,\n    turnFailedAt: state.turnFailedAt,\n    touchedRepos,\n  };\n}\n\nexport function getPendingTurnStateRootPath(): string {\n  return stateRoot();\n}\n\nexport async function loadPendingTurnState(sessionId: string): Promise<PendingTurnState | null> {\n  const raw = await fs.readFile(statePath(sessionId), \"utf8\").catch(() => null);\n  if (!raw) return null;\n  try {\n    const parsed = JSON.parse(raw) as Partial<PendingTurnState>;\n    if (!parsed || typeof parsed !== \"object\") return null;\n    if (typeof parsed.sessionId !== \"string\" || typeof parsed.turnId !== \"string\" || typeof parsed.prompt !== \"string\") {\n      return null;\n    }\n    return {\n      sessionId: parsed.sessionId,\n      turnId: parsed.turnId,\n      sourceConversation: normalizeClaudeSourceConversation(parsed.sourceConversation),\n      prompt: parsed.prompt,\n      initialCwd: normalizeString(parsed.initialCwd),\n      intent: normalizeIntent(parsed.intent),\n      submittedAt: typeof parsed.submittedAt === \"string\" ? parsed.submittedAt : new Date().toISOString(),\n      consultedMemory: Boolean(parsed.consultedMemory),\n      touchedRepos: normalizeTouchedRepos(parsed.touchedRepos),\n      turnFailureMessage: normalizeString(parsed.turnFailureMessage),\n      turnFailureHint: normalizeString(parsed.turnFailureHint),\n      turnFailedAt: normalizeString(parsed.turnFailedAt),\n    };\n  } catch {\n    return null;\n  }\n}\n\nexport async function savePendingTurnState(state: PendingTurnState): Promise<void> {\n  await writeJsonAtomic(statePath(state.sessionId), state);\n}\n\nexport async function createPendingTurnState(params: {\n  sessionId: string;\n  prompt: string;\n  initialCwd?: string | null;\n  intent: TurnIntent;\n}): Promise<PendingTurnState> {\n  return withStateLock(params.sessionId, async () => {\n    const turnId = randomUUID();\n    const state: PendingTurnState = {\n      sessionId: params.sessionId,\n      turnId,\n      sourceConversation: createClaudeSourceConversation(params.sessionId, turnId),\n      prompt: params.prompt,\n      initialCwd: params.initialCwd?.trim() || null,\n      intent: params.intent,\n      submittedAt: new Date().toISOString(),\n      consultedMemory: false,\n      touchedRepos: {},\n      turnFailureMessage: null,\n      turnFailureHint: null,\n      turnFailedAt: null,\n    };\n    await savePendingTurnState(state);\n    return state;\n  });\n}\n\nexport async function upsertTouchedRepo(\n  sessionId: string,\n  params: {\n    repoRoot: string;\n    projectId?: string | null;\n    currentAppId?: string | null;\n    upstreamAppId?: string | null;\n    touchedBy?: string | null;\n    hasObservedWrite?: boolean;\n  },\n): Promise<TouchedRepoState | null> {\n  const normalizedRepoRoot = params.repoRoot.trim();\n  if (!normalizedRepoRoot) return null;\n  const state = await updatePendingTurnState(sessionId, (existing) => {\n    const current =\n      existing.touchedRepos[normalizedRepoRoot] ??\n      createTouchedRepo({\n        repoRoot: normalizedRepoRoot,\n        projectId: params.projectId,\n        currentAppId: params.currentAppId,\n        upstreamAppId: params.upstreamAppId,\n        touchedBy: params.touchedBy,\n        hasObservedWrite: params.hasObservedWrite,\n      });\n\n    current.projectId = normalizeString(params.projectId) ?? current.projectId;\n    current.currentAppId = normalizeString(params.currentAppId) ?? current.currentAppId;\n    current.upstreamAppId = normalizeString(params.upstreamAppId) ?? current.upstreamAppId;\n    current.lastTouchedAt = new Date().toISOString();\n    if (params.touchedBy?.trim() && !current.touchedBy.includes(params.touchedBy.trim())) {\n      current.touchedBy = [...current.touchedBy, params.touchedBy.trim()].sort((a, b) => a.localeCompare(b));\n    }\n    if (params.hasObservedWrite) {\n      current.hasObservedWrite = true;\n      current.lastObservedWriteAt = new Date().toISOString();\n    }\n    existing.touchedRepos[normalizedRepoRoot] = current;\n  });\n  return state?.touchedRepos[normalizedRepoRoot] ?? null;\n}\n\nexport async function markTouchedRepoObservedWrite(\n  sessionId: string,\n  repoRoot: string,\n  params?: { toolName?: string | null },\n): Promise<void> {\n  await upsertTouchedRepo(sessionId, {\n    repoRoot,\n    touchedBy: params?.toolName ?? null,\n    hasObservedWrite: true,\n  });\n}\n\nexport async function markTouchedRepoManuallyRecorded(\n  sessionId: string,\n  repoRoot: string,\n  params?: { toolName?: string | null; scope?: ManualRecordingScope | null; remoteChangeRecorded?: boolean },\n): Promise<void> {\n  await updatePendingTurnState(sessionId, (existing) => {\n    const normalizedRepoRoot = repoRoot.trim();\n    if (!normalizedRepoRoot) return false;\n    const current =\n      existing.touchedRepos[normalizedRepoRoot] ??\n      createTouchedRepo({\n        repoRoot: normalizedRepoRoot,\n        touchedBy: params?.toolName ?? null,\n        hasObservedWrite: false,\n      });\n    current.lastTouchedAt = new Date().toISOString();\n    current.manuallyRecorded = true;\n    current.manuallyRecordedAt = new Date().toISOString();\n    current.manuallyRecordedByTool = normalizeString(params?.toolName) ?? current.manuallyRecordedByTool;\n    current.manualRecordingScope = params?.scope ?? current.manualRecordingScope;\n    if (params?.remoteChangeRecorded) {\n      current.manualRemoteChangeRecordedAt = current.manuallyRecordedAt;\n    }\n    current.recordingFailureMessage = null;\n    current.recordingFailureHint = null;\n    current.recordingFailedAt = null;\n    if (params?.toolName?.trim() && !current.touchedBy.includes(params.toolName.trim())) {\n      current.touchedBy = [...current.touchedBy, params.toolName.trim()].sort((a, b) => a.localeCompare(b));\n    }\n    existing.touchedRepos[normalizedRepoRoot] = current;\n  });\n}\n\nexport async function markPendingTurnConsultedMemory(sessionId: string): Promise<void> {\n  await updatePendingTurnState(sessionId, (existing) => {\n    if (existing.consultedMemory) return false;\n    existing.consultedMemory = true;\n  });\n}\n\nexport async function markTouchedRepoStopAttempted(sessionId: string, repoRoot: string): Promise<void> {\n  await updatePendingTurnState(sessionId, (existing) => {\n    const current = existing.touchedRepos[repoRoot];\n    if (!current) return false;\n    current.stopAttempted = true;\n    current.lastTouchedAt = new Date().toISOString();\n  });\n}\n\nexport async function markTouchedRepoStopRecorded(\n  sessionId: string,\n  repoRoot: string,\n  params: {\n    mode: RepoRecordMode;\n  },\n): Promise<void> {\n  await updatePendingTurnState(sessionId, (existing) => {\n    const current = existing.touchedRepos[repoRoot];\n    if (!current) return false;\n    current.stopAttempted = true;\n    current.stopRecorded = true;\n    current.stopRecordedAt = new Date().toISOString();\n    current.stopRecordedMode = params.mode;\n    current.recordingFailureMessage = null;\n    current.recordingFailureHint = null;\n    current.recordingFailedAt = null;\n    current.lastTouchedAt = new Date().toISOString();\n  });\n}\n\nexport async function markTouchedRepoRecordingFailure(\n  sessionId: string,\n  repoRoot: string,\n  params: {\n    message: string;\n    hint?: string | null;\n  },\n): Promise<void> {\n  await updatePendingTurnState(sessionId, (existing) => {\n    const current = existing.touchedRepos[repoRoot];\n    if (!current) return false;\n    current.stopAttempted = true;\n    current.recordingFailureMessage = params.message.trim();\n    current.recordingFailureHint = params.hint?.trim() || null;\n    current.recordingFailedAt = new Date().toISOString();\n    current.lastTouchedAt = new Date().toISOString();\n  });\n}\n\nfunction lastFinalizedPath(sessionId: string): string {\n  return path.join(stateRoot(), `${sessionId}.last-finalized.json`);\n}\n\nexport async function markLastFinalizedTurn(\n  sessionId: string,\n  turnId: string,\n  prompt: string,\n): Promise<void> {\n  const record: LastFinalizedTurnRecord = {\n    sessionId,\n    turnId,\n    sourceConversation: createClaudeSourceConversation(sessionId, turnId),\n    prompt,\n    finalizedAt: new Date().toISOString(),\n  };\n  await writeJsonAtomic(lastFinalizedPath(sessionId), record);\n}\n\nexport async function loadLastFinalizedTurn(sessionId: string): Promise<LastFinalizedTurnRecord | null> {\n  const raw = await fs.readFile(lastFinalizedPath(sessionId), \"utf8\").catch(() => null);\n  if (!raw) return null;\n  try {\n    const parsed = JSON.parse(raw) as Partial<LastFinalizedTurnRecord>;\n    if (\n      typeof parsed.sessionId === \"string\" &&\n      typeof parsed.turnId === \"string\" &&\n      typeof parsed.prompt === \"string\" &&\n      typeof parsed.finalizedAt === \"string\"\n    ) {\n      return {\n        sessionId: parsed.sessionId,\n        turnId: parsed.turnId,\n        sourceConversation: normalizeClaudeSourceConversation(parsed.sourceConversation),\n        prompt: parsed.prompt,\n        finalizedAt: parsed.finalizedAt,\n      };\n    }\n    return null;\n  } catch {\n    return null;\n  }\n}\n\nexport async function markPendingTurnFailure(\n  sessionId: string,\n  params: {\n    message: string;\n    hint?: string | null;\n  },\n): Promise<void> {\n  await updatePendingTurnState(sessionId, (existing) => {\n    existing.turnFailureMessage = params.message.trim();\n    existing.turnFailureHint = params.hint?.trim() || null;\n    existing.turnFailedAt = new Date().toISOString();\n  });\n}\n\nexport async function listTouchedRepos(sessionId: string): Promise<TouchedRepoState[]> {\n  const existing = await loadPendingTurnState(sessionId);\n  if (!existing) return [];\n  return Object.values(existing.touchedRepos).sort((a, b) => a.repoRoot.localeCompare(b.repoRoot));\n}\n\nexport async function listPendingTurnStateSummaries(): Promise<PendingTurnStateSummary[]> {\n  const root = stateRoot();\n  const entries = await fs.readdir(root, { withFileTypes: true }).catch(() => []);\n  const sessionIds = entries\n    .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n    .map((entry) => entry.name.replace(/\\.json$/, \"\"))\n    .sort((a, b) => a.localeCompare(b));\n  const states = await Promise.all(sessionIds.map((sessionId) => loadPendingTurnState(sessionId)));\n  return states\n    .filter((state): state is PendingTurnState => state !== null)\n    .sort((a, b) => b.submittedAt.localeCompare(a.submittedAt))\n    .map((state) => summarizePendingTurnState(state));\n}\n\nexport async function clearPendingTurnState(sessionId: string): Promise<void> {\n  await withStateLock(sessionId, async () => {\n    await fs.rm(statePath(sessionId), { force: true }).catch(() => undefined);\n  });\n}\n","import * as coreCollab from \"@remixhq/core/collab\";\n\nimport { getPluginRuntime } from \"./runtime.js\";\n\nexport type ClaudeSourceConversation = {\n  provider: \"claude\";\n  sessionId: string;\n  nativeTurnId: string;\n} | {\n  provider: \"codex\";\n  sessionId: string;\n  nativeTurnId: string;\n};\n\nexport function createClaudeSourceConversation(\n  sessionId: string,\n  nativeTurnId: string,\n): ClaudeSourceConversation {\n  return {\n    provider: getPluginRuntime(),\n    sessionId: sessionId.trim(),\n    nativeTurnId: nativeTurnId.trim(),\n  };\n}\n\nexport function normalizeClaudeSourceConversation(value: unknown): ClaudeSourceConversation | null {\n  if (!value || typeof value !== \"object\") return null;\n  const parsed = value as Partial<ClaudeSourceConversation>;\n  if (\n    (parsed.provider !== \"claude\" && parsed.provider !== \"codex\") ||\n    typeof parsed.sessionId !== \"string\" ||\n    !parsed.sessionId.trim() ||\n    typeof parsed.nativeTurnId !== \"string\" ||\n    !parsed.nativeTurnId.trim()\n  ) {\n    return null;\n  }\n  return {\n    provider: parsed.provider,\n    sessionId: parsed.sessionId.trim(),\n    nativeTurnId: parsed.nativeTurnId.trim(),\n  };\n}\n\ntype CoreFinalizeParams = Parameters<typeof coreCollab.collabFinalizeTurn>[0];\ntype CoreFinalizeResult = ReturnType<typeof coreCollab.collabFinalizeTurn>;\n\nexport const collabFinalizeTurn = coreCollab.collabFinalizeTurn as (\n  params: CoreFinalizeParams & { sourceConversation?: ClaudeSourceConversation },\n) => CoreFinalizeResult;\n","{\n  \"name\": \"@remixhq/claude-plugin\",\n  \"version\": \"0.1.53\",\n  \"description\": \"Claude Code plugin for Remix collaboration workflows\",\n  \"homepage\": \"https://github.com/RemixDotOne/remix-claude-plugin\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/RemixDotOne/remix-claude-plugin.git\"\n  },\n  \"type\": \"module\",\n  \"engines\": {\n    \"node\": \">=20\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"files\": [\n    \"dist\",\n    \".claude-plugin/plugin.json\",\n    \".mcp.json\",\n    \"skills\",\n    \"hooks\",\n    \"agents\"\n  ],\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.js\"\n    }\n  },\n  \"scripts\": {\n    \"build\": \"tsup\",\n    \"postbuild\": \"node -e \\\"const fs=require('node:fs'); for (const p of ['dist/mcp-server.cjs','dist/hook-pre-git.cjs','dist/hook-user-prompt.cjs','dist/hook-post-collab.cjs','dist/hook-stop-collab.cjs']) fs.chmodSync(p, 0o755);\\\"\",\n    \"dev\": \"tsx src/mcp-server.ts\",\n    \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n    \"test\": \"node --import tsx --test src/auto-fix-dispatcher.test.ts src/deferred-turn-drainer.test.ts src/deferred-turn-queue.test.ts src/finalize-failure-marker.test.ts src/hook-post-collab.test.ts src/remix-cli-path.test.ts src/source-conversation.test.ts src/transient-failure.test.ts src/usage/claudeCodeSession.test.ts src/usage/claudeCodeUsageHarvester.test.ts src/usage/integration.test.ts src/usage/sliceTranscriptIntoTurns.test.ts\",\n    \"prepack\": \"npm run build\"\n  },\n  \"dependencies\": {\n    \"@remixhq/core\": \"^0.1.47\",\n    \"@remixhq/mcp\": \"^0.1.46\",\n    \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n    \"zod\": \"^3.25.76\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^25.4.0\",\n    \"tsup\": \"^8.5.1\",\n    \"tsx\": \"^4.21.0\",\n    \"typescript\": \"^5.9.3\"\n  }\n}\n","import pkg from \"../package.json\";\n\nexport const pluginMetadata = {\n  name: pkg.name,\n  version: pkg.version,\n  description: pkg.description,\n  pluginId: \"remix\",\n  agentName: \"remix-collab\",\n};\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nconst MIN_REMIX_CLI_VERSION = \"0.1.38\";\n\ntype CliSource = \"env\" | \"cli-env-file\";\n\nexport type RemixCliResolution =\n  | { ok: true; path: string; source: CliSource }\n  | { ok: false; message: string };\n\nfunction cliEnvFilePath(): string {\n  const override = process.env.REMIX_CLI_ENV_FILE?.trim();\n  return override || path.join(os.homedir(), \".remix\", \"cli-env.json\");\n}\n\nfunction readCliEnvFile(): string | null {\n  try {\n    const parsed = JSON.parse(readFileSync(cliEnvFilePath(), \"utf8\")) as Record<string, unknown>;\n    const value = parsed.REMIX_CLI_PATH ?? parsed.remixCliPath;\n    return typeof value === \"string\" && value.trim() ? value.trim() : null;\n  } catch {\n    return null;\n  }\n}\n\nfunction parseVersion(value: string): string | null {\n  const match = value.match(/\\d+\\.\\d+\\.\\d+/);\n  return match?.[0] ?? null;\n}\n\nfunction compareVersions(a: string, b: string): number {\n  const left = a.split(\".\").map((part) => Number.parseInt(part, 10));\n  const right = b.split(\".\").map((part) => Number.parseInt(part, 10));\n  for (let i = 0; i < Math.max(left.length, right.length); i += 1) {\n    const diff = (left[i] ?? 0) - (right[i] ?? 0);\n    if (diff !== 0) return diff;\n  }\n  return 0;\n}\n\nfunction validateCli(candidate: string): string | null {\n  if (!existsSync(candidate)) {\n    return `Remix plugin is configured to use ${candidate}, but that file does not exist. Open Remix Desktop to repair the plugin integration.`;\n  }\n  const version = spawnSync(candidate, [\"--version\"], {\n    encoding: \"utf8\",\n    timeout: 5000,\n  });\n  if (version.error || version.status !== 0) {\n    const detail = version.error instanceof Error ? version.error.message : (version.stderr || version.stdout || \"version check failed\");\n    return `Remix plugin could not validate the configured CLI at ${candidate}: ${String(detail).trim()}. Open Remix Desktop to repair the plugin integration.`;\n  }\n  const parsedVersion = parseVersion(`${version.stdout}\\n${version.stderr}`);\n  if (!parsedVersion) {\n    return `Remix plugin could not read a version from the configured CLI at ${candidate}. Open Remix Desktop to repair the plugin integration.`;\n  }\n  if (compareVersions(parsedVersion, MIN_REMIX_CLI_VERSION) < 0) {\n    return `Remix plugin CLI is outdated (${parsedVersion}; need ${MIN_REMIX_CLI_VERSION}+). Open Remix Desktop to repair the plugin integration.`;\n  }\n  return null;\n}\n\nexport function resolveRemixCliForHook(): RemixCliResolution {\n  const envPath = process.env.REMIX_CLI_PATH?.trim();\n  const source: CliSource = envPath ? \"env\" : \"cli-env-file\";\n  const candidate = envPath || readCliEnvFile();\n  if (!candidate) {\n    return {\n      ok: false,\n      message: \"Remix plugin is not configured with a CLI path. Open Remix Desktop to repair the plugin integration.\",\n    };\n  }\n  const error = validateCli(candidate);\n  if (error) return { ok: false, message: error };\n  return { ok: true, path: candidate, source };\n}\n","// Deferred-turn queue.\n//\n// Why this exists: when a user sends a prompt on a brand-new git branch in\n// a repo that's already bound to Remix on other branches, the\n// `UserPromptSubmit` hook spawns `remix collab init` detached and lets\n// the prompt go through unblocked (see hook-user-prompt.ts for the full\n// rationale). Init typically takes 15-25s; many models reply faster than\n// that, so by the time the `Stop` hook fires the new branch is still\n// not in `branchBindings` and recording cannot resolve a lane.\n//\n// Previously that turn was silently dropped. This queue is the recovery\n// channel: instead of dropping, we serialize the prompt + response + repo\n// coords into a small JSON file. Every subsequent successful finalize for\n// the same repo drains the queue, so the deferred turn lands on the server\n// the moment the new branch is bound (usually one user prompt later).\n//\n// Storage: `<stateRoot()>/deferred-turns/<sessionId>-<turnId>.json`. We\n// reuse the existing hook-state root (an env-overridable path inside\n// `os.tmpdir()`) so the queue lives next to the other per-session state\n// the plugin already manages. Files are JSON with a stable schema,\n// written atomically via tmp-then-rename.\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { getHookStateRoot } from \"./runtime.js\";\nimport {\n  normalizeClaudeSourceConversation,\n  type ClaudeSourceConversation,\n} from \"./source-conversation.js\";\n\n// Schema versioning so we can evolve the record shape later without\n// silently mis-reading old files. Drainers refuse to read records with\n// unknown schemaVersion (they're just left in place for a human to look\n// at if they care, then pruned by the TTL sweep).\n//\n// Note on additive changes: the safe pattern is to add an OPTIONAL field\n// to `DeferredTurnRecord` and coerce it to a sane default in\n// `readDeferredTurnFile` (see `attemptCount` for an example), without\n// bumping the schemaVersion. This keeps records written by older plugin\n// versions readable by newer ones. Bump only when the meaning of an\n// existing field changes or a previously-optional field becomes required.\nexport const DEFERRED_TURN_SCHEMA_VERSION = 1 as const;\n\n// Hard cap on retries before we give up on a deferred turn and promote\n// it to a permanent failure (write a marker, delete the queue file).\n//\n// Why 10: the deferred-turn queue is a *recovery* channel — its only job\n// is to outlive a transient blip (a few seconds of network unavailability,\n// a backend pod restart, a flapping DNS resolver). The healthy path\n// drains a deferred turn within 1–2 prompts. A turn that has failed\n// 10 distinct drain attempts is no longer \"transient\" — it's a\n// persistent state mismatch (deleted lane, server expecting different\n// snapshot, auth permanently broken) and silently re-trying it forever\n// would be data loss with no audit trail. At 10 attempts we surface a\n// failure marker so the user gets the existing manual-recovery advisory\n// on the next prompt.\n//\n// The number itself is conservative on purpose: at 1 prompt per attempt\n// (the most common case) it covers ~10 minutes of intermittent\n// connectivity, which is well past any normal blip; at 1 attempt per\n// drainer pass (~3 s in the standalone drainer) it's ~30 s of\n// continuous failure before we give up. Anything in between sits\n// comfortably between \"patient\" and \"indefinite\".\nexport const DEFERRED_TURN_MAX_ATTEMPTS = 10;\n\nexport type DeferredTurnRecord = {\n  schemaVersion: typeof DEFERRED_TURN_SCHEMA_VERSION;\n  // Claude session/conversation id at the time the turn was submitted.\n  // Carried for diagnostics + potential dedup; the drainer does NOT\n  // require the current sessionId to match.\n  sessionId: string;\n  // Pending-turn turnId (also used for the recording idempotency key\n  // so a deferred turn that gets retried multiple times still\n  // de-duplicates server-side).\n  turnId: string;\n  sourceConversation: ClaudeSourceConversation | null;\n  // Absolute path to the repo root the turn happened in. Drain matches\n  // queued records to the currently-recording repo on this exact path\n  // (no symlink resolution — keep it boring).\n  repoRoot: string;\n  // The user prompt text and the model response text. Both are required\n  // for collabFinalizeTurn; if either is missing/empty at write time\n  // we don't queue the turn (caller checks).\n  prompt: string;\n  assistantResponse: string;\n  // ISO8601 of the original submit time (from PendingTurnState.submittedAt).\n  // The drainer forwards this to `collabFinalizeTurn` as `promptedAt`,\n  // which surfaces under `workspace_metadata.promptedAt` so the dashboard\n  // timeline sorts this turn by its true submission time instead of by\n  // server ingestion time (which would otherwise be the drain time, not\n  // when the user actually typed it — potentially hours later).\n  submittedAt: string;\n  // ISO8601 of when this record was written (for staleness / TTL).\n  deferredAt: string;\n  // The reason we deferred:\n  //   - `current_branch_unbound`: branch-init race (the user prompted\n  //     on a freshly-created branch and `remix collab init` hasn't\n  //     finished landing the binding yet).\n  //   - `recovery_in_progress`: auto-fixable preflight failure (e.g.\n  //     `not_bound`, `branch_binding_missing`) where a recovery command\n  //     is being dispatched concurrently and we want to drain the turn\n  //     once it completes.\n  //   - `transient_recording_failure`: the recording call failed with a\n  //     transient error (timeout, network blip, 5xx) and is expected to\n  //     succeed on retry without user intervention. Silent — no failure\n  //     marker is written on the first defer; the in-process drainer\n  //     replays the turn on the next Stop hook.\n  reason: \"current_branch_unbound\" | \"recovery_in_progress\" | \"transient_recording_failure\";\n  // Branch name the turn was submitted on, captured at defer-time.\n  // Drain refuses to record if the current branch differs (the user\n  // checked out a different branch before init landed) — the turn\n  // would otherwise be attributed to the wrong branch.\n  branchAtDefer: string | null;\n  // Remix `currentAppId` of the lane the user was on when we deferred.\n  // Captured so the drainer can detect a binding swap (typically a\n  // `remix collab init --force-new`, which mints a new app id for the\n  // same `repoRoot` + branch). Without this, deferred turns from the\n  // *old* app silently get re-attributed to the new app on the next\n  // drain pass, surfacing as live \"prompts\" alongside the user's\n  // brand-new lane history. May be `null` for records written by\n  // pre-appId-aware plugin versions or when no binding was readable\n  // at defer-time; in that case the drainer keeps today's behavior\n  // (record on whatever binding currently resolves) so we don't\n  // regress legacy records.\n  appIdAtDefer: string | null;\n  // Companion to `appIdAtDefer`. Same defer-time snapshot, kept for\n  // diagnostics + future fork detection (project rotates when the\n  // user re-imports the repo as a brand-new project).\n  projectIdAtDefer: string | null;\n  // Number of drain attempts that have failed against this record.\n  // Starts at 0 on initial defer; the drainer increments via\n  // `recordDeferredTurnFailedAttempt` after each failed\n  // `collabFinalizeTurn` call. When the count reaches\n  // `DEFERRED_TURN_MAX_ATTEMPTS`, the drainer promotes the record to\n  // a permanent failure (writes a failure marker for the user, deletes\n  // the queue file) instead of looping forever on a turn that's never\n  // going to record. Optional in the on-disk shape: pre-attemptCount\n  // records coerce to 0 in `readDeferredTurnFile`.\n  attemptCount: number;\n};\n\n// 24h: comfortable upper bound for \"the user is still working on this\".\n// Past that the prompt context is almost certainly stale and silently\n// recording it could surprise the user; the prune sweep deletes records\n// older than this and emits a diagnostics event so it's not silent.\nexport const DEFERRED_TURN_TTL_MS = 24 * 60 * 60 * 1000;\n\nconst DEFERRED_TURN_DIR = \"deferred-turns\";\n\nfunction stateRoot(): string {\n  return getHookStateRoot();\n}\n\nexport function getDeferredTurnDirPath(): string {\n  return path.join(stateRoot(), DEFERRED_TURN_DIR);\n}\n\nfunction deferredTurnFileName(sessionId: string, turnId: string): string {\n  // Sanitize defensively: sessionId / turnId are normally UUIDs but\n  // we don't want a malicious payload to escape the directory.\n  const safe = (s: string) => s.replace(/[^A-Za-z0-9_-]/g, \"_\");\n  return `${safe(sessionId)}-${safe(turnId)}.json`;\n}\n\nexport function getDeferredTurnFilePath(sessionId: string, turnId: string): string {\n  return path.join(getDeferredTurnDirPath(), deferredTurnFileName(sessionId, turnId));\n}\n\n// Atomically persist a deferred turn. Overwrites any prior record for\n// the same (sessionId, turnId), which is fine — the prompt + response\n// haven't changed; we'd only retry-write if a previous defer crashed\n// mid-flight.\nexport async function writeDeferredTurn(record: DeferredTurnRecord): Promise<string> {\n  if (record.schemaVersion !== DEFERRED_TURN_SCHEMA_VERSION) {\n    throw new Error(`writeDeferredTurn: unsupported schemaVersion ${record.schemaVersion}`);\n  }\n  if (!record.prompt.trim() || !record.assistantResponse.trim()) {\n    throw new Error(\"writeDeferredTurn: prompt and assistantResponse must be non-empty\");\n  }\n  const dir = getDeferredTurnDirPath();\n  await fs.mkdir(dir, { recursive: true });\n  const filePath = getDeferredTurnFilePath(record.sessionId, record.turnId);\n  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;\n  await fs.writeFile(tmpPath, JSON.stringify(record), \"utf8\");\n  await fs.rename(tmpPath, filePath);\n  return filePath;\n}\n\n// Returned with the parsed record so the caller can delete the file\n// after a successful drain (or leave it in place for later retry).\nexport type DeferredTurnEntry = {\n  filePath: string;\n  record: DeferredTurnRecord;\n};\n\nasync function readDeferredTurnFile(filePath: string): Promise<DeferredTurnRecord | null> {\n  const raw = await fs.readFile(filePath, \"utf8\").catch(() => null);\n  if (!raw) return null;\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(raw);\n  } catch {\n    return null;\n  }\n  if (!parsed || typeof parsed !== \"object\") return null;\n  const record = parsed as Partial<DeferredTurnRecord>;\n  if (record.schemaVersion !== DEFERRED_TURN_SCHEMA_VERSION) return null;\n  if (\n    typeof record.sessionId !== \"string\" ||\n    typeof record.turnId !== \"string\" ||\n    typeof record.repoRoot !== \"string\" ||\n    typeof record.prompt !== \"string\" ||\n    typeof record.assistantResponse !== \"string\" ||\n    typeof record.submittedAt !== \"string\" ||\n    typeof record.deferredAt !== \"string\" ||\n    (record.reason !== \"current_branch_unbound\" &&\n      record.reason !== \"recovery_in_progress\" &&\n      record.reason !== \"transient_recording_failure\")\n  ) {\n    return null;\n  }\n  return {\n    schemaVersion: DEFERRED_TURN_SCHEMA_VERSION,\n    sessionId: record.sessionId,\n    turnId: record.turnId,\n    sourceConversation: normalizeClaudeSourceConversation(record.sourceConversation),\n    repoRoot: record.repoRoot,\n    prompt: record.prompt,\n    assistantResponse: record.assistantResponse,\n    submittedAt: record.submittedAt,\n    deferredAt: record.deferredAt,\n    reason: record.reason,\n    branchAtDefer:\n      typeof record.branchAtDefer === \"string\" || record.branchAtDefer === null ? record.branchAtDefer : null,\n    // Additive fields: pre-appId-aware records on disk won't have these\n    // keys at all. Coerce missing/invalid to `null` (drainer treats\n    // null as \"legacy, drain as today\" — see drainer for the policy).\n    appIdAtDefer: typeof record.appIdAtDefer === \"string\" ? record.appIdAtDefer : null,\n    projectIdAtDefer: typeof record.projectIdAtDefer === \"string\" ? record.projectIdAtDefer : null,\n    // Pre-attemptCount records coerce to 0 — they've never been\n    // counted against the cap, so giving them the cap's full budget\n    // is correct (we'd rather over-retry a legacy record than drop it\n    // unexpectedly). Negative or non-finite values also coerce to 0.\n    attemptCount:\n      typeof record.attemptCount === \"number\" && Number.isFinite(record.attemptCount) && record.attemptCount >= 0\n        ? Math.floor(record.attemptCount)\n        : 0,\n  };\n}\n\n// List all deferred entries whose `repoRoot` exactly matches `repoRoot`.\n// Sorted by submittedAt ascending so the drainer records turns in\n// original chronological order.\nexport async function listDeferredTurnsForRepo(repoRoot: string): Promise<DeferredTurnEntry[]> {\n  const dir = getDeferredTurnDirPath();\n  const dirEntries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);\n  const entries: DeferredTurnEntry[] = [];\n  for (const entry of dirEntries) {\n    if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n    const filePath = path.join(dir, entry.name);\n    const record = await readDeferredTurnFile(filePath);\n    if (!record) continue;\n    if (record.repoRoot !== repoRoot) continue;\n    entries.push({ filePath, record });\n  }\n  entries.sort((a, b) => {\n    const aMs = Date.parse(a.record.submittedAt);\n    const bMs = Date.parse(b.record.submittedAt);\n    if (Number.isFinite(aMs) && Number.isFinite(bMs)) return aMs - bMs;\n    return 0;\n  });\n  return entries;\n}\n\n// Delete a single deferred-turn file. Idempotent — a missing file is\n// not an error (the drainer might race with a concurrent drainer).\nexport async function deleteDeferredTurnFile(filePath: string): Promise<void> {\n  await fs.rm(filePath, { force: true }).catch(() => undefined);\n}\n\n// Sweep the queue dir and delete records older than maxAgeMs. Returns\n// the absolute paths that were pruned so the caller can emit a\n// diagnostics event for each (silent prune would be data loss with no\n// audit trail).\nexport async function pruneStaleDeferredTurns(maxAgeMs: number = DEFERRED_TURN_TTL_MS): Promise<string[]> {\n  const dir = getDeferredTurnDirPath();\n  const dirEntries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);\n  const pruned: string[] = [];\n  const now = Date.now();\n  for (const entry of dirEntries) {\n    if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n    const filePath = path.join(dir, entry.name);\n    const record = await readDeferredTurnFile(filePath);\n    if (!record) {\n      // Unparseable / wrong-schema record. Treat as garbage if it's\n      // older than the TTL by mtime; otherwise leave it alone (a\n      // future plugin version may know how to read it).\n      const stat = await fs.stat(filePath).catch(() => null);\n      if (stat && now - stat.mtimeMs > maxAgeMs) {\n        await deleteDeferredTurnFile(filePath);\n        pruned.push(filePath);\n      }\n      continue;\n    }\n    const deferredAtMs = Date.parse(record.deferredAt);\n    if (!Number.isFinite(deferredAtMs)) continue;\n    if (now - deferredAtMs > maxAgeMs) {\n      await deleteDeferredTurnFile(filePath);\n      pruned.push(filePath);\n    }\n  }\n  return pruned;\n}\n\nexport function buildDeferredTurnRecord(params: {\n  sessionId: string;\n  turnId: string;\n  sourceConversation?: ClaudeSourceConversation | null;\n  repoRoot: string;\n  prompt: string;\n  assistantResponse: string;\n  submittedAt: string;\n  branchAtDefer: string | null;\n  // Defer-time binding identity. Optional to keep call-sites that\n  // can't resolve a binding (e.g. failure paths where the binding\n  // file is unreadable) source-compatible; absent → stamped as\n  // `null` and drainer falls back to legacy behavior.\n  appIdAtDefer?: string | null;\n  projectIdAtDefer?: string | null;\n  reason?: DeferredTurnRecord[\"reason\"];\n}): DeferredTurnRecord {\n  return {\n    schemaVersion: DEFERRED_TURN_SCHEMA_VERSION,\n    sessionId: params.sessionId,\n    turnId: params.turnId,\n    sourceConversation: params.sourceConversation ?? null,\n    repoRoot: params.repoRoot,\n    prompt: params.prompt,\n    assistantResponse: params.assistantResponse,\n    submittedAt: params.submittedAt,\n    deferredAt: new Date().toISOString(),\n    reason: params.reason ?? \"current_branch_unbound\",\n    branchAtDefer: params.branchAtDefer,\n    appIdAtDefer: params.appIdAtDefer ?? null,\n    projectIdAtDefer: params.projectIdAtDefer ?? null,\n    // Fresh records start at zero attempts — the next drain pass will\n    // be the first attempt and bump this to 1 if it fails.\n    attemptCount: 0,\n  };\n}\n\n// Outcome reported by `recordDeferredTurnFailedAttempt`. Drainers use\n// `promoted: true` as the signal to write a failure marker for the user\n// (the deferred turn has exhausted its retry budget and should now be\n// surfaced as a permanent failure on the next prompt). When `promoted`\n// is false the file is still on disk with an updated `attemptCount`\n// and the next drainer pass will retry it.\nexport type DeferredTurnFailedAttemptOutcome =\n  | { promoted: false; newAttemptCount: number }\n  | { promoted: true; finalAttemptCount: number };\n\n/**\n * Record one failed drain attempt against an existing on-disk deferred\n * turn record. Atomically reads the latest persisted attemptCount,\n * increments it by 1, and either:\n *   - rewrites the file with the new count (when the cap is not yet\n *     reached) — caller will see the bumped record on the next drain\n *     pass and retry; OR\n *   - deletes the queue file and returns `promoted: true` (when the\n *     cap is reached) — caller is responsible for surfacing a\n *     permanent failure marker so the user gets the recovery advisory\n *     on the next prompt.\n *\n * Re-reads the file before mutating instead of trusting the in-memory\n * `record` parameter so two drainer instances racing on the same record\n * each see the other's increment (last-writer-wins on the Math.max).\n * The risk of double-counting is greater than the risk of under-counting,\n * but with `process.pid` lockfiles in the standalone drainer this race\n * is rare in practice — this just makes it safe.\n *\n * Idempotency: if the file is already gone (a concurrent drainer\n * deleted it) we return `promoted: true` with the count we *would*\n * have written. The caller's marker write is itself idempotent so\n * concurrent promotions are safe.\n */\nexport async function recordDeferredTurnFailedAttempt(\n  filePath: string,\n): Promise<DeferredTurnFailedAttemptOutcome> {\n  const current = await readDeferredTurnFile(filePath);\n  if (!current) {\n    // File vanished or was un-parseable. Best we can do is treat the\n    // record as exhausted so the caller surfaces a marker — silent\n    // re-defer of an unreadable file would just spin.\n    return { promoted: true, finalAttemptCount: DEFERRED_TURN_MAX_ATTEMPTS };\n  }\n  const newAttemptCount = current.attemptCount + 1;\n  if (newAttemptCount >= DEFERRED_TURN_MAX_ATTEMPTS) {\n    await deleteDeferredTurnFile(filePath);\n    return { promoted: true, finalAttemptCount: newAttemptCount };\n  }\n  const next: DeferredTurnRecord = { ...current, attemptCount: newAttemptCount };\n  // Reuse `writeDeferredTurn` so the atomic tmp-then-rename pattern\n  // applies here too — a crash mid-bump should not leave a torn JSON\n  // on disk (the next drain would just refuse to parse and treat the\n  // record as garbage).\n  await writeDeferredTurn(next);\n  return { promoted: false, newAttemptCount };\n}\n","// Standalone deferred-turn drainer.\n//\n// Why this exists: previously the only thing that drained a deferred turn\n// for a repo was the *next* successful Stop hook for that same repo. If\n// the user abandoned the session right after init finished (or Stop never\n// fired again), the deferred prompt would sit on disk indefinitely and\n// the user would see the very-first prompt on a new branch silently\n// disappear from their timeline.\n//\n// This module spawns a long-lived detached worker the moment a turn is\n// deferred. The worker:\n//   1. Acquires a per-repo PID-aware lockfile so duplicate spawns\n//      collapse to one drainer per repo.\n//   2. Polls every `DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS` for either\n//      (a) the queue going empty (we're done) or (b) the current\n//      branch becoming bound. Once bound, finalizes each deferred turn\n//      using the existing `collabFinalizeTurn` API client and deletes\n//      the file.\n//   3. Times out after `DEFERRED_TURN_DRAIN_MAX_WAIT_MS` and exits.\n//      The TTL sweep in `deferred-turn-queue.ts` will then clean up\n//      whatever's left after 24h.\n//\n// Diagnostics events are written to the same hook diagnostics file\n// the in-process drain uses, so a single timeline reconstructs both\n// paths. The drainer never throws — every error is logged and the\n// loop continues / exits cleanly.\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\n\nimport { readCollabBindingState } from \"@remixhq/core/binding\";\nimport * as coreCollab from \"@remixhq/core/collab\";\n\nimport { dispatchFinalizeFailure } from \"./auto-fix-dispatcher.js\";\nimport {\n  deleteDeferredTurnFile,\n  getDeferredTurnDirPath,\n  listDeferredTurnsForRepo,\n  pruneStaleDeferredTurns,\n  recordDeferredTurnFailedAttempt,\n  type DeferredTurnEntry,\n} from \"./deferred-turn-queue.js\";\nimport { createHookCollabApiClient } from \"./hook-auth.js\";\nimport { appendHookDiagnosticsEvent } from \"./hook-diagnostics.js\";\nimport { pluginMetadata } from \"./metadata.js\";\nimport { isFinalizePreflightFailureCode, type FinalizePreflightFailureCode } from \"@remixhq/core/collab\";\nimport { getHookActor, getRuntimeScopedTurnId } from \"./runtime.js\";\nimport { collabFinalizeTurn } from \"./source-conversation.js\";\n\n// `collabFinalizeTurn` is misleadingly named — it enqueues the turn\n// to a local pending-finalize queue under\n// `~/.remix/collab-state/finalize-queue/` and returns `queued: true`.\n// The actual server-side push happens when\n// `drainPendingFinalizeQueue` runs against the API. The standalone\n// deferred-turn drainer must trigger that drainer itself or the turns\n// it \"records\" stay on disk forever and never appear on the dashboard.\nconst drainPendingFinalizeQueue: ((params: { api: unknown }) => Promise<unknown>) | undefined = (\n  coreCollab as { drainPendingFinalizeQueue?: (params: { api: unknown }) => Promise<unknown> }\n).drainPendingFinalizeQueue;\n\nconst HOOK_ACTOR = getHookActor(pluginMetadata.version);\n\n// Lightweight error-shape extractor for the drainer's promotion path.\n//\n// We deliberately don't import the full `getErrorDetails` from\n// `hook-stop-collab.ts` to keep the module dependency graph clean (the\n// drainer module is the entrypoint for a detached subprocess and pulling\n// in the Stop hook would drag in transcript-harvest and Claude-session\n// resolution code that the drainer never needs). The signature mirrors\n// `hook-stop-collab.ts#getErrorDetails` so any future consolidation\n// remains a straightforward swap.\nfunction getDrainerErrorDetails(error: unknown): {\n  message: string;\n  hint: string | null;\n  preflightCode: FinalizePreflightFailureCode | null;\n} {\n  if (error instanceof Error) {\n    const hint = typeof (error as { hint?: unknown }).hint === \"string\" ? String((error as { hint?: unknown }).hint) : null;\n    const codeRaw = (error as { code?: unknown }).code;\n    const preflightCode = isFinalizePreflightFailureCode(codeRaw) ? codeRaw : null;\n    return { message: error.message || \"Deferred turn recording failed.\", hint, preflightCode };\n  }\n  const message = typeof error === \"string\" && error.trim() ? error.trim() : \"Deferred turn recording failed.\";\n  return { message, hint: null, preflightCode: null };\n}\n\n// Tuned to roughly match the slow-init timeline:\n//   - poll every 3s so a freshly-bound branch lands within 3s of init\n//     completing (no perceivable delay vs the in-process drain).\n//   - cap the worker at 15 minutes — covers a worst-case backend\n//     queue stall after `remix collab init` plus generous slack.\nconst DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS = 3_000;\nconst DEFERRED_TURN_DRAIN_MAX_WAIT_MS = 15 * 60 * 1000;\n\n// Lockfile staleness. Heartbeat (mtime touch) every 30s; if the\n// lockfile mtime hasn't moved in 90s AND the recorded PID is dead,\n// the lock is stale and a new drainer can take over.\nconst DEFERRED_TURN_DRAIN_LOCK_HEARTBEAT_MS = 30_000;\nconst DEFERRED_TURN_DRAIN_LOCK_STALE_MS = 90_000;\n\nfunction isPidAlive(pid: number): boolean {\n  if (!Number.isFinite(pid) || pid <= 0) return false;\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction repoLockFileName(repoRoot: string): string {\n  // sha256 of the absolute repoRoot — stable, filesystem-safe, and\n  // doesn't leak path characters into the dir listing.\n  const hash = createHash(\"sha256\").update(repoRoot).digest(\"hex\").slice(0, 16);\n  return `.drainer-${hash}.lock`;\n}\n\nfunction repoLockPath(repoRoot: string): string {\n  return path.join(getDeferredTurnDirPath(), repoLockFileName(repoRoot));\n}\n\ntype DrainLockMetadata = {\n  pid: number;\n  repoRoot: string;\n  startedAt: string;\n};\n\nasync function readDrainLockMetadata(lockPath: string): Promise<DrainLockMetadata | null> {\n  const raw = await fs.readFile(lockPath, \"utf8\").catch(() => null);\n  if (!raw) return null;\n  try {\n    const parsed = JSON.parse(raw) as Partial<DrainLockMetadata>;\n    if (typeof parsed.pid !== \"number\" || typeof parsed.repoRoot !== \"string\" || typeof parsed.startedAt !== \"string\") {\n      return null;\n    }\n    return { pid: parsed.pid, repoRoot: parsed.repoRoot, startedAt: parsed.startedAt };\n  } catch {\n    return null;\n  }\n}\n\nasync function writeDrainLockMetadata(lockPath: string, metadata: DrainLockMetadata): Promise<void> {\n  const tmpPath = `${lockPath}.tmp-${process.pid}-${Date.now()}`;\n  await fs.writeFile(tmpPath, JSON.stringify(metadata), \"utf8\");\n  await fs.rename(tmpPath, lockPath);\n}\n\nasync function tryAcquireDrainLock(repoRoot: string): Promise<{ acquired: boolean; lockPath: string }> {\n  const lockPath = repoLockPath(repoRoot);\n  await fs.mkdir(path.dirname(lockPath), { recursive: true });\n\n  const existingMeta = await readDrainLockMetadata(lockPath);\n  if (existingMeta) {\n    const lockStat = await fs.stat(lockPath).catch(() => null);\n    const ageMs = lockStat ? Date.now() - lockStat.mtimeMs : Number.POSITIVE_INFINITY;\n    const fresh = ageMs <= DEFERRED_TURN_DRAIN_LOCK_STALE_MS;\n    const alive = isPidAlive(existingMeta.pid);\n    if (fresh && alive) {\n      return { acquired: false, lockPath };\n    }\n    // Stale or dead — take it.\n  }\n\n  await writeDrainLockMetadata(lockPath, {\n    pid: process.pid,\n    repoRoot,\n    startedAt: new Date().toISOString(),\n  });\n  return { acquired: true, lockPath };\n}\n\nasync function releaseDrainLock(lockPath: string): Promise<void> {\n  // Only delete if we still own it (best-effort — a racing drainer that\n  // took over after staleness should not have its lock removed).\n  const meta = await readDrainLockMetadata(lockPath);\n  if (meta && meta.pid !== process.pid) return;\n  await fs.rm(lockPath, { force: true }).catch(() => undefined);\n}\n\nasync function heartbeatDrainLock(lockPath: string): Promise<void> {\n  const now = new Date();\n  await fs.utimes(lockPath, now, now).catch(() => undefined);\n}\n\nasync function sleep(ms: number): Promise<void> {\n  await new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction buildIdempotencyKey(turnId: string, repoRoot: string): string {\n  // Mirrors `hook-stop-collab.ts#buildRepoIdempotencyKey` for un-tracked\n  // repos (no app id) — same shape so server-side dedup matches a\n  // later in-process drain attempt for the same deferred turn.\n  return `${getRuntimeScopedTurnId(turnId)}:${repoRoot}:finalize_turn`;\n}\n\n// Pushes locally-queued finalize-turn jobs (written by\n// `collabFinalizeTurn`) to the Remix backend. Diagnostics-only on\n// failure — the local queue is durable so a later spawn (next Stop,\n// manual `--drain-finalize-queue`, etc.) will retry.\nasync function pushPendingFinalizeQueueToServer(params: {\n  sessionMarker: string;\n  repoRoot: string;\n  api: unknown;\n}): Promise<void> {\n  if (typeof drainPendingFinalizeQueue !== \"function\") {\n    await appendHookDiagnosticsEvent({\n      hook: \"deferredTurnDrainer\",\n      sessionId: params.sessionMarker,\n      stage: \"finalize_queue_push_skipped\",\n      result: \"info\",\n      reason: \"drain_pending_finalize_queue_unavailable\",\n      repoRoot: params.repoRoot,\n    });\n    return;\n  }\n  try {\n    await drainPendingFinalizeQueue({ api: params.api });\n    await appendHookDiagnosticsEvent({\n      hook: \"deferredTurnDrainer\",\n      sessionId: params.sessionMarker,\n      stage: \"finalize_queue_pushed\",\n      result: \"success\",\n      repoRoot: params.repoRoot,\n    });\n  } catch (err) {\n    await appendHookDiagnosticsEvent({\n      hook: \"deferredTurnDrainer\",\n      sessionId: params.sessionMarker,\n      stage: \"finalize_queue_push_failed\",\n      result: \"error\",\n      reason: \"exception\",\n      repoRoot: params.repoRoot,\n      message: err instanceof Error ? err.message : String(err),\n    });\n  }\n}\n\nasync function recordOneDeferredTurn(params: {\n  entry: DeferredTurnEntry;\n  api: Awaited<ReturnType<typeof createHookCollabApiClient>>;\n}): Promise<{ recorded: boolean; error?: unknown }> {\n  const { entry, api } = params;\n  const { record, filePath } = entry;\n  try {\n    await collabFinalizeTurn({\n      api,\n      cwd: record.repoRoot,\n      prompt: record.prompt,\n      assistantResponse: record.assistantResponse,\n      idempotencyKey: buildIdempotencyKey(record.turnId, record.repoRoot),\n      actor: HOOK_ACTOR,\n      sourceConversation: record.sourceConversation ?? undefined,\n      turnUsage: null,\n      // The deferred queue can hold a turn for a long time (until the next\n      // `remix collab init` lands a binding), so the server's ingestion\n      // timestamp would otherwise be hours/days off from the real prompt\n      // time. Forward the original submit time so the dashboard timeline\n      // sorts this turn into its true position relative to siblings.\n      promptedAt: record.submittedAt,\n    });\n    await deleteDeferredTurnFile(filePath);\n    return { recorded: true };\n  } catch (error) {\n    return { recorded: false, error };\n  }\n}\n\n// Public: synchronous-feeling main entry for the standalone worker.\n// Exits cleanly when:\n//   - The lock is held by another live drainer (no-op fast exit).\n//   - The queue for `repoRoot` is empty AND we drained at least once\n//     (or it was empty on first poll — nothing to do).\n//   - We hit the wall-clock cap.\n//\n// NEVER throws — all errors get logged to the hook diagnostics file\n// and we return normally so the spawning hook process can `unref` and\n// move on without worrying about exit codes.\nexport async function runStandaloneDeferredTurnDrainer(repoRoot: string): Promise<void> {\n  const startedAt = Date.now();\n  const sessionMarker = `drainer-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;\n  const acquireResult = await tryAcquireDrainLock(repoRoot);\n  if (!acquireResult.acquired) {\n    await appendHookDiagnosticsEvent({\n      hook: \"deferredTurnDrainer\",\n      sessionId: sessionMarker,\n      stage: \"lock_skipped\",\n      result: \"skip\",\n      reason: \"another_drainer_active\",\n      repoRoot,\n    });\n    return;\n  }\n\n  await appendHookDiagnosticsEvent({\n    hook: \"deferredTurnDrainer\",\n    sessionId: sessionMarker,\n    stage: \"drainer_started\",\n    result: \"info\",\n    repoRoot,\n    fields: {\n      pid: process.pid,\n      maxWaitMs: DEFERRED_TURN_DRAIN_MAX_WAIT_MS,\n      pollIntervalMs: DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS,\n    },\n  });\n\n  const heartbeat = setInterval(() => {\n    void heartbeatDrainLock(acquireResult.lockPath).catch(() => undefined);\n  }, DEFERRED_TURN_DRAIN_LOCK_HEARTBEAT_MS);\n  heartbeat.unref?.();\n\n  let api: Awaited<ReturnType<typeof createHookCollabApiClient>> | null = null;\n  let recordedTotal = 0;\n  let failedTotal = 0;\n  let droppedTotal = 0;\n  let exitReason: \"queue_empty\" | \"timeout\" | \"api_init_failed\" = \"queue_empty\";\n\n  try {\n    while (true) {\n      if (Date.now() - startedAt > DEFERRED_TURN_DRAIN_MAX_WAIT_MS) {\n        exitReason = \"timeout\";\n        break;\n      }\n\n      let entries: DeferredTurnEntry[] = [];\n      try {\n        entries = await listDeferredTurnsForRepo(repoRoot);\n      } catch (listErr) {\n        await appendHookDiagnosticsEvent({\n          hook: \"deferredTurnDrainer\",\n          sessionId: sessionMarker,\n          stage: \"list_failed\",\n          result: \"error\",\n          reason: \"exception\",\n          repoRoot,\n          message: listErr instanceof Error ? listErr.message : String(listErr),\n        });\n        await sleep(DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS);\n        continue;\n      }\n\n      if (entries.length === 0) {\n        exitReason = \"queue_empty\";\n        break;\n      }\n\n      const bindingState = await readCollabBindingState(repoRoot).catch(() => null);\n      const currentBranch = bindingState?.currentBranch ?? null;\n      const isCurrentBranchBound = bindingState?.binding != null;\n      const currentAppId = bindingState?.binding?.currentAppId ?? null;\n      const currentProjectId = bindingState?.binding?.projectId ?? bindingState?.projectId ?? null;\n\n      // Step 1: drop deferred records whose defer-time binding\n      // identity no longer matches the repo's current binding. This\n      // is the post-`force-new` path: the user explicitly minted a\n      // brand-new app/project for the same `repoRoot`, so any turn\n      // captured against the *old* identity belongs to the old app's\n      // history and must not silently surface on the new app's\n      // timeline. Pre-appId-aware records (both fields null) fall\n      // through to today's branch-only check.\n      let droppedThisPass = 0;\n      const liveEntries: DeferredTurnEntry[] = [];\n      for (const entry of entries) {\n        const appIdMismatch =\n          entry.record.appIdAtDefer != null &&\n          currentAppId != null &&\n          entry.record.appIdAtDefer !== currentAppId;\n        const projectIdMismatch =\n          entry.record.projectIdAtDefer != null &&\n          currentProjectId != null &&\n          entry.record.projectIdAtDefer !== currentProjectId;\n        if (appIdMismatch || projectIdMismatch) {\n          await deleteDeferredTurnFile(entry.filePath);\n          droppedThisPass += 1;\n          await appendHookDiagnosticsEvent({\n            hook: \"deferredTurnDrainer\",\n            sessionId: sessionMarker,\n            stage: \"deferred_turn_dropped\",\n            result: \"info\",\n            reason: appIdMismatch ? \"app_id_mismatch\" : \"project_id_mismatch\",\n            repoRoot,\n            fields: {\n              deferredTurnId: entry.record.turnId,\n              deferredSessionId: entry.record.sessionId,\n              appIdAtDefer: entry.record.appIdAtDefer,\n              projectIdAtDefer: entry.record.projectIdAtDefer,\n              currentAppId,\n              currentProjectId,\n            },\n          });\n          continue;\n        }\n        liveEntries.push(entry);\n      }\n\n      if (droppedThisPass > 0) {\n        droppedTotal += droppedThisPass;\n      }\n\n      if (liveEntries.length === 0) {\n        // Either the queue was entirely composed of mismatched\n        // records (now deleted) or there's nothing else to do for\n        // this repo right now. Re-check the queue: if it's empty\n        // we exit; otherwise we wait for binding/branch to land.\n        const remaining = await listDeferredTurnsForRepo(repoRoot).catch(() => []);\n        if (remaining.length === 0) {\n          exitReason = \"queue_empty\";\n          break;\n        }\n        await sleep(DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS);\n        continue;\n      }\n\n      const attemptable = liveEntries.filter(\n        (e) =>\n          isCurrentBranchBound && (!e.record.branchAtDefer || e.record.branchAtDefer === currentBranch),\n      );\n\n      if (attemptable.length === 0) {\n        await sleep(DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS);\n        continue;\n      }\n\n      if (!api) {\n        try {\n          api = await createHookCollabApiClient();\n        } catch (apiErr) {\n          await appendHookDiagnosticsEvent({\n            hook: \"deferredTurnDrainer\",\n            sessionId: sessionMarker,\n            stage: \"api_client_failed\",\n            result: \"error\",\n            reason: \"exception\",\n            repoRoot,\n            message: apiErr instanceof Error ? apiErr.message : String(apiErr),\n          });\n          exitReason = \"api_init_failed\";\n          break;\n        }\n      }\n\n      let recordedThisPass = 0;\n      let failedThisPass = 0;\n      for (const entry of attemptable) {\n        const result = await recordOneDeferredTurn({ entry, api });\n        if (result.recorded) {\n          recordedThisPass += 1;\n          recordedTotal += 1;\n          await appendHookDiagnosticsEvent({\n            hook: \"deferredTurnDrainer\",\n            sessionId: sessionMarker,\n            stage: \"deferred_turn_recorded\",\n            result: \"success\",\n            repoRoot,\n            fields: {\n              deferredTurnId: entry.record.turnId,\n              deferredSessionId: entry.record.sessionId,\n              deferredAt: entry.record.deferredAt,\n              submittedAt: entry.record.submittedAt,\n              recordingDelayMs: Math.max(0, Date.now() - Date.parse(entry.record.deferredAt)),\n              recoveredBy: \"standalone_drainer\",\n            },\n          });\n        } else {\n          failedThisPass += 1;\n          failedTotal += 1;\n          // Bump the per-record attempt counter so a stuck record\n          // doesn't retry forever. When the cap is reached we surface\n          // a user-visible failure marker via `dispatchFinalizeFailure`\n          // (delegating to the same dispatcher the hook uses keeps the\n          // marker copy and hint shape consistent across failure\n          // paths) and the queue file is deleted by the bump helper.\n          const outcome = await recordDeferredTurnFailedAttempt(entry.filePath).catch(() => null);\n          const promoted = outcome?.promoted === true;\n          await appendHookDiagnosticsEvent({\n            hook: \"deferredTurnDrainer\",\n            sessionId: sessionMarker,\n            stage: \"deferred_turn_record_failed\",\n            result: \"error\",\n            reason: \"exception\",\n            repoRoot,\n            message: result.error instanceof Error ? result.error.message : String(result.error ?? \"\"),\n            fields: {\n              deferredTurnId: entry.record.turnId,\n              deferredSessionId: entry.record.sessionId,\n              attemptCount: outcome?.promoted === false\n                ? outcome.newAttemptCount\n                : outcome?.promoted === true\n                ? outcome.finalAttemptCount\n                : null,\n              promoted,\n            },\n          });\n          if (promoted) {\n            const errorDetails = getDrainerErrorDetails(result.error);\n            await dispatchFinalizeFailure({\n              // The dispatcher only knows about the two real Claude hook\n              // entrypoints. The standalone drainer is logically a\n              // post-Stop background process and the marker we're about\n              // to write is consumed by the next prompt's UserPromptSubmit\n              // hook, so attributing the failure to \"Stop\" matches what\n              // the user will see.\n              hook: \"Stop\",\n              sessionId: sessionMarker,\n              turnId: entry.record.turnId,\n              repoRoot,\n              preflightCode: errorDetails.preflightCode,\n              message: `Deferred turn could not be recorded after ${outcome?.finalAttemptCount ?? \"max\"} attempts: ${errorDetails.message}`,\n              hint: errorDetails.hint,\n            }).catch(async (dispatchErr) => {\n              await appendHookDiagnosticsEvent({\n                hook: \"deferredTurnDrainer\",\n                sessionId: sessionMarker,\n                stage: \"deferred_turn_promotion_dispatch_failed\",\n                result: \"error\",\n                reason: \"exception\",\n                repoRoot,\n                message: dispatchErr instanceof Error ? dispatchErr.message : String(dispatchErr),\n                fields: {\n                  deferredTurnId: entry.record.turnId,\n                  deferredSessionId: entry.record.sessionId,\n                },\n              });\n            });\n          }\n        }\n      }\n\n      if (recordedThisPass > 0) {\n        await pushPendingFinalizeQueueToServer({\n          sessionMarker,\n          repoRoot,\n          api,\n        });\n      }\n\n      if (recordedThisPass > 0 && failedThisPass === 0) {\n        const remaining = await listDeferredTurnsForRepo(repoRoot).catch(() => []);\n        if (remaining.length === 0) {\n          exitReason = \"queue_empty\";\n          break;\n        }\n      }\n\n      await sleep(DEFERRED_TURN_DRAIN_POLL_INTERVAL_MS);\n    }\n\n    if (recordedTotal > 0 && api) {\n      await pushPendingFinalizeQueueToServer({\n        sessionMarker,\n        repoRoot,\n        api,\n      });\n    }\n\n    try {\n      const pruned = await pruneStaleDeferredTurns();\n      if (pruned.length > 0) {\n        await appendHookDiagnosticsEvent({\n          hook: \"deferredTurnDrainer\",\n          sessionId: sessionMarker,\n          stage: \"ttl_pruned\",\n          result: \"info\",\n          repoRoot,\n          fields: { prunedCount: pruned.length },\n        });\n      }\n    } catch {\n      // non-fatal\n    }\n  } finally {\n    clearInterval(heartbeat);\n    await releaseDrainLock(acquireResult.lockPath);\n    await appendHookDiagnosticsEvent({\n      hook: \"deferredTurnDrainer\",\n      sessionId: sessionMarker,\n      stage: \"drainer_completed\",\n      result: exitReason === \"queue_empty\" ? \"success\" : \"info\",\n      reason: exitReason,\n      repoRoot,\n      fields: {\n        recordedTotal,\n        failedTotal,\n        droppedTotal,\n        elapsedMs: Date.now() - startedAt,\n      },\n    });\n  }\n}\n\n// Best-effort sentinel used by the spawning side to bail out early if\n// the inputs would cause the drainer to no-op anyway.\nexport function getDeferredTurnDrainerLockPathForRepo(repoRoot: string): string {\n  return repoLockPath(repoRoot);\n}\n\n// Pull the repoRoot argument out of argv when the entrypoint was\n// invoked with `--drain-deferred-turns <repoRoot>`.\nexport function parseDeferredTurnDrainerArgv(argv: readonly string[]): string | null {\n  for (let i = 0; i < argv.length; i += 1) {\n    const arg = argv[i];\n    if (!arg) continue;\n    if (arg === \"--drain-deferred-turns\") {\n      const next = argv[i + 1];\n      if (next && !next.startsWith(\"--\")) return next;\n      return null;\n    }\n    if (arg.startsWith(\"--drain-deferred-turns=\")) {\n      const value = arg.slice(\"--drain-deferred-turns=\".length);\n      return value || null;\n    }\n  }\n  return null;\n}\n\nexport async function maybeRunDeferredTurnDrainerFromArgv(): Promise<boolean> {\n  const repoRoot = parseDeferredTurnDrainerArgv(process.argv);\n  if (!repoRoot) return false;\n  await runStandaloneDeferredTurnDrainer(repoRoot);\n  return true;\n}\n","import {\n  RemixError\n} from \"./chunk-7XJGOKEO.js\";\n\n// src/api/clientQuery.ts\nfunction appendStatus(qs, status) {\n  if (Array.isArray(status)) {\n    for (const value of status) qs.append(\"status\", value);\n  } else if (typeof status === \"string\") {\n    qs.set(\"status\", status);\n  }\n}\nfunction suffix(qs) {\n  const value = qs.toString();\n  return value ? `?${value}` : \"\";\n}\nfunction buildRuntimeEnvQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.repoFingerprint) qs.set(\"repoFingerprint\", params.repoFingerprint);\n  if (params?.environment) qs.set(\"environment\", params.environment);\n  if (params?.target) qs.set(\"target\", params.target);\n  return qs.toString();\n}\nfunction buildRuntimeTargetQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.repoFingerprint) qs.set(\"repoFingerprint\", params.repoFingerprint);\n  if (params?.environment) qs.set(\"environment\", params.environment);\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  return qs.toString();\n}\nfunction buildTriggerQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.repoFingerprint) qs.set(\"repoFingerprint\", params.repoFingerprint);\n  if (params?.environment) qs.set(\"environment\", params.environment);\n  if (params?.eventType) qs.set(\"eventType\", params.eventType);\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (params?.appId) qs.set(\"appId\", params.appId);\n  return qs.toString();\n}\nfunction buildProjectListQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.organizationId) qs.set(\"organizationId\", params.organizationId);\n  if (params?.clientAppId) qs.set(\"clientAppId\", params.clientAppId);\n  return suffix(qs);\n}\nfunction buildAppPreviewQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.environment) qs.set(\"environment\", params.environment);\n  if (params?.autostart !== void 0) qs.set(\"autostart\", params.autostart ? \"true\" : \"false\");\n  if (params?.probe) qs.set(\"probe\", params.probe);\n  if (params?.targetKind) qs.set(\"targetKind\", params.targetKind);\n  return suffix(qs);\n}\nfunction buildAppListQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.projectId) qs.set(\"projectId\", params.projectId);\n  if (params?.organizationId) qs.set(\"organizationId\", params.organizationId);\n  if (params?.ownership) qs.set(\"ownership\", params.ownership);\n  if (params?.accessScope) qs.set(\"accessScope\", params.accessScope);\n  if (params?.createdBy) qs.set(\"createdBy\", params.createdBy);\n  if (params?.forked) qs.set(\"forked\", params.forked);\n  if (params?.status) qs.set(\"status\", params.status);\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n  return suffix(qs);\n}\nfunction buildPaginationQuery(params) {\n  const qs = new URLSearchParams();\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n  return suffix(qs);\n}\nfunction buildAppTimelineQuery(params) {\n  const qs = new URLSearchParams();\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (params?.cursor) qs.set(\"cursor\", params.cursor);\n  if (params?.threadId) qs.set(\"threadId\", params.threadId);\n  if (typeof params?.includeHistorical === \"boolean\") qs.set(\"includeHistorical\", String(params.includeHistorical));\n  if (typeof params?.includeCosts === \"boolean\") qs.set(\"includeCosts\", String(params.includeCosts));\n  if (typeof params?.includeMergeRequestHistory === \"boolean\") {\n    qs.set(\"includeMergeRequestHistory\", String(params.includeMergeRequestHistory));\n  }\n  return suffix(qs);\n}\nfunction buildAppEditQueueQuery(params) {\n  const qs = new URLSearchParams(buildPaginationQuery(params).replace(/^\\?/, \"\"));\n  if (params?.threadId) qs.set(\"threadId\", params.threadId);\n  return suffix(qs);\n}\nfunction buildAppJobQueueQuery(params) {\n  const qs = new URLSearchParams();\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n  for (const kind of params?.kind ?? []) qs.append(\"kind\", kind);\n  for (const status of params?.status ?? []) qs.append(\"status\", status);\n  return suffix(qs);\n}\nfunction buildMergeRequestListQuery(params) {\n  const qs = new URLSearchParams();\n  if (params?.queue) qs.set(\"queue\", params.queue);\n  if (params?.appId) qs.set(\"appId\", params.appId);\n  if (params?.sourceAppId) qs.set(\"sourceAppId\", params.sourceAppId);\n  if (params?.targetAppId) qs.set(\"targetAppId\", params.targetAppId);\n  appendStatus(qs, params?.status);\n  if (params?.kind) qs.set(\"kind\", params.kind);\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n  return suffix(qs);\n}\nfunction buildMergeRequestInboxQuery(params) {\n  const qs = new URLSearchParams();\n  appendStatus(qs, params?.status);\n  if (params?.kind) qs.set(\"kind\", params.kind);\n  if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n  if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n  if (typeof params?.includeReview === \"boolean\") qs.set(\"includeReview\", String(params.includeReview));\n  if (typeof params?.includeDiffs === \"boolean\") qs.set(\"includeDiffs\", String(params.includeDiffs));\n  return suffix(qs);\n}\n\n// src/api/client.ts\nasync function readJsonSafe(res) {\n  const ct = res.headers.get(\"content-type\") ?? \"\";\n  if (!ct.toLowerCase().includes(\"application/json\")) return null;\n  try {\n    return await res.json();\n  } catch {\n    return null;\n  }\n}\nfunction createApiClient(config, opts) {\n  const apiKey = (opts?.apiKey ?? \"\").trim();\n  const tokenProvider = opts?.tokenProvider;\n  const defaultTimeoutMs = typeof opts?.defaultRequestTimeoutMs === \"number\" && opts.defaultRequestTimeoutMs > 0 ? opts.defaultRequestTimeoutMs : null;\n  const CLIENT_KEY_HEADER = \"x-comerge-api-key\";\n  function makeTimeoutSignal(timeoutMs) {\n    const ms = typeof timeoutMs === \"number\" && timeoutMs > 0 ? timeoutMs : defaultTimeoutMs;\n    return ms != null ? AbortSignal.timeout(ms) : void 0;\n  }\n  async function request(path, init, opts2) {\n    if (!tokenProvider) {\n      throw new RemixError(\"API client is missing a token provider.\", {\n        exitCode: 1,\n        hint: \"Configure auth before creating the Remix API client.\"\n      });\n    }\n    const auth = await tokenProvider();\n    const url = new URL(path, config.apiUrl).toString();\n    const doFetch = async (bearer) => fetch(url, {\n      ...init,\n      signal: makeTimeoutSignal(opts2?.timeoutMs),\n      headers: {\n        Accept: \"application/json\",\n        \"Content-Type\": \"application/json\",\n        ...init?.headers ?? {},\n        Authorization: `Bearer ${bearer}`,\n        ...apiKey ? { [CLIENT_KEY_HEADER]: apiKey } : {}\n      }\n    });\n    let res = await doFetch(auth.token);\n    if (res.status === 401 && !auth.fromEnv && auth.session?.refresh_token) {\n      const refreshed = await tokenProvider({ forceRefresh: true });\n      res = await doFetch(refreshed.token);\n    }\n    if (!res.ok) {\n      const body = await readJsonSafe(res);\n      const msg = (body && typeof body === \"object\" && body && \"message\" in body && typeof body.message === \"string\" ? body.message : null) ?? `Request failed (status ${res.status})`;\n      throw new RemixError(msg, {\n        exitCode: 1,\n        hint: body ? JSON.stringify(body, null, 2) : null,\n        statusCode: res.status\n      });\n    }\n    const json = await readJsonSafe(res);\n    return json ?? null;\n  }\n  async function requestBinary(path, init, opts2) {\n    if (!tokenProvider) {\n      throw new RemixError(\"API client is missing a token provider.\", {\n        exitCode: 1,\n        hint: \"Configure auth before creating the Remix API client.\"\n      });\n    }\n    const auth = await tokenProvider();\n    const url = new URL(path, config.apiUrl).toString();\n    const doFetch = async (bearer) => fetch(url, {\n      ...init,\n      signal: makeTimeoutSignal(opts2?.timeoutMs),\n      headers: {\n        Accept: \"*/*\",\n        ...init?.headers ?? {},\n        Authorization: `Bearer ${bearer}`,\n        ...apiKey ? { [CLIENT_KEY_HEADER]: apiKey } : {}\n      }\n    });\n    let res = await doFetch(auth.token);\n    if (res.status === 401 && !auth.fromEnv && auth.session?.refresh_token) {\n      const refreshed = await tokenProvider({ forceRefresh: true });\n      res = await doFetch(refreshed.token);\n    }\n    if (!res.ok) {\n      const body = await readJsonSafe(res);\n      const msg = (body && typeof body === \"object\" && body && \"message\" in body && typeof body.message === \"string\" ? body.message : null) ?? `Request failed (status ${res.status})`;\n      throw new RemixError(msg, {\n        exitCode: 1,\n        hint: body ? JSON.stringify(body, null, 2) : null,\n        statusCode: res.status\n      });\n    }\n    const contentDisposition = res.headers.get(\"content-disposition\") ?? \"\";\n    const fileNameMatch = contentDisposition.match(/filename=\\\"([^\\\"]+)\\\"/i);\n    return {\n      data: Buffer.from(await res.arrayBuffer()),\n      fileName: fileNameMatch?.[1] ?? null,\n      contentType: res.headers.get(\"content-type\")\n    };\n  }\n  return {\n    getMe: () => request(\"/v1/me\", { method: \"GET\" }),\n    listOrganizations: () => request(\"/v1/organizations\", { method: \"GET\" }),\n    getOrganization: (orgId) => request(`/v1/organizations/${encodeURIComponent(orgId)}`, { method: \"GET\" }),\n    listProjects: (params) => request(`/v1/projects${buildProjectListQuery(params)}`, { method: \"GET\" }),\n    getProject: (projectId) => request(`/v1/projects/${encodeURIComponent(projectId)}`, { method: \"GET\" }),\n    listProjectRuntimeEnv: (projectId, params) => {\n      const qs = buildRuntimeEnvQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/repo-env${suffix2}`, { method: \"GET\" });\n    },\n    setProjectRuntimeEnv: (projectId, name, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/repo-env/${encodeURIComponent(name)}`, {\n      method: \"PUT\",\n      body: JSON.stringify(payload)\n    }),\n    importProjectRuntimeEnv: (projectId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/repo-env/import`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    deleteProjectRuntimeEnv: (projectId, name, params) => {\n      const qs = buildRuntimeEnvQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/repo-env/${encodeURIComponent(name)}${suffix2}`, {\n        method: \"DELETE\"\n      });\n    },\n    resolveProjectRuntimeEnvForLocalPull: (projectId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/repo-env/resolve-local`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    listProjectRuntimeTargets: (projectId, params) => {\n      const qs = buildRuntimeTargetQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/runtime-targets${suffix2}`, { method: \"GET\" });\n    },\n    detectProjectRuntimeTargets: (projectId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/runtime-targets/detect`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    setProjectRuntimeTarget: (projectId, targetId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/runtime-targets/${encodeURIComponent(targetId)}`, {\n      method: \"PUT\",\n      body: JSON.stringify(payload)\n    }),\n    deleteProjectRuntimeTarget: (projectId, targetId, params) => {\n      const qs = buildRuntimeTargetQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/runtime-targets/${encodeURIComponent(targetId)}${suffix2}`, {\n        method: \"DELETE\"\n      });\n    },\n    runAppRuntimeTarget: (appId, targetId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/runtime-targets/${encodeURIComponent(targetId)}/run`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    getAppRuntimeTargetStatus: (appId, targetId, params) => {\n      const qs = buildRuntimeTargetQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/runtime-targets/${encodeURIComponent(targetId)}/status${suffix2}`, {\n        method: \"GET\"\n      });\n    },\n    getAppRuntimeTargetLogs: (appId, targetId, params) => {\n      const qs = buildRuntimeTargetQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/runtime-targets/${encodeURIComponent(targetId)}/logs${suffix2}`, {\n        method: \"GET\"\n      });\n    },\n    stopAppRuntimeTarget: (appId, targetId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/runtime-targets/${encodeURIComponent(targetId)}/stop`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    getAppPreview: (appId, params) => request(`/v1/apps/${encodeURIComponent(appId)}/preview${buildAppPreviewQuery(params)}`, { method: \"GET\" }),\n    getGithubStatus: () => request(\"/v1/github/status\", { method: \"GET\" }),\n    startGithubOAuth: () => request(\"/v1/github/oauth/start\", { method: \"GET\" }),\n    getGithubInstallUrl: () => request(\"/v1/github/install-url\", { method: \"GET\" }),\n    syncGithubInstallations: () => request(\"/v1/github/installations/sync\", { method: \"POST\" }),\n    listGithubInstallations: () => request(\"/v1/github/installations\", { method: \"GET\" }),\n    listGithubRepositories: (installationId) => request(`/v1/github/installations/${encodeURIComponent(String(installationId))}/repositories`, { method: \"GET\" }),\n    linkAppGithubSource: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/github/link`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    getAppGithubPullRequest: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/github/pull-request`, { method: \"GET\" }),\n    createAppGithubPullRequest: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/github/pull-request`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    updateAppGithubPullRequest: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/github/pull-request`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    createAppShareLink: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/share-links`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    runAppSandboxCommand: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/sandbox/commands/run`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    listAppSandboxCommandHistory: (appId, params) => {\n      const qs = new URLSearchParams();\n      if (params?.limit !== void 0) qs.set(\"limit\", String(params.limit));\n      const suffix2 = qs.toString() ? `?${qs.toString()}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/sandbox/commands/history${suffix2}`, { method: \"GET\" });\n    },\n    listProjectTriggerEvents: (projectId) => request(`/v1/projects/${encodeURIComponent(projectId)}/triggers/events`, { method: \"GET\" }),\n    listProjectTriggers: (projectId, params) => {\n      const qs = buildTriggerQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/triggers${suffix2}`, { method: \"GET\" });\n    },\n    createProjectTrigger: (projectId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/triggers`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    updateProjectTrigger: (projectId, triggerId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/triggers/${encodeURIComponent(triggerId)}`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload)\n    }),\n    deleteProjectTrigger: (projectId, triggerId) => request(`/v1/projects/${encodeURIComponent(projectId)}/triggers/${encodeURIComponent(triggerId)}`, {\n      method: \"DELETE\"\n    }),\n    resolveProjectTriggers: (projectId, params) => {\n      const qs = buildTriggerQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/triggers/resolve${suffix2}`, { method: \"GET\" });\n    },\n    runAppTrigger: (appId, triggerId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/triggers/${encodeURIComponent(triggerId)}/run`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    runAppTriggerEvent: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/triggers/run-event`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    listProjectTriggerRuns: (projectId, params) => {\n      const qs = buildTriggerQuery(params);\n      const suffix2 = qs ? `?${qs}` : \"\";\n      return request(`/v1/projects/${encodeURIComponent(projectId)}/triggers/runs${suffix2}`, { method: \"GET\" });\n    },\n    getProjectTriggerRun: (projectId, runId) => request(`/v1/projects/${encodeURIComponent(projectId)}/triggers/runs/${encodeURIComponent(runId)}`, {\n      method: \"GET\"\n    }),\n    resolveProjectBinding: (params) => {\n      const qs = new URLSearchParams();\n      if (params.repoFingerprint) qs.set(\"repoFingerprint\", params.repoFingerprint);\n      if (params.remoteUrl) qs.set(\"remoteUrl\", params.remoteUrl);\n      if (params.branchName) qs.set(\"branchName\", params.branchName);\n      return request(`/v1/projects/bindings/resolve?${qs.toString()}`, { method: \"GET\" });\n    },\n    resolveProjectLaneBinding: (params) => {\n      const qs = new URLSearchParams();\n      if (params.projectId) qs.set(\"projectId\", params.projectId);\n      if (params.repoFingerprint) qs.set(\"repoFingerprint\", params.repoFingerprint);\n      if (params.remoteUrl) qs.set(\"remoteUrl\", params.remoteUrl);\n      if (params.defaultBranch) qs.set(\"defaultBranch\", params.defaultBranch);\n      if (params.currentAppId) qs.set(\"currentAppId\", params.currentAppId);\n      if (params.upstreamAppId) qs.set(\"upstreamAppId\", params.upstreamAppId);\n      qs.set(\"branchName\", params.branchName);\n      return request(`/v1/projects/bindings/resolve-lane?${qs.toString()}`, { method: \"GET\" });\n    },\n    ensureProjectLaneBinding: (payload) => request(\"/v1/projects/bindings/ensure-lane\", { method: \"POST\", body: JSON.stringify(payload) }),\n    bootstrapFreshProjectLane: (payload) => request(\"/v1/projects/bindings/bootstrap-fresh-lane\", { method: \"POST\", body: JSON.stringify(payload) }),\n    autoEnableDeveloper: () => request(\"/v1/developer/auto-enable\", { method: \"POST\" }),\n    listClientApps: (params) => {\n      const qs = params?.orgId ? `?orgId=${encodeURIComponent(params.orgId)}` : \"\";\n      return request(`/v1/developer/client-apps${qs}`, { method: \"GET\" });\n    },\n    createClientApp: (payload) => request(\"/v1/developer/client-apps\", { method: \"POST\", body: JSON.stringify(payload) }),\n    createClientAppKey: (clientAppId, payload) => request(`/v1/developer/client-apps/${encodeURIComponent(clientAppId)}/keys`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    listApps: (params) => request(`/v1/apps${buildAppListQuery(params)}`, { method: \"GET\" }),\n    getApp: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}`, { method: \"GET\" }),\n    updateAppStatus: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/status`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload)\n    }),\n    openApp: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/open`, { method: \"POST\", body: JSON.stringify(payload ?? {}) }),\n    listAppThreads: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/threads`, { method: \"GET\" }),\n    createAppThread: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/threads`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    renameAppThread: (appId, threadId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/threads/${encodeURIComponent(threadId)}`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload)\n    }),\n    archiveAppThread: (appId, threadId) => request(`/v1/apps/${encodeURIComponent(appId)}/threads/${encodeURIComponent(threadId)}/archive`, {\n      method: \"POST\",\n      body: JSON.stringify({})\n    }),\n    openAppThread: (appId, threadId) => request(`/v1/apps/${encodeURIComponent(appId)}/threads/${encodeURIComponent(threadId)}/open`, {\n      method: \"POST\",\n      body: JSON.stringify({})\n    }),\n    getAppContext: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/context`, { method: \"GET\" }),\n    getAppOverview: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/overview`, { method: \"GET\" }),\n    getAppMergePreview: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/merge-preview`, { method: \"GET\" }),\n    listAppTimeline: (appId, params) => request(`/v1/apps/${encodeURIComponent(appId)}/timeline${buildAppTimelineQuery(params)}`, { method: \"GET\" }),\n    getAppTimelineEvent: (appId, eventId) => request(`/v1/apps/${encodeURIComponent(appId)}/timeline/${encodeURIComponent(eventId)}`, { method: \"GET\" }),\n    listAppEditQueue: (appId, params) => request(`/v1/apps/${encodeURIComponent(appId)}/edit-queue${buildAppEditQueueQuery(params)}`, {\n      method: \"GET\"\n    }),\n    cancelAppEditQueueItem: (appId, queueItemId) => request(`/v1/apps/${encodeURIComponent(appId)}/edit-queue/${encodeURIComponent(queueItemId)}`, {\n      method: \"DELETE\"\n    }),\n    listAppJobQueue: (appId, params) => request(`/v1/apps/${encodeURIComponent(appId)}/job-queue${buildAppJobQueueQuery(params)}`, { method: \"GET\" }),\n    getMergeRequest: (mrId) => request(`/v1/merge-requests/${encodeURIComponent(mrId)}`, { method: \"GET\" }),\n    presignImportUpload: (payload) => request(\"/v1/apps/import/upload/presign\", { method: \"POST\", body: JSON.stringify(payload) }),\n    importFromUpload: (payload) => request(\"/v1/apps/import/upload\", { method: \"POST\", body: JSON.stringify(payload) }),\n    presignImportUploadFirstParty: (payload) => request(\"/v1/apps/import/upload/presign/first-party\", { method: \"POST\", body: JSON.stringify(payload) }),\n    importFromUploadFirstParty: (payload) => request(\"/v1/apps/import/upload/first-party\", { method: \"POST\", body: JSON.stringify(payload) }),\n    importFromGithubFirstParty: (payload) => request(\"/v1/apps/import/github/first-party\", { method: \"POST\", body: JSON.stringify(payload) }),\n    forkApp: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/fork`, { method: \"POST\", body: JSON.stringify(payload ?? {}) }),\n    getAppHead: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/head`, { method: \"GET\" }),\n    getAppDelta: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/delta`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    downloadAppBundle: (appId) => requestBinary(`/v1/apps/${encodeURIComponent(appId)}/download.bundle`, { method: \"GET\" }),\n    createChangeStep: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    listChangeSteps: (appId, params) => {\n      const qs = new URLSearchParams();\n      if (params?.limit !== void 0) qs.set(\"limit\", String(params.limit));\n      if (params?.offset !== void 0) qs.set(\"offset\", String(params.offset));\n      if (params?.idempotencyKey) qs.set(\"idempotencyKey\", params.idempotencyKey);\n      if (params?.threadId) qs.set(\"threadId\", params.threadId);\n      const suffix2 = qs.toString() ? `?${qs.toString()}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/change-steps${suffix2}`, { method: \"GET\" });\n    },\n    createCollabTurn: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    attachCollabTurnUsage: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns/attach-usage`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    listCollabTurns: (appId, params) => {\n      const qs = new URLSearchParams();\n      if (params?.limit !== void 0) qs.set(\"limit\", String(params.limit));\n      if (params?.offset !== void 0) qs.set(\"offset\", String(params.offset));\n      if (params?.changeStepId) qs.set(\"changeStepId\", params.changeStepId);\n      if (params?.threadId) qs.set(\"threadId\", params.threadId);\n      if (params?.collabLaneId) qs.set(\"collabLaneId\", params.collabLaneId);\n      if (params?.createdAfter) qs.set(\"createdAfter\", params.createdAfter);\n      if (params?.createdBefore) qs.set(\"createdBefore\", params.createdBefore);\n      const suffix2 = qs.toString() ? `?${qs.toString()}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns${suffix2}`, { method: \"GET\" });\n    },\n    getCollabTurn: (appId, collabTurnId) => request(`/v1/apps/${encodeURIComponent(appId)}/collab-turns/${encodeURIComponent(collabTurnId)}`, {\n      method: \"GET\"\n    }),\n    getAgentMemorySummary: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/agent-memory/summary`, { method: \"GET\" }),\n    listAgentMemoryTimeline: (appId, params) => {\n      const qs = new URLSearchParams();\n      if (params?.limit !== void 0) qs.set(\"limit\", String(params.limit));\n      if (params?.offset !== void 0) qs.set(\"offset\", String(params.offset));\n      if (params?.createdAfter) qs.set(\"createdAfter\", params.createdAfter);\n      if (params?.createdBefore) qs.set(\"createdBefore\", params.createdBefore);\n      if (params?.threadId) qs.set(\"threadId\", params.threadId);\n      if (params?.kinds?.length) {\n        for (const kind of params.kinds) qs.append(\"kinds\", kind);\n      }\n      const suffix2 = qs.toString() ? `?${qs.toString()}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/agent-memory/timeline${suffix2}`, { method: \"GET\" });\n    },\n    searchAgentMemory: (appId, params) => {\n      const qs = new URLSearchParams();\n      qs.set(\"q\", params.q);\n      if (params.limit !== void 0) qs.set(\"limit\", String(params.limit));\n      if (params.offset !== void 0) qs.set(\"offset\", String(params.offset));\n      if (params.createdAfter) qs.set(\"createdAfter\", params.createdAfter);\n      if (params.createdBefore) qs.set(\"createdBefore\", params.createdBefore);\n      if (params.threadId) qs.set(\"threadId\", params.threadId);\n      if (params.kinds?.length) {\n        for (const kind of params.kinds) qs.append(\"kinds\", kind);\n      }\n      return request(`/v1/apps/${encodeURIComponent(appId)}/agent-memory/search?${qs.toString()}`, { method: \"GET\" });\n    },\n    getChangeStep: (appId, changeStepId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/${encodeURIComponent(changeStepId)}`, { method: \"GET\" }),\n    getChangeStepDiff: (appId, changeStepId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/${encodeURIComponent(changeStepId)}/diff`, {\n      method: \"GET\"\n    }),\n    startChangeStepReplay: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/replays`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    getChangeStepReplay: (appId, replayId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/replays/${encodeURIComponent(replayId)}`, {\n      method: \"GET\"\n    }),\n    getChangeStepReplayDiff: (appId, replayId) => request(`/v1/apps/${encodeURIComponent(appId)}/change-steps/replays/${encodeURIComponent(replayId)}/diff`, {\n      method: \"GET\"\n    }),\n    listMergeRequests: (params) => request(`/v1/merge-requests${buildMergeRequestListQuery(params)}`, { method: \"GET\" }),\n    listMergeRequestInbox: (params) => request(`/v1/merge-requests/inbox${buildMergeRequestInboxQuery(params)}`, { method: \"GET\" }),\n    openMergeRequest: (sourceAppId) => request(\"/v1/merge-requests\", { method: \"POST\", body: JSON.stringify({ sourceAppId }) }),\n    getMergeRequestReview: (mrId) => request(`/v1/merge-requests/${encodeURIComponent(mrId)}/review`, { method: \"GET\" }),\n    updateMergeRequest: (mrId, payload) => request(`/v1/merge-requests/${encodeURIComponent(mrId)}`, { method: \"PATCH\", body: JSON.stringify(payload) }),\n    createOrganizationInvite: (orgId, payload) => request(`/v1/organizations/${encodeURIComponent(orgId)}/invitations`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    createProjectInvite: (projectId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/invitations`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    createAppInvite: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/invitations`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    listOrganizationMembers: (orgId, params) => request(`/v1/organizations/${encodeURIComponent(orgId)}/members${buildPaginationQuery(params)}`, { method: \"GET\" }),\n    updateOrganizationMember: (orgId, userId, payload) => request(`/v1/organizations/${encodeURIComponent(orgId)}/members/${encodeURIComponent(userId)}`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload)\n    }),\n    listProjectMembers: (projectId, params) => request(`/v1/projects/${encodeURIComponent(projectId)}/members${buildPaginationQuery(params)}`, { method: \"GET\" }),\n    updateProjectMember: (projectId, userId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/members/${encodeURIComponent(userId)}`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload)\n    }),\n    listAppMembers: (appId, params) => request(`/v1/apps/${encodeURIComponent(appId)}/members${buildPaginationQuery(params)}`, { method: \"GET\" }),\n    updateAppMember: (appId, userId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/members/${encodeURIComponent(userId)}`, {\n      method: \"PATCH\",\n      body: JSON.stringify(payload)\n    }),\n    listOrganizationInvites: (orgId, params) => request(`/v1/organizations/${encodeURIComponent(orgId)}/invitations${buildPaginationQuery(params)}`, { method: \"GET\" }),\n    listProjectInvites: (projectId, params) => request(`/v1/projects/${encodeURIComponent(projectId)}/invitations${buildPaginationQuery(params)}`, { method: \"GET\" }),\n    listAppInvites: (appId, params) => request(`/v1/apps/${encodeURIComponent(appId)}/invitations${buildPaginationQuery(params)}`, { method: \"GET\" }),\n    resendOrganizationInvite: (orgId, inviteId, payload) => request(`/v1/organizations/${encodeURIComponent(orgId)}/invitations/${encodeURIComponent(inviteId)}/resend`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    resendProjectInvite: (projectId, inviteId, payload) => request(`/v1/projects/${encodeURIComponent(projectId)}/invitations/${encodeURIComponent(inviteId)}/resend`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    resendAppInvite: (appId, inviteId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/invitations/${encodeURIComponent(inviteId)}/resend`, {\n      method: \"POST\",\n      body: JSON.stringify(payload ?? {})\n    }),\n    revokeOrganizationInvite: (orgId, inviteId) => request(`/v1/organizations/${encodeURIComponent(orgId)}/invitations/${encodeURIComponent(inviteId)}`, {\n      method: \"DELETE\"\n    }),\n    revokeProjectInvite: (projectId, inviteId) => request(`/v1/projects/${encodeURIComponent(projectId)}/invitations/${encodeURIComponent(inviteId)}`, {\n      method: \"DELETE\"\n    }),\n    revokeAppInvite: (appId, inviteId) => request(`/v1/apps/${encodeURIComponent(appId)}/invitations/${encodeURIComponent(inviteId)}`, {\n      method: \"DELETE\"\n    }),\n    acceptInvitation: (payload) => request(\"/v1/invitations/accept\", { method: \"POST\", body: JSON.stringify(payload) }),\n    listMyInvitations: () => request(\"/v1/me/invitations\", { method: \"GET\" }),\n    acceptMyInvitation: (scope, inviteId) => request(\n      `/v1/me/invitations/${encodeURIComponent(scope)}/${encodeURIComponent(inviteId)}/accept`,\n      { method: \"POST\", body: JSON.stringify({}) }\n    ),\n    declineMyInvitation: (scope, inviteId) => request(\n      `/v1/me/invitations/${encodeURIComponent(scope)}/${encodeURIComponent(inviteId)}/decline`,\n      { method: \"POST\", body: JSON.stringify({}) }\n    ),\n    syncUpstreamApp: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/sync-upstream`, {\n      method: \"POST\",\n      body: JSON.stringify({})\n    }),\n    preflightAppReconcile: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/reconcile/preflight`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    startAppReconcile: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/reconcile/start`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    getAppReconcile: (appId, reconcileId) => request(`/v1/apps/${encodeURIComponent(appId)}/reconcile/${encodeURIComponent(reconcileId)}`, { method: \"GET\" }),\n    downloadAppReconcileBundle: (appId, reconcileId) => requestBinary(`/v1/apps/${encodeURIComponent(appId)}/reconcile/${encodeURIComponent(reconcileId)}/download.bundle`, {\n      method: \"GET\"\n    }),\n    syncLocalApp: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/sync-local`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    reportLocalCheckoutState: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/local-alignment/checkout-state`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    getLatestLocalCheckoutState: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/local-alignment/checkout-state/latest`, { method: \"GET\" }),\n    recordLocalAlignmentEvent: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/local-alignment/events`, {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    initiateBundle: (appId, payload) => request(`/v1/apps/${encodeURIComponent(appId)}/bundles`, { method: \"POST\", body: JSON.stringify(payload) }),\n    getBundle: (appId, bundleId) => request(`/v1/apps/${encodeURIComponent(appId)}/bundles/${encodeURIComponent(bundleId)}`, { method: \"GET\" }),\n    getBundleDownloadUrl: (appId, bundleId, options) => request(\n      `/v1/apps/${encodeURIComponent(appId)}/bundles/${encodeURIComponent(bundleId)}/download?redirect=${options?.redirect ?? false}`,\n      { method: \"GET\" }\n    ),\n    getBundleAssetsDownloadUrl: (appId, bundleId, options) => {\n      const qs = new URLSearchParams({\n        redirect: String(options?.redirect ?? false),\n        kind: options?.kind ?? \"metro-assets\"\n      });\n      return request(\n        `/v1/apps/${encodeURIComponent(appId)}/bundles/${encodeURIComponent(bundleId)}/assets/download?${qs.toString()}`,\n        { method: \"GET\" }\n      );\n    },\n    listAgentRuns: (appId, params) => {\n      const qs = new URLSearchParams();\n      if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n      if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n      if (params?.status) qs.set(\"status\", params.status);\n      if (params?.threadId) qs.set(\"threadId\", params.threadId);\n      if (params?.currentPhase) qs.set(\"currentPhase\", params.currentPhase);\n      if (params?.createdAfter) qs.set(\"createdAfter\", params.createdAfter);\n      if (params?.createdBefore) qs.set(\"createdBefore\", params.createdBefore);\n      const suffix2 = qs.toString() ? `?${qs.toString()}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/agent-runs${suffix2}`, { method: \"GET\" });\n    },\n    getAgentRun: (appId, runId) => request(`/v1/apps/${encodeURIComponent(appId)}/agent-runs/${encodeURIComponent(runId)}`, { method: \"GET\" }),\n    listAgentRunEvents: (appId, runId, params) => {\n      const qs = new URLSearchParams();\n      if (typeof params?.limit === \"number\") qs.set(\"limit\", String(params.limit));\n      if (typeof params?.offset === \"number\") qs.set(\"offset\", String(params.offset));\n      if (params?.createdAfter) qs.set(\"createdAfter\", params.createdAfter);\n      if (params?.createdBefore) qs.set(\"createdBefore\", params.createdBefore);\n      const suffix2 = qs.toString() ? `?${qs.toString()}` : \"\";\n      return request(`/v1/apps/${encodeURIComponent(appId)}/agent-runs/${encodeURIComponent(runId)}/events${suffix2}`, {\n        method: \"GET\"\n      });\n    },\n    getSandboxStatus: (appId) => request(`/v1/apps/${encodeURIComponent(appId)}/sandbox/status`, { method: \"GET\" }),\n    editAgentApp: (payload) => request(\"/v1/agent/editApp\", {\n      method: \"POST\",\n      body: JSON.stringify(payload)\n    }),\n    importHistory: async (payload) => {\n      const res = await request(\"/v1/history/import\", {\n        method: \"POST\",\n        body: JSON.stringify(payload)\n      });\n      const envelope = res;\n      if (!envelope || typeof envelope !== \"object\" || !envelope.responseObject) {\n        throw new RemixError(\"Malformed importHistory response from server.\", {\n          exitCode: 1,\n          hint: \"Expected `{ responseObject: ImportHistoryResponse }`.\"\n        });\n      }\n      return envelope.responseObject;\n    }\n  };\n}\n\nexport {\n  createApiClient\n};\n","import {\n  RemixError\n} from \"./chunk-7XJGOKEO.js\";\n\n// src/auth/session.ts\nimport { z } from \"zod\";\nvar storedSessionSchema = z.object({\n  access_token: z.string().min(1),\n  refresh_token: z.string().min(1),\n  expires_at: z.number().int().positive(),\n  token_type: z.string().min(1).optional(),\n  user: z.object({\n    id: z.string().min(1),\n    email: z.string().email().optional().nullable()\n  }).optional()\n});\n\n// src/auth/localSessionStore.ts\nimport fs2 from \"fs/promises\";\nimport os2 from \"os\";\nimport path2 from \"path\";\n\n// src/auth/refreshLock.ts\nimport fs from \"fs/promises\";\nimport os from \"os\";\nimport path from \"path\";\nvar DEFAULT_STALE_MS = 3e4;\nvar DEFAULT_MAX_WAIT_MS = 15e3;\nvar DEFAULT_POLL_MS = 50;\nfunction createRefreshLock(opts) {\n  const staleMs = opts.staleMs ?? DEFAULT_STALE_MS;\n  const maxWaitMs = opts.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;\n  const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;\n  let inProcess = null;\n  return async function withRefreshLock(fn) {\n    if (inProcess) {\n      await inProcess.catch(() => {\n      });\n    }\n    const job = (async () => {\n      const start = Date.now();\n      while (true) {\n        try {\n          await fs.mkdir(path.dirname(opts.lockPath), { recursive: true });\n          const fh = await fs.open(opts.lockPath, \"wx\");\n          try {\n            await fh.writeFile(`${process.pid}\n${Date.now()}\n${os.hostname()}\n`);\n          } finally {\n            await fh.close().catch(() => {\n            });\n          }\n          try {\n            return await fn();\n          } finally {\n            await fs.unlink(opts.lockPath).catch(() => {\n            });\n          }\n        } catch (err) {\n          const code = err?.code;\n          if (code !== \"EEXIST\") throw err;\n          const stat = await fs.stat(opts.lockPath).catch(() => null);\n          if (stat && Date.now() - stat.mtimeMs > staleMs) {\n            await fs.unlink(opts.lockPath).catch(() => {\n            });\n            continue;\n          }\n          if (Date.now() - start > maxWaitMs) {\n            return await fn();\n          }\n          await sleep(pollMs);\n        }\n      }\n    })();\n    inProcess = job;\n    try {\n      return await job;\n    } finally {\n      if (inProcess === job) inProcess = null;\n    }\n  };\n}\nfunction sleep(ms) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n// src/auth/localSessionStore.ts\nvar loadKeytarModule = () => new Function(\"return import('keytar')\")();\nfunction xdgConfigHome() {\n  const value = process.env.XDG_CONFIG_HOME;\n  if (typeof value === \"string\" && value.trim()) return value;\n  return path2.join(os2.homedir(), \".config\");\n}\nasync function maybeLoadKeytar() {\n  try {\n    const mod = await loadKeytarModule();\n    const candidates = [mod, mod?.default].filter(Boolean);\n    for (const candidate of candidates) {\n      const value = candidate;\n      if (typeof value.getPassword === \"function\" && typeof value.setPassword === \"function\") {\n        return value;\n      }\n    }\n  } catch {\n    return null;\n  }\n  return null;\n}\nasync function ensurePathPermissions(filePath) {\n  const dir = path2.dirname(filePath);\n  await fs2.mkdir(dir, { recursive: true });\n  try {\n    await fs2.chmod(dir, 448);\n  } catch {\n  }\n  try {\n    await fs2.chmod(filePath, 384);\n  } catch {\n  }\n}\nasync function writeJsonAtomic(filePath, value) {\n  await fs2.mkdir(path2.dirname(filePath), { recursive: true });\n  const tmpPath = `${filePath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n  await fs2.writeFile(tmpPath, JSON.stringify(value, null, 2) + \"\\n\", \"utf8\");\n  await fs2.rename(tmpPath, filePath);\n}\nasync function writeSessionFileFallback(filePath, session) {\n  await writeJsonAtomic(filePath, session);\n  await ensurePathPermissions(filePath);\n}\nfunction createLocalSessionStore(params) {\n  const service = params?.service?.trim() || \"remix-cli\";\n  const account = params?.account?.trim() || \"default\";\n  const filePath = params?.filePath?.trim() || path2.join(xdgConfigHome(), \"remix\", \"session.json\");\n  async function readKeytar() {\n    const keytar = await maybeLoadKeytar();\n    if (!keytar) return null;\n    const raw = await keytar.getPassword(service, account).catch(() => null);\n    if (!raw) return null;\n    try {\n      const parsed = storedSessionSchema.safeParse(JSON.parse(raw));\n      return parsed.success ? parsed.data : null;\n    } catch {\n      return null;\n    }\n  }\n  async function readFile() {\n    const raw = await fs2.readFile(filePath, \"utf8\").catch(() => null);\n    if (!raw) return null;\n    try {\n      const parsed = storedSessionSchema.safeParse(JSON.parse(raw));\n      if (!parsed.success) return null;\n      await ensurePathPermissions(filePath);\n      return parsed.data;\n    } catch {\n      return null;\n    }\n  }\n  function pickFreshest(a, b) {\n    if (!a) return b;\n    if (!b) return a;\n    return a.expires_at >= b.expires_at ? a : b;\n  }\n  return {\n    async getSession() {\n      const [k, f] = await Promise.all([readKeytar(), readFile()]);\n      return pickFreshest(k, f);\n    },\n    async setSession(session) {\n      const parsed = storedSessionSchema.safeParse(session);\n      if (!parsed.success) {\n        throw new Error(\"Session data is invalid and was not stored.\");\n      }\n      await writeSessionFileFallback(filePath, parsed.data);\n      const keytar = await maybeLoadKeytar();\n      if (keytar) {\n        try {\n          await keytar.setPassword(service, account, JSON.stringify(parsed.data));\n        } catch {\n        }\n      }\n    }\n  };\n}\nfunction defaultSessionFilePath() {\n  return path2.join(xdgConfigHome(), \"remix\", \"session.json\");\n}\nfunction createDefaultRefreshLock(filePath) {\n  const target = filePath?.trim() || defaultSessionFilePath();\n  return createRefreshLock({ lockPath: `${target}.lock` });\n}\n\n// src/auth/refreshErrors.ts\nvar NETWORK_CODE_PATTERN = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENOTFOUND|EPIPE|EHOSTUNREACH|EADDRNOTAVAIL|UND_ERR_)/;\nvar NETWORK_MESSAGE_PATTERN = /fetch failed|failed to fetch|network request failed|socket hang up|network error|aborted/i;\nfunction isNetworkError(err) {\n  if (!err || typeof err !== \"object\") return false;\n  const e = err;\n  const code = typeof e.code === \"string\" ? e.code : void 0;\n  const errno = typeof e.errno === \"string\" ? e.errno : void 0;\n  const msg = typeof e.message === \"string\" ? e.message : \"\";\n  if (code && NETWORK_CODE_PATTERN.test(code)) return true;\n  if (errno && NETWORK_CODE_PATTERN.test(errno)) return true;\n  if (e.name === \"TypeError\" && NETWORK_MESSAGE_PATTERN.test(msg)) return true;\n  if (e.name === \"AbortError\") return true;\n  if (NETWORK_MESSAGE_PATTERN.test(msg)) return true;\n  if (e.cause) return isNetworkError(e.cause);\n  return false;\n}\nvar INVALID_GRANT_MESSAGE_PATTERN = /invalid[_ ]grant|invalid refresh token|refresh[_ ]token[_ ]not[_ ]found|refresh token (has )?(been )?(expired|revoked)|token has expired or (been )?revoked|already used|user from sub claim in jwt does not exist/i;\nfunction isInvalidGrantError(err) {\n  if (!err || typeof err !== \"object\") return false;\n  const e = err;\n  const code = typeof e.code === \"string\" ? e.code : \"\";\n  const msg = typeof e.message === \"string\" ? e.message : \"\";\n  if (code === \"invalid_grant\" || code === \"refresh_token_not_found\") return true;\n  if (INVALID_GRANT_MESSAGE_PATTERN.test(msg)) return true;\n  if (e.cause) return isInvalidGrantError(e.cause);\n  return false;\n}\n\n// src/auth/tokenProvider.ts\nfunction firstNonEmptyEnvToken() {\n  for (const value of [process.env.REMIX_ACCESS_TOKEN, process.env.COMERGE_ACCESS_TOKEN]) {\n    if (typeof value === \"string\" && value.trim().length > 0) return value.trim();\n  }\n  return null;\n}\nfunction shouldRefreshSoon(session, skewSeconds = 60) {\n  const nowSec = Math.floor(Date.now() / 1e3);\n  return session.expires_at <= nowSec + skewSeconds;\n}\nfunction createStoredSessionTokenProvider(params) {\n  const withLock = params.withRefreshLock ?? (async (fn) => fn());\n  return async (opts) => {\n    const forceRefresh = Boolean(opts?.forceRefresh);\n    const envToken = firstNonEmptyEnvToken();\n    if (envToken) {\n      return { token: envToken, session: null, fromEnv: true };\n    }\n    let session = await params.sessionStore.getSession();\n    if (!session) {\n      throw new RemixError(\"Not signed in.\", {\n        exitCode: 2,\n        hint: \"Run `remix login`, or set REMIX_ACCESS_TOKEN for CI.\"\n      });\n    }\n    if (forceRefresh || shouldRefreshSoon(session)) {\n      const sessionAtEntry = session;\n      try {\n        session = await withLock(async () => {\n          const latest = await params.sessionStore.getSession();\n          const base = latest ?? sessionAtEntry;\n          if (!base) {\n            throw new RemixError(\"Not signed in.\", {\n              exitCode: 2,\n              hint: \"Run `remix login`, or set REMIX_ACCESS_TOKEN for CI.\"\n            });\n          }\n          const siblingRefreshed = latest != null && latest.access_token !== sessionAtEntry.access_token;\n          if (siblingRefreshed && !forceRefresh && !shouldRefreshSoon(base, 5)) {\n            return base;\n          }\n          const refreshed = await params.refreshStoredSession({\n            config: params.config,\n            session: base\n          });\n          await params.sessionStore.setSession(refreshed);\n          return refreshed;\n        });\n      } catch (err) {\n        if (isInvalidGrantError(err)) {\n          throw new RemixError(\"Session expired. Please sign in again.\", {\n            exitCode: 2,\n            hint: \"Run `remix login` to re-authenticate.\"\n          });\n        }\n        if (isNetworkError(err)) {\n        } else {\n        }\n      }\n    }\n    return { token: session.access_token, session, fromEnv: false };\n  };\n}\n\n// src/auth/supabase.ts\nimport crypto from \"crypto\";\nvar RemixAuthContinuationError = class extends RemixError {\n  challenge;\n  constructor(message, challenge, statusCode) {\n    super(message, { code: challenge.code, exitCode: 1, statusCode });\n    this.name = \"RemixAuthContinuationError\";\n    this.challenge = challenge;\n  }\n};\nfunction isRecord(value) {\n  return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\nfunction isWorkosAuthChallenge(value) {\n  return isRecord(value) && typeof value.code === \"string\";\n}\nasync function postBackend(config, path3, body, options) {\n  const response = await fetch(new URL(path3, config.apiUrl), {\n    method: \"POST\",\n    headers: { \"Content-Type\": \"application/json\", \"X-Requested-By\": \"remix-cli\" },\n    ...options?.credentials ? { credentials: options.credentials } : {},\n    body: JSON.stringify(body)\n  });\n  const payload = await response.json();\n  if (response.status === 403 && !payload.success && isWorkosAuthChallenge(payload.responseObject)) {\n    throw new RemixAuthContinuationError(\n      payload.message || payload.responseObject.message || \"Authentication continuation required.\",\n      {\n        ...payload.responseObject,\n        message: payload.responseObject.message || payload.message || \"Authentication continuation required.\"\n      },\n      response.status\n    );\n  }\n  if (!response.ok || !payload.success || payload.responseObject == null) {\n    throw new RemixError(payload.message || `Remix backend request failed with status ${response.status}.`, {\n      exitCode: 1\n    });\n  }\n  return payload.responseObject;\n}\nfunction toStoredSession(payload) {\n  if (!payload.accessToken || !payload.refreshToken) {\n    throw new RemixError(\"Remix backend did not return a token pair.\", { exitCode: 1 });\n  }\n  const expiresIn = Number.isFinite(payload.expiresIn) && payload.expiresIn ? payload.expiresIn : 15 * 60;\n  return {\n    access_token: payload.accessToken,\n    refresh_token: payload.refreshToken,\n    expires_at: Math.floor(Date.now() / 1e3) + expiresIn,\n    token_type: payload.tokenType ?? \"Bearer\",\n    user: payload.user?.id ? { id: payload.user.id, email: payload.user.email ?? null } : void 0\n  };\n}\nfunction createPkcePair() {\n  const codeVerifier = crypto.randomBytes(32).toString(\"base64url\");\n  const codeChallenge = crypto.createHash(\"sha256\").update(codeVerifier).digest(\"base64url\");\n  return { codeVerifier, codeChallenge };\n}\nfunction normalizeBrowserReturnTo(redirectTo) {\n  try {\n    const url = new URL(redirectTo);\n    if (url.protocol === \"http:\" || url.protocol === \"https:\") {\n      return `${url.pathname}${url.search}${url.hash}`;\n    }\n  } catch {\n  }\n  return redirectTo;\n}\nfunction createRemixAuthHelpers(config) {\n  async function startLogin(params) {\n    const path3 = params.state ? \"/v1/auth/cli/login-url\" : \"/v1/auth/login-url\";\n    const pkce = params.state ? createPkcePair() : null;\n    const body = params.state ? { returnTo: params.redirectTo, state: params.state, codeChallenge: pkce?.codeChallenge, provider: params.provider ?? \"authkit\" } : { returnTo: normalizeBrowserReturnTo(params.redirectTo), provider: params.provider ?? \"authkit\" };\n    const result = await postBackend(config, path3, body, params.state ? void 0 : { credentials: \"include\" });\n    if (!result.url) throw new RemixError(\"Remix backend did not return an auth URL.\", { exitCode: 1 });\n    return pkce ? { url: result.url, codeVerifier: pkce.codeVerifier } : { url: result.url };\n  }\n  return {\n    startLogin,\n    async startAuthKitLogin(params) {\n      return startLogin({ ...params, provider: \"authkit\" });\n    },\n    async startGoogleLogin(params) {\n      return startLogin({ ...params, provider: \"google\" });\n    },\n    async startGithubLogin(params) {\n      return startLogin({ ...params, provider: \"github\" });\n    },\n    async exchangeCode(params) {\n      const result = await postBackend(config, \"/v1/auth/cli/exchange\", {\n        code: params.code,\n        ...params.codeVerifier ? { codeVerifier: params.codeVerifier } : {}\n      });\n      return toStoredSession(result);\n    },\n    async continueAuthentication(input) {\n      const result = await postBackend(config, \"/v1/auth/cli/continue\", input);\n      return toStoredSession(result);\n    },\n    async refreshWithStoredSession(params) {\n      const result = await postBackend(config, \"/v1/auth/token/refresh\", {\n        refreshToken: params.session.refresh_token\n      });\n      return toStoredSession(result);\n    }\n  };\n}\n\nexport {\n  storedSessionSchema,\n  createRefreshLock,\n  createLocalSessionStore,\n  defaultSessionFilePath,\n  createDefaultRefreshLock,\n  isNetworkError,\n  isInvalidGrantError,\n  shouldRefreshSoon,\n  createStoredSessionTokenProvider,\n  RemixAuthContinuationError,\n  createRemixAuthHelpers\n};\n","import {\n  RemixError\n} from \"./chunk-7XJGOKEO.js\";\n\n// src/config/model.ts\nimport { z } from \"zod\";\nvar DEFAULT_API_URL = \"https://api.remix.one\";\nvar DEFAULT_SUPABASE_URL = \"https://iheivdccexqigeoiekvc.supabase.co\";\nvar DEFAULT_SUPABASE_ANON_KEY = \"sb_publishable_YipyrVON-lwzW3ugjE3T1g_cE2do_JW\";\nfunction createDefaultConfigRaw() {\n  return {\n    apiUrl: process.env.REMIX_API_URL ?? DEFAULT_API_URL,\n    supabaseUrl: DEFAULT_SUPABASE_URL,\n    supabaseAnonKey: DEFAULT_SUPABASE_ANON_KEY\n  };\n}\nvar defaultConfigRaw = createDefaultConfigRaw();\nfunction isValidUrl(value) {\n  try {\n    new URL(value);\n    return true;\n  } catch {\n    return false;\n  }\n}\nvar urlSchema = z.string().min(1).transform((s) => s.trim()).refine((s) => isValidUrl(s), \"Invalid URL.\").transform((s) => s.replace(/\\/+$/, \"\"));\nvar configSchema = z.object({\n  apiUrl: urlSchema,\n  supabaseUrl: urlSchema,\n  supabaseAnonKey: z.string().min(1)\n});\nvar cachedConfig = null;\nasync function resolveConfig(_opts) {\n  if (cachedConfig) return cachedConfig;\n  const parsedCfg = configSchema.safeParse(defaultConfigRaw);\n  if (!parsedCfg.success) {\n    throw new RemixError(\"Invalid core configuration.\", {\n      exitCode: 1,\n      hint: parsedCfg.error.issues.map((i) => `${i.path.join(\".\") || \"config\"}: ${i.message}`).join(\"; \")\n    });\n  }\n  cachedConfig = parsedCfg.data;\n  return parsedCfg.data;\n}\n\nexport {\n  configSchema,\n  resolveConfig\n};\n","import {\n  createApiClient,\n  createDefaultRefreshLock,\n  createLocalSessionStore,\n  createRemixAuthHelpers,\n  createStoredSessionTokenProvider,\n  resolveConfig,\n} from \"@remixhq/core\";\nimport type { CollabApiClient } from \"@remixhq/core/collab\";\n\n// Per-request wall-clock budget for every backend call this hook makes.\n//\n// Why 8 seconds: the healthy round-trip for `collabFinalizeTurn`'s API\n// dependencies (resolve-lane, ensure-lane, detect-repo-state, etc.) is\n// ~1–2 s on a healthy backend. 8 s is a 4–8x cushion for transient slow\n// paths (DNS hiccup, momentary backend pressure) without keeping the\n// Stop hook's \"running stop hooks…\" UI blocked for a noticeable freeze\n// when the network actually drops.\n//\n// Failure path on timeout: the Stop hook catches the resulting\n// `TimeoutError` / `AbortError`, classifies it as transient via the\n// `isTransientRecordingFailure` helper, and stashes the prompt + response\n// in the deferred-turn queue. The drainer at the start of the next Stop\n// hook picks it up silently — the user perceives at worst a single\n// 8 s wait instead of the 80 s+ that an unbounded fetch produces when\n// the backend stalls.\nconst HOOK_API_REQUEST_TIMEOUT_MS = 60_000;\n\nexport async function createHookCollabApiClient(): Promise<CollabApiClient> {\n  const config = await resolveConfig();\n  const sessionStore = createLocalSessionStore();\n  const tokenProvider = createStoredSessionTokenProvider({\n    config,\n    sessionStore,\n    refreshStoredSession: async ({ config: refreshConfig, session }) => {\n      const auth = createRemixAuthHelpers(refreshConfig);\n      return auth.refreshWithStoredSession({ session });\n    },\n    withRefreshLock: createDefaultRefreshLock(),\n  });\n  return createApiClient(config, {\n    tokenProvider,\n    defaultRequestTimeoutMs: HOOK_API_REQUEST_TIMEOUT_MS,\n  }) as unknown as CollabApiClient;\n}\n","// Small helpers for spawning detached worker subprocesses from any\n// hook entrypoint. Centralised so UserPromptSubmit and Stop hooks\n// share the same spawn semantics for the deferred-turn drainer.\nimport { spawn } from \"node:child_process\";\n\n// Fire-and-forget detached worker that polls for the branch becoming\n// bound and then drains any deferred turns for `repoRoot`. Spawned at\n// the moment a turn is deferred (so the recovery path is independent\n// of the user sending another prompt) and again on UserPromptSubmit\n// when there are queued records and the branch is now bound (so a\n// freshly-bound branch drains within milliseconds of the next prompt).\n//\n// Single-instance enforcement (PID-aware lockfile) lives inside the\n// drainer entrypoint so duplicate spawns from rapid re-prompts no-op\n// instead of hammering the API.\nexport function spawnDeferredTurnDrainer(repoRoot: string): void {\n  const entrypoint = process.argv[1];\n  if (!entrypoint) return;\n  if (!repoRoot) return;\n  const child = spawn(\n    process.execPath,\n    [...process.execArgv, entrypoint, \"--drain-deferred-turns\", repoRoot],\n    {\n      detached: true,\n      stdio: \"ignore\",\n      env: process.env,\n    },\n  );\n  child.unref();\n}\n","// Classifier for \"did this finalize-turn failure look transient enough to\n// retry on the next prompt?\"\n//\n// Background: the Stop hook's recording call can fail for two very\n// different reasons:\n//\n//   1. *Permanent* failures — structured preflight codes (`not_bound`,\n//      `branch_binding_missing`, `metadata_conflict`, etc.) or 4xx\n//      validation errors. These are the user's fault or our fault, and\n//      retrying without intervention will fail the same way. They get\n//      surfaced via the failure marker + advisory on the next prompt.\n//\n//   2. *Transient* failures — network blips, the recording call hitting\n//      the per-request timeout (`AbortSignal.timeout`), or a 5xx from the\n//      backend (e.g. local backend's undici pool hung after a sleep/wake,\n//      a backing service momentarily unavailable). These are very likely to\n//      succeed on a retry one prompt later, so we silently defer the\n//      turn to the deferred-turn queue and let the in-process drainer\n//      replay it on the next Stop hook.\n//\n// Why this lives in its own module: the classifier is also called from\n// `deferred-turn-drainer.ts` when the drainer's *own* retry attempt\n// fails — keeping the logic in one place means both call-sites agree\n// on what counts as transient, and we can unit-test the classifier\n// without spinning up the rest of the hook flow.\n//\n// The check is intentionally structural — we look at error names and\n// status codes, not message substrings — because message text drifts\n// across Node versions and backend revisions and is the wrong key to\n// hash against. The narrow exception is the `TypeError(\"fetch failed\")`\n// that Node throws for network-level errors before any status code\n// exists; there's no other reliable shape for that one and the message\n// has been stable since `undici` shipped.\n\n/**\n * Returns true when `error` is plausibly the kind of failure that\n * succeeds on a retry without any user action. The caller uses this\n * to decide whether to defer the turn (silent retry) vs. surface the\n * failure marker (manual recovery).\n *\n * Categories detected:\n *   - `AbortError` / `TimeoutError`: our own per-request timeout fired\n *     (`AbortSignal.timeout(ms)`). The DOM spec says timeout aborts use\n *     `TimeoutError`; older Node 18 used `AbortError`. We accept both.\n *   - `TypeError` with message \"fetch failed\": Node's standard wrapping\n *     of any network-level error (`ECONNRESET`, `ECONNREFUSED`,\n *     `ENOTFOUND`, `ETIMEDOUT` from kernel TCP, `UND_ERR_*` from undici).\n *     The actual cause sits in `error.cause`; we don't need to inspect it\n *     to make the transient/permanent decision — the wrapping itself is\n *     a sufficient signal.\n *   - `RemixError` (and any error with a numeric `statusCode`) where\n *     `statusCode >= 500 && statusCode < 600`: server-side errors that\n *     are conventionally retriable (overload, dependency outage, etc.).\n *     4xx is excluded because it indicates a permanent client-side issue\n *     that won't change on retry.\n *\n * Returns false for anything else, including null/undefined/non-error\n * values — when in doubt, be conservative and treat the failure as\n * permanent so the user gets explicit feedback instead of a silent loop.\n */\nexport function isTransientRecordingFailure(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n\n  if (error instanceof Error) {\n    if (error.name === \"AbortError\" || error.name === \"TimeoutError\") return true;\n    if (error instanceof TypeError && /fetch failed/i.test(error.message)) return true;\n  }\n\n  const candidate = error as { statusCode?: unknown };\n  if (typeof candidate.statusCode === \"number\" && candidate.statusCode >= 500 && candidate.statusCode < 600) {\n    return true;\n  }\n\n  return false;\n}\n","// src/history/claudeCodeTranscript.ts\nimport fs from \"fs/promises\";\nasync function readAndParseTranscript(transcriptPath) {\n  let raw;\n  try {\n    raw = await fs.readFile(transcriptPath, \"utf8\");\n  } catch (err) {\n    const code = err && typeof err === \"object\" && \"code\" in err ? err.code : null;\n    if (code === \"ENOENT\") {\n      return { ok: false, reason: \"transcript_not_found\" };\n    }\n    return { ok: false, reason: \"transcript_unreadable\" };\n  }\n  const events = [];\n  for (const line of raw.split(\"\\n\")) {\n    const trimmed = line.trim();\n    if (!trimmed) continue;\n    try {\n      const parsed = JSON.parse(trimmed);\n      if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n        events.push(parsed);\n      }\n    } catch {\n    }\n  }\n  return { ok: true, events };\n}\n\n// src/history/claudeCodeUsageHarvester.ts\nvar HARVESTER_WARNING_CODES = [\n  \"cache_split_unavailable\",\n  \"unknown_server_tool\",\n  \"transcript_truncated\",\n  \"subagent_model_differs\",\n  \"server_tool_count_mismatch\"\n];\nvar BOUNDARY_TIMESTAMP_TOLERANCE_MS = 500;\nfunction parseTimestamp(value) {\n  if (typeof value !== \"string\") return null;\n  const ms = Date.parse(value);\n  return Number.isFinite(ms) ? ms : null;\n}\nfunction extractUserContentText(message) {\n  if (!message || typeof message !== \"object\") return null;\n  const content = message.content;\n  if (typeof content === \"string\") return content;\n  if (Array.isArray(content)) {\n    const textBlocks = content.filter((block) => Boolean(block) && typeof block === \"object\").filter((block) => block.type === \"text\" && typeof block.text === \"string\").map((block) => block.text);\n    if (textBlocks.length === 0) return null;\n    return textBlocks.join(\"\\n\");\n  }\n  return null;\n}\nfunction isUserBoundary(event) {\n  return event.type === \"user\" && event.isMeta !== true && event.isSidechain !== true;\n}\nfunction extractAssistantContentText(turnEvents) {\n  const chunks = [];\n  for (const ev of turnEvents) {\n    if (ev.type !== \"assistant\") continue;\n    const text = extractUserContentText(ev.message);\n    if (text && text.length > 0) chunks.push(text);\n  }\n  if (chunks.length === 0) return null;\n  const deduped = [];\n  for (const chunk of chunks) {\n    if (deduped[deduped.length - 1] !== chunk) deduped.push(chunk);\n  }\n  return deduped.join(\"\\n\");\n}\nfunction findBoundary(sessionEvents, promptText, submittedAt, upperMs) {\n  const isWithinUpperBound = (ev) => {\n    if (upperMs === null) return true;\n    const ms = parseTimestamp(ev.timestamp);\n    return ms !== null && ms < upperMs;\n  };\n  let contentMatch = null;\n  for (let i = sessionEvents.length - 1; i >= 0; i--) {\n    const ev = sessionEvents[i];\n    if (!isUserBoundary(ev)) continue;\n    if (!isWithinUpperBound(ev)) continue;\n    const text = extractUserContentText(ev.message);\n    if (text !== null && text === promptText) {\n      contentMatch = ev;\n      break;\n    }\n  }\n  if (contentMatch) return { boundary: contentMatch, usedFallback: false };\n  const submittedMs = parseTimestamp(submittedAt);\n  if (submittedMs === null) return { boundary: null, usedFallback: false };\n  for (let i = sessionEvents.length - 1; i >= 0; i--) {\n    const ev = sessionEvents[i];\n    if (!isUserBoundary(ev)) continue;\n    if (!isWithinUpperBound(ev)) continue;\n    const ms = parseTimestamp(ev.timestamp);\n    if (ms === null) continue;\n    if (ms >= submittedMs - BOUNDARY_TIMESTAMP_TOLERANCE_MS) {\n      return { boundary: ev, usedFallback: true };\n    }\n  }\n  return { boundary: null, usedFallback: false };\n}\nfunction asNumberOrNull(value) {\n  return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\nfunction asStringOrNull(value) {\n  return typeof value === \"string\" ? value : null;\n}\nfunction extractAssistantMessage(event) {\n  const message = event.message;\n  if (!message || typeof message !== \"object\") return null;\n  const msg = message;\n  if (msg.role !== \"assistant\" && msg.role !== void 0) {\n  }\n  const content = Array.isArray(msg.content) ? msg.content : [];\n  const usage = msg.usage && typeof msg.usage === \"object\" ? msg.usage : null;\n  return {\n    id: asStringOrNull(msg.id),\n    model: asStringOrNull(msg.model),\n    content,\n    usage\n  };\n}\nfunction usageIsComplete(usage) {\n  if (!usage) return false;\n  const hasInput = typeof usage.input_tokens === \"number\";\n  const hasOutput = typeof usage.output_tokens === \"number\";\n  const hasCacheRead = typeof usage.cache_read_input_tokens === \"number\";\n  return hasInput && hasOutput && hasCacheRead;\n}\nfunction buildModelCall(event, msg) {\n  const usage = msg.usage ?? {};\n  const cacheCreation = usage.cache_creation && typeof usage.cache_creation === \"object\" ? usage.cache_creation : null;\n  const has5m = cacheCreation && typeof cacheCreation.ephemeral_5m_input_tokens === \"number\";\n  const has1h = cacheCreation && typeof cacheCreation.ephemeral_1h_input_tokens === \"number\";\n  const cacheWrite5mTokens = has5m ? cacheCreation.ephemeral_5m_input_tokens : null;\n  const cacheWrite1hTokens = has1h ? cacheCreation.ephemeral_1h_input_tokens : null;\n  const splitAvailable = has5m || has1h;\n  const cacheWriteTokens = splitAvailable ? null : asNumberOrNull(usage.cache_creation_input_tokens);\n  return {\n    provider: \"anthropic\",\n    model: msg.model,\n    tier: asStringOrNull(usage.service_tier),\n    requestId: asStringOrNull(event.requestId),\n    timestamp: asStringOrNull(event.timestamp),\n    isSidechain: event.isSidechain === true,\n    inputTokens: asNumberOrNull(usage.input_tokens),\n    outputTokens: asNumberOrNull(usage.output_tokens),\n    cacheReadTokens: asNumberOrNull(usage.cache_read_input_tokens),\n    cacheWriteTokens,\n    cacheWrite5mTokens,\n    cacheWrite1hTokens,\n    reasoningTokens: null,\n    audioInputTokens: null,\n    imageInputTokens: null\n  };\n}\nfunction scanServerToolUses(content) {\n  const uses = [];\n  for (const block of content) {\n    if (!block || typeof block !== \"object\") continue;\n    const b = block;\n    const id = b.id;\n    if (typeof id !== \"string\" || !id.startsWith(\"srvtoolu_\")) continue;\n    const name = typeof b.name === \"string\" ? b.name : \"\";\n    switch (name) {\n      case \"web_search\":\n        uses.push({ tool: \"web_search\", unit: \"per_request\", isKnown: true, id, source: \"direct\" });\n        break;\n      case \"web_fetch\":\n        uses.push({ tool: \"web_fetch\", unit: \"per_request\", isKnown: true, id, source: \"direct\" });\n        break;\n      case \"code_execution\":\n        uses.push({ tool: \"code_execution\", unit: \"invocation\", isKnown: true, id, source: \"direct\" });\n        break;\n      default:\n        uses.push({ tool: name || \"unknown\", unit: \"invocation\", isKnown: false, id, source: \"direct\" });\n        break;\n    }\n  }\n  return uses;\n}\nfunction buildClientToolNameMap(turnEvents) {\n  const map = /* @__PURE__ */ new Map();\n  for (const ev of turnEvents) {\n    if (ev.type !== \"assistant\") continue;\n    const msg = ev.message;\n    if (!msg || typeof msg !== \"object\") continue;\n    const content = msg.content;\n    if (!Array.isArray(content)) continue;\n    for (const block of content) {\n      if (!block || typeof block !== \"object\") continue;\n      const b = block;\n      if (b.type !== \"tool_use\") continue;\n      const id = b.id;\n      const name = b.name;\n      if (typeof id !== \"string\" || typeof name !== \"string\") continue;\n      if (!id.startsWith(\"toolu_\")) continue;\n      map.set(id, name);\n    }\n  }\n  return map;\n}\nfunction scanEmbeddedServerToolUses(turnEvents, clientToolNames) {\n  const uses = [];\n  for (const ev of turnEvents) {\n    if (ev.type !== \"user\") continue;\n    const tur = ev.toolUseResult;\n    if (!tur || typeof tur !== \"object\") continue;\n    const results = tur.results;\n    if (!Array.isArray(results)) continue;\n    let parentToolName = \"\";\n    const userMsg = ev.message;\n    if (userMsg && typeof userMsg === \"object\") {\n      const userContent = userMsg.content;\n      if (Array.isArray(userContent)) {\n        for (const block of userContent) {\n          if (!block || typeof block !== \"object\") continue;\n          const b = block;\n          if (b.type !== \"tool_result\") continue;\n          const parentId = b.tool_use_id;\n          if (typeof parentId === \"string\") {\n            parentToolName = clientToolNames.get(parentId) ?? \"\";\n            break;\n          }\n        }\n      }\n    }\n    for (const entry of results) {\n      if (!entry || typeof entry !== \"object\") continue;\n      const srvId = entry.tool_use_id;\n      if (typeof srvId !== \"string\" || !srvId.startsWith(\"srvtoolu_\")) continue;\n      if (parentToolName === \"WebFetch\") {\n        uses.push({ tool: \"web_fetch\", unit: \"per_request\", isKnown: true, id: srvId, source: \"embedded\" });\n      } else {\n        uses.push({ tool: \"web_search\", unit: \"per_request\", isKnown: true, id: srvId, source: \"embedded\" });\n      }\n    }\n  }\n  return uses;\n}\nfunction dedupeByServerToolId(records) {\n  const seen = /* @__PURE__ */ new Map();\n  for (const r of records) {\n    const existing = seen.get(r.id);\n    if (!existing) {\n      seen.set(r.id, r);\n      continue;\n    }\n    if (existing.source === \"embedded\" && r.source === \"direct\") {\n      seen.set(r.id, r);\n    }\n  }\n  return Array.from(seen.values());\n}\nfunction aggregateServerTools(uses) {\n  const map = /* @__PURE__ */ new Map();\n  let sawUnknown = false;\n  let sawEmbedded = false;\n  for (const use of uses) {\n    if (!use.isKnown) sawUnknown = true;\n    if (use.source === \"embedded\") sawEmbedded = true;\n    const key = `anthropic|${use.tool}|${use.unit}`;\n    const existing = map.get(key);\n    if (existing) {\n      existing.quantity += 1;\n    } else {\n      map.set(key, { provider: \"anthropic\", tool: use.tool, unit: use.unit, quantity: 1 });\n    }\n  }\n  return { serverTools: Array.from(map.values()), sawUnknown, sawEmbedded };\n}\nfunction sumCrossCheckCounts(usageBlocks) {\n  const totals = /* @__PURE__ */ new Map();\n  const keyFor = (raw) => {\n    if (raw === \"web_search_requests\") return \"web_search\";\n    if (raw === \"web_fetch_requests\") return \"web_fetch\";\n    return null;\n  };\n  for (const usage of usageBlocks) {\n    const stu = usage.server_tool_use;\n    if (!stu || typeof stu !== \"object\") continue;\n    for (const [rawKey, rawVal] of Object.entries(stu)) {\n      const mapped = keyFor(rawKey);\n      if (!mapped) continue;\n      if (typeof rawVal !== \"number\" || !Number.isFinite(rawVal)) continue;\n      totals.set(mapped, (totals.get(mapped) ?? 0) + rawVal);\n    }\n  }\n  return totals;\n}\nfunction primaryToolCounts(serverTools) {\n  const map = /* @__PURE__ */ new Map();\n  for (const entry of serverTools) {\n    map.set(entry.tool, (map.get(entry.tool) ?? 0) + entry.quantity);\n  }\n  return map;\n}\nfunction resolveVersion(events) {\n  for (const ev of events) {\n    if (typeof ev.version === \"string\" && ev.version.trim()) return ev.version.trim();\n  }\n  return null;\n}\nfunction buildTurnUsage(args) {\n  const assistantEvents = args.turnEvents.filter((ev) => ev.type === \"assistant\");\n  if (assistantEvents.length === 0) {\n    return { ok: false, reason: \"no_messages_for_turn\" };\n  }\n  const warnings = [...args.initialWarnings];\n  const calls = [];\n  const usageBlocks = [];\n  let anyIncomplete = false;\n  let anyComplete = false;\n  let sawLumpSumFallback = false;\n  const collectedServerToolUses = [];\n  const mainModels = /* @__PURE__ */ new Set();\n  const sidechainModels = /* @__PURE__ */ new Set();\n  for (const ev of assistantEvents) {\n    const msg = extractAssistantMessage(ev);\n    if (!msg) continue;\n    if (usageIsComplete(msg.usage)) {\n      anyComplete = true;\n    } else {\n      anyIncomplete = true;\n    }\n    if (msg.usage) usageBlocks.push(msg.usage);\n    const call = buildModelCall(ev, msg);\n    calls.push(call);\n    if (call.cacheWrite5mTokens === null && call.cacheWrite1hTokens === null && call.cacheWriteTokens !== null) {\n      sawLumpSumFallback = true;\n    }\n    collectedServerToolUses.push(...scanServerToolUses(msg.content));\n    if (call.model) {\n      if (call.isSidechain) sidechainModels.add(call.model);\n      else mainModels.add(call.model);\n    }\n  }\n  if (calls.length === 0) {\n    return { ok: false, reason: \"no_messages_for_turn\" };\n  }\n  if (sawLumpSumFallback) {\n    warnings.push({\n      code: \"cache_split_unavailable\",\n      message: \"Assistant message reported lump-sum cache_creation_input_tokens without the 5m/1h split.\"\n    });\n  }\n  const clientToolNames = buildClientToolNameMap(args.turnEvents);\n  const embeddedUses = scanEmbeddedServerToolUses(args.turnEvents, clientToolNames);\n  const merged = dedupeByServerToolId([...collectedServerToolUses, ...embeddedUses]);\n  const { serverTools, sawUnknown, sawEmbedded } = aggregateServerTools(merged);\n  if (sawUnknown) {\n    warnings.push({\n      code: \"unknown_server_tool\",\n      message: \"Encountered a server tool whose name is not in the known list (web_search, web_fetch, code_execution).\"\n    });\n  }\n  const crossCheck = sumCrossCheckCounts(usageBlocks);\n  const primary = primaryToolCounts(serverTools);\n  const allTools = /* @__PURE__ */ new Set([...crossCheck.keys(), ...primary.keys()]);\n  for (const tool of allTools) {\n    const crossVal = crossCheck.get(tool) ?? 0;\n    const primVal = primary.get(tool) ?? 0;\n    if (crossVal === primVal) continue;\n    if (sawEmbedded && crossVal === 0) continue;\n    warnings.push({\n      code: \"server_tool_count_mismatch\",\n      message: `Server-tool ${tool} count mismatch: srvtoolu_ scan=${primVal}, usage.server_tool_use=${crossVal}. Trusting srvtoolu_ count.`\n    });\n    break;\n  }\n  const subagentMismatch = mainModels.size > 0 && sidechainModels.size > 0 && [...sidechainModels].some((m) => !mainModels.has(m));\n  if (subagentMismatch) {\n    warnings.push({\n      code: \"subagent_model_differs\",\n      message: \"At least one sidechain ModelCall uses a model different from the main-chain model in this turn.\"\n    });\n  }\n  let confidence;\n  if (!anyComplete && anyIncomplete) confidence = \"unknown\";\n  else if (anyIncomplete) confidence = \"partial\";\n  else if (anyComplete) confidence = \"exact\";\n  else confidence = \"unknown\";\n  if (args.checkSubsequentEvent) {\n    const lastAssistantMs = (() => {\n      const msList = assistantEvents.map((ev) => parseTimestamp(ev.timestamp)).filter((ms) => ms !== null);\n      return msList.length ? Math.max(...msList) : null;\n    })();\n    const hasSubsequent = lastAssistantMs !== null && args.sessionEvents.some((ev) => {\n      const ms = parseTimestamp(ev.timestamp);\n      if (ms === null || ms <= lastAssistantMs) return false;\n      if (args.upperMs !== null && ms >= args.upperMs) return false;\n      return true;\n    });\n    if (!hasSubsequent && confidence === \"exact\") {\n      confidence = \"partial\";\n      warnings.push({\n        code: \"transcript_truncated\",\n        message: \"Previous turn has no subsequent event after its last assistant message; transcript may be truncated.\"\n      });\n    }\n  }\n  const resolvedVersion = args.agent.version ?? resolveVersion(args.turnEvents) ?? resolveVersion(args.sessionEvents);\n  const usage = {\n    schemaVersion: 1,\n    capturedAt: args.capturedAt,\n    captureSource: args.captureSource,\n    confidence,\n    agent: {\n      name: args.agent.name,\n      version: resolvedVersion,\n      sessionId: args.agent.sessionId,\n      turnId: args.agent.turnId,\n      plan: args.agent.plan\n    },\n    calls,\n    serverTools,\n    warnings,\n    extensions: args.extensions\n  };\n  return { ok: true, usage };\n}\nfunction harvestClaudeCodeUsage(input) {\n  const sessionEvents = input.events.filter((ev) => ev.sessionId === input.sessionId);\n  const upperMs = input.nextBoundaryAt ? parseTimestamp(input.nextBoundaryAt) : null;\n  const { boundary, usedFallback } = findBoundary(\n    sessionEvents,\n    input.promptText,\n    input.submittedAt,\n    upperMs\n  );\n  if (!boundary) {\n    return { ok: false, reason: \"no_user_boundary_found\" };\n  }\n  const boundaryMs = parseTimestamp(boundary.timestamp);\n  if (boundaryMs === null) {\n    return { ok: false, reason: \"no_user_boundary_found\" };\n  }\n  const turnEvents = sessionEvents.filter((ev) => {\n    const ms = parseTimestamp(ev.timestamp);\n    if (ms === null || ms <= boundaryMs) return false;\n    if (upperMs !== null && ms >= upperMs) return false;\n    return true;\n  });\n  const initialWarnings = [];\n  if (usedFallback) {\n    initialWarnings.push({\n      code: \"transcript_truncated\",\n      message: \"Prompt-text equality match failed; used timestamp-tolerance fallback to locate the user boundary.\"\n    });\n  }\n  const built = buildTurnUsage({\n    sessionEvents,\n    turnEvents,\n    upperMs,\n    initialWarnings,\n    agent: input.agent,\n    capturedAt: input.capturedAt,\n    captureSource: \"hook\",\n    extensions: input.extensions,\n    checkSubsequentEvent: input.checkSubsequentEvent === true\n  });\n  if (!built.ok) return built;\n  return {\n    ok: true,\n    usage: built.usage,\n    boundaryAt: typeof boundary.timestamp === \"string\" ? boundary.timestamp : null\n  };\n}\nfunction sliceTranscriptIntoTurns(input) {\n  const sessionEvents = input.events.filter((ev) => ev.sessionId === input.sessionId);\n  const boundaries = sessionEvents.filter(isUserBoundary);\n  const result = [];\n  for (let i = 0; i < boundaries.length; i++) {\n    const boundary = boundaries[i];\n    const nextBoundary = boundaries[i + 1] ?? null;\n    const boundaryMs = parseTimestamp(boundary.timestamp);\n    if (boundaryMs === null) continue;\n    const occurredAt = asStringOrNull(boundary.timestamp);\n    if (occurredAt === null) continue;\n    const upperMs = nextBoundary ? parseTimestamp(nextBoundary.timestamp) : null;\n    const turnEvents = sessionEvents.filter((ev) => {\n      const ms = parseTimestamp(ev.timestamp);\n      if (ms === null || ms <= boundaryMs) return false;\n      if (upperMs !== null && ms >= upperMs) return false;\n      return true;\n    });\n    const promptId = asStringOrNull(boundary.promptId);\n    const promptText = extractUserContentText(boundary.message);\n    const assistantText = extractAssistantContentText(turnEvents);\n    const gitBranch = asStringOrNull(boundary.gitBranch);\n    const cwd = asStringOrNull(boundary.cwd);\n    const built = buildTurnUsage({\n      sessionEvents,\n      turnEvents,\n      upperMs,\n      initialWarnings: [],\n      agent: {\n        name: \"claude-code\",\n        version: null,\n        sessionId: input.sessionId,\n        turnId: promptId,\n        plan: null\n      },\n      capturedAt: input.capturedAt,\n      captureSource: \"historical_import\",\n      extensions: input.extensions ?? null,\n      checkSubsequentEvent: false\n    });\n    if (!built.ok) continue;\n    result.push({\n      sessionId: input.sessionId,\n      promptId,\n      promptText,\n      assistantText,\n      occurredAt,\n      gitBranch,\n      cwd,\n      usage: built.usage\n    });\n  }\n  return result;\n}\nexport {\n  HARVESTER_WARNING_CODES,\n  harvestClaudeCodeUsage,\n  readAndParseTranscript,\n  sliceTranscriptIntoTurns\n};\n","import { spawnSync } from \"node:child_process\";\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport type ClaudeCodeSessionResolved = {\n  agent: {\n    name: \"claude-code\";\n    sessionId: string | null;\n    plan: string | null;\n  };\n  // Intentionally null. We deliberately do NOT surface email / orgId /\n  // orgName / accountUuid in workspace_metadata: that blob ships to every\n  // collab member who can view the timeline, and PII has no place there.\n  // If richer agent context is ever wanted, it must go through a privacy\n  // review and a separate, admin-only surface — never this field.\n  extensions: null;\n};\n\n// Persistent cache of the resolved plan. Lives at:\n//   ${REMIX_COLLAB_STATE_ROOT:-~/.remix/collab-state}/claude-auth-cache.json\n// Subscription tier doesn't churn on a per-turn basis, so we cache for an\n// hour to avoid spawning `claude` for every Stop hook invocation.\ntype AuthCacheRecord = {\n  schemaVersion: 1;\n  plan: string | null;\n  capturedAt: string;\n  // Tombstone records (plan = null after a failed probe) live for 5 min;\n  // success records live for 1 hour. Storing ttlMs alongside the record\n  // lets the reader honor both without a second config knob.\n  ttlMs: number;\n};\n\nconst CACHE_SCHEMA_VERSION = 1 as const;\nconst SUCCESS_TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FAILURE_TTL_MS = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_SPAWN_TIMEOUT_MS = 5000;\n\n// Per-process memo of the resolved plan so multiple resolve() calls within\n// the same process (e.g. current + previous turn harvest in the same Stop\n// hook) don't re-read the cache file.\nlet inProcessCache: { plan: string | null } | null = null;\n\n// Test-injectable spawner so unit tests can simulate ENOENT / non-zero\n// exit / malformed JSON without actually invoking `claude`. Production\n// callers always go through the default implementation below.\ntype SpawnResult = { stdout: string; status: number; failed: boolean };\nlet spawnerImpl: (timeoutMs: number) => SpawnResult = defaultSpawnClaudeAuthStatus;\n\nfunction defaultSpawnClaudeAuthStatus(timeoutMs: number): SpawnResult {\n  let result: ReturnType<typeof spawnSync>;\n  try {\n    result = spawnSync(\"claude\", [\"auth\", \"status\", \"--json\"], {\n      stdio: [\"ignore\", \"pipe\", \"pipe\"],\n      timeout: timeoutMs,\n      env: process.env,\n    });\n  } catch {\n    return { stdout: \"\", status: -1, failed: true };\n  }\n  if (result.error) {\n    return { stdout: \"\", status: -1, failed: true };\n  }\n  return {\n    stdout: result.stdout?.toString(\"utf8\") ?? \"\",\n    status: result.status ?? -1,\n    failed: false,\n  };\n}\n\nfunction getCollabStateRoot(): string {\n  // Mirrors remix-core's `getCollabStateRoot()` so plugin state lands in\n  // the same directory the rest of the toolchain reads from. Inlined\n  // rather than imported so the plugin doesn't grow a hard dep on a\n  // remix-core path helper for one constant.\n  const configured = process.env.REMIX_COLLAB_STATE_ROOT?.trim();\n  return configured || join(homedir(), \".remix\", \"collab-state\");\n}\n\nfunction getAuthCachePath(): string {\n  return join(getCollabStateRoot(), \"claude-auth-cache.json\");\n}\n\nfunction getSpawnTimeoutMs(): number {\n  const raw = process.env.REMIX_CLAUDE_AUTH_TIMEOUT_MS?.trim();\n  if (!raw) return DEFAULT_SPAWN_TIMEOUT_MS;\n  const parsed = Number.parseInt(raw, 10);\n  if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_SPAWN_TIMEOUT_MS;\n  return parsed;\n}\n\nfunction readAuthCache(): AuthCacheRecord | null {\n  let raw: string;\n  try {\n    raw = readFileSync(getAuthCachePath(), \"utf8\");\n  } catch {\n    return null;\n  }\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(raw);\n  } catch {\n    return null;\n  }\n  if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n  const record = parsed as Record<string, unknown>;\n  if (record.schemaVersion !== CACHE_SCHEMA_VERSION) return null;\n  const planRaw = record.plan;\n  const capturedAtRaw = record.capturedAt;\n  const ttlRaw = record.ttlMs;\n  const plan: string | null =\n    planRaw === null\n      ? null\n      : typeof planRaw === \"string\" && planRaw.trim().length > 0\n        ? planRaw.trim()\n        : null;\n  if (typeof capturedAtRaw !== \"string\") return null;\n  if (typeof ttlRaw !== \"number\" || !Number.isFinite(ttlRaw) || ttlRaw <= 0) return null;\n  return { schemaVersion: CACHE_SCHEMA_VERSION, plan, capturedAt: capturedAtRaw, ttlMs: ttlRaw };\n}\n\nfunction isCacheFresh(record: AuthCacheRecord): boolean {\n  const captured = Date.parse(record.capturedAt);\n  if (!Number.isFinite(captured)) return false;\n  return Date.now() - captured < record.ttlMs;\n}\n\nfunction writeAuthCache(record: AuthCacheRecord): void {\n  const cachePath = getAuthCachePath();\n  try {\n    mkdirSync(dirname(cachePath), { recursive: true });\n    // Write-then-rename to avoid torn reads if two Stop hooks race here.\n    // Last writer wins; since both writers see the same upstream truth,\n    // the resolved plan is identical either way.\n    const tmpPath = `${cachePath}.${process.pid}.${Date.now()}.tmp`;\n    writeFileSync(tmpPath, JSON.stringify(record), \"utf8\");\n    renameSync(tmpPath, cachePath);\n  } catch {\n    // Cache persistence is a perf optimization, not correctness. If we\n    // can't write the file we just lose the optimization; the hook\n    // continues with the in-process cache for this run.\n  }\n}\n\nfunction parseAuthStatusJson(stdout: string): { plan: string | null } {\n  if (!stdout) return { plan: null };\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(stdout);\n  } catch {\n    return { plan: null };\n  }\n  if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return { plan: null };\n  const root = parsed as Record<string, unknown>;\n  // Logged-out accounts and raw-API-key users (no claude.ai auth) won't\n  // have a subscriptionType. Treat both as null and let the dashboard\n  // render \"(unknown)\".\n  if (root.loggedIn === false) return { plan: null };\n  const subscriptionTypeRaw = root.subscriptionType;\n  if (typeof subscriptionTypeRaw !== \"string\") return { plan: null };\n  const plan = subscriptionTypeRaw.trim();\n  return { plan: plan.length > 0 ? plan : null };\n}\n\nfunction probeClaudePlan(): { plan: string | null } {\n  if (inProcessCache) return inProcessCache;\n\n  const cached = readAuthCache();\n  if (cached && isCacheFresh(cached)) {\n    inProcessCache = { plan: cached.plan };\n    return inProcessCache;\n  }\n\n  const result = spawnerImpl(getSpawnTimeoutMs());\n  let probed: { plan: string | null };\n  if (result.failed || result.status !== 0) {\n    probed = { plan: null };\n  } else {\n    probed = parseAuthStatusJson(result.stdout);\n  }\n\n  inProcessCache = probed;\n  writeAuthCache({\n    schemaVersion: CACHE_SCHEMA_VERSION,\n    plan: probed.plan,\n    capturedAt: new Date().toISOString(),\n    ttlMs: probed.plan === null ? FAILURE_TTL_MS : SUCCESS_TTL_MS,\n  });\n  return probed;\n}\n\nexport function resolveClaudeCodeSession(hookPayload: Record<string, unknown>): ClaudeCodeSessionResolved {\n  const sessionIdRaw = hookPayload?.session_id;\n  const sessionId = typeof sessionIdRaw === \"string\" && sessionIdRaw.trim() ? sessionIdRaw.trim() : null;\n  const probe = probeClaudePlan();\n  return {\n    agent: { name: \"claude-code\", sessionId, plan: probe.plan },\n    extensions: null,\n  };\n}\n\n// Test-only helpers. Not exported from the package's public entry;\n// only `claudeCodeSession.test.ts` reaches in via the relative path.\nexport const __testHelpers = {\n  resetInProcessCache(): void {\n    inProcessCache = null;\n  },\n  setSpawner(impl: (timeoutMs: number) => SpawnResult): void {\n    spawnerImpl = impl;\n  },\n  resetSpawner(): void {\n    spawnerImpl = defaultSpawnClaudeAuthStatus;\n  },\n  getAuthCachePath,\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { readCollabBinding } from \"@remixhq/core/binding\";\n\ntype BindingSummary = {\n  repoRoot: string;\n  projectId: string | null;\n  currentAppId: string | null;\n  upstreamAppId: string | null;\n};\n\nexport async function readJsonStdin(): Promise<Record<string, unknown>> {\n  const chunks: Buffer[] = [];\n  for await (const chunk of process.stdin) {\n    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n  }\n  const raw = Buffer.concat(chunks).toString(\"utf8\").trim();\n  if (!raw) return {};\n  try {\n    const parsed = JSON.parse(raw);\n    return parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n  } catch {\n    return {};\n  }\n}\n\nfunction getNestedRecord(value: unknown): Record<string, unknown> | null {\n  return value && typeof value === \"object\" ? (value as Record<string, unknown>) : null;\n}\n\nexport function extractToolInput(payload: Record<string, unknown>): Record<string, unknown> {\n  return getNestedRecord(payload.tool_input) ?? getNestedRecord(payload.toolInput) ?? payload;\n}\n\nexport function extractToolResponse(payload: Record<string, unknown>): Record<string, unknown> | null {\n  return getNestedRecord(payload.tool_response) ?? getNestedRecord(payload.toolResponse);\n}\n\nfunction extractToolStructuredData(payload: Record<string, unknown>): Record<string, unknown> | null {\n  const toolResponse = extractToolResponse(payload);\n  const structuredContent = getNestedRecord(toolResponse?.structuredContent) ?? getNestedRecord(payload.structuredContent);\n  return (\n    getNestedRecord(toolResponse?.data) ??\n    getNestedRecord(structuredContent?.data) ??\n    structuredContent\n  );\n}\n\nexport function extractToolName(payload: Record<string, unknown>): string | null {\n  return extractString(payload, [\"tool_name\", \"toolName\"]);\n}\n\nexport function normalizeHookToolName(toolName: string | null): string | null {\n  if (!toolName) return null;\n  const trimmed = toolName.trim();\n  if (!trimmed) return null;\n\n  const remixToolIndex = trimmed.toLowerCase().indexOf(\"remix_collab_\");\n  if (remixToolIndex >= 0) {\n    return trimmed.slice(remixToolIndex);\n  }\n\n  return trimmed;\n}\n\nexport function extractAssistantResponse(payload: Record<string, unknown>): string | null {\n  const candidateKeys = [\n    \"last_assistant_message\",\n    \"lastAssistantMessage\",\n    \"assistant_response\",\n    \"assistantResponse\",\n    \"assistant_message\",\n    \"assistantMessage\",\n    \"response\",\n    \"message\",\n  ];\n\n  return (\n    extractString(payload, candidateKeys) ??\n    extractString(extractToolResponse(payload) ?? {}, candidateKeys) ??\n    extractString(extractToolStructuredData(payload) ?? {}, candidateKeys) ??\n    extractString(extractToolInput(payload), candidateKeys)\n  );\n}\n\nexport function extractFinalizeTurnMode(payload: Record<string, unknown>): \"changed_turn\" | \"no_diff_turn\" | \"conversation_only\" | null {\n  const mode =\n    extractString(extractToolStructuredData(payload) ?? {}, [\"mode\"]) ??\n    extractString(extractToolResponse(payload) ?? {}, [\"mode\"]) ??\n    extractString(payload, [\"mode\"]);\n  if (mode === \"changed_turn\" || mode === \"no_diff_turn\" || mode === \"conversation_only\") {\n    return mode;\n  }\n  return null;\n}\n\nexport function extractString(input: Record<string, unknown>, keys: string[]): string | null {\n  for (const key of keys) {\n    const value = input[key];\n    if (typeof value === \"string\" && value.trim()) {\n      return value.trim();\n    }\n  }\n  return null;\n}\n\nexport function extractBoolean(input: Record<string, unknown>, keys: string[]): boolean | null {\n  for (const key of keys) {\n    const value = input[key];\n    if (typeof value === \"boolean\") {\n      return value;\n    }\n  }\n  return null;\n}\n\n// Claude Code's CLI populates `cwd` in the hook payload, but the Claude Desktop\n// app omits it even when a project is selected. Fall back to the documented\n// `CLAUDE_PROJECT_DIR` env var (set by Claude Code before spawning the hook),\n// then to the hook process's own working directory as a last resort. This is\n// what allows the Remix plugin to attribute prompts when the desktop app's\n// payload serializer drops the field.\nexport function extractCwd(payload: Record<string, unknown>): string | null {\n  const direct = extractString(payload, [\"cwd\"]);\n  if (direct) return direct;\n  const envCwd = process.env.CLAUDE_PROJECT_DIR?.trim();\n  if (envCwd) return envCwd;\n  const processCwd = process.cwd();\n  return processCwd && processCwd !== \"/\" ? processCwd : null;\n}\n\nexport function extractToolCwd(payload: Record<string, unknown>): string | null {\n  const toolInput = extractToolInput(payload);\n  return extractString(toolInput, [\"cwd\"]) ?? extractCwd(payload);\n}\n\nexport function extractBashCommand(payload: Record<string, unknown>): string | null {\n  const toolInput = extractToolInput(payload);\n  return extractString(toolInput, [\"command\", \"cmd\", \"bash_command\", \"bashCommand\"]);\n}\n\nexport function extractToolErrorMessage(payload: Record<string, unknown>): string | null {\n  const toolResponse = extractToolResponse(payload);\n  const toolError = getNestedRecord(toolResponse?.error) ?? getNestedRecord(payload.error);\n  return (\n    extractString(toolError ?? {}, [\"message\"]) ??\n    extractString(toolResponse ?? {}, [\"errorMessage\", \"message\"]) ??\n    extractString(payload, [\"errorMessage\"])\n  );\n}\n\nfunction extractToolStatus(payload: Record<string, unknown>): string | null {\n  const toolResponse = extractToolResponse(payload);\n  return (\n    extractString(toolResponse ?? {}, [\"status\", \"state\"]) ??\n    extractString(payload, [\"status\", \"state\"])\n  );\n}\n\nexport function didToolSucceed(payload: Record<string, unknown>): boolean {\n  const toolResponse = extractToolResponse(payload);\n  const explicitSuccess = toolResponse ? extractBoolean(toolResponse, [\"success\", \"ok\"]) : null;\n  if (explicitSuccess !== null) {\n    return explicitSuccess;\n  }\n\n  if (extractToolErrorMessage(payload)) {\n    return false;\n  }\n\n  const status = extractToolStatus(payload)?.toLowerCase();\n  if (status === \"error\" || status === \"failed\" || status === \"failure\") {\n    return false;\n  }\n\n  const hookEventName = extractString(payload, [\"hook_event_name\", \"hookEventName\"]);\n  return hookEventName === \"PostToolUse\";\n}\n\nfunction collectStringPathValue(value: unknown): string[] {\n  if (typeof value === \"string\" && value.trim()) return [value.trim()];\n  if (Array.isArray(value)) {\n    return value.flatMap((entry) => collectStringPathValue(entry));\n  }\n  return [];\n}\n\nfunction collectPathTargetsFromObject(input: Record<string, unknown>, keys: string[]): string[] {\n  return keys.flatMap((key) => collectStringPathValue(input[key]));\n}\n\nfunction resolveCandidatePath(targetPath: string, baseDir: string): string {\n  return path.isAbsolute(targetPath) ? path.normalize(targetPath) : path.resolve(baseDir, targetPath);\n}\n\nexport function extractToolPathTargets(payload: Record<string, unknown>, toolName?: string | null): string[] {\n  const name = (toolName ?? extractToolName(payload) ?? \"\").trim().toLowerCase();\n  const toolInput = extractToolInput(payload);\n  const baseDir = extractToolCwd(payload) ?? process.cwd();\n  const baseKeys = [\"path\", \"paths\", \"file_path\", \"filePath\", \"target_file\", \"targetFile\", \"filename\"];\n\n  const targets =\n    name === \"notebookedit\"\n      ? collectPathTargetsFromObject(toolInput, [\"target_notebook\", \"notebook_path\", \"notebookPath\", ...baseKeys])\n      : collectPathTargetsFromObject(toolInput, baseKeys);\n\n  return Array.from(new Set(targets.map((entry) => resolveCandidatePath(entry, baseDir))));\n}\n\nexport async function findBoundRepo(startPath: string | null): Promise<string | null> {\n  if (!startPath) return null;\n  let current = path.resolve(startPath);\n  let stats = await fs.stat(current).catch(() => null);\n  if (stats?.isFile()) {\n    current = path.dirname(current);\n  }\n\n  while (true) {\n    const bindingPath = path.join(current, \".remix\", \"config.json\");\n    const bindingStats = await fs.stat(bindingPath).catch(() => null);\n    if (bindingStats?.isFile()) return current;\n    const parent = path.dirname(current);\n    if (parent === current) return null;\n    current = parent;\n  }\n}\n\nexport async function resolveBoundRepoSummary(startPath: string | null): Promise<BindingSummary | null> {\n  const repoRoot = await findBoundRepo(startPath);\n  if (!repoRoot) return null;\n  const binding = await readCollabBinding(repoRoot).catch(() => null);\n  if (!binding) return null;\n  return {\n    repoRoot,\n    projectId: binding.projectId,\n    currentAppId: binding.currentAppId,\n    upstreamAppId: binding.upstreamAppId,\n  };\n}\n\nexport async function resolveTouchedBoundReposFromPaths(paths: string[]): Promise<BindingSummary[]> {\n  const resolved = await Promise.all(paths.map((targetPath) => resolveBoundRepoSummary(targetPath)));\n  const unique = new Map<string, BindingSummary>();\n  for (const repo of resolved) {\n    if (!repo) continue;\n    unique.set(repo.repoRoot, repo);\n  }\n  return Array.from(unique.values()).sort((a, b) => a.repoRoot.localeCompare(b.repoRoot));\n}\n\nexport async function resolveBoundRepoFromToolCwd(payload: Record<string, unknown>): Promise<BindingSummary | null> {\n  return resolveBoundRepoSummary(extractToolCwd(payload));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,kCAAAA,UAAAC,SAAA;AAAA;AAAA,IAAAA,QAAO,UAAU;AACjB,UAAM,OAAO;AAEb,QAAIC,OAAK,QAAQ,IAAI;AAErB,aAAS,aAAcC,QAAM,SAAS;AACpC,UAAI,UAAU,QAAQ,YAAY,SAChC,QAAQ,UAAU,QAAQ,IAAI;AAEhC,UAAI,CAAC,SAAS;AACZ,eAAO;AAAA,MACT;AAEA,gBAAU,QAAQ,MAAM,GAAG;AAC3B,UAAI,QAAQ,QAAQ,EAAE,MAAM,IAAI;AAC9B,eAAO;AAAA,MACT;AACA,eAASC,KAAI,GAAGA,KAAI,QAAQ,QAAQA,MAAK;AACvC,YAAI,IAAI,QAAQA,EAAC,EAAE,YAAY;AAC/B,YAAI,KAAKD,OAAK,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,MAAM,GAAG;AACnD,iBAAO;AAAA,QACT;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAEA,aAAS,UAAW,MAAMA,QAAM,SAAS;AACvC,UAAI,CAAC,KAAK,eAAe,KAAK,CAAC,KAAK,OAAO,GAAG;AAC5C,eAAO;AAAA,MACT;AACA,aAAO,aAAaA,QAAM,OAAO;AAAA,IACnC;AAEA,aAAS,MAAOA,QAAM,SAAS,IAAI;AACjC,MAAAD,KAAG,KAAKC,QAAM,SAAU,IAAI,MA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,EACH,SAAS,OAAO;AACd,UAAM,UAAU,gBAAgB,KAAK;AACrC,UAAM,uBAAuB,WAAW,EAAE,SAAS,QAAQ,SAAS,MAAM,QAAQ,KAAK,CAAC;AACxF,UAAM,2BAA2B;AAAA,MAC/B;AAAA,MACA;AAAA,MACA,QAAQ,MAAM;AAAA,MACd,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,SAAS,QAAQ;AAAA,MACjB,QAAQ;AAAA,QACN,MAAM,QAAQ;AAAA,QACd,eAAe,QAAQ;AAAA,MACzB;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAEA,eAAe,OAAsB;AAKnC,MAAI,MAAM,oCAAoC,GAAG;AAC/C;AAAA,EACF;AACA,MAAI,QAAQ,KAAK,SAAS,wBAAwB,GAAG;AACnD,UAAM,MAAM,MAAM,0BAA0B;AAC5C,UAAMK,6BACH;AACH,QAAI,OAAOA,+BAA8B,YAAY;AACnD,YAAMA,2BAA0B,EAAE,IAAI,CAAC;AAAA,IACzC;AACA;AAAA,EACF;AACA,QAAM,UAAU,MAAM,cAAc;AACpC,QAAM,kBAAkB,OAAO;AACjC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,OAAK,2BAA2B;AAAA,IAC9B,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR;AAAA,EACF,CAAC;AACD,UAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AACnC,UAAQ,WAAW;AACrB,CAAC;","names":["exports","module","fs","path","i","exports","module","fs","path","u","o","exports","module","fs","path","exports","module","path","i","exports","module","pathKey","platform","exports","module","path","exports","module","exports","module","exports","module","path","exports","module","fs","exports","module","path","exports","module","exports","module","spawn","spawnSync","import_node_child_process","expression","import_node_child_process","process","import_node_util","import_node_process","import_node_util","import_node_process","process","tty","import_node_process","import_node_path","import_node_process","import_node_process","import_node_path","platform","import_node_util","import_node_child_process","import_node_url","execFileCallback","path","process","execPath","path","import_node_os","import_node_os","signals","signals","normalizeSignal","import_promises","import_node_util","isConnected","import_node_events","import_node_events","import_node_events","import_node_events","import_promises","import_promises","import_node_process","import_node_path","path","correctEncoding","import_node_path","import_node_process","path","process","crossSpawn","process","path","import_node_util","import_node_events","import_promises","objectToString","identity","identity","textEncoder","textDecoder","identity","suffix","count","milliseconds","import_node_fs","isReadableStream","isWritableStream","import_node_process","isWritableStream","process","addDefaultValue","import_node_fs","import_node_tty","tty","addProperties","optionName","value","stripFinalNewline","LF","import_node_buffer","import_node_string_decoder","textEncoder","import_node_util","identityGenerator","encoding","generators","import_node_fs","stripFinalNewline","path","import_node_events","import_node_events","import_node_child_process","import_node_process","import_node_events","throwOnDisconnect","import_node_events","process","import_node_child_process","import_node_stream","import_node_fs","import_node_buffer","import_node_stream","addProperties","import_node_events","import_node_stream","import_promises","PassThroughStream","aborted","noop","increment","import_promises","import_node_events","process","global","i","count","a","import_promises","import_node_util","import_promises","import_node_events","import_node_stream","stripFinalNewline","stripFinalNewline","getStreamContents","import_promises","stripFinalNewline","stripFinalNewline","import_node_events","isVerbose","stripFinalNewline","import_node_stream","import_node_util","import_promises","readable","import_node_stream","import_node_util","writable","import_node_stream","import_node_util","duplex","mapArguments","boundOptions","setBoundExeca","sendMessage","getOneMessage","getEachMessage","getCancelSignal","import_promises","import_path","path","fs","path2","fs2","util","objectUtil","i","path","errorUtil","path","handleResult","errorMap","ctx","i","result","issues","a","elements","processed","result","a","r","ZodFirstPartyTypeKind","import_promises","import_path","import_crypto","import_os","import_crypto","import_promises","import_path","import_stream","import_crypto","path","os","path2","fs","a","path3","fs2","createHash2","path4","fs3","randomUUID2","os2","path5","fs4","randomUUID3","createHash3","normalizeBranchName","n","c","path6","fs5","randomUUID4","fs10","randomUUID6","import_node_child_process","import_node_crypto","import_node_fs","import_node_path","import_promises","import_node_path","path","fs","path","import_node_path","import_node_fs","import_node_os","import_node_path","path","os","sha256Hex","path","import_node_crypto","import_promises","import_node_os","import_node_path","import_promises","import_node_path","import_node_crypto","collabFinalizeTurn","stateRoot","path","writeJsonAtomic","fs","sleep","a","fs","writeJsonAtomic","a","path","stateRoot","writeJsonAtomic","fs","a","fs","path","os","fs","path","import_node_child_process","import_node_fs","import_node_os","import_node_path","path","os","a","i","stateRoot","sha256Hex","path","import_promises","import_node_path","stateRoot","path","fs","a","import_promises","import_node_path","import_node_crypto","path","import_promises","import_os","import_path","import_crypto","fs","path","os","sleep","path2","os2","fs2","writeJsonAtomic","a","path3","crypto","i","drainPendingFinalizeQueue","path","fs","sleep","collabFinalizeTurn","i","import_node_child_process","import_promises","fs","i","import_node_child_process","import_node_fs","import_node_os","import_node_path","getCollabStateRoot","import_promises","import_node_path","path","fs","HOOK_ACTOR","sleep","listPendingFinalizeJobs","updatePendingFinalizeJob","collabFinalizeTurn","drainPendingFinalizeQueue"]}