openmeld 0.3.265 → 0.3.267

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/{add-me-membership-C-hYgI77.js → add-me-membership-CVitWAvM.js} +2 -2
  2. package/dist/{add-me-membership-C-hYgI77.js.map → add-me-membership-CVitWAvM.js.map} +1 -1
  3. package/dist/{agents-Md_F3Gra.js → agents-F_iMKQMx.js} +8 -8
  4. package/dist/{agents-Md_F3Gra.js.map → agents-F_iMKQMx.js.map} +1 -1
  5. package/dist/{api-client-foundation-C5ZaSjU1.js → api-client-foundation-BvouKgzy.js} +5 -5
  6. package/dist/{api-client-foundation-C5ZaSjU1.js.map → api-client-foundation-BvouKgzy.js.map} +1 -1
  7. package/dist/{api-client-foundation-BF1pLt74.js → api-client-foundation-IW-NHLFs.js} +1 -1
  8. package/dist/auth-session-CbgSdpUw.js +3 -0
  9. package/dist/{auth-session-CBj_4DTC.js → auth-session-DdKYfcTd.js} +2 -2
  10. package/dist/{auth-session-CBj_4DTC.js.map → auth-session-DdKYfcTd.js.map} +1 -1
  11. package/dist/{channel-CXHi8I41.js → channel-CyxGZZoL.js} +3 -3
  12. package/dist/{channel-CXHi8I41.js.map → channel-CyxGZZoL.js.map} +1 -1
  13. package/dist/{cloud-computer-PyyF6Hyd.js → cloud-computer-bdiIAGMh.js} +4 -4
  14. package/dist/{cloud-computer-PyyF6Hyd.js.map → cloud-computer-bdiIAGMh.js.map} +1 -1
  15. package/dist/{command-BHM28-OM.js → command-DojmfRBr.js} +16 -16
  16. package/dist/{command-BHM28-OM.js.map → command-DojmfRBr.js.map} +1 -1
  17. package/dist/{computer-connection-review-uyI9Yf7d.js → computer-connection-review-CzFi6jR7.js} +4 -4
  18. package/dist/{computer-connection-review-uyI9Yf7d.js.map → computer-connection-review-CzFi6jR7.js.map} +1 -1
  19. package/dist/{computer-disconnect-SxPwgwKA.js → computer-disconnect-Dcyzw5dK.js} +6 -6
  20. package/dist/{computer-disconnect-SxPwgwKA.js.map → computer-disconnect-Dcyzw5dK.js.map} +1 -1
  21. package/dist/{computer-setup-continuation-DWQq1-wU.js → computer-setup-continuation-BZMqpaOJ.js} +3 -3
  22. package/dist/{computer-setup-continuation-DWQq1-wU.js.map → computer-setup-continuation-BZMqpaOJ.js.map} +1 -1
  23. package/dist/{computer-update-wait-aNTYop7y.js → computer-update-wait-CYLkQ0bZ.js} +2 -2
  24. package/dist/{computer-update-wait-aNTYop7y.js.map → computer-update-wait-CYLkQ0bZ.js.map} +1 -1
  25. package/dist/{context-CPcfgM2v.js → context-DZDM_qxZ.js} +5 -5
  26. package/dist/{context-CPcfgM2v.js.map → context-DZDM_qxZ.js.map} +1 -1
  27. package/dist/{daemon-device-id-CWNSDLn0.js → daemon-device-id-inMyF5ja.js} +3 -3
  28. package/dist/{daemon-device-id-CWNSDLn0.js.map → daemon-device-id-inMyF5ja.js.map} +1 -1
  29. package/dist/{daemon-lifecycle-journal-BeR-Ee6p.js → daemon-lifecycle-journal-BH8zeHI4.js} +3 -3
  30. package/dist/{daemon-lifecycle-journal-BeR-Ee6p.js.map → daemon-lifecycle-journal-BH8zeHI4.js.map} +1 -1
  31. package/dist/{daemon-service-runtime-CoGRqEcr.js → daemon-service-runtime-JyvS9oaS.js} +2 -2
  32. package/dist/{daemon-service-runtime-CoGRqEcr.js.map → daemon-service-runtime-JyvS9oaS.js.map} +1 -1
  33. package/dist/{daemon-service-update-coordinator-CeYEqTZJ.js → daemon-service-update-coordinator-OS-U-RHH.js} +12 -12
  34. package/dist/{daemon-service-update-coordinator-CeYEqTZJ.js.map → daemon-service-update-coordinator-OS-U-RHH.js.map} +1 -1
  35. package/dist/{dispatch-owned-runtime-CMfcYCiq.js → dispatch-owned-runtime-CGnMTFSh.js} +11 -11
  36. package/dist/dispatch-owned-runtime-CGnMTFSh.js.map +1 -0
  37. package/dist/dist-BIRxdACi.js +34 -0
  38. package/dist/{dist-C419okuW.js → dist-CLaPWoWc.js} +3 -3
  39. package/dist/dist-CLaPWoWc.js.map +1 -0
  40. package/dist/{dist-BcOBjT4x.js → dist-Cdj9kcbj.js} +2 -2
  41. package/dist/{dist-BcOBjT4x.js.map → dist-Cdj9kcbj.js.map} +1 -1
  42. package/dist/{dist-D0TMjWq1.js → dist-CwcyTyxS.js} +4 -4
  43. package/dist/{dist-D0TMjWq1.js.map → dist-CwcyTyxS.js.map} +1 -1
  44. package/dist/{dist-C0dh3mDJ.js → dist-anHhJ1vT.js} +3 -3
  45. package/dist/{dist-CHI5ut7F.js → dist-gCy54pfG.js} +1 -1
  46. package/dist/{dual-view-guide-catalog-DQQ0POxk.js → dual-view-guide-catalog-DOa4AfY5.js} +3 -3
  47. package/dist/{dual-view-guide-catalog-DQQ0POxk.js.map → dual-view-guide-catalog-DOa4AfY5.js.map} +1 -1
  48. package/dist/{entry-BHFQs9Av.js → entry-LJyrWCwR.js} +7 -7
  49. package/dist/{entry-BHFQs9Av.js.map → entry-LJyrWCwR.js.map} +1 -1
  50. package/dist/{installation-inventory-BnTaYkma.js → installation-inventory-uQok-1rK.js} +3 -3
  51. package/dist/{installation-inventory-BnTaYkma.js.map → installation-inventory-uQok-1rK.js.map} +1 -1
  52. package/dist/{installer-Dg4Te7cR.js → installer-Dq3bNnrN.js} +2 -2
  53. package/dist/{installer-Dg4Te7cR.js.map → installer-Dq3bNnrN.js.map} +1 -1
  54. package/dist/{meta-api-khtBq4Wb.js → meta-api-DKaW4zYC.js} +8 -8
  55. package/dist/{meta-api-khtBq4Wb.js.map → meta-api-DKaW4zYC.js.map} +1 -1
  56. package/dist/{openmeld-Dd7Xf2d9.js → openmeld-Cwv-yfCx.js} +40 -40
  57. package/dist/{openmeld-Dd7Xf2d9.js.map → openmeld-Cwv-yfCx.js.map} +1 -1
  58. package/dist/{openmeld-maintenance-worker-R2jXfotf.js → openmeld-maintenance-worker-BMTMD8SZ.js} +9 -9
  59. package/dist/{openmeld-maintenance-worker-R2jXfotf.js.map → openmeld-maintenance-worker-BMTMD8SZ.js.map} +1 -1
  60. package/dist/openmeld.js +5 -5
  61. package/dist/{prepare-provider-runtime-rTByjw6W.js → prepare-provider-runtime-Yoil0psr.js} +11 -11
  62. package/dist/prepare-provider-runtime-Yoil0psr.js.map +1 -0
  63. package/dist/{prepare-session-executor-1R0oGDG9.js → prepare-session-executor-CPjBJSXD.js} +16 -16
  64. package/dist/{prepare-session-executor-1R0oGDG9.js.map → prepare-session-executor-CPjBJSXD.js.map} +1 -1
  65. package/dist/{process-channel-cCYyQbxG.js → process-channel-BZ3IprPb.js} +2 -2
  66. package/dist/{process-channel-cCYyQbxG.js.map → process-channel-BZ3IprPb.js.map} +1 -1
  67. package/dist/{runtime-Ca-ntwQs.js → runtime-CqGzVm1N.js} +19 -19
  68. package/dist/{runtime-Ca-ntwQs.js.map → runtime-CqGzVm1N.js.map} +1 -1
  69. package/dist/{runtime-agent-controller-reporting-submission-Dtp3kora.js → runtime-agent-controller-reporting-submission-D9pMCHuO.js} +10 -10
  70. package/dist/runtime-agent-controller-reporting-submission-D9pMCHuO.js.map +1 -0
  71. package/dist/{runtime-transport-DZ6xufQ_.js → runtime-transport-CzsmHWDa.js} +2 -2
  72. package/dist/{runtime-transport-DZ6xufQ_.js.map → runtime-transport-CzsmHWDa.js.map} +1 -1
  73. package/dist/{sensitive-operation-credentials-CUDbLNiK.js → sensitive-operation-credentials-CmDLTj46.js} +4 -4
  74. package/dist/{sensitive-operation-credentials-CUDbLNiK.js.map → sensitive-operation-credentials-CmDLTj46.js.map} +1 -1
  75. package/dist/{service-vTpkcASU.js → service-BCeEKP6s.js} +19 -19
  76. package/dist/{service-vTpkcASU.js.map → service-BCeEKP6s.js.map} +1 -1
  77. package/dist/{service-account-authorization-D1BoJBbZ.js → service-account-authorization-4yg8JCS-.js} +2 -2
  78. package/dist/{service-account-authorization-D1BoJBbZ.js.map → service-account-authorization-4yg8JCS-.js.map} +1 -1
  79. package/dist/{service-account-control-Dn0qsjos.js → service-account-control-B7glNprY.js} +8 -8
  80. package/dist/{service-account-control-Dn0qsjos.js.map → service-account-control-B7glNprY.js.map} +1 -1
  81. package/dist/{service-control-capabilities-BS6Nv5h0.js → service-control-capabilities-CgHPIANR.js} +2 -2
  82. package/dist/{service-control-capabilities-BS6Nv5h0.js.map → service-control-capabilities-CgHPIANR.js.map} +1 -1
  83. package/dist/{service-control-capabilities-DvKisnUW.js → service-control-capabilities-D3eSmbYs.js} +1 -1
  84. package/dist/{state-Cp9cnsPW.js → state-BclB40b1.js} +2 -2
  85. package/dist/{state-Cp9cnsPW.js.map → state-BclB40b1.js.map} +1 -1
  86. package/dist/{task-result-6WL2KgsT.js → task-result-Cft38W1I.js} +25 -5
  87. package/dist/task-result-Cft38W1I.js.map +1 -0
  88. package/dist/{updates-api-B9DPJB3W.js → updates-api-muCTUcL0.js} +14 -14
  89. package/dist/{updates-api-B9DPJB3W.js.map → updates-api-muCTUcL0.js.map} +1 -1
  90. package/dist/upgrade-D1mfVr67.js +3 -0
  91. package/dist/{upgrade-DpqDEfNJ.js → upgrade-mGx6_7pJ.js} +6 -6
  92. package/dist/{upgrade-DpqDEfNJ.js.map → upgrade-mGx6_7pJ.js.map} +1 -1
  93. package/dist/windows/openmeld-windows-process.exe +0 -0
  94. package/package.json +15 -15
  95. package/dist/auth-session-ByALWu67.js +0 -3
  96. package/dist/dispatch-owned-runtime-CMfcYCiq.js.map +0 -1
  97. package/dist/dist-C419okuW.js.map +0 -1
  98. package/dist/dist-DoxDNCZs.js +0 -34
  99. package/dist/prepare-provider-runtime-rTByjw6W.js.map +0 -1
  100. package/dist/runtime-agent-controller-reporting-submission-Dtp3kora.js.map +0 -1
  101. package/dist/task-result-6WL2KgsT.js.map +0 -1
  102. package/dist/upgrade-9hoVjYTU.js +0 -3
@@ -1 +1 @@
1
- {"version":3,"file":"dist-BcOBjT4x.js","names":["REQUEST_ENV","normalizeOptionalText","toErrorMessage","normalizeOptionalText","normalizeOptionalText"],"sources":["../../../runtime/adapters/core/dist/dispatch-space-tools.js","../../../runtime/adapters/core/dist/provider-original-error.js","../../../runtime/adapters/core/dist/windows-process-job.js","../../../runtime/adapters/core/dist/agent-controller-process.js","../../../runtime/adapters/core/dist/drivers/cli-driver.js","../../../runtime/adapters/core/dist/launch-contract.js","../../../runtime/adapters/core/dist/acp-process-session.js","../../../runtime/adapters/core/dist/conversation-bridge.js","../../../runtime/adapters/core/dist/dispatch-space-action-mcp.js","../../../runtime/adapters/core/dist/runtime-permission-denial.js","../../../runtime/adapters/core/dist/index.js"],"sourcesContent":["import { toJSONSchema } from \"zod/v4\";\n/** Public definitions only: never serialize handlers or captured Wake authority. */\nexport function describeDispatchSpaceTools(capability) {\n return capability.tools.map((tool) => ({\n name: tool.name,\n title: tool.title ?? tool.name,\n description: tool.description,\n inputSchema: toJSONSchema(tool.inputSchema, {\n target: \"draft-07\",\n io: \"input\",\n }),\n }));\n}\nexport const DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV = \"OPENMELD_SPACE_ACTION_DELIVERY_ONLY\";\nexport function isDispatchSpaceActionDeliveryOnly(env) {\n return env?.[DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV] === \"1\";\n}\n","import { isOriginalErrorSafeForMessageDetails, OPENMELD_ORIGINAL_ERROR_MAX_LENGTH, } from \"@openmeld/schemas\";\nexport function createProviderOriginalError(value) {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n if (normalized.length === 0 ||\n !isOriginalErrorSafeForMessageDetails(normalized)) {\n return null;\n }\n return normalized.slice(0, OPENMELD_ORIGINAL_ERROR_MAX_LENGTH);\n}\n","import { execFile, spawn, } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { win32 } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { windowsNativeProcessRequestSchema } from \"@openmeld/schemas\";\nimport { normalizeCommandEnvironment } from \"./process-environment.js\";\nimport { quoteWindowsProcessArgument, resolveWindowsCommandPath, } from \"./process-launch.js\";\nimport { WINDOWS_NATIVE_PROCESS_REQUEST_ENV as REQUEST_ENV, resolveWindowsNativeProcessHelper, } from \"./windows-native-process.js\";\nimport { readWindowsProcessStartFileTime } from \"./windows-system.js\";\nconst DRAIN_RECEIPT = \"openmeld-windows-job-drained-v1\";\nconst CLEANUP_TIMEOUT_MS = 15_000;\nexport function spawnWindowsJobProcess(input) {\n const env = normalizeCommandEnvironment(input.env, \"win32\");\n const executable = resolveWindowsCommandPath(input.invocation.bin, env);\n if (!(win32.isAbsolute(executable) && win32.isAbsolute(input.cwd))) {\n throw Object.assign(new Error(\"The selected Windows controller needs an absolute executable and working directory.\"), { code: \"ENOENT\" });\n }\n const ownerStartedAt = readWindowsProcessStartFileTime(process.pid);\n if (!ownerStartedAt) {\n throw new Error(\"Windows could not verify the process that owns this invocation.\");\n }\n const jobName = `Local\\\\OpenMeld-Process-${randomUUID()}`;\n const commandLine = [\n quoteWindowsProcessArgument(executable),\n ...input.invocation.args.map((arg) => input.invocation.windowsVerbatimArguments\n ? arg\n : quoteWindowsProcessArgument(arg)),\n ].join(\" \");\n const request = windowsNativeProcessRequestSchema.parse({\n operation: \"launch\",\n jobName,\n executable,\n commandLine,\n workingDirectory: input.cwd,\n ownerPid: process.pid,\n ownerStartedAt,\n });\n const payload = Buffer.from(JSON.stringify(request), \"utf8\").toString(\"base64\");\n if (payload.length > 32_000) {\n throw new Error(\"The Windows controller arguments exceed the native launch envelope. Send large input through stdin instead.\");\n }\n const helper = resolveWindowsNativeProcessHelper();\n const child = spawn(helper, [], {\n cwd: input.cwd,\n env: { ...env, [REQUEST_ENV]: payload },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n const closed = new Promise((resolve) => child.once(\"close\", () => resolve()));\n const terminate = (signal) => {\n // Node retains the native process handle. Never signal a potentially reused\n // PID after exit; closing the supervisor's only Job handle kills descendants.\n if (child.exitCode !== null ||\n child.signalCode !== null ||\n child.pid === undefined) {\n return false;\n }\n return child.kill(signal);\n };\n return {\n child,\n terminate,\n async cleanup() {\n let timer;\n let signalSent = false;\n try {\n signalSent = terminate(\"SIGKILL\");\n await Promise.race([\n closed,\n new Promise((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(\"Windows supervisor exit could not be confirmed.\")), CLEANUP_TIMEOUT_MS);\n }),\n ]);\n // Query only AFTER the supervisor exits, so an absent Job cannot race a\n // delayed creation. A cleanup timeout/error is not a successful stop.\n const drain = windowsNativeProcessRequestSchema.parse({\n operation: \"drain\",\n jobName,\n });\n const { stdout } = await promisify(execFile)(helper, [], {\n env: {\n ...env,\n [REQUEST_ENV]: Buffer.from(JSON.stringify(drain), \"utf8\").toString(\"base64\"),\n },\n encoding: \"utf8\",\n windowsHide: true,\n timeout: CLEANUP_TIMEOUT_MS,\n maxBuffer: 4096,\n });\n if (stdout !== DRAIN_RECEIPT) {\n throw new Error(\"Windows returned an invalid process cleanup receipt.\");\n }\n return { ok: true, signalSent };\n }\n catch (error) {\n return { ok: false, signalSent, error };\n }\n finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n },\n };\n}\n","import { execFile, spawn, } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { normalizeCommandEnvironment } from \"./process-environment.js\";\nimport { resolvePlatformCommand } from \"./process-launch.js\";\nimport { spawnWindowsJobProcess } from \"./windows-process-job.js\";\nconst PROCESS_TABLE_COLUMN_SEPARATOR = /\\s+/u;\nconst PROCESS_TABLE_LINE_SEPARATOR = /\\r?\\n/u;\nconst PROCESS_SUPERVISION_ENV_KEY = \"OPENMELD_PROCESS_SUPERVISION_ID\";\nconst PROCESS_SUPERVISION_DISCOVERY_RETRY_DELAY_MS = 100;\nconst PROCESS_SUPERVISION_DISCOVERY_MAX_ATTEMPTS = 2;\nconst PROCESS_TABLE_STOP_PHASE_SNAPSHOT_MAX_AGE_MS = 75;\nconst PROCESS_DISCOVERY_DIAGNOSTIC_WINDOW_MS = 60_000;\nexport function createAgentControllerProcessTableSnapshotReader(input) {\n if (!(Number.isFinite(input.maxAgeMs) && input.maxAgeMs > 0)) {\n throw new Error(\"process table snapshot max age must be positive\");\n }\n const now = input.now ?? Date.now;\n let snapshot = null;\n return async (options) => {\n const readAtMs = now();\n if (snapshot && !options?.fresh) {\n const ageMs = readAtMs - snapshot.capturedAtMs;\n if (snapshot.pending || (ageMs >= 0 && ageMs < input.maxAgeMs)) {\n return await snapshot.processTable;\n }\n }\n const processTable = input.readProcessTable();\n const currentSnapshot = {\n capturedAtMs: readAtMs,\n pending: true,\n processTable,\n };\n snapshot = currentSnapshot;\n try {\n return await processTable;\n }\n finally {\n currentSnapshot.pending = false;\n }\n };\n}\nexport function createAgentControllerProcessDiscoveryDiagnosticAggregator(input) {\n const now = input?.now ?? Date.now;\n const windowMs = input?.windowMs ?? PROCESS_DISCOVERY_DIAGNOSTIC_WINDOW_MS;\n const write = input?.write ?? ((level, event, payload) => console[level](event, payload));\n const aggregates = new Map();\n return {\n failure: (failure) => {\n const observedAtMs = now();\n const error = normalizeErrorForDiagnostic(failure.error);\n const reasonCode = isProcessDiscoveryTimeoutError(failure.error)\n ? \"process_discovery_timeout\"\n : \"process_discovery_failed\";\n const key = `${failure.source}:${reasonCode}:${error.name}`;\n const aggregate = aggregates.get(key) ?? {\n affectedProcessIds: new Set(),\n error,\n firstAtMs: observedAtMs,\n lastAtMs: observedAtMs,\n lastReportedAtMs: Number.NEGATIVE_INFINITY,\n occurrenceCount: 0,\n reporterError: failure.reporterError\n ? normalizeErrorForDiagnostic(failure.reporterError)\n : null,\n source: failure.source,\n };\n aggregate.affectedProcessIds.add(failure.processId);\n aggregate.error = error;\n aggregate.lastAtMs = observedAtMs;\n aggregate.occurrenceCount += 1;\n aggregates.set(key, aggregate);\n if (observedAtMs - aggregate.lastReportedAtMs < windowMs) {\n return;\n }\n aggregate.lastReportedAtMs = observedAtMs;\n write(\"warn\", \"[openmeld.agent_controller.process_discovery_failed]\", {\n affectedProcessIds: [...aggregate.affectedProcessIds].slice(0, 20),\n durationMs: observedAtMs - aggregate.firstAtMs,\n errorCode: error.code,\n errorMessage: error.message,\n errorName: error.name,\n occurrenceCount: aggregate.occurrenceCount,\n reasonCode,\n ...(aggregate.reporterError\n ? {\n reporterErrorMessage: aggregate.reporterError.message,\n reporterErrorName: aggregate.reporterError.name,\n }\n : {}),\n signal: failure.signal,\n source: failure.source,\n });\n },\n recovered: (source) => {\n const recoveredAtMs = now();\n for (const [key, aggregate] of aggregates) {\n if (aggregate.source !== source) {\n continue;\n }\n write(\"info\", \"[openmeld.agent_controller.process_discovery_recovered]\", {\n affectedProcessIds: [...aggregate.affectedProcessIds].slice(0, 20),\n durationMs: recoveredAtMs - aggregate.firstAtMs,\n occurrenceCount: aggregate.occurrenceCount,\n reasonCode: \"process_discovery_recovered\",\n source,\n });\n aggregates.delete(key);\n }\n },\n };\n}\nfunction isProcessDiscoveryTimeoutError(error) {\n if (!(error instanceof Error)) {\n return false;\n }\n const processError = error;\n return processError.code === \"ETIMEDOUT\" || processError.killed === true;\n}\nconst processDiscoveryDiagnostics = createAgentControllerProcessDiscoveryDiagnosticAggregator();\n// Agent CLI process trees this process launched whose cleanup has not yet\n// completed. A root exit alone does not end a tree: a descendant that kept the\n// process group or supervision marker stays until descendant cleanup finishes.\nconst liveAgentControllerProcesses = new Set();\nconst LIVE_PROCESS_TERM_GRACE_MS = 1000;\nconst LIVE_PROCESS_CLEANUP_TIMEOUT_MS = 3000;\n// Set once shutdown cleanup begins. Background work still running then, such as\n// a controller report moving on to its next probe, must not start a tree that\n// the cleanup has already passed and the process exit would orphan.\nlet agentControllerLaunchesClosed = false;\nfunction trackLiveAgentControllerProcess(spawned) {\n if (spawned.processId === null) {\n return spawned;\n }\n const tracked = {\n ...spawned,\n terminateRemainingDescendants: async () => {\n const result = await spawned.terminateRemainingDescendants();\n if (result.ok) {\n liveAgentControllerProcesses.delete(tracked);\n }\n return result;\n },\n };\n liveAgentControllerProcesses.add(tracked);\n return tracked;\n}\n/**\n * Ends every agent CLI process tree launched by this process whose cleanup has\n * not completed. Only for a process that is ending after its accepted work\n * drained: whatever remains is abandoned background work, such as a controller\n * probe. It first closes further launches, so no tree can start behind it.\n * Roots get SIGTERM and a short grace, then the existing descendant cleanup\n * force-kills what is left; a tree whose cleanup failed is retried. The whole\n * call is bounded so the caller still exits promptly.\n */\nexport async function terminateLiveAgentControllerProcesses(input = {}) {\n agentControllerLaunchesClosed = true;\n const graceMs = input.graceMs ?? LIVE_PROCESS_TERM_GRACE_MS;\n const deadline = Date.now() + graceMs + (input.timeoutMs ?? LIVE_PROCESS_CLEANUP_TIMEOUT_MS);\n let terminated = false;\n while (liveAgentControllerProcesses.size > 0 && Date.now() < deadline) {\n const tracked = [...liveAgentControllerProcesses];\n if (!terminated) {\n terminated = true;\n for (const spawned of tracked) {\n // An exited root's stored group ID may be reused; the descendant\n // cleanup below decides what it may still signal.\n if (hasRootExited(spawned)) {\n continue;\n }\n try {\n spawned.terminate(\"SIGTERM\");\n }\n catch {\n // A tree that exited meanwhile needs no signal; cleanup still runs.\n }\n }\n await settleWithin(Promise.all(tracked.map(waitForRootExit)), Math.min(graceMs, deadline - Date.now()));\n }\n await settleWithin(Promise.allSettled(tracked.map((spawned) => spawned.terminateRemainingDescendants())), deadline - Date.now());\n }\n}\nfunction hasRootExited(spawned) {\n return spawned.child.exitCode !== null || spawned.child.signalCode !== null;\n}\nfunction waitForRootExit(spawned) {\n if (hasRootExited(spawned)) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n spawned.child.once(\"exit\", () => resolve());\n });\n}\nasync function settleWithin(work, timeoutMs) {\n let timer;\n await Promise.race([\n work.catch(() => undefined),\n new Promise((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n}\nexport function spawnAgentControllerProcess(input) {\n if (agentControllerLaunchesClosed) {\n throw new Error(\"Agent CLI launches are closed because this process is shutting down.\");\n }\n const signalTarget = resolveAgentControllerProcessSignalTarget();\n const supervisionId = input.supervisionId ?? randomUUID();\n const env = {\n ...normalizeCommandEnvironment(input.env),\n [PROCESS_SUPERVISION_ENV_KEY]: supervisionId,\n };\n const invocation = resolvePlatformCommand(input.bin, input.args, env);\n if (process.platform === \"win32\") {\n const job = spawnWindowsJobProcess({ invocation, env, cwd: input.cwd });\n return trackLiveAgentControllerProcess({\n child: job.child,\n processId: job.child.pid ?? null,\n signalTarget,\n supervisionId,\n terminate: job.terminate,\n terminateRemainingDescendants: job.cleanup,\n });\n }\n const child = spawn(invocation.bin, invocation.args, {\n cwd: input.cwd,\n detached: signalTarget === \"process_group\",\n env: {\n ...env,\n [PROCESS_SUPERVISION_ENV_KEY]: supervisionId,\n },\n shell: input.shell,\n windowsVerbatimArguments: invocation.windowsVerbatimArguments,\n windowsHide: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n const processId = typeof child.pid === \"number\" ? child.pid : null;\n const trackedDescendantProcessIds = new Set();\n return trackLiveAgentControllerProcess({\n child,\n processId,\n signalTarget,\n supervisionId,\n terminate: (signal) => signalAgentControllerProcessTree({\n processId,\n signal,\n signalTarget,\n trackedDescendantProcessIds,\n }),\n terminateRemainingDescendants: () => terminateRemainingAgentControllerProcesses({\n isRootExited: () => child.exitCode !== null || child.signalCode !== null,\n processId,\n signalTarget,\n supervisionId,\n trackedDescendantProcessIds,\n }),\n });\n}\nexport function resolveAgentControllerProcessSignalTarget(platform = process.platform) {\n return platform === \"win32\" ? \"process\" : \"process_group\";\n}\nexport function resolveAgentControllerProcessSignalId(input) {\n return input.signalTarget === \"process_group\"\n ? -input.processId\n : input.processId;\n}\nexport function signalAgentControllerProcessTree(input) {\n if (input.processId === null) {\n return false;\n }\n if (input.signalTarget === \"process\") {\n return signalProcessId({\n killProcess: input.killProcess,\n processId: input.processId,\n signal: input.signal,\n });\n }\n const trackedDescendantProcessIds = input.trackedDescendantProcessIds ?? new Set();\n let sent = false;\n const signalFailures = [];\n const attemptSignal = (processId) => {\n try {\n sent =\n signalProcessId({\n killProcess: input.killProcess,\n processId,\n signal: input.signal,\n }) || sent;\n }\n catch (error) {\n signalFailures.push(error);\n }\n };\n attemptSignal(resolveAgentControllerProcessSignalId({\n processId: input.processId,\n signalTarget: input.signalTarget,\n }));\n for (const descendantProcessId of trackedDescendantProcessIds) {\n attemptSignal(descendantProcessId);\n }\n if (signalFailures.length > 0) {\n throw signalFailures[0];\n }\n return sent;\n}\nexport function terminateRemainingAgentControllerProcesses(input) {\n return runRemainingAgentControllerProcessCleanup(input);\n}\nasync function runRemainingAgentControllerProcessCleanup(input) {\n let sent = false;\n const trackedDescendantProcessIds = input.trackedDescendantProcessIds ?? new Set();\n for (let attempt = 1; attempt <= PROCESS_SUPERVISION_DISCOVERY_MAX_ATTEMPTS; attempt += 1) {\n let cleanupError = null;\n const groupReused = isReusedExitedRootGroup(input);\n const discovery = await collectSupervisedProcessIds({\n listSupervisedProcessIds: input.listSupervisedProcessIds,\n markerOnly: groupReused,\n processId: input.processId,\n reportDiscoveryFailure: input.reportDiscoveryFailure,\n signalTarget: input.signalTarget,\n supervisionId: input.supervisionId,\n trackedDescendantProcessIds,\n });\n const discoveryError = discovery.error;\n try {\n sent =\n (groupReused\n ? signalCurrentSupervisedProcesses({\n killProcess: input.killProcess,\n processIds: discovery.currentProcessIds,\n })\n : signalAgentControllerProcessTree({\n killProcess: input.killProcess,\n processId: input.processId,\n signal: \"SIGKILL\",\n signalTarget: input.signalTarget,\n trackedDescendantProcessIds,\n })) || sent;\n }\n catch (error) {\n cleanupError = error;\n reportAgentControllerProcessCleanupFailure({\n failure: {\n error,\n processId: input.processId,\n signal: \"SIGKILL\",\n },\n reporter: input.reportCleanupFailure,\n });\n }\n const terminalError = cleanupError ?? discoveryError;\n const reachedFinalAttempt = attempt >= PROCESS_SUPERVISION_DISCOVERY_MAX_ATTEMPTS;\n const cleanupSettled = discoveryError === null && (cleanupError !== null || sent);\n if (reachedFinalAttempt || cleanupSettled) {\n return terminalError === null\n ? { ok: true, signalSent: sent }\n : { error: terminalError, ok: false, signalSent: sent };\n }\n await (input.waitForDiscoveryRetry ?? waitForAgentControllerProcessDiscoveryRetry)();\n }\n return { ok: true, signalSent: sent };\n}\n// A process group ID stays reserved while the group has members, so the\n// exited root's group is still ours unless a live process now holds that PID.\n// In that case the stored group may be someone else's: signal only processes\n// that a fresh marker-only scan finds carrying this invocation's marker.\nfunction isReusedExitedRootGroup(input) {\n if (input.signalTarget !== \"process_group\" ||\n input.processId === null ||\n input.isRootExited?.() !== true) {\n return false;\n }\n try {\n (input.killProcess ?? process.kill)(input.processId, 0);\n return true;\n }\n catch (error) {\n return !isNoSuchProcessError(error);\n }\n}\nfunction signalCurrentSupervisedProcesses(input) {\n let sent = false;\n for (const processId of input.processIds) {\n sent =\n signalProcessId({\n killProcess: input.killProcess,\n processId,\n signal: \"SIGKILL\",\n }) || sent;\n }\n return sent;\n}\nasync function collectSupervisedProcessIds(input) {\n if (input.signalTarget !== \"process_group\" || input.processId === null) {\n return { currentProcessIds: [], error: null };\n }\n const listSupervisedProcessIds = input.listSupervisedProcessIds ?? listAgentControllerSupervisedProcessIds;\n try {\n const supervisedProcessIds = await listSupervisedProcessIds({\n processId: input.markerOnly === true ? null : input.processId,\n supervisionId: input.supervisionId,\n });\n for (const descendantProcessId of supervisedProcessIds) {\n input.trackedDescendantProcessIds.add(descendantProcessId);\n }\n return { currentProcessIds: [...supervisedProcessIds], error: null };\n }\n catch (error) {\n reportAgentControllerProcessDiscoveryFailure({\n failure: {\n error,\n processId: input.processId,\n signal: \"SIGKILL\",\n source: \"supervision_marker\",\n },\n reporter: input.reportDiscoveryFailure,\n });\n return { currentProcessIds: [], error };\n }\n}\nfunction waitForAgentControllerProcessDiscoveryRetry() {\n return new Promise((resolve) => {\n setTimeout(resolve, PROCESS_SUPERVISION_DISCOVERY_RETRY_DELAY_MS);\n });\n}\nexport const listAgentControllerDescendantProcessIds = async (processId) => {\n const processTable = await readProcessTable([\"-axo\", \"pid=,ppid=,pgid=\"], {\n maxBuffer: 4 * 1024 * 1024,\n });\n processDiscoveryDiagnostics.recovered(\"descendant_tree\");\n return resolveAgentControllerDescendantProcessIds({\n processId,\n processTable,\n });\n};\nconst readMacOsSupervisedProcessTable = createAgentControllerProcessTableSnapshotReader({\n // One Service drain can stop several controllers in the same event-loop\n // turn. They need one system snapshot, not one blocking `ps eww` scan per\n // controller. Pending reads stay shared even when slow; settled snapshots\n // expire before the bounded 100 ms retry, which still receives a fresh read.\n maxAgeMs: PROCESS_TABLE_STOP_PHASE_SNAPSHOT_MAX_AGE_MS,\n readProcessTable: async () => await readProcessTable([\"eww\", \"-axo\", \"pid=,ppid=,pgid=,command=\"], {\n maxBuffer: 32 * 1024 * 1024,\n }),\n});\nexport const listAgentControllerSupervisedProcessIds = async (input) => {\n if (process.platform === \"linux\") {\n const processTable = await readProcessTable([\"-e\", \"-o\", \"pid=,ppid=,pgid=\"], { maxBuffer: 4 * 1024 * 1024 });\n processDiscoveryDiagnostics.recovered(\"supervision_marker\");\n return resolveAgentControllerSupervisedProcessIds({\n ...input,\n markedProcessIds: await listLinuxSupervisedProcessIds(input.supervisionId),\n processTable,\n });\n }\n const processTable = await readMacOsSupervisedProcessTable({\n fresh: input.fresh,\n });\n processDiscoveryDiagnostics.recovered(\"supervision_marker\");\n return resolveAgentControllerSupervisedProcessIds({\n ...input,\n processTable,\n });\n};\nexport function resolveAgentControllerSupervisedProcessIds(input) {\n return resolveAgentControllerProcessIdsFromTable({\n ...input,\n supervisionMarker: `${PROCESS_SUPERVISION_ENV_KEY}=${input.supervisionId}`,\n });\n}\nfunction resolveAgentControllerProcessIdsFromTable(input) {\n const childrenByParentProcessId = new Map();\n const processGroupByProcessId = new Map();\n const markedProcessIds = new Set(input.markedProcessIds);\n for (const line of input.processTable.split(PROCESS_TABLE_LINE_SEPARATOR)) {\n const [processIdText, parentProcessIdText, processGroupIdText, ...commandParts] = line.trim().split(PROCESS_TABLE_COLUMN_SEPARATOR);\n const processId = Number.parseInt(processIdText ?? \"\", 10);\n const parentProcessId = Number.parseInt(parentProcessIdText ?? \"\", 10);\n const processGroupId = Number.parseInt(processGroupIdText ?? \"\", 10);\n if (!Number.isInteger(processId) ||\n processId <= 0 ||\n !Number.isInteger(parentProcessId) ||\n parentProcessId < 0 ||\n !Number.isInteger(processGroupId) ||\n processGroupId <= 0) {\n continue;\n }\n const children = childrenByParentProcessId.get(parentProcessId) ?? [];\n children.push(processId);\n childrenByParentProcessId.set(parentProcessId, children);\n processGroupByProcessId.set(processId, processGroupId);\n if (input.supervisionMarker !== undefined &&\n commandParts.includes(input.supervisionMarker)) {\n markedProcessIds.add(processId);\n }\n }\n if (input.processId === null) {\n return [...markedProcessIds];\n }\n return resolveOutOfGroupAgentControllerProcessIds({\n childrenByParentProcessId,\n markedProcessIds,\n processGroupByProcessId,\n processId: input.processId,\n });\n}\nasync function listLinuxSupervisedProcessIds(supervisionId) {\n const supervisionMarker = `${PROCESS_SUPERVISION_ENV_KEY}=${supervisionId}`;\n const processIds = [];\n for (const entry of await readdir(\"/proc\", { withFileTypes: true })) {\n if (!entry.isDirectory()) {\n continue;\n }\n const processId = Number.parseInt(entry.name, 10);\n if (!(Number.isInteger(processId) && String(processId) === entry.name)) {\n continue;\n }\n try {\n const environment = await readFile(`/proc/${entry.name}/environ`, \"utf8\");\n if (environment.split(\"\\0\").includes(supervisionMarker)) {\n processIds.push(processId);\n }\n }\n catch (error) {\n if (!isExpectedLinuxProcessInspectionError(error)) {\n throw error;\n }\n }\n }\n return processIds;\n}\nfunction readProcessTable(args, input) {\n return new Promise((resolve, reject) => {\n execFile(\"ps\", [...args], {\n encoding: \"utf8\",\n maxBuffer: input.maxBuffer,\n timeout: 2000,\n }, (error, stdout) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(stdout);\n });\n });\n}\nfunction isExpectedLinuxProcessInspectionError(error) {\n if (!(error instanceof Error && \"code\" in error)) {\n return false;\n }\n const code = String(error.code);\n return (code === \"EACCES\" ||\n code === \"ENOENT\" ||\n code === \"EPERM\" ||\n code === \"ESRCH\");\n}\nfunction resolveOutOfGroupAgentControllerProcessIds(input) {\n const processIds = new Set();\n const pending = [\n ...(input.childrenByParentProcessId.get(input.processId) ?? []),\n ];\n const visited = new Set([input.processId]);\n while (pending.length > 0) {\n const descendantProcessId = pending.shift();\n if (descendantProcessId === undefined || visited.has(descendantProcessId)) {\n continue;\n }\n visited.add(descendantProcessId);\n if (input.processGroupByProcessId.get(descendantProcessId) !== input.processId) {\n processIds.add(descendantProcessId);\n }\n pending.push(...(input.childrenByParentProcessId.get(descendantProcessId) ?? []));\n }\n for (const markedProcessId of input.markedProcessIds) {\n if (markedProcessId !== input.processId &&\n input.processGroupByProcessId.get(markedProcessId) !== input.processId) {\n processIds.add(markedProcessId);\n }\n }\n return [...processIds];\n}\nexport function resolveAgentControllerDescendantProcessIds(input) {\n return resolveAgentControllerProcessIdsFromTable(input);\n}\nfunction signalProcessId(input) {\n try {\n (input.killProcess ?? process.kill)(input.processId, input.signal);\n return true;\n }\n catch (error) {\n if (isNoSuchProcessError(error) ||\n isUnsignalableExitedProcessGroup(error, input.processId)) {\n return false;\n }\n throw error;\n }\n}\nfunction isUnsignalableExitedProcessGroup(error, processId) {\n // Darwin reports EPERM while an isolated process group contains only its\n // already-exited, not-yet-reaped leader. OpenMeld creates every negative\n // target as a same-user isolated group, so a live member remains signalable.\n return (processId < 0 &&\n error instanceof Error &&\n error.code === \"EPERM\");\n}\nfunction isNoSuchProcessError(error) {\n return (error instanceof Error && error.code === \"ESRCH\");\n}\nfunction reportAgentControllerProcessDiscoveryFailure(input) {\n if (input.reporter) {\n try {\n input.reporter(input.failure);\n return;\n }\n catch (reporterError) {\n reportAgentControllerProcessDiscoveryFailureToConsole({\n ...input.failure,\n reporterError,\n });\n return;\n }\n }\n reportAgentControllerProcessDiscoveryFailureToConsole(input.failure);\n}\nfunction reportAgentControllerProcessCleanupFailure(input) {\n if (input.reporter) {\n try {\n input.reporter(input.failure);\n return;\n }\n catch (reporterError) {\n reportAgentControllerProcessCleanupFailureToConsole({\n ...input.failure,\n reporterError,\n });\n return;\n }\n }\n reportAgentControllerProcessCleanupFailureToConsole(input.failure);\n}\nfunction reportAgentControllerProcessCleanupFailureToConsole(input) {\n const error = normalizeErrorForDiagnostic(input.error);\n const reporterError = input.reporterError\n ? normalizeErrorForDiagnostic(input.reporterError)\n : null;\n console.warn(\"[openmeld.agent_controller.process_cleanup_failed]\", {\n errorCode: error.code,\n errorMessage: error.message,\n errorName: error.name,\n processId: input.processId,\n ...(reporterError\n ? {\n reporterErrorMessage: reporterError.message,\n reporterErrorName: reporterError.name,\n }\n : {}),\n signal: input.signal,\n source: \"remaining_descendants_signal\",\n });\n}\nfunction reportAgentControllerProcessDiscoveryFailureToConsole(input) {\n processDiscoveryDiagnostics.failure(input);\n}\nfunction normalizeErrorForDiagnostic(error) {\n if (error instanceof Error) {\n return {\n code: error.code ?? null,\n message: error.message,\n name: error.name,\n };\n }\n return {\n code: null,\n message: String(error),\n name: \"NonError\",\n };\n}\n","import { spawnAgentControllerProcess } from \"../agent-controller-process.js\";\nconst PROCESS_TIMEOUT_FORCE_KILL_GRACE_MS = 1000;\nexport class CliDriverError extends Error {\n code;\n exitCode;\n signal;\n stderrText;\n stdoutText;\n constructor(input) {\n super(input.message);\n this.code = input.code;\n this.name = \"CliDriverError\";\n this.exitCode = input.exitCode;\n this.signal = input.signal;\n this.stderrText = input.stderrText;\n this.stdoutText = input.stdoutText;\n }\n}\nexport async function runCliDriver(input) {\n const args = [...input.args];\n const timeoutMs = normalizeTimeoutMs(input.timeoutMs);\n const binary = normalizeRequiredText(input.bin, \"bin\");\n const cwd = normalizeRequiredText(input.cwd, \"cwd\");\n return await new Promise((resolve, reject) => {\n const runtimeProcess = spawnAgentControllerProcess({\n args,\n bin: binary,\n cwd,\n env: {\n ...process.env,\n ...(input.env ?? {}),\n },\n shell: input.shell ?? false,\n });\n const { child, processId, signalTarget } = runtimeProcess;\n let settled = false;\n let stdoutText = \"\";\n let stderrText = \"\";\n let stdoutLineBuffer = \"\";\n let stderrLineBuffer = \"\";\n let pendingTimeoutFailure = null;\n const lifecycle = {\n exitCode: null,\n exitObservedAtMs: null,\n exitSignal: null,\n firstStderrAtMs: null,\n firstStdoutAtMs: null,\n processId,\n processSpawnedAtMs: Date.now(),\n stdinClosedAtMs: null,\n timeoutTriggeredAtMs: null,\n };\n const processSpawnedAtMs = Date.now();\n lifecycle.processSpawnedAtMs = processSpawnedAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"process_spawned\",\n processId,\n signalTarget,\n tsMs: processSpawnedAtMs,\n });\n emitProcessControlEvent(input.onProcessControlEvent, {\n phase: \"process_spawned\",\n processId,\n signalTarget,\n });\n const complete = (handler, value) => {\n if (settled) {\n return;\n }\n settled = true;\n handler(value);\n };\n const fail = (error) => {\n if (error instanceof CliDriverError) {\n complete(reject, error);\n return;\n }\n const message = error instanceof Error ? error.message : String(error);\n complete(reject, new CliDriverError({\n code: \"process.spawn_failed\",\n message: `process.spawn_failed: ${message}`,\n }));\n };\n let forceKillTimeout = null;\n let processTimeout = null;\n const clearTimers = () => {\n if (processTimeout !== null) {\n clearTimeout(processTimeout);\n }\n if (forceKillTimeout) {\n clearTimeout(forceKillTimeout);\n }\n };\n const requestProcessTermination = () => {\n runtimeProcess.terminate(\"SIGTERM\");\n forceKillTimeout = setTimeout(() => {\n runtimeProcess.terminate(\"SIGKILL\");\n }, PROCESS_TIMEOUT_FORCE_KILL_GRACE_MS);\n forceKillTimeout.unref?.();\n };\n const completeFromProviderTerminalOutput = (decision) => {\n if (settled || decision.complete !== true) {\n return;\n }\n clearTimers();\n if (decision.terminateProcess !== false) {\n requestProcessTermination();\n }\n complete(resolve, {\n exitCode: lifecycle.exitCode ?? 0,\n lifecycle: {\n ...lifecycle,\n },\n signal: lifecycle.exitSignal,\n stderrText,\n stdoutText,\n });\n };\n const markStdinClosed = () => {\n if (lifecycle.stdinClosedAtMs !== null) {\n return;\n }\n const stdinClosedAtMs = Date.now();\n lifecycle.stdinClosedAtMs = stdinClosedAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"stdin_closed\",\n processId,\n tsMs: stdinClosedAtMs,\n });\n };\n processTimeout =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n const timeoutTriggeredAtMs = Date.now();\n lifecycle.timeoutTriggeredAtMs = timeoutTriggeredAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"timeout_triggered\",\n processId,\n tsMs: timeoutTriggeredAtMs,\n });\n pendingTimeoutFailure = {\n timeoutMs,\n };\n runtimeProcess.terminate(\"SIGTERM\");\n forceKillTimeout = setTimeout(() => {\n runtimeProcess.terminate(\"SIGKILL\");\n }, PROCESS_TIMEOUT_FORCE_KILL_GRACE_MS);\n }, timeoutMs);\n child.on(\"error\", (error) => {\n clearTimers();\n fail(error);\n });\n child.stdin.on(\"error\", (error) => {\n if (isBenignStdinCloseError(error)) {\n markStdinClosed();\n return;\n }\n fail(error);\n });\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n if (settled) {\n return;\n }\n const text = String(chunk);\n if (lifecycle.firstStdoutAtMs === null) {\n const firstStdoutAtMs = Date.now();\n lifecycle.firstStdoutAtMs = firstStdoutAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"first_stdout\",\n processId,\n tsMs: firstStdoutAtMs,\n });\n }\n stdoutText += text;\n const lineEmission = emitLines({\n buffer: stdoutLineBuffer + text,\n onLine: input.onStdoutLine,\n });\n stdoutLineBuffer = lineEmission.buffer;\n if (lineEmission.completionDecision) {\n completeFromProviderTerminalOutput(lineEmission.completionDecision);\n }\n });\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk) => {\n if (settled) {\n return;\n }\n const text = String(chunk);\n if (lifecycle.firstStderrAtMs === null) {\n const firstStderrAtMs = Date.now();\n lifecycle.firstStderrAtMs = firstStderrAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"first_stderr\",\n processId,\n tsMs: firstStderrAtMs,\n });\n }\n stderrText += text;\n const lineEmission = emitLines({\n buffer: stderrLineBuffer + text,\n onLine: input.onStderrLine,\n });\n stderrLineBuffer = lineEmission.buffer;\n if (lineEmission.completionDecision) {\n completeFromProviderTerminalOutput(lineEmission.completionDecision);\n }\n });\n child.on(\"close\", async (exitCode, signal) => {\n await runtimeProcess.terminateRemainingDescendants();\n clearTimers();\n const exitObservedAtMs = Date.now();\n lifecycle.exitCode = exitCode;\n lifecycle.exitSignal = signal;\n lifecycle.exitObservedAtMs = exitObservedAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n exitCode,\n phase: \"process_exit\",\n processId,\n signal,\n signalTarget,\n tsMs: exitObservedAtMs,\n });\n emitProcessControlEvent(input.onProcessControlEvent, {\n phase: \"process_exit\",\n processId,\n signalTarget,\n });\n flushLineBuffer(stdoutLineBuffer, input.onStdoutLine);\n flushLineBuffer(stderrLineBuffer, input.onStderrLine);\n const closeFailure = resolveCliDriverCloseFailure({\n allowNonZeroExit: input.allowNonZeroExit,\n exitCode,\n pendingTimeoutFailure,\n signal,\n stderrText,\n stdoutText,\n });\n if (closeFailure) {\n complete(reject, closeFailure);\n return;\n }\n complete(resolve, {\n exitCode: exitCode ?? 0,\n lifecycle,\n signal,\n stderrText,\n stdoutText,\n });\n });\n child.stdin.end((input.inputText ?? \"\").toString(), () => {\n markStdinClosed();\n });\n });\n}\nconst normalizeTimeoutMs = (value) => {\n if (value === null || typeof value === \"undefined\") {\n return null;\n }\n if (!Number.isInteger(value) || value <= 0) {\n throw new CliDriverError({\n code: \"input.invalid\",\n message: \"input.invalid: timeoutMs must be a positive integer\",\n });\n }\n return value;\n};\nconst resolveCliDriverCloseFailure = (input) => {\n if (input.pendingTimeoutFailure) {\n return new CliDriverError({\n code: \"process.timeout\",\n message: `process.timeout: command exceeded ${String(input.pendingTimeoutFailure.timeoutMs)}ms`,\n exitCode: input.exitCode,\n signal: input.signal,\n stderrText: input.stderrText,\n stdoutText: input.stdoutText,\n });\n }\n if (input.exitCode === 0 || input.allowNonZeroExit === true) {\n return null;\n }\n return new CliDriverError({\n code: \"process.non_zero_exit\",\n message: `process.non_zero_exit: command exited with code ${String(input.exitCode)}${input.signal ? ` (signal=${input.signal})` : \"\"}`,\n exitCode: input.exitCode,\n signal: input.signal,\n stderrText: input.stderrText,\n stdoutText: input.stdoutText,\n });\n};\nconst normalizeRequiredText = (value, field) => {\n const normalized = value.trim();\n if (!normalized) {\n throw new CliDriverError({\n code: \"input.invalid\",\n message: `input.invalid: ${field} is required`,\n });\n }\n return normalized;\n};\nconst isBenignStdinCloseError = (error) => {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = \"code\" in error && typeof error.code === \"string\" ? error.code : null;\n return code === \"EPIPE\" || code === \"ERR_STREAM_DESTROYED\";\n};\nconst emitLines = (input) => {\n const lines = input.buffer.split(\"\\n\");\n const pending = lines.pop() ?? \"\";\n let completionDecision = null;\n for (const line of lines) {\n const decision = input.onLine?.({\n line,\n });\n if (isCliDriverLineDecision(decision) && decision.complete === true) {\n completionDecision = decision;\n }\n }\n return {\n buffer: pending,\n completionDecision,\n };\n};\nconst flushLineBuffer = (lineBuffer, onLine) => {\n if (!lineBuffer) {\n return;\n }\n onLine?.({\n line: lineBuffer,\n });\n};\nconst isCliDriverLineDecision = (value) => typeof value === \"object\" && value !== null;\nconst emitLifecycleEvent = (onLifecycleEvent, event) => {\n onLifecycleEvent?.(event);\n};\nconst emitProcessControlEvent = (onProcessControlEvent, event) => {\n onProcessControlEvent?.(event);\n};\n","import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { accessSync, constants, readFileSync } from \"node:fs\";\nimport { access, open, realpath } from \"node:fs/promises\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { delimiter, dirname, extname, isAbsolute, join } from \"node:path\";\nimport { CliDriverError, runCliDriver } from \"./drivers/cli-driver.js\";\nconst ENV_NODE_SHEBANG = \"#!/usr/bin/env node\";\nconst WINDOWS_PATHEXT = [\".com\", \".exe\", \".bat\", \".cmd\"];\nconst SHEBANG_ARGS_SPLIT_RE = /\\s+/;\nconst FIRST_LINE_SPLIT_RE = /\\r?\\n/u;\nconst LOGIN_SHELL_OUTPUT_LINE_SPLIT_RE = /\\r?\\n/u;\nconst SAFE_POSIX_SHELL_TOKEN_RE = /^[A-Za-z0-9_./:@%+=,-]+$/u;\nconst NVM_VERSION_VALUE_RE = /^v?\\d+(?:\\.\\d+){0,2}$/u;\nconst NODE_VERSION_PATH_RE = /(?:^|\\/)v?(\\d+\\.\\d+\\.\\d+)(?:\\/|$)/u;\nconst MACOS_TEMP_FOLDER_RE = /^\\/var\\/folders\\/[^/]+\\/[^/]+\\/t(?:\\/|$)/u;\nconst WRAPPER_PATH_SEGMENT_RE = /(?:^|[-_.])(?:shim|shims|wrapper|wrappers)(?:$|[-_.])/u;\nconst MAX_LAUNCH_SCRIPT_INSPECTION_BYTES = 64 * 1024;\nconst DEFAULT_LOGIN_SHELL_LOOKUP_TIMEOUT_MS = 1500;\nconst HOME_DIR = normalizeOptionalText(homedir());\nconst TEMP_DIR = normalizeOptionalText(tmpdir());\nconst loginShellExecutablePathsCache = new Map();\nexport function buildExecutableLaunchContract(input) {\n return {\n kind: \"executable\",\n commandPath: input.commandPath,\n ...(input.argsPrefix && input.argsPrefix.length > 0\n ? { argsPrefix: [...input.argsPrefix] }\n : {}),\n };\n}\nexport function materializeCliLaunchCommand(input) {\n if (input.launchContract.kind === \"executable\") {\n const shell = commandPathRequiresShell(input.launchContract.commandPath);\n return {\n argsPrefix: [...(input.launchContract.argsPrefix ?? [])],\n bin: input.launchContract.commandPath,\n ...(shell ? { shell: true } : {}),\n };\n }\n return {\n argsPrefix: [\n input.launchContract.scriptPath,\n ...(input.launchContract.argsPrefix ?? []),\n ],\n bin: input.launchContract.nodePath,\n };\n}\nfunction resolveLaunchContractEntrypointPath(launchContract) {\n return launchContract.kind === \"executable\"\n ? launchContract.commandPath\n : launchContract.scriptPath;\n}\nexport function buildCliLaunchInvocation(input) {\n const launchCommand = materializeCliLaunchCommand({\n launchContract: input.launchContract,\n });\n return {\n args: [...launchCommand.argsPrefix, ...input.args],\n bin: launchCommand.bin,\n ...(launchCommand.shell ? { shell: true } : {}),\n };\n}\nexport async function verifyLaunchContractFiles(input) {\n try {\n const launchCommand = materializeCliLaunchCommand(input);\n if (input.launchContract.kind === \"executable\") {\n await assertExecutablePath(input.launchContract.commandPath);\n }\n else {\n await assertExecutablePath(input.launchContract.nodePath);\n await assertReadablePath(input.launchContract.scriptPath);\n }\n return {\n launchCommand,\n ok: true,\n };\n }\n catch (error) {\n const code = error instanceof Error && \"code\" in error ? error.code : null;\n let failureReason;\n if (code === \"ENOENT\") {\n failureReason = \"installation_missing\";\n }\n else if (code === \"EACCES\" || code === \"EPERM\") {\n failureReason = \"installation_access_denied\";\n }\n return {\n errorMessage: toErrorMessage(error),\n failureKind: \"completed_negative\",\n ...(failureReason ? { failureReason } : {}),\n ok: false,\n };\n }\n}\nexport async function verifyCliLaunchContract(input) {\n const fileCheck = await verifyLaunchContractFiles({\n launchContract: input.launchContract,\n });\n if (!fileCheck.ok) {\n return {\n errorMessage: `${input.displayName} launch contract is broken on this device: ${fileCheck.errorMessage}`,\n failureKind: \"completed_negative\",\n ok: false,\n };\n }\n try {\n const invocation = buildCliLaunchInvocation({\n args: input.probeArgs,\n launchContract: input.launchContract,\n });\n await runCliDriver({\n allowNonZeroExit: false,\n args: invocation.args,\n bin: invocation.bin,\n cwd: input.cwd,\n env: input.env,\n timeoutMs: input.timeoutMs ?? 15_000,\n });\n return fileCheck;\n }\n catch (error) {\n return {\n errorMessage: `${input.displayName} can't start on this device: ${toErrorMessage(error)}`,\n failureKind: classifyLaunchContractVerificationFailure(error),\n ok: false,\n };\n }\n}\nexport async function resolveLaunchCandidatesAfterVerification(input) {\n const outcomes = await Promise.all(input.candidates.map(async (candidate) => ({\n candidate,\n verification: await input.verify(candidate),\n })));\n const verifiedCandidates = outcomes\n .filter(({ verification }) => verification.ok)\n .map(({ candidate }) => candidate);\n if (verifiedCandidates.length > 0) {\n return verifiedCandidates;\n }\n return outcomes\n .filter(({ verification }) => !verification.ok && verification.failureKind === \"incomplete_check\")\n .map(({ candidate }) => candidate);\n}\nfunction classifyLaunchContractVerificationFailure(error) {\n return error instanceof CliDriverError &&\n error.code === \"process.non_zero_exit\" &&\n typeof error.exitCode === \"number\"\n ? \"completed_negative\"\n : \"incomplete_check\";\n}\nexport async function resolveInstalledNodeScriptLaunchContract(input) {\n const candidates = await resolveInstalledNodeScriptLaunchCandidates({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: input.commandName,\n configuredCommand: input.configuredCommand ?? null,\n displayName: input.displayName,\n });\n if (!candidates.ok) {\n return candidates;\n }\n const candidate = candidates.candidates[0] ?? null;\n if (!candidate) {\n return {\n errorMessage: `${input.displayName} is not installed on this device.`,\n ok: false,\n };\n }\n return {\n commandPath: candidate.commandPath,\n launchContract: candidate.launchContract,\n ok: true,\n };\n}\nexport async function resolveInstalledNodeScriptLaunchCandidates(input) {\n const preferredCommandPath = input.preferredLaunchContract\n ? resolveLaunchContractEntrypointPath(input.preferredLaunchContract)\n : null;\n const commandPaths = await resolveInstalledCommandPathsForLaunch({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: input.commandName,\n configuredCommand: input.configuredCommand ?? null,\n preferredCommandPath,\n });\n if (commandPaths.length === 0) {\n return {\n errorMessage: `${input.displayName} is not installed on this device.`,\n reason: \"not_installed\",\n ok: false,\n };\n }\n const candidates = [];\n const candidateIds = new Set();\n const inspectionErrors = [];\n for (const commandPath of commandPaths) {\n const candidate = await inspectInstalledNodeScriptLaunchCandidate({\n commandPath,\n displayName: input.displayName,\n });\n if (!candidate.ok) {\n inspectionErrors.push(candidate.errorMessage);\n continue;\n }\n if (candidateIds.has(candidate.dedupeId)) {\n continue;\n }\n candidateIds.add(candidate.dedupeId);\n candidates.push({\n ...candidate,\n preferred: preferredCommandPath !== null &&\n normalizePathForDetection(commandPath) ===\n normalizePathForDetection(preferredCommandPath),\n });\n }\n if (candidates.length === 0) {\n return {\n errorMessage: inspectionErrors[0] ??\n `${input.displayName} is installed, but OpenMeld could not inspect its launch files.`,\n reason: \"not_launchable\",\n ok: false,\n };\n }\n const stableCandidates = candidates.filter((candidate) => !candidate.transientWrapper);\n // Ignore incidental temporary wrappers once a stable install exists, but\n // never hide the wrapper this computer is already configured to use.\n const selectedCandidates = stableCandidates.length > 0\n ? candidates.filter((candidate) => !candidate.transientWrapper || candidate.preferred)\n : candidates;\n return {\n candidates: finalizeLaunchCandidateDisplayMetadata(selectedCandidates.map((candidate) => candidate.launchCandidate)),\n ok: true,\n };\n}\nasync function inspectInstalledNodeScriptLaunchCandidate(input) {\n try {\n await assertExecutablePath(input.commandPath);\n const resolvedScriptPath = await realpath(input.commandPath);\n const script = await readLaunchScriptInspection(resolvedScriptPath);\n const nodePath = await resolvePinnedNodePath({\n firstLine: script.firstLine,\n commandPath: input.commandPath,\n scriptPath: resolvedScriptPath,\n });\n const transientWrapper = isTransientPathWrapper({\n commandPath: input.commandPath,\n contents: script.contents,\n firstLine: script.firstLine,\n scriptPath: resolvedScriptPath,\n });\n const launchContract = nodePath\n ? {\n kind: \"node_script\",\n nodePath,\n // Keep the user-facing command entrypoint in the launch contract.\n // Managed CLIs such as cursor-agent update this symlink in place;\n // persisting its resolved version file would pin OpenMeld to the old\n // release forever even though the official command has moved on.\n scriptPath: input.commandPath,\n }\n : buildExecutableLaunchContract({\n commandPath: input.commandPath,\n });\n const canonicalLaunchContract = nodePath\n ? {\n kind: \"node_script\",\n nodePath,\n scriptPath: resolvedScriptPath,\n }\n : buildExecutableLaunchContract({\n commandPath: resolvedScriptPath,\n });\n return {\n dedupeId: buildLaunchCandidateInstallId(canonicalLaunchContract),\n launchCandidate: buildLaunchCandidate({\n commandPath: input.commandPath,\n launchContract,\n transientWrapper,\n }),\n ok: true,\n transientWrapper,\n };\n }\n catch (error) {\n return {\n errorMessage: `${input.displayName} is installed, but OpenMeld could not inspect its launch files: ${toErrorMessage(error)}`,\n ok: false,\n };\n }\n}\nexport function resolveInstalledCommandPath(input) {\n return resolveInstalledCommandPaths(input)[0] ?? null;\n}\nexport function resolveInstalledCommandPaths(input) {\n const configuredCommand = normalizeOptionalText(input.configuredCommand);\n if (configuredCommand) {\n if (isAbsolute(configuredCommand)) {\n return [configuredCommand];\n }\n if (configuredCommand.includes(\"/\") || configuredCommand.includes(\"\\\\\")) {\n return [];\n }\n return resolveExecutablePathsOnPath(configuredCommand);\n }\n return resolveExecutablePathsOnPath(input.commandName);\n}\nasync function resolveInstalledCommandPathsForLaunch(input) {\n const preferredCommandPath = normalizeOptionalText(input.preferredCommandPath);\n // A saved install may no longer be reachable through this Service process's\n // PATH. Treat it as one more discovery seed, never as trusted inventory:\n // every returned path is still inspected here and launch-verified by the\n // owning adapter.\n const preferredCommandPaths = preferredCommandPath && isAbsolute(preferredCommandPath)\n ? [preferredCommandPath]\n : [];\n const configuredCommand = normalizeOptionalText(input.configuredCommand);\n if (configuredCommand) {\n if (isAbsolute(configuredCommand)) {\n return mergeUniquePaths(preferredCommandPaths, [configuredCommand]);\n }\n if (configuredCommand.includes(\"/\") || configuredCommand.includes(\"\\\\\")) {\n return preferredCommandPaths;\n }\n return mergeUniquePaths(preferredCommandPaths, await resolveExecutablePathsFromSearchSurface({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: configuredCommand,\n }));\n }\n return mergeUniquePaths(preferredCommandPaths, await resolveExecutablePathsFromSearchSurface({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: input.commandName,\n }));\n}\nexport function resolveExecutableOnPath(commandName) {\n return resolveExecutablePathsOnPath(commandName)[0] ?? null;\n}\nexport function resolveExecutablePathsOnPath(commandName) {\n const normalizedCommandName = normalizeOptionalText(commandName);\n if (!normalizedCommandName) {\n return [];\n }\n const resolvedPaths = [];\n for (const directory of resolvePathDirectories()) {\n for (const candidateName of resolveCommandFileNameCandidates(normalizedCommandName)) {\n const candidate = join(directory, candidateName);\n if (pathLooksExecutable(candidate) &&\n !resolvedPaths.includes(candidate)) {\n resolvedPaths.push(candidate);\n }\n }\n }\n return resolvedPaths;\n}\nasync function resolveExecutablePathsFromSearchSurface(input) {\n const pathMatches = resolveExecutablePathsOnPath(input.commandName);\n const additionalDirectoryMatches = resolveExecutablePathsFromDirectories({\n commandName: input.commandName,\n directories: input.additionalCommandDirectories ?? [],\n });\n const knownInstallMatches = resolveExecutablePathsFromKnownInstallDirectories(input.commandName);\n const localMatches = mergeUniquePaths(mergeUniquePaths(pathMatches, additionalDirectoryMatches), knownInstallMatches);\n if (localMatches.length > 0) {\n return localMatches;\n }\n const loginShellPaths = await resolveExecutablePathsFromLoginShell(input.commandName);\n return mergeUniquePaths(localMatches, loginShellPaths);\n}\nfunction resolvePathDirectories() {\n const directories = [];\n const pathValue = normalizeOptionalText(process.env.PATH);\n for (const pathEntry of pathValue?.split(delimiter) ?? []) {\n addUniqueDirectory(directories, pathEntry);\n }\n return directories;\n}\nfunction resolveExecutablePathsFromKnownInstallDirectories(commandName) {\n return resolveExecutablePathsFromDirectories({\n commandName,\n directories: resolveKnownInstallDirectories(),\n });\n}\nfunction resolveExecutablePathsFromDirectories(input) {\n const normalizedCommandName = normalizeOptionalText(input.commandName);\n if (!normalizedCommandName) {\n return [];\n }\n const resolvedPaths = [];\n for (const directory of input.directories) {\n for (const candidateName of resolveCommandFileNameCandidates(normalizedCommandName)) {\n const candidate = join(directory, candidateName);\n if (pathLooksExecutable(candidate) &&\n !resolvedPaths.includes(candidate)) {\n resolvedPaths.push(candidate);\n }\n }\n }\n return resolvedPaths;\n}\nfunction resolveKnownInstallDirectories() {\n const directories = [];\n if (process.platform === \"win32\") {\n return directories;\n }\n const home = resolveHomeDirectory();\n const nvmDir = normalizeOptionalText(process.env.NVM_DIR) ?? join(home, \".nvm\");\n const pnpmHome = normalizeOptionalText(process.env.PNPM_HOME) ??\n (process.platform === \"darwin\"\n ? join(home, \"Library\", \"pnpm\")\n : join(home, \".local\", \"share\", \"pnpm\"));\n const bunHome = normalizeOptionalText(process.env.BUN_INSTALL) ?? join(home, \".bun\");\n const voltaHome = normalizeOptionalText(process.env.VOLTA_HOME) ?? join(home, \".volta\");\n const asdfHome = normalizeOptionalText(process.env.ASDF_DIR) ?? join(home, \".asdf\");\n const fnmHome = normalizeOptionalText(process.env.FNM_DIR) ?? join(home, \".fnm\");\n addUniqueDirectory(directories, join(home, \".local\", \"bin\"));\n addUniqueDirectory(directories, \"/usr/local/bin\");\n addUniqueDirectory(directories, \"/opt/homebrew/bin\");\n addUniqueDirectory(directories, join(bunHome, \"bin\"));\n addUniqueDirectory(directories, pnpmHome);\n addUniqueDirectory(directories, join(home, \".npm-global\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".yarn\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".config\", \"yarn\", \"global\", \"node_modules\", \".bin\"));\n addUniqueDirectory(directories, join(voltaHome, \"bin\"));\n addUniqueDirectory(directories, join(asdfHome, \"shims\"));\n addUniqueDirectory(directories, join(fnmHome, \"aliases\", \"default\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".local\", \"share\", \"fnm\", \"aliases\", \"default\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".local\", \"share\", \"fnm\", \"current\", \"bin\"));\n for (const nvmBinDir of resolveNvmDefaultBinDirectories(nvmDir)) {\n addUniqueDirectory(directories, nvmBinDir);\n }\n const npmConfigPrefix = normalizeOptionalText(process.env.NPM_CONFIG_PREFIX);\n if (npmConfigPrefix) {\n addUniqueDirectory(directories, join(npmConfigPrefix, \"bin\"));\n }\n return directories;\n}\nfunction addUniqueDirectory(directories, value) {\n const directory = normalizeOptionalText(value);\n if (directory && !directories.includes(directory)) {\n directories.push(directory);\n }\n}\nasync function resolveExecutablePathsFromLoginShell(commandName) {\n const normalizedCommandName = normalizeOptionalText(commandName);\n if (!(normalizedCommandName && process.platform !== \"win32\")) {\n return [];\n }\n const shell = normalizeOptionalText(process.env.SHELL);\n if (!(shell && isAbsolute(shell) && pathLooksExecutable(shell))) {\n return [];\n }\n const cacheKey = [\n shell,\n normalizedCommandName,\n process.env.HOME ?? \"\",\n process.env.PATH ?? \"\",\n ].join(\"\\0\");\n let cached = loginShellExecutablePathsCache.get(cacheKey);\n if (!cached) {\n cached = runLoginShellExecutableLookup({\n commandName: normalizedCommandName,\n shell,\n });\n loginShellExecutablePathsCache.set(cacheKey, cached);\n }\n return await cached;\n}\nasync function runLoginShellExecutableLookup(input) {\n const timeoutMs = resolveLoginShellLookupTimeoutMs();\n return await new Promise((resolve) => {\n const child = spawn(input.shell, [\"-lic\", `command -v ${quotePosixShellToken(input.commandName)}`], {\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n windowsHide: true,\n });\n let stdout = \"\";\n let settled = false;\n const finish = (paths) => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timeout);\n resolve(paths);\n };\n const timeout = setTimeout(() => {\n child.kill();\n finish([]);\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.once(\"error\", () => {\n finish([]);\n });\n child.once(\"close\", (code) => {\n if (code !== 0) {\n finish([]);\n return;\n }\n finish(stdout\n .split(LOGIN_SHELL_OUTPUT_LINE_SPLIT_RE)\n .map((line) => normalizeOptionalText(line))\n .filter((line) => Boolean(line && isAbsolute(line) && pathLooksExecutable(line))));\n });\n });\n}\nfunction resolveNvmDefaultBinDirectories(nvmDir) {\n const version = resolveNvmDefaultVersion(nvmDir);\n if (!version) {\n return [];\n }\n return [join(nvmDir, \"versions\", \"node\", version, \"bin\")];\n}\nfunction resolveNvmDefaultVersion(nvmDir) {\n let value = readNvmAlias(nvmDir, \"default\");\n const seenAliases = new Set();\n for (let depth = 0; depth < 4; depth += 1) {\n const normalizedValue = normalizeOptionalText(value);\n if (!normalizedValue) {\n return null;\n }\n if (isNvmVersionValue(normalizedValue)) {\n return normalizedValue.startsWith(\"v\")\n ? normalizedValue\n : `v${normalizedValue}`;\n }\n if (seenAliases.has(normalizedValue)) {\n return null;\n }\n seenAliases.add(normalizedValue);\n value = readNvmAlias(nvmDir, normalizedValue);\n }\n return null;\n}\nfunction readNvmAlias(nvmDir, alias) {\n try {\n return normalizeOptionalText(readFileSync(join(nvmDir, \"alias\", alias), \"utf8\"));\n }\n catch {\n return null;\n }\n}\nfunction isNvmVersionValue(value) {\n return NVM_VERSION_VALUE_RE.test(value);\n}\nfunction resolveHomeDirectory() {\n return normalizeOptionalText(process.env.HOME) ?? homedir();\n}\nfunction resolveLoginShellLookupTimeoutMs() {\n const raw = normalizeOptionalText(process.env.OPENMELD_EXECUTABLE_LOGIN_SHELL_TIMEOUT_MS);\n if (!raw) {\n return DEFAULT_LOGIN_SHELL_LOOKUP_TIMEOUT_MS;\n }\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0\n ? parsed\n : DEFAULT_LOGIN_SHELL_LOOKUP_TIMEOUT_MS;\n}\nfunction mergeUniquePaths(left, right) {\n const merged = [...left];\n for (const path of right) {\n if (!merged.includes(path)) {\n merged.push(path);\n }\n }\n return merged;\n}\nfunction quotePosixShellToken(value) {\n if (SAFE_POSIX_SHELL_TOKEN_RE.test(value)) {\n return value;\n }\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\nexport function resolveSiblingCommandPath(input) {\n const normalizedCommandName = normalizeOptionalText(input.commandName);\n if (!normalizedCommandName) {\n return null;\n }\n const siblingDirectory = dirname(input.anchorPath);\n for (const candidateName of resolveCommandFileNameCandidates(normalizedCommandName)) {\n const candidate = join(siblingDirectory, candidateName);\n if (pathLooksExecutable(candidate)) {\n return candidate;\n }\n }\n return null;\n}\nasync function resolvePinnedNodePath(input) {\n const firstLine = normalizeOptionalText(input.firstLine);\n if (!firstLine) {\n return null;\n }\n if (firstLine === ENV_NODE_SHEBANG) {\n const nodeSiblings = [\n join(dirname(input.commandPath), \"node\"),\n join(dirname(input.scriptPath), \"node\"),\n ].filter((candidate, index, candidates) => {\n return candidates.indexOf(candidate) === index;\n });\n for (const nodeSibling of nodeSiblings) {\n if (await canAccessExecutablePath(nodeSibling)) {\n return nodeSibling;\n }\n }\n return null;\n }\n if (!firstLine.startsWith(\"#!\")) {\n return null;\n }\n const interpreter = normalizeOptionalText(firstLine.slice(2));\n if (!(interpreter && isAbsolute(interpreter))) {\n return null;\n }\n const normalizedInterpreter = interpreter.split(SHEBANG_ARGS_SPLIT_RE, 1)[0] ?? interpreter;\n try {\n await assertExecutablePath(normalizedInterpreter);\n return normalizedInterpreter;\n }\n catch {\n return null;\n }\n}\nasync function assertExecutablePath(path) {\n await access(path, resolveRunnablePathAccessMode());\n}\nasync function canAccessExecutablePath(path) {\n try {\n await assertExecutablePath(path);\n return true;\n }\n catch {\n return false;\n }\n}\nasync function assertReadablePath(path) {\n await access(path, constants.R_OK);\n}\nfunction pathLooksExecutable(path) {\n try {\n accessSync(path, resolveRunnablePathAccessMode());\n return true;\n }\n catch {\n return false;\n }\n}\nfunction commandPathRequiresShell(commandPath) {\n if (process.platform !== \"win32\") {\n return false;\n }\n const normalizedExtension = extname(commandPath).toLowerCase();\n return normalizedExtension === \".cmd\" || normalizedExtension === \".bat\";\n}\nfunction resolveCommandFileNameCandidates(commandName) {\n if (process.platform !== \"win32\") {\n return [commandName];\n }\n const normalizedExtension = extname(commandName).toLowerCase();\n if (normalizedExtension.length > 0) {\n return [commandName];\n }\n return [\n ...resolveWindowsPathExtensions(process.env.PATHEXT).map((extension) => `${commandName}${extension}`),\n commandName,\n ].filter((candidate, index, candidates) => {\n return candidates.indexOf(candidate) === index;\n });\n}\nfunction resolveRunnablePathAccessMode() {\n return process.platform === \"win32\" ? constants.F_OK : constants.X_OK;\n}\nfunction resolveWindowsPathExtensions(value) {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n return [...WINDOWS_PATHEXT];\n }\n return normalized\n .split(\";\")\n .map((entry) => entry.trim().toLowerCase())\n .filter((entry, index, values) => entry && values.indexOf(entry) === index)\n .map((entry) => (entry.startsWith(\".\") ? entry : `.${entry}`));\n}\nfunction normalizeOptionalText(value) {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\nfunction buildLaunchCandidate(input) {\n const installId = buildLaunchCandidateInstallId(input.launchContract);\n const sourceLabel = input.transientWrapper\n ? \"Temporary wrapper\"\n : resolveLaunchCandidateSourceLabel(input.commandPath);\n const detail = resolveLaunchCandidateDetail({\n commandPath: input.commandPath,\n launchContract: input.launchContract,\n transientWrapper: input.transientWrapper,\n });\n return {\n installId,\n label: sourceLabel,\n detail,\n commandPath: input.commandPath,\n launchContract: input.launchContract,\n };\n}\nfunction buildLaunchCandidateInstallId(launchContract) {\n const canonical = JSON.stringify(canonicalizeLaunchContract(launchContract));\n const digest = createHash(\"sha256\").update(canonical).digest(\"hex\");\n return `install_${digest.slice(0, 12)}`;\n}\nfunction canonicalizeLaunchContract(launchContract) {\n if (launchContract.kind === \"executable\") {\n return {\n kind: launchContract.kind,\n commandPath: launchContract.commandPath,\n argsPrefix: [...(launchContract.argsPrefix ?? [])],\n };\n }\n return {\n kind: launchContract.kind,\n nodePath: launchContract.nodePath,\n scriptPath: launchContract.scriptPath,\n argsPrefix: [...(launchContract.argsPrefix ?? [])],\n };\n}\nfunction finalizeLaunchCandidateDisplayMetadata(candidates) {\n const candidateIndexesByLabel = new Map();\n for (const [index, candidate] of candidates.entries()) {\n const currentIndexes = candidateIndexesByLabel.get(candidate.label) ?? [];\n currentIndexes.push(index);\n candidateIndexesByLabel.set(candidate.label, currentIndexes);\n }\n const nextCandidates = candidates.map((candidate) => ({ ...candidate }));\n for (const indexes of candidateIndexesByLabel.values()) {\n if (indexes.length < 2) {\n continue;\n }\n const duplicateCandidates = indexes\n .map((index) => nextCandidates[index])\n .filter((candidate) => Boolean(candidate));\n const labelSuffixes = resolveDistinctLaunchCandidateLabelSuffixes(duplicateCandidates);\n for (const [offset, index] of indexes.entries()) {\n const suffix = labelSuffixes[offset];\n if (!suffix) {\n continue;\n }\n const currentCandidate = nextCandidates[index];\n if (!currentCandidate) {\n continue;\n }\n currentCandidate.label = `${currentCandidate.label} (${suffix})`;\n }\n }\n return nextCandidates;\n}\nfunction resolveDistinctLaunchCandidateLabelSuffixes(candidates) {\n const directoryLabels = candidates.map((candidate) => resolveLaunchCandidateDirectoryLabel(candidate.commandPath));\n if (hasOnlyDistinctValues(directoryLabels)) {\n return directoryLabels;\n }\n const commandLabels = candidates.map((candidate) => shortenPathForDisplay(candidate.commandPath));\n if (hasOnlyDistinctValues(commandLabels)) {\n return commandLabels;\n }\n return candidates.map((candidate) => candidate.installId);\n}\nfunction hasOnlyDistinctValues(values) {\n return values.length === new Set(values).size;\n}\nfunction resolveLaunchCandidateSourceLabel(commandPath) {\n const normalizedPath = commandPath.toLowerCase();\n if (normalizedPath.includes(\".app/contents/\")) {\n return \"App install\";\n }\n if (normalizedPath.includes(\"/.nvm/\")) {\n return \"nvm install\";\n }\n if (normalizedPath.includes(\"/opt/homebrew/\") ||\n normalizedPath.includes(\"/cellar/\") ||\n normalizedPath.includes(\"/homebrew/\")) {\n return \"Homebrew install\";\n }\n if (normalizedPath.includes(\"/.asdf/\")) {\n return \"asdf install\";\n }\n if (normalizedPath.includes(\"/.volta/\")) {\n return \"Volta install\";\n }\n if (normalizedPath.includes(\"/.fnm/\")) {\n return \"fnm install\";\n }\n if (normalizedPath.includes(\"/.local/bin/\")) {\n return \"User install\";\n }\n if (normalizedPath.includes(\"/usr/local/bin/\")) {\n return \"System-wide install\";\n }\n if (normalizedPath.startsWith(\"/usr/bin/\") ||\n normalizedPath.startsWith(\"/bin/\")) {\n return \"System install\";\n }\n return \"Other install\";\n}\nfunction resolveLaunchCandidateDetail(input) {\n const nodeVersion = input.launchContract.kind === \"node_script\"\n ? resolveNodeVersionFromPath(input.launchContract.nodePath)\n : null;\n const commandDirectory = resolveLaunchCandidateDirectoryLabel(input.commandPath);\n if (input.transientWrapper) {\n return `Temporary PATH wrapper · ${commandDirectory}`;\n }\n if (nodeVersion) {\n return `Node ${nodeVersion} · ${commandDirectory}`;\n }\n return commandDirectory;\n}\nfunction resolveLaunchCandidateDirectoryLabel(commandPath) {\n return shortenPathForDisplay(dirname(commandPath));\n}\nfunction shortenPathForDisplay(path) {\n if (!(HOME_DIR && path.startsWith(HOME_DIR))) {\n return path;\n }\n if (path === HOME_DIR) {\n return \"~\";\n }\n return `~${path.slice(HOME_DIR.length)}`;\n}\nfunction resolveNodeVersionFromPath(path) {\n const match = path.match(NODE_VERSION_PATH_RE);\n return normalizeOptionalText(match?.[1]);\n}\nasync function readLaunchScriptInspection(path) {\n const file = await open(path, \"r\");\n let contents = \"\";\n try {\n const buffer = Buffer.allocUnsafe(MAX_LAUNCH_SCRIPT_INSPECTION_BYTES);\n const { bytesRead } = await file.read(buffer, 0, MAX_LAUNCH_SCRIPT_INSPECTION_BYTES, 0);\n contents = buffer.toString(\"utf8\", 0, bytesRead);\n }\n finally {\n await file.close();\n }\n const firstLine = contents.split(FIRST_LINE_SPLIT_RE, 1)[0] ?? \"\";\n return {\n contents,\n firstLine: normalizeOptionalText(firstLine),\n };\n}\nfunction isTransientPathWrapper(input) {\n if (!(isInsideTemporaryDirectory(input.commandPath) ||\n isInsideTemporaryDirectory(input.scriptPath))) {\n return false;\n }\n return (hasWrapperPathSegment(input.commandPath) ||\n hasWrapperPathSegment(input.scriptPath) ||\n shellScriptLooksLikeWrapper(input));\n}\nfunction isInsideTemporaryDirectory(path) {\n const normalizedPath = normalizePathForDetection(path);\n const normalizedTempDir = TEMP_DIR\n ? normalizePathForDetection(TEMP_DIR)\n : null;\n if (normalizedTempDir &&\n pathIsEqualOrDescendant(normalizedPath, normalizedTempDir)) {\n return true;\n }\n return (pathIsEqualOrDescendant(normalizedPath, \"/tmp\") ||\n pathIsEqualOrDescendant(normalizedPath, \"/private/tmp\") ||\n MACOS_TEMP_FOLDER_RE.test(normalizedPath));\n}\nfunction hasWrapperPathSegment(path) {\n return normalizePathForDetection(path)\n .split(\"/\")\n .filter((segment) => segment.length > 0)\n .slice(-4)\n .some((segment) => WRAPPER_PATH_SEGMENT_RE.test(segment));\n}\nfunction shellScriptLooksLikeWrapper(input) {\n const firstLine = normalizeOptionalText(input.firstLine)?.toLowerCase() ?? \"\";\n if (!(firstLine.includes(\"bash\") ||\n firstLine.includes(\"/sh\") ||\n firstLine.includes(\"zsh\"))) {\n return false;\n }\n const contents = input.contents.toLowerCase();\n return (contents.includes(\"wrapper_shim\") ||\n contents.includes(\"shim_root\") ||\n (contents.includes(\"\\nexec \") &&\n (contents.includes(\"wrapper\") || contents.includes(\"shim\"))));\n}\nfunction normalizePathForDetection(path) {\n return path.replaceAll(\"\\\\\", \"/\").replace(/\\/+/gu, \"/\").toLowerCase();\n}\nfunction pathIsEqualOrDescendant(path, parentPath) {\n return path === parentPath || path.startsWith(`${parentPath}/`);\n}\nfunction toErrorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\n","import { spawnAgentControllerProcess, } from \"./agent-controller-process.js\";\nimport { buildCliLaunchInvocation } from \"./launch-contract.js\";\nconst ACP_PROCESS_KILL_GRACE_MS = 1000;\nconst MAX_STDERR_CHARS = 16_000;\nexport class AcpProcessSession {\n #args;\n #createError;\n #cwd;\n #env;\n #launchContract;\n #mapJsonRpcError;\n #onClientRequest;\n #onLifecycleEvent;\n #onNotification;\n #consumeNonProtocolLine;\n #onProcessControlEvent;\n #pending = new Map();\n #processLabel;\n #timeoutMs;\n #child = null;\n #cleanupPromise = null;\n #forceKillTimeout = null;\n #lifecycle = {\n exitCode: null,\n exitObservedAtMs: null,\n exitSignal: null,\n firstStderrAtMs: null,\n firstStdoutAtMs: null,\n processId: null,\n processSpawnedAtMs: null,\n stdinClosedAtMs: null,\n timeoutTriggeredAtMs: null,\n };\n #lineBuffer = \"\";\n #nextRequestId = 1;\n #processTimeout = null;\n #runtimeProcess = null;\n #settledFailure = null;\n #stderr = \"\";\n #stderrLineBuffer = \"\";\n constructor(input) {\n this.#args = input.args;\n this.#createError = input.createError;\n this.#cwd = input.cwd;\n this.#env = input.env;\n this.#launchContract = input.launchContract;\n this.#mapJsonRpcError = input.mapJsonRpcError;\n this.#onClientRequest = input.onClientRequest;\n this.#onLifecycleEvent = input.onLifecycleEvent;\n this.#onNotification = input.onNotification;\n this.#consumeNonProtocolLine = input.consumeNonProtocolLine;\n this.#onProcessControlEvent = input.onProcessControlEvent;\n this.#processLabel = input.processLabel;\n this.#timeoutMs = input.timeoutMs;\n }\n start() {\n if (this.#child) {\n throw this.#error({\n code: \"protocol.invalid\",\n errorType: \"adapter\",\n message: `protocol.invalid: ${this.#processLabel} ACP process has already started`,\n });\n }\n const invocation = buildCliLaunchInvocation({\n args: [...this.#args],\n launchContract: this.#launchContract,\n });\n const runtimeProcess = spawnAgentControllerProcess({\n args: invocation.args,\n bin: invocation.bin,\n cwd: this.#cwd,\n env: {\n ...process.env,\n ...(this.#env ?? {}),\n },\n shell: invocation.shell ?? false,\n });\n const { child, processId, signalTarget } = runtimeProcess;\n this.#child = child;\n this.#runtimeProcess = runtimeProcess;\n const processSpawnedAtMs = Date.now();\n this.#lifecycle.processId = processId;\n this.#lifecycle.processSpawnedAtMs = processSpawnedAtMs;\n this.#onLifecycleEvent?.({\n phase: \"process_spawned\",\n processId,\n signalTarget,\n tsMs: processSpawnedAtMs,\n });\n this.#onProcessControlEvent?.({\n phase: \"process_spawned\",\n processId,\n signalTarget,\n });\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n if (this.#lifecycle.firstStdoutAtMs === null) {\n const firstStdoutAtMs = Date.now();\n this.#lifecycle.firstStdoutAtMs = firstStdoutAtMs;\n this.#onLifecycleEvent?.({\n phase: \"first_stdout\",\n processId,\n tsMs: firstStdoutAtMs,\n });\n }\n this.#consumeStdoutText(String(chunk));\n });\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk) => {\n if (this.#lifecycle.firstStderrAtMs === null) {\n const firstStderrAtMs = Date.now();\n this.#lifecycle.firstStderrAtMs = firstStderrAtMs;\n this.#onLifecycleEvent?.({\n phase: \"first_stderr\",\n processId,\n tsMs: firstStderrAtMs,\n });\n }\n if (this.#consumeNonProtocolLine) {\n this.#stderrLineBuffer += String(chunk);\n let newline = this.#stderrLineBuffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = this.#stderrLineBuffer.slice(0, newline).trim();\n this.#stderrLineBuffer = this.#stderrLineBuffer.slice(newline + 1);\n try {\n if (!this.#consumeNonProtocolLine(line)) {\n this.#stderr = `${this.#stderr}${line}\\n`.slice(-MAX_STDERR_CHARS);\n }\n }\n catch (error) {\n this.#failAll(error);\n }\n newline = this.#stderrLineBuffer.indexOf(\"\\n\");\n }\n this.#stderrLineBuffer = this.#stderrLineBuffer.slice(-MAX_STDERR_CHARS);\n }\n else {\n this.#stderr = `${this.#stderr}${String(chunk)}`.slice(-MAX_STDERR_CHARS);\n }\n });\n child.stdin.on(\"error\", (error) => {\n this.#failAll(this.#buildStdinWriteError(error));\n });\n child.on(\"error\", (error) => {\n this.#failAll(this.#error({\n cause: error,\n code: \"upstream_unreachable\",\n errorType: \"adapter\",\n message: `upstream_unreachable: failed to spawn ${this.#processLabel} ACP (${error.message})`,\n }));\n });\n child.on(\"close\", (exitCode, signal) => {\n this.#ensureRemainingDescendantsCleanup();\n this.#clearTimers();\n this.#lifecycle.exitCode = exitCode;\n this.#lifecycle.exitObservedAtMs = Date.now();\n this.#lifecycle.exitSignal = signal;\n this.#onLifecycleEvent?.({\n exitCode,\n phase: \"process_exit\",\n processId,\n signal,\n signalTarget,\n tsMs: this.#lifecycle.exitObservedAtMs,\n });\n this.#onProcessControlEvent?.({\n phase: \"process_exit\",\n processId,\n signalTarget,\n });\n if (this.#pending.size > 0) {\n this.#failAll(this.#error({\n code: \"upstream_unreachable\",\n errorType: \"adapter\",\n message: `upstream_unreachable: ${this.#processLabel} ACP exited before completing the request${this.formatStderrSuffix()}`,\n }));\n }\n });\n this.#processTimeout =\n this.#timeoutMs === null\n ? null\n : setTimeout(() => {\n const timeoutTriggeredAtMs = Date.now();\n this.#lifecycle.timeoutTriggeredAtMs = timeoutTriggeredAtMs;\n this.#onLifecycleEvent?.({\n phase: \"timeout_triggered\",\n processId,\n tsMs: timeoutTriggeredAtMs,\n });\n this.#failAll(this.#error({\n code: \"process.timeout\",\n errorType: \"timeout\",\n message: `process.timeout: ${this.#processLabel} ACP did not complete within ${this.#timeoutMs}ms`,\n }));\n this.#requestProcessTermination(\"SIGTERM\");\n }, this.#timeoutMs);\n }\n async request(method, params) {\n if (this.#settledFailure) {\n throw this.#settledFailure;\n }\n const id = this.#nextRequestId;\n this.#nextRequestId += 1;\n const result = new Promise((resolve, reject) => {\n this.#pending.set(id, { reject, resolve });\n });\n this.#write({\n id,\n jsonrpc: \"2.0\",\n method,\n params,\n });\n return await result;\n }\n notify(method, params) {\n this.#write({\n jsonrpc: \"2.0\",\n method,\n ...(params === undefined ? {} : { params }),\n });\n }\n fail(error) {\n this.#failAll(error);\n }\n readLifecycle() {\n return { ...this.#lifecycle };\n }\n readStderr() {\n return this.#stderr;\n }\n buildTelemetry(input) {\n return {\n completedAtMs: Date.now(),\n ...(this.#lifecycle.exitCode === null\n ? {}\n : { exitCode: this.#lifecycle.exitCode }),\n ...(this.#lifecycle.exitObservedAtMs === null\n ? {}\n : { exitObservedAtMs: this.#lifecycle.exitObservedAtMs }),\n ...(this.#lifecycle.exitSignal === null\n ? {}\n : { exitSignal: this.#lifecycle.exitSignal }),\n ...(input.firstOutputAtMs === null || input.firstOutputAtMs === undefined\n ? {}\n : { firstOutputAtMs: input.firstOutputAtMs }),\n ...(this.#lifecycle.firstStderrAtMs === null\n ? {}\n : { firstStderrAtMs: this.#lifecycle.firstStderrAtMs }),\n ...(this.#lifecycle.firstStdoutAtMs === null\n ? {}\n : { firstStdoutAtMs: this.#lifecycle.firstStdoutAtMs }),\n invokedAtMs: input.invokedAtMs,\n previewEmitted: input.previewEmitted,\n ...(this.#lifecycle.processId === null\n ? {}\n : { processId: this.#lifecycle.processId }),\n ...(this.#lifecycle.processSpawnedAtMs === null\n ? {}\n : { processSpawnedAtMs: this.#lifecycle.processSpawnedAtMs }),\n resumedContext: input.resumedContext,\n ...(this.#lifecycle.stdinClosedAtMs === null\n ? {}\n : { stdinClosedAtMs: this.#lifecycle.stdinClosedAtMs }),\n streamingMode: input.streamingMode,\n ...(this.#lifecycle.timeoutTriggeredAtMs === null\n ? {}\n : { timeoutTriggeredAtMs: this.#lifecycle.timeoutTriggeredAtMs }),\n };\n }\n async close(input) {\n this.#clearProcessTimeout();\n const child = this.#child;\n if (!child) {\n return;\n }\n if (this.#lifecycle.stdinClosedAtMs === null) {\n this.#lifecycle.stdinClosedAtMs = Date.now();\n this.#onLifecycleEvent?.({\n phase: \"stdin_closed\",\n processId: this.#lifecycle.processId,\n tsMs: this.#lifecycle.stdinClosedAtMs,\n });\n }\n if (!(child.stdin.destroyed || child.stdin.writableEnded)) {\n child.stdin.end();\n }\n if (this.#lifecycle.exitObservedAtMs !== null) {\n await this.#finishRemainingDescendantsCleanup();\n return;\n }\n const gracefulExitMs = input?.gracefulExitMs ?? 0;\n if (gracefulExitMs > 0 && (await this.#waitForClose(gracefulExitMs))) {\n await this.#finishRemainingDescendantsCleanup();\n return;\n }\n this.#requestProcessTermination(\"SIGTERM\");\n if (await this.#waitForClose(ACP_PROCESS_KILL_GRACE_MS)) {\n await this.#finishRemainingDescendantsCleanup();\n return;\n }\n this.#requestProcessTermination(\"SIGKILL\");\n await this.#waitForClose(ACP_PROCESS_KILL_GRACE_MS);\n await this.#finishRemainingDescendantsCleanup();\n }\n formatStderrSuffix() {\n const normalized = this.#stderr.trim();\n return normalized ? `: ${normalized}` : \"\";\n }\n #consumeStdoutText(text) {\n this.#lineBuffer += text;\n while (true) {\n const newlineIndex = this.#lineBuffer.indexOf(\"\\n\");\n if (newlineIndex < 0) {\n return;\n }\n const line = this.#lineBuffer.slice(0, newlineIndex).trim();\n this.#lineBuffer = this.#lineBuffer.slice(newlineIndex + 1);\n if (line) {\n this.#handleStdoutLine(line);\n }\n }\n }\n #handleStdoutLine(line) {\n try {\n if (this.#consumeNonProtocolLine?.(line)) {\n return;\n }\n }\n catch (error) {\n this.#failAll(error);\n return;\n }\n let message;\n try {\n const parsed = JSON.parse(line);\n if (!(parsed && typeof parsed === \"object\" && !Array.isArray(parsed))) {\n throw new TypeError(\"JSON-RPC message must be an object\");\n }\n message = parsed;\n }\n catch (error) {\n this.#failAll(this.#error({\n cause: error,\n code: \"protocol.invalid\",\n errorType: \"adapter\",\n message: `protocol.invalid: ${this.#processLabel} ACP emitted non-JSON-RPC output (${toErrorMessage(error)})`,\n }));\n return;\n }\n if (message.id !== undefined && message.method) {\n this.#handleClientRequest(message).catch((error) => {\n this.#failAll(error);\n });\n return;\n }\n if (message.id !== undefined) {\n this.#handleResponse(message);\n return;\n }\n if (message.method) {\n this.#onNotification?.({\n method: message.method,\n params: message.params,\n });\n }\n }\n #handleResponse(message) {\n const id = message.id;\n if (!(typeof id === \"number\" || typeof id === \"string\")) {\n return;\n }\n const pending = this.#pending.get(id);\n if (!pending) {\n return;\n }\n this.#pending.delete(id);\n if (message.error) {\n pending.reject(this.#toJsonRpcError(message.error));\n return;\n }\n pending.resolve(message.result);\n }\n async #handleClientRequest(message) {\n const id = message.id;\n const method = message.method;\n if (!((typeof id === \"number\" || typeof id === \"string\") && method)) {\n return;\n }\n const response = this.#onClientRequest\n ? await this.#onClientRequest({\n method,\n params: message.params,\n })\n : {\n error: {\n code: -32_601,\n message: `OpenMeld does not support ACP client method '${method}'.`,\n },\n };\n this.#write({\n id,\n jsonrpc: \"2.0\",\n ...response,\n });\n }\n #write(message) {\n const child = this.#child;\n if (this.#settledFailure) {\n throw this.#settledFailure;\n }\n if (!child ||\n this.#lifecycle.exitObservedAtMs !== null ||\n child.stdin.destroyed ||\n child.stdin.writableEnded ||\n !child.stdin.writable) {\n const error = this.#buildStdinWriteError();\n this.#failAll(error);\n throw error;\n }\n try {\n child.stdin.write(`${JSON.stringify(message)}\\n`, (error) => {\n if (error) {\n this.#failAll(this.#buildStdinWriteError(error));\n }\n });\n }\n catch (error) {\n const writeError = this.#buildStdinWriteError(error);\n this.#failAll(writeError);\n throw writeError;\n }\n }\n #buildStdinWriteError(cause) {\n const detail = cause instanceof Error && cause.message.trim()\n ? ` (${cause.message.trim()})`\n : \"\";\n return this.#error({\n cause,\n code: \"upstream_unreachable\",\n errorType: \"adapter\",\n message: `upstream_unreachable: ${this.#processLabel} ACP is not accepting responses${detail}`,\n });\n }\n #toJsonRpcError(error) {\n if (this.#mapJsonRpcError) {\n return this.#mapJsonRpcError(error);\n }\n let code = \"protocol.request_failed\";\n if (error.code === -32_601) {\n code = \"protocol.method_not_found\";\n }\n else if (error.code === -32_602) {\n code = \"protocol.invalid_params\";\n }\n const message = normalizeOptionalText(error.message) ?? \"ACP request failed\";\n return this.#error({\n code,\n errorType: \"adapter\",\n message: `${code}: ${message}`,\n });\n }\n #failAll(error) {\n if (!this.#settledFailure) {\n this.#settledFailure = error;\n }\n for (const pending of this.#pending.values()) {\n pending.reject(error);\n }\n this.#pending.clear();\n }\n #requestProcessTermination(signal) {\n const runtimeProcess = this.#runtimeProcess;\n if (!runtimeProcess || this.#lifecycle.exitObservedAtMs !== null) {\n return;\n }\n runtimeProcess.terminate(signal);\n if (signal === \"SIGTERM\") {\n this.#forceKillTimeout = setTimeout(() => {\n if (this.#lifecycle.exitObservedAtMs === null) {\n runtimeProcess.terminate(\"SIGKILL\");\n }\n }, ACP_PROCESS_KILL_GRACE_MS);\n this.#forceKillTimeout.unref?.();\n }\n }\n #ensureRemainingDescendantsCleanup() {\n this.#cleanupPromise ??=\n this.#runtimeProcess?.terminateRemainingDescendants() ??\n Promise.resolve({ ok: true, signalSent: false });\n return this.#cleanupPromise;\n }\n async #finishRemainingDescendantsCleanup() {\n const result = await this.#ensureRemainingDescendantsCleanup();\n if (result.ok) {\n return;\n }\n throw this.#error({\n cause: result.error,\n code: \"process.cleanup_failed\",\n errorType: \"adapter\",\n message: `process.cleanup_failed: OpenMeld could not stop every ${this.#processLabel} process`,\n });\n }\n async #waitForClose(timeoutMs) {\n const child = this.#child;\n if (!child || this.#lifecycle.exitObservedAtMs !== null) {\n return true;\n }\n return await new Promise((resolve) => {\n let settled = false;\n const onClose = () => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timeout);\n resolve(true);\n };\n const timeout = setTimeout(() => {\n if (settled) {\n return;\n }\n settled = true;\n child.off(\"close\", onClose);\n resolve(false);\n }, timeoutMs);\n timeout.unref?.();\n child.once(\"close\", onClose);\n });\n }\n #clearProcessTimeout() {\n if (this.#processTimeout !== null) {\n clearTimeout(this.#processTimeout);\n this.#processTimeout = null;\n }\n }\n #clearTimers() {\n this.#clearProcessTimeout();\n if (this.#forceKillTimeout !== null) {\n clearTimeout(this.#forceKillTimeout);\n this.#forceKillTimeout = null;\n }\n }\n #error(input) {\n return this.#createError(input);\n }\n}\nfunction normalizeOptionalText(value) {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\nfunction toErrorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\n","import { buildAgentControllerConversationRef, canonicalizeBuiltinAgentControllerRef, resolveBuiltinAgentControllerConversationKind, } from \"@openmeld/schemas\";\nconst normalizeText = (value) => {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n};\nexport const resolveBuiltinAdapterConversationBridgeSpec = (adapterId) => {\n const rawAgentControllerRef = normalizeText(adapterId);\n if (!rawAgentControllerRef) {\n return null;\n }\n const agentControllerRef = canonicalizeBuiltinAgentControllerRef(rawAgentControllerRef);\n if (!agentControllerRef) {\n return null;\n }\n const agentControllerConversationKind = resolveBuiltinAgentControllerConversationKind(agentControllerRef);\n if (!agentControllerConversationKind) {\n return null;\n }\n return {\n agentControllerRef,\n agentControllerConversationKind,\n };\n};\nexport const buildAdapterAgentControllerConversationRef = (input) => buildAgentControllerConversationRef({\n agentControllerRef: input.agentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n agentControllerConversationKind: input.agentControllerConversationKind,\n});\nexport const resolveBridgedAgentControllerConversationId = (input) => {\n const agentControllerConversationId = normalizeText(input.agentControllerConversationId);\n const agentControllerConversation = input.agentControllerConversation;\n if (!agentControllerConversation) {\n return agentControllerConversationId;\n }\n if (agentControllerConversation.agentControllerRef !==\n input.bridgeSpec.agentControllerRef) {\n throw new Error(`conversation.bridge.agent_controller_ref_mismatch: expected agentControllerRef=${input.bridgeSpec.agentControllerRef}, received agentControllerRef=${agentControllerConversation.agentControllerRef}`);\n }\n if (agentControllerConversation.agentControllerConversationKind !==\n input.bridgeSpec.agentControllerConversationKind) {\n throw new Error(`conversation.bridge.agent_controller_conversation_kind_mismatch: expected agentControllerConversationKind=${input.bridgeSpec.agentControllerConversationKind}, received agentControllerConversationKind=${agentControllerConversation.agentControllerConversationKind}`);\n }\n if (agentControllerConversationId &&\n agentControllerConversationId !==\n agentControllerConversation.agentControllerConversationId) {\n throw new Error(`conversation.bridge.agent_controller_conversation_id_mismatch: expected agentControllerConversationId=${agentControllerConversationId}, received agentControllerConversationId=${agentControllerConversation.agentControllerConversationId}`);\n }\n return agentControllerConversation.agentControllerConversationId;\n};\nexport const bridgeAgentControllerConversationRef = (input) => {\n const resolvedContextId = resolveBridgedAgentControllerConversationId(input);\n if (!resolvedContextId) {\n return null;\n }\n return buildAdapterAgentControllerConversationRef({\n agentControllerRef: input.bridgeSpec.agentControllerRef,\n agentControllerConversationId: resolvedContextId,\n agentControllerConversationKind: input.bridgeSpec.agentControllerConversationKind,\n });\n};\n","import { basename, isAbsolute } from \"node:path\";\nimport { DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV, isDispatchSpaceActionDeliveryOnly, } from \"./dispatch-space-tools.js\";\nconst SPACE_ACTION_CONTEXT_PATH_ENV = \"OPENMELD_SPACE_ACTION_CONTEXT_PATH\";\nconst USER_FACING_CLI_COMMAND_ENV = \"OPENMELD_USER_FACING_CLI_COMMAND\";\nconst SPACE_ACTION_TOOL_COMMAND_PATH_ENV = \"OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH\";\nexport const OPENMELD_SPACE_ACTION_MCP_SERVER_ID = \"openmeld_internal_dispatch_space_action\";\nexport const OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES = [\n \"working_copy\",\n \"read_file\",\n \"read_history\",\n \"read_evidence\",\n \"read_thread\",\n \"read_documents\",\n \"read_skills\",\n \"read_result\",\n \"open_direct_message\",\n \"list_tasks\",\n \"create_task\",\n \"start_task\",\n \"submit_task_result\",\n \"review_task\",\n \"cancel_task\",\n \"report_progress\",\n \"reply\",\n \"stay_silent\",\n \"read_receipt\",\n];\nconst FORWARDED_ENV_NAMES = [\n DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV,\n SPACE_ACTION_CONTEXT_PATH_ENV,\n SPACE_ACTION_TOOL_COMMAND_PATH_ENV,\n \"OPENMELD_DISPATCH_RUNTIME_MODE\",\n \"OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID\",\n \"OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID\",\n USER_FACING_CLI_COMMAND_ENV,\n \"OPENMELD_ENV_PRESET\",\n // The tool process must use the carrier's lane, not its host's default home.\n // This is an installation selector, not a credential or additional authority.\n \"OPENMELD_HOME\",\n \"OPENMELD_AUTH_URL\",\n \"OPENMELD_GATEWAY_URL\",\n];\nconst OPENMELD_CLI_COMMANDS = new Set([\n \"openmeld\",\n \"openmeld-dev\",\n \"openmeld-canary\",\n]);\nexport function resolveDispatchSpaceActionMcpServer(env) {\n if (!normalizeOptionalText(env?.[SPACE_ACTION_CONTEXT_PATH_ENV])) {\n return null;\n }\n const command = normalizeOptionalText(env?.[USER_FACING_CLI_COMMAND_ENV]);\n if (!(command && OPENMELD_CLI_COMMANDS.has(command))) {\n throw new Error(\"OpenMeld cannot start the dispatch Space Action tool because the active CLI command is invalid.\");\n }\n const commandPath = normalizeOptionalText(env?.[SPACE_ACTION_TOOL_COMMAND_PATH_ENV]);\n if (!(commandPath &&\n isAbsolute(commandPath) &&\n (basename(commandPath) === command ||\n basename(commandPath) === `${command}.exe`))) {\n throw new Error(\"OpenMeld cannot start the dispatch Space Action tool because its dispatch-owned CLI path is invalid.\");\n }\n return {\n args: [\"space\", \"action\", \"tool-server\"],\n command: command,\n commandPath,\n env: Object.fromEntries(FORWARDED_ENV_NAMES.flatMap((name) => {\n const value = normalizeOptionalText(env?.[name]);\n return value ? [[name, value]] : [];\n })),\n id: OPENMELD_SPACE_ACTION_MCP_SERVER_ID,\n toolNames: isDispatchSpaceActionDeliveryOnly(env)\n ? [\"reply\", \"stay_silent\", \"read_receipt\"]\n : OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES,\n };\n}\nexport function buildDispatchSpaceActionMcpToolIds(separator, env) {\n const names = isDispatchSpaceActionDeliveryOnly(env)\n ? [\"reply\", \"stay_silent\", \"read_receipt\"]\n : OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES;\n return names.map((toolName) => `${OPENMELD_SPACE_ACTION_MCP_SERVER_ID}${separator}${toolName}`);\n}\nexport function buildAcpDispatchSpaceActionMcpServers(env) {\n const config = resolveDispatchSpaceActionMcpServer(env);\n if (!config) {\n return [];\n }\n return [\n {\n args: [...config.args],\n command: config.commandPath,\n env: Object.entries(config.env).map(([name, value]) => ({ name, value })),\n name: config.id,\n },\n ];\n}\nfunction normalizeOptionalText(value) {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","export const RUNTIME_PERMISSION_DENIED_REASON_CODE = \"permission.denied.runtime\";\nconst ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\\\[[0-?]*[ -/]*[@-~]`, \"g\");\nconst OPENCODE_PERMISSION_KIND_RE = /permission requested:\\s*([a-z0-9_.:-]+)/i;\nconst OPENCLAW_PERMISSION_REQUIRED_RE = /\\b[a-z0-9_]+_permission_required\\b/;\nconst OPENCLAW_PERMISSION_KIND_RE = /\\b([a-z0-9_]+)_permission_required\\b/;\nconst UNSAFE_PERMISSION_KIND_CHARACTER_RE = /[^a-z0-9_.:-]+/g;\nconst EDGE_UNDERSCORE_RE = /^_+|_+$/g;\nexport function classifyRuntimePermissionDenialMessage(input) {\n const details = readRuntimePermissionDenialDetails(input.message);\n if (!details) {\n return null;\n }\n const source = input.source ?? details.source;\n const normalizedMessage = details.normalizedMessage;\n return {\n code: RUNTIME_PERMISSION_DENIED_REASON_CODE,\n details: {\n normalizedMessage,\n permissionKind: details.permissionKind,\n source,\n },\n errorType: \"adapter\",\n message: `${RUNTIME_PERMISSION_DENIED_REASON_CODE}: ${normalizedMessage}`,\n };\n}\nexport function looksLikeRuntimePermissionDenialMessage(value) {\n return readRuntimePermissionDenialDetails(value) !== null;\n}\nexport function readRuntimePermissionDenialDetails(value) {\n const normalizedMessage = normalizeRuntimePermissionMessage(value);\n if (!normalizedMessage) {\n return null;\n }\n const lowered = normalizedMessage.toLowerCase();\n if (isAntigravityPermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readAntigravityPermissionKind(lowered),\n source: \"antigravity\",\n };\n }\n if (isOpenCodePermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readOpenCodePermissionKind(normalizedMessage),\n source: \"opencode\",\n };\n }\n if (isClaudeCodePermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readClaudeCodePermissionKind(lowered),\n source: \"claude-code\",\n };\n }\n if (isCodexPermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readCodexPermissionKind(lowered),\n source: \"codex\",\n };\n }\n if (isOpenClawPermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readOpenClawPermissionKind(lowered),\n source: \"openclaw\",\n };\n }\n return null;\n}\nfunction isAntigravityPermissionDenial(value) {\n return (value.includes(\"permission check failed\") ||\n value.includes(\"user denied permission to run command\") ||\n (value.includes(\"tool required the\") &&\n value.includes(\"permission\") &&\n value.includes(\"auto-denied\")));\n}\nfunction readAntigravityPermissionKind(value) {\n if (value.includes(\"command\")) {\n return \"command\";\n }\n if (value.includes(\"mcp\")) {\n return \"mcp\";\n }\n return \"tool_use\";\n}\nfunction normalizeRuntimePermissionMessage(value) {\n const normalized = String(value ?? \"\")\n .replace(ANSI_ESCAPE_RE, \"\")\n .trim();\n return normalized.length > 0 ? normalized : null;\n}\nfunction isOpenCodePermissionDenial(value) {\n return (value.includes(\"permission requested\") &&\n (value.includes(\"auto-reject\") ||\n value.includes(\"auto rejecting\") ||\n value.includes(\"auto rejected\") ||\n value.includes(\"rejecting\")));\n}\nfunction isClaudeCodePermissionDenial(value) {\n return (value.includes(\"permission for this tool use was denied\") ||\n value.includes(\"permission for this action was denied\") ||\n value.includes(\"permission for this action has been denied\") ||\n value.includes(\"denied by auto mode classifier\") ||\n value.includes(\"user rejected tool use\") ||\n (value.includes(\"permission request\") &&\n value.includes(\"not answered in time\")));\n}\nfunction isCodexPermissionDenial(value) {\n return (value.includes(\"command denied by sandbox:\") ||\n value.includes(\"sandbox denied exec error\") ||\n value.includes(\"this action was rejected due to unacceptable risk\") ||\n (value.includes(\"execution denied:\") &&\n (value.includes(\"policy\") ||\n value.includes(\"forbidden\") ||\n value.includes(\"approval\") ||\n value.includes(\"sandbox\"))) ||\n (value.includes(\"rejected:\") && value.includes(\"blocked by policy\")) ||\n (value.includes(\"requires approval\") && value.includes(\"policy\")) ||\n value.includes(\"policy forbids commands starting\"));\n}\nfunction isOpenClawPermissionDenial(value) {\n return (value.includes(\"system_run_denied:\") ||\n value.includes(\"system_run_disabled: security=deny\") ||\n value.includes(\"exec denied:\") ||\n value.includes(\"exec.denied\") ||\n value.includes(\"permission:screenrecording\") ||\n OPENCLAW_PERMISSION_REQUIRED_RE.test(value));\n}\nfunction readOpenCodePermissionKind(value) {\n const match = OPENCODE_PERMISSION_KIND_RE.exec(value);\n return normalizePermissionKind(match?.[1]);\n}\nfunction readClaudeCodePermissionKind(value) {\n if (value.includes(\"tool use\")) {\n return \"tool_use\";\n }\n if (value.includes(\"url\")) {\n return \"url_access\";\n }\n if (value.includes(\"auto mode classifier\")) {\n return \"auto_mode\";\n }\n return null;\n}\nfunction readCodexPermissionKind(value) {\n if (value.includes(\"sandbox\")) {\n return \"sandbox\";\n }\n if (value.includes(\"approval\")) {\n return \"approval\";\n }\n if (value.includes(\"policy\")) {\n return \"policy\";\n }\n return null;\n}\nfunction readOpenClawPermissionKind(value) {\n if (value.includes(\"system_run\")) {\n return \"system_run\";\n }\n if (value.includes(\"exec denied\") || value.includes(\"exec.denied\")) {\n return \"exec\";\n }\n if (value.includes(\"permission:screenrecording\")) {\n return \"screen_recording\";\n }\n const match = OPENCLAW_PERMISSION_KIND_RE.exec(value);\n return normalizePermissionKind(match?.[1]);\n}\nfunction normalizePermissionKind(value) {\n const normalized = String(value ?? \"\")\n .trim()\n .toLowerCase()\n .replace(UNSAFE_PERMISSION_KIND_CHARACTER_RE, \"_\")\n .replace(EDGE_UNDERSCORE_RE, \"\");\n return normalized.length > 0 ? normalized : null;\n}\n","// biome-ignore-all lint/performance/noBarrelFile: Package entrypoint intentionally exports stable adapter-core helpers.\n//\n// Provider runtime integrations must always go through adapter integration.\n// There is no parallel \"lightweight integration\" path outside adapter-core.\n//\n// Use a thin adapter when the provider only needs straightforward transport\n// wiring into the shared runtime shell. Escalate to a full adapter as soon as\n// the provider has any of the following:\n// - continuation-specific behavior\n// - bootstrap or readiness preparation\n// - gateway transport requirements\n// - provider-native workspace semantics\n// - non-trivial parser/codec logic\n// - provider-specific failure/diagnostics mapping\nimport { aiUsageObservationSchema, openMeldDaemonProviderAccessEvidenceSchema, } from \"@openmeld/schemas\";\nexport { agentExecutionSteerRequestSchema } from \"@openmeld/schemas\";\nexport { DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV, describeDispatchSpaceTools, isDispatchSpaceActionDeliveryOnly, } from \"./dispatch-space-tools.js\";\nimport { createProviderOriginalError } from \"./provider-original-error.js\";\nexport { AcpProcessSession, } from \"./acp-process-session.js\";\nexport { createAcpToolActivityTracker, } from \"./acp-tool-activity.js\";\nimport { bridgeAgentControllerConversationRef, buildAdapterAgentControllerConversationRef, resolveBridgedAgentControllerConversationId, } from \"./conversation-bridge.js\";\nexport { createAgentControllerProcessDiscoveryDiagnosticAggregator, listAgentControllerDescendantProcessIds, listAgentControllerSupervisedProcessIds, resolveAgentControllerDescendantProcessIds, resolveAgentControllerProcessSignalId, resolveAgentControllerProcessSignalTarget, resolveAgentControllerSupervisedProcessIds, signalAgentControllerProcessTree, spawnAgentControllerProcess, terminateLiveAgentControllerProcesses, terminateRemainingAgentControllerProcesses, } from \"./agent-controller-process.js\";\nexport { bridgeAgentControllerConversationRef, buildAdapterAgentControllerConversationRef, resolveBridgedAgentControllerConversationId, resolveBuiltinAdapterConversationBridgeSpec, } from \"./conversation-bridge.js\";\nexport { buildAcpDispatchSpaceActionMcpServers, buildDispatchSpaceActionMcpToolIds, OPENMELD_SPACE_ACTION_MCP_SERVER_ID, OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES, resolveDispatchSpaceActionMcpServer, } from \"./dispatch-space-action-mcp.js\";\nexport { buildCliLaunchInvocation, buildExecutableLaunchContract, materializeCliLaunchCommand, resolveExecutableOnPath, resolveExecutablePathsOnPath, resolveInstalledCommandPath, resolveInstalledCommandPaths, resolveInstalledNodeScriptLaunchCandidates, resolveInstalledNodeScriptLaunchContract, resolveLaunchCandidatesAfterVerification, resolveSiblingCommandPath, verifyCliLaunchContract, verifyLaunchContractFiles, } from \"./launch-contract.js\";\nexport { normalizeCommandEnvironment, WINDOWS_RUNTIME_ENV_KEYS, } from \"./process-environment.js\";\nexport { createProviderOriginalError } from \"./provider-original-error.js\";\nexport { createUnavailableProviderUsageLimits, createUnsupportedProviderUsageLimits, } from \"./provider-usage-limits.js\";\nexport { buildProviderExitError, classifyCliDriverTimeoutFailure, } from \"./runtime-failure.js\";\nexport { classifyRuntimePermissionDenialMessage, looksLikeRuntimePermissionDenialMessage, RUNTIME_PERMISSION_DENIED_REASON_CODE, readRuntimePermissionDenialDetails, } from \"./runtime-permission-denial.js\";\nexport { ADAPTER_TOOL_ACTIVITY_NAMES, resolveAdapterToolActivityName, resolveAdapterToolWorkActivity, } from \"./tool-activity.js\";\nexport const AGENT_CONTROLLER_CONVERSATION_OCCUPANCY_CONTRACT_VERSION = 1;\nexport function readAdapterAiUsageObservation(value) {\n const result = aiUsageObservationSchema.safeParse(value);\n return result.success ? result.data : null;\n}\nexport const DEFAULT_GRACEFUL_INTERRUPT_TIMEOUT_MS = 10_000;\nconst DEFAULT_INTERRUPT_REASON = \"service.interrupt\";\nconst DEFAULT_CANCEL_REASON = \"service.cancel\";\nconst TEST_DISABLE_DEFAULT_INVOKE = Symbol.for(\"openmeld.test.disableDefaultInvoke\");\nexport const createSharedDispatchShell = (input) => {\n const bridgeSpec = input.bridgeSpec ?? null;\n return async (dispatchInput) => {\n const transportMode = dispatchInput.transportMode ?? \"local-cli\";\n const transportInvoke = input.invokeByMode?.[transportMode];\n if (input.invokeByMode && !transportInvoke) {\n return {\n errorCode: \"adapter.unreachable\",\n errorMessage: `adapter.unreachable: ${input.adapterId} transport '${transportMode}' is not configured`,\n errorType: \"adapter\",\n status: \"failed\",\n };\n }\n const defaultInvoke = isDefaultInvokeDisabledForTests(input.runtimeOptions)\n ? null\n : (input.resolveDefaultInvoke() ?? null);\n const resolvedInvoke = transportInvoke ?? input.invoke ?? defaultInvoke;\n if (!resolvedInvoke) {\n return {\n errorCode: \"controller.runtime.missing\",\n errorMessage: `controller.runtime.missing: ${input.adapterId} invoke runtime is unavailable`,\n errorType: \"adapter\",\n status: \"failed\",\n };\n }\n try {\n const invokeRequest = input.resolveInvokeRequest?.({\n bridgeSpec,\n request: dispatchInput,\n }) ??\n buildDefaultInvokeRequest({\n bridgeSpec,\n request: dispatchInput,\n });\n const requiredRepairConversationId = resolveRequiredRepairConversationId({\n invokeRequest,\n policy: input.repairConversationPolicy,\n request: dispatchInput,\n });\n const result = await resolvedInvoke(invokeRequest);\n const contextDelta = input.resolveSuccessContextDelta?.({\n bridgeSpec,\n invokeRequest,\n request: dispatchInput,\n result,\n }) ??\n resolveCanonicalContextDelta({\n bridgeSpec,\n contextDelta: result.contextDelta,\n });\n const protectedContextDelta = requireCanonicalRepairConversation({\n canonicalConversationId: requiredRepairConversationId,\n contextDelta,\n });\n return {\n ...(protectedContextDelta\n ? { contextDelta: protectedContextDelta }\n : {}),\n ...(result.diagnostics ? { diagnostics: result.diagnostics } : {}),\n output: result.output,\n status: \"success\",\n ...(result.telemetry ? { telemetry: result.telemetry } : {}),\n };\n }\n catch (error) {\n return toAdapterDispatchFailure(error, \"adapter\");\n }\n };\n};\nclass AdapterRepairConversationMissingError extends Error {\n code = \"repair.conversation_missing\";\n errorType = \"adapter\";\n constructor() {\n super(\"repair.conversation_missing: repair requires an existing Agent Controller conversation\");\n this.name = \"AdapterRepairConversationMissingError\";\n }\n}\nclass AdapterRepairConversationError extends Error {\n code = \"repair.conversation_changed\";\n errorType = \"adapter\";\n constructor() {\n super(\"repair.conversation_changed: repair could not preserve the existing Agent Controller conversation\");\n this.name = \"AdapterRepairConversationError\";\n }\n}\nconst resolveRequiredRepairConversationId = (input) => {\n if (input.policy !== \"require_canonical\" ||\n input.request.executionMode !== \"repair\") {\n return null;\n }\n const canonicalConversationId = normalizeOptionalText(input.invokeRequest.agentControllerConversationId);\n if (!canonicalConversationId) {\n throw new AdapterRepairConversationMissingError();\n }\n return canonicalConversationId;\n};\nconst requireCanonicalRepairConversation = (input) => {\n if (!input.canonicalConversationId) {\n return input.contextDelta;\n }\n const observedConversationId = normalizeOptionalText(input.contextDelta?.agentControllerConversationId);\n if (input.contextDelta?.refreshed === true ||\n observedConversationId !== input.canonicalConversationId) {\n throw new AdapterRepairConversationError();\n }\n return input.contextDelta;\n};\nexport const createSharedControlShell = (input) => ({\n cancel: async (requestInput) => {\n const request = buildAdapterCancelRequest(requestInput);\n const sendCancelSignal = resolveCancelSignalSender({\n sendCancel: input.sendCancel,\n sendInterrupt: input.sendInterrupt,\n });\n if (!sendCancelSignal) {\n return buildUnsupportedCancelResult({\n taskId: request.taskId,\n });\n }\n try {\n await sendCancelSignal.send(request);\n return {\n accepted: true,\n deliveryPath: sendCancelSignal.deliveryPath,\n reasonCode: \"accepted\",\n signalDelivery: \"sent\",\n taskId: request.taskId,\n };\n }\n catch (error) {\n const reasonCode = resolveControlReasonCode(error) ?? \"signal.send_failed\";\n return buildUnsupportedCancelResult({\n reasonCode,\n reasonDetail: resolveControlReasonDetail(error, reasonCode),\n taskId: request.taskId,\n });\n }\n },\n interrupt: async (requestInput) => {\n const plan = buildInterruptPlan({\n gracefulTimeoutMs: requestInput.gracefulTimeoutMs ?? input.gracefulTimeoutMs,\n mode: requestInput.mode,\n reason: requestInput.reason,\n taskId: requestInput.taskId,\n });\n if (!input.sendInterrupt) {\n return buildUnsupportedInterruptResult({\n plan,\n reasonCode: \"adapter.unsupported\",\n taskId: requestInput.taskId,\n });\n }\n try {\n await executeInterruptPlan({\n plan,\n sendSignal: input.sendInterrupt,\n waitForMs: input.waitForMs,\n });\n return {\n accepted: true,\n plan,\n reasonCode: \"accepted\",\n signalDelivery: \"sent\",\n taskId: requestInput.taskId,\n };\n }\n catch (error) {\n const reasonCode = resolveControlReasonCode(error) ?? \"signal.send_failed\";\n return buildUnsupportedInterruptResult({\n plan,\n reasonCode,\n reasonDetail: resolveControlReasonDetail(error, reasonCode),\n taskId: requestInput.taskId,\n });\n }\n },\n});\nexport const invokeWithSingleContextHeal = async (input) => {\n try {\n const first = await input.invokeOnce(input.contextId);\n return {\n contextHealed: false,\n contextId: first.contextId,\n ...(first.diagnostics ? { diagnostics: first.diagnostics } : {}),\n output: first.output,\n telemetry: first.telemetry,\n };\n }\n catch (firstError) {\n if (!(input.contextId && input.isContextLostError(firstError))) {\n throw firstError;\n }\n if (input.contextLossPolicy === \"fail\") {\n throw firstError;\n }\n await input.onContextLost?.();\n try {\n const healed = await input.invokeOnce(null);\n return {\n contextHealed: true,\n contextId: healed.contextId,\n ...(healed.diagnostics ? { diagnostics: healed.diagnostics } : {}),\n output: healed.output,\n telemetry: healed.telemetry\n ? {\n ...healed.telemetry,\n contextHealed: true,\n resumedContext: input.contextId !== null,\n }\n : undefined,\n };\n }\n catch (healError) {\n throw input.createRebuildFailedError(healError);\n }\n }\n};\nexport const buildInterruptPlan = (input) => {\n const mode = input.mode ?? \"graceful\";\n const reason = input.reason ?? DEFAULT_INTERRUPT_REASON;\n if (mode === \"force\") {\n return {\n initial: {\n mode: \"force\",\n reason,\n taskId: input.taskId,\n },\n };\n }\n const delayMs = normalizeGracefulTimeoutMs(input.gracefulTimeoutMs);\n return {\n initial: {\n mode: \"graceful\",\n reason,\n taskId: input.taskId,\n },\n escalation: {\n delayMs,\n mode: \"force\",\n reason,\n taskId: input.taskId,\n },\n };\n};\nexport const executeInterruptPlan = async (input) => {\n await input.sendSignal(input.plan.initial);\n if (!input.plan.escalation) {\n return;\n }\n const waitForMs = input.waitForMs ?? defaultWaitForMs;\n await waitForMs(input.plan.escalation.delayMs);\n await input.sendSignal({\n mode: input.plan.escalation.mode,\n reason: input.plan.escalation.reason,\n taskId: input.plan.escalation.taskId,\n });\n};\nexport const buildUnsupportedInterruptResult = (input) => ({\n accepted: false,\n plan: input.plan,\n reasonCode: input.reasonCode ?? \"adapter.unsupported\",\n ...(input.reasonDetail ? { reasonDetail: input.reasonDetail } : {}),\n signalDelivery: \"not_sent\",\n taskId: input.taskId,\n});\nexport const buildUnsupportedCancelResult = (input) => ({\n accepted: false,\n reasonCode: input.reasonCode ?? \"adapter.unsupported\",\n ...(input.reasonDetail ? { reasonDetail: input.reasonDetail } : {}),\n signalDelivery: \"not_sent\",\n taskId: input.taskId,\n});\nexport const buildAdapterCancelRequest = (input) => ({\n reason: normalizeControlReason(input.reason, DEFAULT_CANCEL_REASON),\n taskId: input.taskId,\n});\nexport const toAdapterDispatchFailure = (error, defaultErrorType = \"adapter\") => {\n const errorCode = extractErrorCode(error);\n const agentControllerConversationOccupancy = extractAgentControllerConversationOccupancy(error);\n const errorType = extractErrorType(error) ?? defaultErrorType;\n const diagnostics = extractDispatchDiagnostics(error);\n const providerAccessEvidence = extractProviderAccessEvidence(error);\n const originalError = extractProviderOriginalError(error);\n const telemetry = extractDispatchTelemetry(error);\n return {\n ...(agentControllerConversationOccupancy\n ? { agentControllerConversationOccupancy }\n : {}),\n ...(diagnostics ? { diagnostics } : {}),\n ...(errorCode ? { errorCode } : {}),\n errorMessage: error instanceof Error ? error.message : \"adapter dispatch failed\",\n errorType,\n ...(originalError ? { originalError } : {}),\n ...(providerAccessEvidence ? { providerAccessEvidence } : {}),\n status: \"failed\",\n ...(telemetry ? { telemetry } : {}),\n };\n};\nconst extractAgentControllerConversationOccupancy = (error) => {\n if (!(error && typeof error === \"object\")) {\n return null;\n }\n const value = error\n .agentControllerConversationOccupancy;\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const occupancy = value;\n const agentControllerConversationId = typeof occupancy.agentControllerConversationId === \"string\"\n ? occupancy.agentControllerConversationId.trim()\n : \"\";\n if (!agentControllerConversationId ||\n occupancy.contractVersion !==\n AGENT_CONTROLLER_CONVERSATION_OCCUPANCY_CONTRACT_VERSION ||\n occupancy.state !== \"occupied\") {\n return null;\n }\n return {\n agentControllerConversationId,\n contractVersion: AGENT_CONTROLLER_CONVERSATION_OCCUPANCY_CONTRACT_VERSION,\n state: \"occupied\",\n };\n};\nconst extractProviderOriginalError = (error) => {\n if (!(error && typeof error === \"object\")) {\n return null;\n }\n return createProviderOriginalError(error.originalError);\n};\nconst extractDispatchTelemetry = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const telemetry = toUnknownRecord(error.telemetry);\n if (!(telemetry &&\n isFiniteNumber(telemetry.completedAtMs) &&\n isFiniteNumber(telemetry.invokedAtMs) &&\n typeof telemetry.resumedContext === \"boolean\")) {\n return null;\n }\n const tokenUsage = extractAdapterTokenUsage(telemetry.tokenUsage);\n return {\n completedAtMs: telemetry.completedAtMs,\n ...(typeof telemetry.contextCompactionObserved === \"boolean\"\n ? { contextCompactionObserved: telemetry.contextCompactionObserved }\n : {}),\n ...(typeof telemetry.contextHealed === \"boolean\"\n ? { contextHealed: telemetry.contextHealed }\n : {}),\n ...(isFiniteNumber(telemetry.exitCode)\n ? { exitCode: telemetry.exitCode }\n : {}),\n ...(isFiniteNumber(telemetry.exitObservedAtMs)\n ? { exitObservedAtMs: telemetry.exitObservedAtMs }\n : {}),\n ...(isNodeSignal(telemetry.exitSignal)\n ? { exitSignal: telemetry.exitSignal }\n : {}),\n ...(isFiniteNumber(telemetry.firstOutputAtMs)\n ? { firstOutputAtMs: telemetry.firstOutputAtMs }\n : {}),\n ...(isFiniteNumber(telemetry.firstStderrAtMs)\n ? { firstStderrAtMs: telemetry.firstStderrAtMs }\n : {}),\n ...(isFiniteNumber(telemetry.firstStdoutAtMs)\n ? { firstStdoutAtMs: telemetry.firstStdoutAtMs }\n : {}),\n invokedAtMs: telemetry.invokedAtMs,\n ...(typeof telemetry.previewEmitted === \"boolean\"\n ? { previewEmitted: telemetry.previewEmitted }\n : {}),\n ...(isFiniteNumber(telemetry.processId)\n ? { processId: telemetry.processId }\n : {}),\n ...(isFiniteNumber(telemetry.processSpawnedAtMs)\n ? { processSpawnedAtMs: telemetry.processSpawnedAtMs }\n : {}),\n resumedContext: telemetry.resumedContext,\n ...(isFiniteNumber(telemetry.stdinClosedAtMs)\n ? { stdinClosedAtMs: telemetry.stdinClosedAtMs }\n : {}),\n ...(telemetry.streamingMode === \"final\" ||\n telemetry.streamingMode === \"stream\"\n ? { streamingMode: telemetry.streamingMode }\n : {}),\n ...(isFiniteNumber(telemetry.timeoutTriggeredAtMs)\n ? { timeoutTriggeredAtMs: telemetry.timeoutTriggeredAtMs }\n : {}),\n ...(tokenUsage ? { tokenUsage } : {}),\n ...extractAiUsageTelemetry(telemetry.aiUsage),\n };\n};\nfunction extractAiUsageTelemetry(value) {\n const result = aiUsageObservationSchema.array().safeParse(value);\n return result.success ? { aiUsage: result.data } : {};\n}\nfunction extractAdapterTokenUsage(value) {\n const usage = toUnknownRecord(value);\n const last = extractAdapterTokenUsageBreakdown(usage?.last);\n const total = extractAdapterTokenUsageBreakdown(usage?.total);\n const modelContextWindow = usage?.modelContextWindow;\n if (!(usage &&\n last &&\n total &&\n (modelContextWindow === null || isNonNegativeInteger(modelContextWindow)))) {\n return null;\n }\n return { last, modelContextWindow, total };\n}\nfunction extractAdapterTokenUsageBreakdown(value) {\n const usage = toUnknownRecord(value);\n if (!(usage &&\n isNonNegativeInteger(usage.cachedInputTokens) &&\n isNonNegativeInteger(usage.inputTokens) &&\n isNonNegativeInteger(usage.outputTokens) &&\n isNonNegativeInteger(usage.reasoningOutputTokens) &&\n isNonNegativeInteger(usage.totalTokens) &&\n (usage.cacheWriteInputTokens === undefined ||\n isNonNegativeInteger(usage.cacheWriteInputTokens)))) {\n return null;\n }\n return {\n ...(usage.cacheWriteInputTokens === undefined\n ? {}\n : { cacheWriteInputTokens: usage.cacheWriteInputTokens }),\n cachedInputTokens: usage.cachedInputTokens,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n totalTokens: usage.totalTokens,\n };\n}\nfunction isNonNegativeInteger(value) {\n return Number.isInteger(value) && Number(value) >= 0;\n}\nfunction isFiniteNumber(value) {\n return typeof value === \"number\" && Number.isFinite(value);\n}\nfunction isNodeSignal(value) {\n return typeof value === \"string\" && value.startsWith(\"SIG\");\n}\nconst extractDispatchDiagnostics = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const diagnostics = error.diagnostics;\n const record = toUnknownRecord(diagnostics);\n const modelNegotiation = parseModelNegotiationDiagnostics(record?.modelNegotiation);\n return modelNegotiation ? { modelNegotiation } : null;\n};\nconst MODEL_DIAGNOSTIC_ID_LIMIT = 100;\nconst MODEL_DIAGNOSTIC_ID_MAX_LENGTH = 512;\nfunction parseModelNegotiationDiagnostics(value) {\n const record = toUnknownRecord(value);\n if (!record) {\n return null;\n }\n const configAvailableModelIds = parseBoundedModelIds(record.configAvailableModelIds);\n const legacyAvailableModelIds = parseBoundedModelIds(record.legacyAvailableModelIds);\n const configAvailableModelCount = parseModelCount(record.configAvailableModelCount, configAvailableModelIds?.length);\n const legacyAvailableModelCount = parseModelCount(record.legacyAvailableModelCount, legacyAvailableModelIds?.length);\n const configCurrentModelId = parseNullableModelId(record.configCurrentModelId);\n const currentModelId = parseNullableModelId(record.currentModelId);\n const legacyCurrentModelId = parseNullableModelId(record.legacyCurrentModelId);\n const requestedModelId = parseNullableModelId(record.requestedModelId);\n if ((record.checkAttempt !== 1 && record.checkAttempt !== 2) ||\n configAvailableModelIds === null ||\n configAvailableModelCount === null ||\n typeof record.configAvailableModelIdsTruncated !== \"boolean\" ||\n configCurrentModelId === undefined ||\n currentModelId === undefined ||\n legacyAvailableModelIds === null ||\n legacyAvailableModelCount === null ||\n typeof record.legacyAvailableModelIdsTruncated !== \"boolean\" ||\n legacyCurrentModelId === undefined ||\n record.protocol !== \"acp/v1\" ||\n requestedModelId === undefined ||\n typeof record.requestedPresentInConfigOptions !== \"boolean\" ||\n typeof record.requestedPresentInLegacyModels !== \"boolean\" ||\n (record.sessionOperation !== \"load\" &&\n record.sessionOperation !== \"new\" &&\n record.sessionOperation !== \"resume\") ||\n !isModelSourceState(record.sourceState)) {\n return null;\n }\n return {\n checkAttempt: record.checkAttempt,\n configAvailableModelCount,\n configAvailableModelIds,\n configAvailableModelIdsTruncated: record.configAvailableModelIdsTruncated,\n configCurrentModelId,\n currentModelId,\n legacyAvailableModelCount,\n legacyAvailableModelIds,\n legacyAvailableModelIdsTruncated: record.legacyAvailableModelIdsTruncated,\n legacyCurrentModelId,\n protocol: record.protocol,\n requestedModelId,\n requestedPresentInConfigOptions: record.requestedPresentInConfigOptions,\n requestedPresentInLegacyModels: record.requestedPresentInLegacyModels,\n sessionOperation: record.sessionOperation,\n sourceState: record.sourceState,\n };\n}\nfunction parseBoundedModelIds(value) {\n if (!Array.isArray(value) ||\n value.length > MODEL_DIAGNOSTIC_ID_LIMIT ||\n !value.every((modelId) => typeof modelId === \"string\" &&\n modelId.length > 0 &&\n modelId.length <= MODEL_DIAGNOSTIC_ID_MAX_LENGTH)) {\n return null;\n }\n return [...value];\n}\nfunction parseModelCount(value, visibleCount) {\n return typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= (visibleCount ?? Number.POSITIVE_INFINITY)\n ? value\n : null;\n}\nfunction parseNullableModelId(value) {\n if (value === null) {\n return null;\n }\n return typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MODEL_DIAGNOSTIC_ID_MAX_LENGTH\n ? value\n : undefined;\n}\nfunction isModelSourceState(value) {\n return (value === \"config_options_only\" ||\n value === \"conflicting\" ||\n value === \"consistent\" ||\n value === \"legacy_models_only\" ||\n value === \"missing\");\n}\nfunction toUnknownRecord(value) {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value\n : null;\n}\nexport const resolveAdapterAgentContext = (input) => {\n const env = input.env ?? {};\n const rawValue = env[input.spec.sourceField];\n const agentControllerConversationId = typeof rawValue === \"string\" && rawValue.trim().length > 0\n ? rawValue.trim()\n : null;\n const agentControllerConversation = input.bridgeSpec && agentControllerConversationId\n ? buildAdapterAgentControllerConversationRef({\n agentControllerRef: input.bridgeSpec.agentControllerRef,\n agentControllerConversationId,\n agentControllerConversationKind: input.bridgeSpec.agentControllerConversationKind,\n })\n : null;\n return {\n agentControllerConversationId,\n sourceField: input.spec.sourceField,\n mappingVersion: input.spec.mappingVersion,\n ...(agentControllerConversation ? { agentControllerConversation } : {}),\n };\n};\nconst defaultWaitForMs = async (delayMs) => {\n if (delayMs <= 0) {\n return;\n }\n await new Promise((resolve) => {\n setTimeout(() => {\n resolve();\n }, delayMs);\n });\n};\nconst normalizeGracefulTimeoutMs = (gracefulTimeoutMs) => {\n if (!Number.isInteger(gracefulTimeoutMs) || gracefulTimeoutMs === undefined) {\n return DEFAULT_GRACEFUL_INTERRUPT_TIMEOUT_MS;\n }\n return gracefulTimeoutMs > 0\n ? gracefulTimeoutMs\n : DEFAULT_GRACEFUL_INTERRUPT_TIMEOUT_MS;\n};\nconst extractErrorCode = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const code = error.code;\n if (typeof code !== \"string\") {\n return null;\n }\n const normalized = code.trim();\n return normalized.length > 0 ? normalized : null;\n};\nconst extractErrorType = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const errorType = error.errorType;\n if (typeof errorType !== \"string\") {\n return null;\n }\n const normalized = errorType.trim();\n switch (normalized) {\n case \"adapter\":\n return \"adapter\";\n case \"auth\":\n return \"auth\";\n case \"config\":\n return \"config\";\n case \"timeout\":\n return \"timeout\";\n case \"network\":\n return \"network\";\n case \"unknown\":\n return \"unknown\";\n default:\n return null;\n }\n};\nconst extractProviderAccessEvidence = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const evidence = error\n .providerAccessEvidence;\n if (!evidence || typeof evidence !== \"object\") {\n return null;\n }\n const parsed = openMeldDaemonProviderAccessEvidenceSchema.safeParse(evidence);\n return parsed.success ? parsed.data : null;\n};\nconst normalizeControlReason = (reason, fallback) => {\n if (typeof reason !== \"string\") {\n return fallback;\n }\n const normalized = reason.trim();\n return normalized.length > 0 ? normalized : fallback;\n};\nconst resolveCanonicalContextDelta = (input) => {\n if (!input.contextDelta) {\n return undefined;\n }\n const canonicalContextDelta = {\n agentControllerConversationId: input.contextDelta.agentControllerConversationId,\n ...(input.contextDelta.refreshed === true ? { refreshed: true } : {}),\n ...(input.contextDelta.agentControllerConversation\n ? {\n agentControllerConversation: input.contextDelta.agentControllerConversation,\n }\n : {}),\n };\n if (!input.bridgeSpec) {\n return canonicalContextDelta;\n }\n const agentControllerConversation = bridgeAgentControllerConversationRef({\n agentControllerConversationId: canonicalContextDelta.agentControllerConversationId,\n bridgeSpec: input.bridgeSpec,\n agentControllerConversation: canonicalContextDelta.agentControllerConversation,\n });\n return {\n ...canonicalContextDelta,\n ...(agentControllerConversation ? { agentControllerConversation } : {}),\n };\n};\nconst buildDefaultInvokeRequest = (input) => {\n const agentControllerConversationId = input.bridgeSpec\n ? resolveBridgedAgentControllerConversationId({\n agentControllerConversationId: input.request.agentControllerConversationId,\n bridgeSpec: input.bridgeSpec,\n agentControllerConversation: input.request.agentControllerConversation,\n })\n : normalizeOptionalText(input.request.agentControllerConversationId);\n return {\n ...input.request,\n agentControllerConversationId,\n };\n};\nconst normalizeOptionalText = (value) => {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n};\nconst isDefaultInvokeDisabledForTests = (runtimeOptions) => runtimeOptions?.[TEST_DISABLE_DEFAULT_INVOKE] === true;\nconst resolveCancelSignalSender = (input) => {\n if (input.sendCancel) {\n return {\n deliveryPath: \"cancel\",\n send: input.sendCancel,\n };\n }\n if (!input.sendInterrupt) {\n return null;\n }\n return {\n deliveryPath: \"force_interrupt_fallback\",\n send: async (request) => {\n await input.sendInterrupt?.({\n mode: \"force\",\n reason: request.reason ?? DEFAULT_CANCEL_REASON,\n taskId: request.taskId,\n });\n },\n };\n};\nconst resolveControlReasonCode = (error) => {\n const code = extractErrorCode(error);\n switch (code) {\n case \"adapter.unsupported\":\n case \"signal.not_sent\":\n case \"signal.send_failed\":\n case \"task.not_found\":\n case \"task.not_running\":\n return code;\n default:\n return null;\n }\n};\nconst toUnknownErrorMessage = (error) => error instanceof Error ? error.message : \"unknown adapter control error\";\nconst resolveControlReasonDetail = (error, reasonCode) => reasonCode === \"adapter.unsupported\"\n ? undefined\n : toUnknownErrorMessage(error);\n"],"mappings":";;;;;;;;;;;;;;;;;;AAEA,SAAgB,2BAA2B,YAAY;CACnD,OAAO,WAAW,M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CAEJ,IAAI,CAAC,MAAM,eACP,OAAO;CAEX,OAAO;EACH,cAAc;EACd,MAAM,OAAO,YAAY;GACrB,MAAM,MAAM,gBAAgB;IACxB,MAAM;IACN,QAAQ,QAAQ,UAAU;IAC1B,QAAQ,QAAQ;GACpB,CAAC;EACL;CACJ;AACJ;AACA,MAAM,4BAA4B,UAAU;CACxC,MAAM,OAAO,iBAAiB,KAAK;CACnC,QAAQ,MAAR;EACI,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,oBACD,OAAO;EACX,SACI,OAAO;CACf;AACJ;AACA,MAAM,yBAAyB,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AAClF,MAAM,8BAA8B,OAAO,eAAe,eAAe,wBACnE,KAAA,IACA,sBAAsB,KAAK"}
1
+ {"version":3,"file":"dist-Cdj9kcbj.js","names":["REQUEST_ENV","normalizeOptionalText","toErrorMessage","normalizeOptionalText","normalizeOptionalText"],"sources":["../../../runtime/adapters/core/dist/dispatch-space-tools.js","../../../runtime/adapters/core/dist/provider-original-error.js","../../../runtime/adapters/core/dist/windows-process-job.js","../../../runtime/adapters/core/dist/agent-controller-process.js","../../../runtime/adapters/core/dist/drivers/cli-driver.js","../../../runtime/adapters/core/dist/launch-contract.js","../../../runtime/adapters/core/dist/acp-process-session.js","../../../runtime/adapters/core/dist/conversation-bridge.js","../../../runtime/adapters/core/dist/dispatch-space-action-mcp.js","../../../runtime/adapters/core/dist/runtime-permission-denial.js","../../../runtime/adapters/core/dist/index.js"],"sourcesContent":["import { toJSONSchema } from \"zod/v4\";\n/** Public definitions only: never serialize handlers or captured Wake authority. */\nexport function describeDispatchSpaceTools(capability) {\n return capability.tools.map((tool) => ({\n name: tool.name,\n title: tool.title ?? tool.name,\n description: tool.description,\n inputSchema: toJSONSchema(tool.inputSchema, {\n target: \"draft-07\",\n io: \"input\",\n }),\n }));\n}\nexport const DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV = \"OPENMELD_SPACE_ACTION_DELIVERY_ONLY\";\nexport function isDispatchSpaceActionDeliveryOnly(env) {\n return env?.[DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV] === \"1\";\n}\n","import { isOriginalErrorSafeForMessageDetails, OPENMELD_ORIGINAL_ERROR_MAX_LENGTH, } from \"@openmeld/schemas\";\nexport function createProviderOriginalError(value) {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n if (normalized.length === 0 ||\n !isOriginalErrorSafeForMessageDetails(normalized)) {\n return null;\n }\n return normalized.slice(0, OPENMELD_ORIGINAL_ERROR_MAX_LENGTH);\n}\n","import { execFile, spawn, } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { win32 } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { windowsNativeProcessRequestSchema } from \"@openmeld/schemas\";\nimport { normalizeCommandEnvironment } from \"./process-environment.js\";\nimport { quoteWindowsProcessArgument, resolveWindowsCommandPath, } from \"./process-launch.js\";\nimport { WINDOWS_NATIVE_PROCESS_REQUEST_ENV as REQUEST_ENV, resolveWindowsNativeProcessHelper, } from \"./windows-native-process.js\";\nimport { readWindowsProcessStartFileTime } from \"./windows-system.js\";\nconst DRAIN_RECEIPT = \"openmeld-windows-job-drained-v1\";\nconst CLEANUP_TIMEOUT_MS = 15_000;\nexport function spawnWindowsJobProcess(input) {\n const env = normalizeCommandEnvironment(input.env, \"win32\");\n const executable = resolveWindowsCommandPath(input.invocation.bin, env);\n if (!(win32.isAbsolute(executable) && win32.isAbsolute(input.cwd))) {\n throw Object.assign(new Error(\"The selected Windows controller needs an absolute executable and working directory.\"), { code: \"ENOENT\" });\n }\n const ownerStartedAt = readWindowsProcessStartFileTime(process.pid);\n if (!ownerStartedAt) {\n throw new Error(\"Windows could not verify the process that owns this invocation.\");\n }\n const jobName = `Local\\\\OpenMeld-Process-${randomUUID()}`;\n const commandLine = [\n quoteWindowsProcessArgument(executable),\n ...input.invocation.args.map((arg) => input.invocation.windowsVerbatimArguments\n ? arg\n : quoteWindowsProcessArgument(arg)),\n ].join(\" \");\n const request = windowsNativeProcessRequestSchema.parse({\n operation: \"launch\",\n jobName,\n executable,\n commandLine,\n workingDirectory: input.cwd,\n ownerPid: process.pid,\n ownerStartedAt,\n });\n const payload = Buffer.from(JSON.stringify(request), \"utf8\").toString(\"base64\");\n if (payload.length > 32_000) {\n throw new Error(\"The Windows controller arguments exceed the native launch envelope. Send large input through stdin instead.\");\n }\n const helper = resolveWindowsNativeProcessHelper();\n const child = spawn(helper, [], {\n cwd: input.cwd,\n env: { ...env, [REQUEST_ENV]: payload },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n const closed = new Promise((resolve) => child.once(\"close\", () => resolve()));\n const terminate = (signal) => {\n // Node retains the native process handle. Never signal a potentially reused\n // PID after exit; closing the supervisor's only Job handle kills descendants.\n if (child.exitCode !== null ||\n child.signalCode !== null ||\n child.pid === undefined) {\n return false;\n }\n return child.kill(signal);\n };\n return {\n child,\n terminate,\n async cleanup() {\n let timer;\n let signalSent = false;\n try {\n signalSent = terminate(\"SIGKILL\");\n await Promise.race([\n closed,\n new Promise((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(\"Windows supervisor exit could not be confirmed.\")), CLEANUP_TIMEOUT_MS);\n }),\n ]);\n // Query only AFTER the supervisor exits, so an absent Job cannot race a\n // delayed creation. A cleanup timeout/error is not a successful stop.\n const drain = windowsNativeProcessRequestSchema.parse({\n operation: \"drain\",\n jobName,\n });\n const { stdout } = await promisify(execFile)(helper, [], {\n env: {\n ...env,\n [REQUEST_ENV]: Buffer.from(JSON.stringify(drain), \"utf8\").toString(\"base64\"),\n },\n encoding: \"utf8\",\n windowsHide: true,\n timeout: CLEANUP_TIMEOUT_MS,\n maxBuffer: 4096,\n });\n if (stdout !== DRAIN_RECEIPT) {\n throw new Error(\"Windows returned an invalid process cleanup receipt.\");\n }\n return { ok: true, signalSent };\n }\n catch (error) {\n return { ok: false, signalSent, error };\n }\n finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n },\n };\n}\n","import { execFile, spawn, } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { normalizeCommandEnvironment } from \"./process-environment.js\";\nimport { resolvePlatformCommand } from \"./process-launch.js\";\nimport { spawnWindowsJobProcess } from \"./windows-process-job.js\";\nconst PROCESS_TABLE_COLUMN_SEPARATOR = /\\s+/u;\nconst PROCESS_TABLE_LINE_SEPARATOR = /\\r?\\n/u;\nconst PROCESS_SUPERVISION_ENV_KEY = \"OPENMELD_PROCESS_SUPERVISION_ID\";\nconst PROCESS_SUPERVISION_DISCOVERY_RETRY_DELAY_MS = 100;\nconst PROCESS_SUPERVISION_DISCOVERY_MAX_ATTEMPTS = 2;\nconst PROCESS_TABLE_STOP_PHASE_SNAPSHOT_MAX_AGE_MS = 75;\nconst PROCESS_DISCOVERY_DIAGNOSTIC_WINDOW_MS = 60_000;\nexport function createAgentControllerProcessTableSnapshotReader(input) {\n if (!(Number.isFinite(input.maxAgeMs) && input.maxAgeMs > 0)) {\n throw new Error(\"process table snapshot max age must be positive\");\n }\n const now = input.now ?? Date.now;\n let snapshot = null;\n return async (options) => {\n const readAtMs = now();\n if (snapshot && !options?.fresh) {\n const ageMs = readAtMs - snapshot.capturedAtMs;\n if (snapshot.pending || (ageMs >= 0 && ageMs < input.maxAgeMs)) {\n return await snapshot.processTable;\n }\n }\n const processTable = input.readProcessTable();\n const currentSnapshot = {\n capturedAtMs: readAtMs,\n pending: true,\n processTable,\n };\n snapshot = currentSnapshot;\n try {\n return await processTable;\n }\n finally {\n currentSnapshot.pending = false;\n }\n };\n}\nexport function createAgentControllerProcessDiscoveryDiagnosticAggregator(input) {\n const now = input?.now ?? Date.now;\n const windowMs = input?.windowMs ?? PROCESS_DISCOVERY_DIAGNOSTIC_WINDOW_MS;\n const write = input?.write ?? ((level, event, payload) => console[level](event, payload));\n const aggregates = new Map();\n return {\n failure: (failure) => {\n const observedAtMs = now();\n const error = normalizeErrorForDiagnostic(failure.error);\n const reasonCode = isProcessDiscoveryTimeoutError(failure.error)\n ? \"process_discovery_timeout\"\n : \"process_discovery_failed\";\n const key = `${failure.source}:${reasonCode}:${error.name}`;\n const aggregate = aggregates.get(key) ?? {\n affectedProcessIds: new Set(),\n error,\n firstAtMs: observedAtMs,\n lastAtMs: observedAtMs,\n lastReportedAtMs: Number.NEGATIVE_INFINITY,\n occurrenceCount: 0,\n reporterError: failure.reporterError\n ? normalizeErrorForDiagnostic(failure.reporterError)\n : null,\n source: failure.source,\n };\n aggregate.affectedProcessIds.add(failure.processId);\n aggregate.error = error;\n aggregate.lastAtMs = observedAtMs;\n aggregate.occurrenceCount += 1;\n aggregates.set(key, aggregate);\n if (observedAtMs - aggregate.lastReportedAtMs < windowMs) {\n return;\n }\n aggregate.lastReportedAtMs = observedAtMs;\n write(\"warn\", \"[openmeld.agent_controller.process_discovery_failed]\", {\n affectedProcessIds: [...aggregate.affectedProcessIds].slice(0, 20),\n durationMs: observedAtMs - aggregate.firstAtMs,\n errorCode: error.code,\n errorMessage: error.message,\n errorName: error.name,\n occurrenceCount: aggregate.occurrenceCount,\n reasonCode,\n ...(aggregate.reporterError\n ? {\n reporterErrorMessage: aggregate.reporterError.message,\n reporterErrorName: aggregate.reporterError.name,\n }\n : {}),\n signal: failure.signal,\n source: failure.source,\n });\n },\n recovered: (source) => {\n const recoveredAtMs = now();\n for (const [key, aggregate] of aggregates) {\n if (aggregate.source !== source) {\n continue;\n }\n write(\"info\", \"[openmeld.agent_controller.process_discovery_recovered]\", {\n affectedProcessIds: [...aggregate.affectedProcessIds].slice(0, 20),\n durationMs: recoveredAtMs - aggregate.firstAtMs,\n occurrenceCount: aggregate.occurrenceCount,\n reasonCode: \"process_discovery_recovered\",\n source,\n });\n aggregates.delete(key);\n }\n },\n };\n}\nfunction isProcessDiscoveryTimeoutError(error) {\n if (!(error instanceof Error)) {\n return false;\n }\n const processError = error;\n return processError.code === \"ETIMEDOUT\" || processError.killed === true;\n}\nconst processDiscoveryDiagnostics = createAgentControllerProcessDiscoveryDiagnosticAggregator();\n// Agent CLI process trees this process launched whose cleanup has not yet\n// completed. A root exit alone does not end a tree: a descendant that kept the\n// process group or supervision marker stays until descendant cleanup finishes.\nconst liveAgentControllerProcesses = new Set();\nconst LIVE_PROCESS_TERM_GRACE_MS = 1000;\nconst LIVE_PROCESS_CLEANUP_TIMEOUT_MS = 3000;\n// Set once shutdown cleanup begins. Background work still running then, such as\n// a controller report moving on to its next probe, must not start a tree that\n// the cleanup has already passed and the process exit would orphan.\nlet agentControllerLaunchesClosed = false;\nfunction trackLiveAgentControllerProcess(spawned) {\n if (spawned.processId === null) {\n return spawned;\n }\n const tracked = {\n ...spawned,\n terminateRemainingDescendants: async () => {\n const result = await spawned.terminateRemainingDescendants();\n if (result.ok) {\n liveAgentControllerProcesses.delete(tracked);\n }\n return result;\n },\n };\n liveAgentControllerProcesses.add(tracked);\n return tracked;\n}\n/**\n * Ends every agent CLI process tree launched by this process whose cleanup has\n * not completed. Only for a process that is ending after its accepted work\n * drained: whatever remains is abandoned background work, such as a controller\n * probe. It first closes further launches, so no tree can start behind it.\n * Roots get SIGTERM and a short grace, then the existing descendant cleanup\n * force-kills what is left; a tree whose cleanup failed is retried. The whole\n * call is bounded so the caller still exits promptly.\n */\nexport async function terminateLiveAgentControllerProcesses(input = {}) {\n agentControllerLaunchesClosed = true;\n const graceMs = input.graceMs ?? LIVE_PROCESS_TERM_GRACE_MS;\n const deadline = Date.now() + graceMs + (input.timeoutMs ?? LIVE_PROCESS_CLEANUP_TIMEOUT_MS);\n let terminated = false;\n while (liveAgentControllerProcesses.size > 0 && Date.now() < deadline) {\n const tracked = [...liveAgentControllerProcesses];\n if (!terminated) {\n terminated = true;\n for (const spawned of tracked) {\n // An exited root's stored group ID may be reused; the descendant\n // cleanup below decides what it may still signal.\n if (hasRootExited(spawned)) {\n continue;\n }\n try {\n spawned.terminate(\"SIGTERM\");\n }\n catch {\n // A tree that exited meanwhile needs no signal; cleanup still runs.\n }\n }\n await settleWithin(Promise.all(tracked.map(waitForRootExit)), Math.min(graceMs, deadline - Date.now()));\n }\n await settleWithin(Promise.allSettled(tracked.map((spawned) => spawned.terminateRemainingDescendants())), deadline - Date.now());\n }\n}\nfunction hasRootExited(spawned) {\n return spawned.child.exitCode !== null || spawned.child.signalCode !== null;\n}\nfunction waitForRootExit(spawned) {\n if (hasRootExited(spawned)) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n spawned.child.once(\"exit\", () => resolve());\n });\n}\nasync function settleWithin(work, timeoutMs) {\n let timer;\n await Promise.race([\n work.catch(() => undefined),\n new Promise((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n}\nexport function spawnAgentControllerProcess(input) {\n if (agentControllerLaunchesClosed) {\n throw new Error(\"Agent CLI launches are closed because this process is shutting down.\");\n }\n const signalTarget = resolveAgentControllerProcessSignalTarget();\n const supervisionId = input.supervisionId ?? randomUUID();\n const env = {\n ...normalizeCommandEnvironment(input.env),\n [PROCESS_SUPERVISION_ENV_KEY]: supervisionId,\n };\n const invocation = resolvePlatformCommand(input.bin, input.args, env);\n if (process.platform === \"win32\") {\n const job = spawnWindowsJobProcess({ invocation, env, cwd: input.cwd });\n return trackLiveAgentControllerProcess({\n child: job.child,\n processId: job.child.pid ?? null,\n signalTarget,\n supervisionId,\n terminate: job.terminate,\n terminateRemainingDescendants: job.cleanup,\n });\n }\n const child = spawn(invocation.bin, invocation.args, {\n cwd: input.cwd,\n detached: signalTarget === \"process_group\",\n env: {\n ...env,\n [PROCESS_SUPERVISION_ENV_KEY]: supervisionId,\n },\n shell: input.shell,\n windowsVerbatimArguments: invocation.windowsVerbatimArguments,\n windowsHide: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n const processId = typeof child.pid === \"number\" ? child.pid : null;\n const trackedDescendantProcessIds = new Set();\n return trackLiveAgentControllerProcess({\n child,\n processId,\n signalTarget,\n supervisionId,\n terminate: (signal) => signalAgentControllerProcessTree({\n processId,\n signal,\n signalTarget,\n trackedDescendantProcessIds,\n }),\n terminateRemainingDescendants: () => terminateRemainingAgentControllerProcesses({\n isRootExited: () => child.exitCode !== null || child.signalCode !== null,\n processId,\n signalTarget,\n supervisionId,\n trackedDescendantProcessIds,\n }),\n });\n}\nexport function resolveAgentControllerProcessSignalTarget(platform = process.platform) {\n return platform === \"win32\" ? \"process\" : \"process_group\";\n}\nexport function resolveAgentControllerProcessSignalId(input) {\n return input.signalTarget === \"process_group\"\n ? -input.processId\n : input.processId;\n}\nexport function signalAgentControllerProcessTree(input) {\n if (input.processId === null) {\n return false;\n }\n if (input.signalTarget === \"process\") {\n return signalProcessId({\n killProcess: input.killProcess,\n processId: input.processId,\n signal: input.signal,\n });\n }\n const trackedDescendantProcessIds = input.trackedDescendantProcessIds ?? new Set();\n let sent = false;\n const signalFailures = [];\n const attemptSignal = (processId) => {\n try {\n sent =\n signalProcessId({\n killProcess: input.killProcess,\n processId,\n signal: input.signal,\n }) || sent;\n }\n catch (error) {\n signalFailures.push(error);\n }\n };\n attemptSignal(resolveAgentControllerProcessSignalId({\n processId: input.processId,\n signalTarget: input.signalTarget,\n }));\n for (const descendantProcessId of trackedDescendantProcessIds) {\n attemptSignal(descendantProcessId);\n }\n if (signalFailures.length > 0) {\n throw signalFailures[0];\n }\n return sent;\n}\nexport function terminateRemainingAgentControllerProcesses(input) {\n return runRemainingAgentControllerProcessCleanup(input);\n}\nasync function runRemainingAgentControllerProcessCleanup(input) {\n let sent = false;\n const trackedDescendantProcessIds = input.trackedDescendantProcessIds ?? new Set();\n for (let attempt = 1; attempt <= PROCESS_SUPERVISION_DISCOVERY_MAX_ATTEMPTS; attempt += 1) {\n let cleanupError = null;\n const groupReused = isReusedExitedRootGroup(input);\n const discovery = await collectSupervisedProcessIds({\n listSupervisedProcessIds: input.listSupervisedProcessIds,\n markerOnly: groupReused,\n processId: input.processId,\n reportDiscoveryFailure: input.reportDiscoveryFailure,\n signalTarget: input.signalTarget,\n supervisionId: input.supervisionId,\n trackedDescendantProcessIds,\n });\n const discoveryError = discovery.error;\n try {\n sent =\n (groupReused\n ? signalCurrentSupervisedProcesses({\n killProcess: input.killProcess,\n processIds: discovery.currentProcessIds,\n })\n : signalAgentControllerProcessTree({\n killProcess: input.killProcess,\n processId: input.processId,\n signal: \"SIGKILL\",\n signalTarget: input.signalTarget,\n trackedDescendantProcessIds,\n })) || sent;\n }\n catch (error) {\n cleanupError = error;\n reportAgentControllerProcessCleanupFailure({\n failure: {\n error,\n processId: input.processId,\n signal: \"SIGKILL\",\n },\n reporter: input.reportCleanupFailure,\n });\n }\n const terminalError = cleanupError ?? discoveryError;\n const reachedFinalAttempt = attempt >= PROCESS_SUPERVISION_DISCOVERY_MAX_ATTEMPTS;\n const cleanupSettled = discoveryError === null && (cleanupError !== null || sent);\n if (reachedFinalAttempt || cleanupSettled) {\n return terminalError === null\n ? { ok: true, signalSent: sent }\n : { error: terminalError, ok: false, signalSent: sent };\n }\n await (input.waitForDiscoveryRetry ?? waitForAgentControllerProcessDiscoveryRetry)();\n }\n return { ok: true, signalSent: sent };\n}\n// A process group ID stays reserved while the group has members, so the\n// exited root's group is still ours unless a live process now holds that PID.\n// In that case the stored group may be someone else's: signal only processes\n// that a fresh marker-only scan finds carrying this invocation's marker.\nfunction isReusedExitedRootGroup(input) {\n if (input.signalTarget !== \"process_group\" ||\n input.processId === null ||\n input.isRootExited?.() !== true) {\n return false;\n }\n try {\n (input.killProcess ?? process.kill)(input.processId, 0);\n return true;\n }\n catch (error) {\n return !isNoSuchProcessError(error);\n }\n}\nfunction signalCurrentSupervisedProcesses(input) {\n let sent = false;\n for (const processId of input.processIds) {\n sent =\n signalProcessId({\n killProcess: input.killProcess,\n processId,\n signal: \"SIGKILL\",\n }) || sent;\n }\n return sent;\n}\nasync function collectSupervisedProcessIds(input) {\n if (input.signalTarget !== \"process_group\" || input.processId === null) {\n return { currentProcessIds: [], error: null };\n }\n const listSupervisedProcessIds = input.listSupervisedProcessIds ?? listAgentControllerSupervisedProcessIds;\n try {\n const supervisedProcessIds = await listSupervisedProcessIds({\n processId: input.markerOnly === true ? null : input.processId,\n supervisionId: input.supervisionId,\n });\n for (const descendantProcessId of supervisedProcessIds) {\n input.trackedDescendantProcessIds.add(descendantProcessId);\n }\n return { currentProcessIds: [...supervisedProcessIds], error: null };\n }\n catch (error) {\n reportAgentControllerProcessDiscoveryFailure({\n failure: {\n error,\n processId: input.processId,\n signal: \"SIGKILL\",\n source: \"supervision_marker\",\n },\n reporter: input.reportDiscoveryFailure,\n });\n return { currentProcessIds: [], error };\n }\n}\nfunction waitForAgentControllerProcessDiscoveryRetry() {\n return new Promise((resolve) => {\n setTimeout(resolve, PROCESS_SUPERVISION_DISCOVERY_RETRY_DELAY_MS);\n });\n}\nexport const listAgentControllerDescendantProcessIds = async (processId) => {\n const processTable = await readProcessTable([\"-axo\", \"pid=,ppid=,pgid=\"], {\n maxBuffer: 4 * 1024 * 1024,\n });\n processDiscoveryDiagnostics.recovered(\"descendant_tree\");\n return resolveAgentControllerDescendantProcessIds({\n processId,\n processTable,\n });\n};\nconst readMacOsSupervisedProcessTable = createAgentControllerProcessTableSnapshotReader({\n // One Service drain can stop several controllers in the same event-loop\n // turn. They need one system snapshot, not one blocking `ps eww` scan per\n // controller. Pending reads stay shared even when slow; settled snapshots\n // expire before the bounded 100 ms retry, which still receives a fresh read.\n maxAgeMs: PROCESS_TABLE_STOP_PHASE_SNAPSHOT_MAX_AGE_MS,\n readProcessTable: async () => await readProcessTable([\"eww\", \"-axo\", \"pid=,ppid=,pgid=,command=\"], {\n maxBuffer: 32 * 1024 * 1024,\n }),\n});\nexport const listAgentControllerSupervisedProcessIds = async (input) => {\n if (process.platform === \"linux\") {\n const processTable = await readProcessTable([\"-e\", \"-o\", \"pid=,ppid=,pgid=\"], { maxBuffer: 4 * 1024 * 1024 });\n processDiscoveryDiagnostics.recovered(\"supervision_marker\");\n return resolveAgentControllerSupervisedProcessIds({\n ...input,\n markedProcessIds: await listLinuxSupervisedProcessIds(input.supervisionId),\n processTable,\n });\n }\n const processTable = await readMacOsSupervisedProcessTable({\n fresh: input.fresh,\n });\n processDiscoveryDiagnostics.recovered(\"supervision_marker\");\n return resolveAgentControllerSupervisedProcessIds({\n ...input,\n processTable,\n });\n};\nexport function resolveAgentControllerSupervisedProcessIds(input) {\n return resolveAgentControllerProcessIdsFromTable({\n ...input,\n supervisionMarker: `${PROCESS_SUPERVISION_ENV_KEY}=${input.supervisionId}`,\n });\n}\nfunction resolveAgentControllerProcessIdsFromTable(input) {\n const childrenByParentProcessId = new Map();\n const processGroupByProcessId = new Map();\n const markedProcessIds = new Set(input.markedProcessIds);\n for (const line of input.processTable.split(PROCESS_TABLE_LINE_SEPARATOR)) {\n const [processIdText, parentProcessIdText, processGroupIdText, ...commandParts] = line.trim().split(PROCESS_TABLE_COLUMN_SEPARATOR);\n const processId = Number.parseInt(processIdText ?? \"\", 10);\n const parentProcessId = Number.parseInt(parentProcessIdText ?? \"\", 10);\n const processGroupId = Number.parseInt(processGroupIdText ?? \"\", 10);\n if (!Number.isInteger(processId) ||\n processId <= 0 ||\n !Number.isInteger(parentProcessId) ||\n parentProcessId < 0 ||\n !Number.isInteger(processGroupId) ||\n processGroupId <= 0) {\n continue;\n }\n const children = childrenByParentProcessId.get(parentProcessId) ?? [];\n children.push(processId);\n childrenByParentProcessId.set(parentProcessId, children);\n processGroupByProcessId.set(processId, processGroupId);\n if (input.supervisionMarker !== undefined &&\n commandParts.includes(input.supervisionMarker)) {\n markedProcessIds.add(processId);\n }\n }\n if (input.processId === null) {\n return [...markedProcessIds];\n }\n return resolveOutOfGroupAgentControllerProcessIds({\n childrenByParentProcessId,\n markedProcessIds,\n processGroupByProcessId,\n processId: input.processId,\n });\n}\nasync function listLinuxSupervisedProcessIds(supervisionId) {\n const supervisionMarker = `${PROCESS_SUPERVISION_ENV_KEY}=${supervisionId}`;\n const processIds = [];\n for (const entry of await readdir(\"/proc\", { withFileTypes: true })) {\n if (!entry.isDirectory()) {\n continue;\n }\n const processId = Number.parseInt(entry.name, 10);\n if (!(Number.isInteger(processId) && String(processId) === entry.name)) {\n continue;\n }\n try {\n const environment = await readFile(`/proc/${entry.name}/environ`, \"utf8\");\n if (environment.split(\"\\0\").includes(supervisionMarker)) {\n processIds.push(processId);\n }\n }\n catch (error) {\n if (!isExpectedLinuxProcessInspectionError(error)) {\n throw error;\n }\n }\n }\n return processIds;\n}\nfunction readProcessTable(args, input) {\n return new Promise((resolve, reject) => {\n execFile(\"ps\", [...args], {\n encoding: \"utf8\",\n maxBuffer: input.maxBuffer,\n timeout: 2000,\n }, (error, stdout) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(stdout);\n });\n });\n}\nfunction isExpectedLinuxProcessInspectionError(error) {\n if (!(error instanceof Error && \"code\" in error)) {\n return false;\n }\n const code = String(error.code);\n return (code === \"EACCES\" ||\n code === \"ENOENT\" ||\n code === \"EPERM\" ||\n code === \"ESRCH\");\n}\nfunction resolveOutOfGroupAgentControllerProcessIds(input) {\n const processIds = new Set();\n const pending = [\n ...(input.childrenByParentProcessId.get(input.processId) ?? []),\n ];\n const visited = new Set([input.processId]);\n while (pending.length > 0) {\n const descendantProcessId = pending.shift();\n if (descendantProcessId === undefined || visited.has(descendantProcessId)) {\n continue;\n }\n visited.add(descendantProcessId);\n if (input.processGroupByProcessId.get(descendantProcessId) !== input.processId) {\n processIds.add(descendantProcessId);\n }\n pending.push(...(input.childrenByParentProcessId.get(descendantProcessId) ?? []));\n }\n for (const markedProcessId of input.markedProcessIds) {\n if (markedProcessId !== input.processId &&\n input.processGroupByProcessId.get(markedProcessId) !== input.processId) {\n processIds.add(markedProcessId);\n }\n }\n return [...processIds];\n}\nexport function resolveAgentControllerDescendantProcessIds(input) {\n return resolveAgentControllerProcessIdsFromTable(input);\n}\nfunction signalProcessId(input) {\n try {\n (input.killProcess ?? process.kill)(input.processId, input.signal);\n return true;\n }\n catch (error) {\n if (isNoSuchProcessError(error) ||\n isUnsignalableExitedProcessGroup(error, input.processId)) {\n return false;\n }\n throw error;\n }\n}\nfunction isUnsignalableExitedProcessGroup(error, processId) {\n // Darwin reports EPERM while an isolated process group contains only its\n // already-exited, not-yet-reaped leader. OpenMeld creates every negative\n // target as a same-user isolated group, so a live member remains signalable.\n return (processId < 0 &&\n error instanceof Error &&\n error.code === \"EPERM\");\n}\nfunction isNoSuchProcessError(error) {\n return (error instanceof Error && error.code === \"ESRCH\");\n}\nfunction reportAgentControllerProcessDiscoveryFailure(input) {\n if (input.reporter) {\n try {\n input.reporter(input.failure);\n return;\n }\n catch (reporterError) {\n reportAgentControllerProcessDiscoveryFailureToConsole({\n ...input.failure,\n reporterError,\n });\n return;\n }\n }\n reportAgentControllerProcessDiscoveryFailureToConsole(input.failure);\n}\nfunction reportAgentControllerProcessCleanupFailure(input) {\n if (input.reporter) {\n try {\n input.reporter(input.failure);\n return;\n }\n catch (reporterError) {\n reportAgentControllerProcessCleanupFailureToConsole({\n ...input.failure,\n reporterError,\n });\n return;\n }\n }\n reportAgentControllerProcessCleanupFailureToConsole(input.failure);\n}\nfunction reportAgentControllerProcessCleanupFailureToConsole(input) {\n const error = normalizeErrorForDiagnostic(input.error);\n const reporterError = input.reporterError\n ? normalizeErrorForDiagnostic(input.reporterError)\n : null;\n console.warn(\"[openmeld.agent_controller.process_cleanup_failed]\", {\n errorCode: error.code,\n errorMessage: error.message,\n errorName: error.name,\n processId: input.processId,\n ...(reporterError\n ? {\n reporterErrorMessage: reporterError.message,\n reporterErrorName: reporterError.name,\n }\n : {}),\n signal: input.signal,\n source: \"remaining_descendants_signal\",\n });\n}\nfunction reportAgentControllerProcessDiscoveryFailureToConsole(input) {\n processDiscoveryDiagnostics.failure(input);\n}\nfunction normalizeErrorForDiagnostic(error) {\n if (error instanceof Error) {\n return {\n code: error.code ?? null,\n message: error.message,\n name: error.name,\n };\n }\n return {\n code: null,\n message: String(error),\n name: \"NonError\",\n };\n}\n","import { spawnAgentControllerProcess } from \"../agent-controller-process.js\";\nconst PROCESS_TIMEOUT_FORCE_KILL_GRACE_MS = 1000;\nexport class CliDriverError extends Error {\n code;\n exitCode;\n signal;\n stderrText;\n stdoutText;\n constructor(input) {\n super(input.message);\n this.code = input.code;\n this.name = \"CliDriverError\";\n this.exitCode = input.exitCode;\n this.signal = input.signal;\n this.stderrText = input.stderrText;\n this.stdoutText = input.stdoutText;\n }\n}\nexport async function runCliDriver(input) {\n const args = [...input.args];\n const timeoutMs = normalizeTimeoutMs(input.timeoutMs);\n const binary = normalizeRequiredText(input.bin, \"bin\");\n const cwd = normalizeRequiredText(input.cwd, \"cwd\");\n return await new Promise((resolve, reject) => {\n const runtimeProcess = spawnAgentControllerProcess({\n args,\n bin: binary,\n cwd,\n env: {\n ...process.env,\n ...(input.env ?? {}),\n },\n shell: input.shell ?? false,\n });\n const { child, processId, signalTarget } = runtimeProcess;\n let settled = false;\n let stdoutText = \"\";\n let stderrText = \"\";\n let stdoutLineBuffer = \"\";\n let stderrLineBuffer = \"\";\n let pendingTimeoutFailure = null;\n const lifecycle = {\n exitCode: null,\n exitObservedAtMs: null,\n exitSignal: null,\n firstStderrAtMs: null,\n firstStdoutAtMs: null,\n processId,\n processSpawnedAtMs: Date.now(),\n stdinClosedAtMs: null,\n timeoutTriggeredAtMs: null,\n };\n const processSpawnedAtMs = Date.now();\n lifecycle.processSpawnedAtMs = processSpawnedAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"process_spawned\",\n processId,\n signalTarget,\n tsMs: processSpawnedAtMs,\n });\n emitProcessControlEvent(input.onProcessControlEvent, {\n phase: \"process_spawned\",\n processId,\n signalTarget,\n });\n const complete = (handler, value) => {\n if (settled) {\n return;\n }\n settled = true;\n handler(value);\n };\n const fail = (error) => {\n if (error instanceof CliDriverError) {\n complete(reject, error);\n return;\n }\n const message = error instanceof Error ? error.message : String(error);\n complete(reject, new CliDriverError({\n code: \"process.spawn_failed\",\n message: `process.spawn_failed: ${message}`,\n }));\n };\n let forceKillTimeout = null;\n let processTimeout = null;\n const clearTimers = () => {\n if (processTimeout !== null) {\n clearTimeout(processTimeout);\n }\n if (forceKillTimeout) {\n clearTimeout(forceKillTimeout);\n }\n };\n const requestProcessTermination = () => {\n runtimeProcess.terminate(\"SIGTERM\");\n forceKillTimeout = setTimeout(() => {\n runtimeProcess.terminate(\"SIGKILL\");\n }, PROCESS_TIMEOUT_FORCE_KILL_GRACE_MS);\n forceKillTimeout.unref?.();\n };\n const completeFromProviderTerminalOutput = (decision) => {\n if (settled || decision.complete !== true) {\n return;\n }\n clearTimers();\n if (decision.terminateProcess !== false) {\n requestProcessTermination();\n }\n complete(resolve, {\n exitCode: lifecycle.exitCode ?? 0,\n lifecycle: {\n ...lifecycle,\n },\n signal: lifecycle.exitSignal,\n stderrText,\n stdoutText,\n });\n };\n const markStdinClosed = () => {\n if (lifecycle.stdinClosedAtMs !== null) {\n return;\n }\n const stdinClosedAtMs = Date.now();\n lifecycle.stdinClosedAtMs = stdinClosedAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"stdin_closed\",\n processId,\n tsMs: stdinClosedAtMs,\n });\n };\n processTimeout =\n timeoutMs === null\n ? null\n : setTimeout(() => {\n const timeoutTriggeredAtMs = Date.now();\n lifecycle.timeoutTriggeredAtMs = timeoutTriggeredAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"timeout_triggered\",\n processId,\n tsMs: timeoutTriggeredAtMs,\n });\n pendingTimeoutFailure = {\n timeoutMs,\n };\n runtimeProcess.terminate(\"SIGTERM\");\n forceKillTimeout = setTimeout(() => {\n runtimeProcess.terminate(\"SIGKILL\");\n }, PROCESS_TIMEOUT_FORCE_KILL_GRACE_MS);\n }, timeoutMs);\n child.on(\"error\", (error) => {\n clearTimers();\n fail(error);\n });\n child.stdin.on(\"error\", (error) => {\n if (isBenignStdinCloseError(error)) {\n markStdinClosed();\n return;\n }\n fail(error);\n });\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n if (settled) {\n return;\n }\n const text = String(chunk);\n if (lifecycle.firstStdoutAtMs === null) {\n const firstStdoutAtMs = Date.now();\n lifecycle.firstStdoutAtMs = firstStdoutAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"first_stdout\",\n processId,\n tsMs: firstStdoutAtMs,\n });\n }\n stdoutText += text;\n const lineEmission = emitLines({\n buffer: stdoutLineBuffer + text,\n onLine: input.onStdoutLine,\n });\n stdoutLineBuffer = lineEmission.buffer;\n if (lineEmission.completionDecision) {\n completeFromProviderTerminalOutput(lineEmission.completionDecision);\n }\n });\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk) => {\n if (settled) {\n return;\n }\n const text = String(chunk);\n if (lifecycle.firstStderrAtMs === null) {\n const firstStderrAtMs = Date.now();\n lifecycle.firstStderrAtMs = firstStderrAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n phase: \"first_stderr\",\n processId,\n tsMs: firstStderrAtMs,\n });\n }\n stderrText += text;\n const lineEmission = emitLines({\n buffer: stderrLineBuffer + text,\n onLine: input.onStderrLine,\n });\n stderrLineBuffer = lineEmission.buffer;\n if (lineEmission.completionDecision) {\n completeFromProviderTerminalOutput(lineEmission.completionDecision);\n }\n });\n child.on(\"close\", async (exitCode, signal) => {\n await runtimeProcess.terminateRemainingDescendants();\n clearTimers();\n const exitObservedAtMs = Date.now();\n lifecycle.exitCode = exitCode;\n lifecycle.exitSignal = signal;\n lifecycle.exitObservedAtMs = exitObservedAtMs;\n emitLifecycleEvent(input.onLifecycleEvent, {\n exitCode,\n phase: \"process_exit\",\n processId,\n signal,\n signalTarget,\n tsMs: exitObservedAtMs,\n });\n emitProcessControlEvent(input.onProcessControlEvent, {\n phase: \"process_exit\",\n processId,\n signalTarget,\n });\n flushLineBuffer(stdoutLineBuffer, input.onStdoutLine);\n flushLineBuffer(stderrLineBuffer, input.onStderrLine);\n const closeFailure = resolveCliDriverCloseFailure({\n allowNonZeroExit: input.allowNonZeroExit,\n exitCode,\n pendingTimeoutFailure,\n signal,\n stderrText,\n stdoutText,\n });\n if (closeFailure) {\n complete(reject, closeFailure);\n return;\n }\n complete(resolve, {\n exitCode: exitCode ?? 0,\n lifecycle,\n signal,\n stderrText,\n stdoutText,\n });\n });\n child.stdin.end((input.inputText ?? \"\").toString(), () => {\n markStdinClosed();\n });\n });\n}\nconst normalizeTimeoutMs = (value) => {\n if (value === null || typeof value === \"undefined\") {\n return null;\n }\n if (!Number.isInteger(value) || value <= 0) {\n throw new CliDriverError({\n code: \"input.invalid\",\n message: \"input.invalid: timeoutMs must be a positive integer\",\n });\n }\n return value;\n};\nconst resolveCliDriverCloseFailure = (input) => {\n if (input.pendingTimeoutFailure) {\n return new CliDriverError({\n code: \"process.timeout\",\n message: `process.timeout: command exceeded ${String(input.pendingTimeoutFailure.timeoutMs)}ms`,\n exitCode: input.exitCode,\n signal: input.signal,\n stderrText: input.stderrText,\n stdoutText: input.stdoutText,\n });\n }\n if (input.exitCode === 0 || input.allowNonZeroExit === true) {\n return null;\n }\n return new CliDriverError({\n code: \"process.non_zero_exit\",\n message: `process.non_zero_exit: command exited with code ${String(input.exitCode)}${input.signal ? ` (signal=${input.signal})` : \"\"}`,\n exitCode: input.exitCode,\n signal: input.signal,\n stderrText: input.stderrText,\n stdoutText: input.stdoutText,\n });\n};\nconst normalizeRequiredText = (value, field) => {\n const normalized = value.trim();\n if (!normalized) {\n throw new CliDriverError({\n code: \"input.invalid\",\n message: `input.invalid: ${field} is required`,\n });\n }\n return normalized;\n};\nconst isBenignStdinCloseError = (error) => {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = \"code\" in error && typeof error.code === \"string\" ? error.code : null;\n return code === \"EPIPE\" || code === \"ERR_STREAM_DESTROYED\";\n};\nconst emitLines = (input) => {\n const lines = input.buffer.split(\"\\n\");\n const pending = lines.pop() ?? \"\";\n let completionDecision = null;\n for (const line of lines) {\n const decision = input.onLine?.({\n line,\n });\n if (isCliDriverLineDecision(decision) && decision.complete === true) {\n completionDecision = decision;\n }\n }\n return {\n buffer: pending,\n completionDecision,\n };\n};\nconst flushLineBuffer = (lineBuffer, onLine) => {\n if (!lineBuffer) {\n return;\n }\n onLine?.({\n line: lineBuffer,\n });\n};\nconst isCliDriverLineDecision = (value) => typeof value === \"object\" && value !== null;\nconst emitLifecycleEvent = (onLifecycleEvent, event) => {\n onLifecycleEvent?.(event);\n};\nconst emitProcessControlEvent = (onProcessControlEvent, event) => {\n onProcessControlEvent?.(event);\n};\n","import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { accessSync, constants, readFileSync } from \"node:fs\";\nimport { access, open, realpath } from \"node:fs/promises\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { delimiter, dirname, extname, isAbsolute, join } from \"node:path\";\nimport { CliDriverError, runCliDriver } from \"./drivers/cli-driver.js\";\nconst ENV_NODE_SHEBANG = \"#!/usr/bin/env node\";\nconst WINDOWS_PATHEXT = [\".com\", \".exe\", \".bat\", \".cmd\"];\nconst SHEBANG_ARGS_SPLIT_RE = /\\s+/;\nconst FIRST_LINE_SPLIT_RE = /\\r?\\n/u;\nconst LOGIN_SHELL_OUTPUT_LINE_SPLIT_RE = /\\r?\\n/u;\nconst SAFE_POSIX_SHELL_TOKEN_RE = /^[A-Za-z0-9_./:@%+=,-]+$/u;\nconst NVM_VERSION_VALUE_RE = /^v?\\d+(?:\\.\\d+){0,2}$/u;\nconst NODE_VERSION_PATH_RE = /(?:^|\\/)v?(\\d+\\.\\d+\\.\\d+)(?:\\/|$)/u;\nconst MACOS_TEMP_FOLDER_RE = /^\\/var\\/folders\\/[^/]+\\/[^/]+\\/t(?:\\/|$)/u;\nconst WRAPPER_PATH_SEGMENT_RE = /(?:^|[-_.])(?:shim|shims|wrapper|wrappers)(?:$|[-_.])/u;\nconst MAX_LAUNCH_SCRIPT_INSPECTION_BYTES = 64 * 1024;\nconst DEFAULT_LOGIN_SHELL_LOOKUP_TIMEOUT_MS = 1500;\nconst HOME_DIR = normalizeOptionalText(homedir());\nconst TEMP_DIR = normalizeOptionalText(tmpdir());\nconst loginShellExecutablePathsCache = new Map();\nexport function buildExecutableLaunchContract(input) {\n return {\n kind: \"executable\",\n commandPath: input.commandPath,\n ...(input.argsPrefix && input.argsPrefix.length > 0\n ? { argsPrefix: [...input.argsPrefix] }\n : {}),\n };\n}\nexport function materializeCliLaunchCommand(input) {\n if (input.launchContract.kind === \"executable\") {\n const shell = commandPathRequiresShell(input.launchContract.commandPath);\n return {\n argsPrefix: [...(input.launchContract.argsPrefix ?? [])],\n bin: input.launchContract.commandPath,\n ...(shell ? { shell: true } : {}),\n };\n }\n return {\n argsPrefix: [\n input.launchContract.scriptPath,\n ...(input.launchContract.argsPrefix ?? []),\n ],\n bin: input.launchContract.nodePath,\n };\n}\nfunction resolveLaunchContractEntrypointPath(launchContract) {\n return launchContract.kind === \"executable\"\n ? launchContract.commandPath\n : launchContract.scriptPath;\n}\nexport function buildCliLaunchInvocation(input) {\n const launchCommand = materializeCliLaunchCommand({\n launchContract: input.launchContract,\n });\n return {\n args: [...launchCommand.argsPrefix, ...input.args],\n bin: launchCommand.bin,\n ...(launchCommand.shell ? { shell: true } : {}),\n };\n}\nexport async function verifyLaunchContractFiles(input) {\n try {\n const launchCommand = materializeCliLaunchCommand(input);\n if (input.launchContract.kind === \"executable\") {\n await assertExecutablePath(input.launchContract.commandPath);\n }\n else {\n await assertExecutablePath(input.launchContract.nodePath);\n await assertReadablePath(input.launchContract.scriptPath);\n }\n return {\n launchCommand,\n ok: true,\n };\n }\n catch (error) {\n const code = error instanceof Error && \"code\" in error ? error.code : null;\n let failureReason;\n if (code === \"ENOENT\") {\n failureReason = \"installation_missing\";\n }\n else if (code === \"EACCES\" || code === \"EPERM\") {\n failureReason = \"installation_access_denied\";\n }\n return {\n errorMessage: toErrorMessage(error),\n failureKind: \"completed_negative\",\n ...(failureReason ? { failureReason } : {}),\n ok: false,\n };\n }\n}\nexport async function verifyCliLaunchContract(input) {\n const fileCheck = await verifyLaunchContractFiles({\n launchContract: input.launchContract,\n });\n if (!fileCheck.ok) {\n return {\n errorMessage: `${input.displayName} launch contract is broken on this device: ${fileCheck.errorMessage}`,\n failureKind: \"completed_negative\",\n ok: false,\n };\n }\n try {\n const invocation = buildCliLaunchInvocation({\n args: input.probeArgs,\n launchContract: input.launchContract,\n });\n await runCliDriver({\n allowNonZeroExit: false,\n args: invocation.args,\n bin: invocation.bin,\n cwd: input.cwd,\n env: input.env,\n timeoutMs: input.timeoutMs ?? 15_000,\n });\n return fileCheck;\n }\n catch (error) {\n return {\n errorMessage: `${input.displayName} can't start on this device: ${toErrorMessage(error)}`,\n failureKind: classifyLaunchContractVerificationFailure(error),\n ok: false,\n };\n }\n}\nexport async function resolveLaunchCandidatesAfterVerification(input) {\n const outcomes = await Promise.all(input.candidates.map(async (candidate) => ({\n candidate,\n verification: await input.verify(candidate),\n })));\n const verifiedCandidates = outcomes\n .filter(({ verification }) => verification.ok)\n .map(({ candidate }) => candidate);\n if (verifiedCandidates.length > 0) {\n return verifiedCandidates;\n }\n return outcomes\n .filter(({ verification }) => !verification.ok && verification.failureKind === \"incomplete_check\")\n .map(({ candidate }) => candidate);\n}\nfunction classifyLaunchContractVerificationFailure(error) {\n return error instanceof CliDriverError &&\n error.code === \"process.non_zero_exit\" &&\n typeof error.exitCode === \"number\"\n ? \"completed_negative\"\n : \"incomplete_check\";\n}\nexport async function resolveInstalledNodeScriptLaunchContract(input) {\n const candidates = await resolveInstalledNodeScriptLaunchCandidates({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: input.commandName,\n configuredCommand: input.configuredCommand ?? null,\n displayName: input.displayName,\n });\n if (!candidates.ok) {\n return candidates;\n }\n const candidate = candidates.candidates[0] ?? null;\n if (!candidate) {\n return {\n errorMessage: `${input.displayName} is not installed on this device.`,\n ok: false,\n };\n }\n return {\n commandPath: candidate.commandPath,\n launchContract: candidate.launchContract,\n ok: true,\n };\n}\nexport async function resolveInstalledNodeScriptLaunchCandidates(input) {\n const preferredCommandPath = input.preferredLaunchContract\n ? resolveLaunchContractEntrypointPath(input.preferredLaunchContract)\n : null;\n const commandPaths = await resolveInstalledCommandPathsForLaunch({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: input.commandName,\n configuredCommand: input.configuredCommand ?? null,\n preferredCommandPath,\n });\n if (commandPaths.length === 0) {\n return {\n errorMessage: `${input.displayName} is not installed on this device.`,\n reason: \"not_installed\",\n ok: false,\n };\n }\n const candidates = [];\n const candidateIds = new Set();\n const inspectionErrors = [];\n for (const commandPath of commandPaths) {\n const candidate = await inspectInstalledNodeScriptLaunchCandidate({\n commandPath,\n displayName: input.displayName,\n });\n if (!candidate.ok) {\n inspectionErrors.push(candidate.errorMessage);\n continue;\n }\n if (candidateIds.has(candidate.dedupeId)) {\n continue;\n }\n candidateIds.add(candidate.dedupeId);\n candidates.push({\n ...candidate,\n preferred: preferredCommandPath !== null &&\n normalizePathForDetection(commandPath) ===\n normalizePathForDetection(preferredCommandPath),\n });\n }\n if (candidates.length === 0) {\n return {\n errorMessage: inspectionErrors[0] ??\n `${input.displayName} is installed, but OpenMeld could not inspect its launch files.`,\n reason: \"not_launchable\",\n ok: false,\n };\n }\n const stableCandidates = candidates.filter((candidate) => !candidate.transientWrapper);\n // Ignore incidental temporary wrappers once a stable install exists, but\n // never hide the wrapper this computer is already configured to use.\n const selectedCandidates = stableCandidates.length > 0\n ? candidates.filter((candidate) => !candidate.transientWrapper || candidate.preferred)\n : candidates;\n return {\n candidates: finalizeLaunchCandidateDisplayMetadata(selectedCandidates.map((candidate) => candidate.launchCandidate)),\n ok: true,\n };\n}\nasync function inspectInstalledNodeScriptLaunchCandidate(input) {\n try {\n await assertExecutablePath(input.commandPath);\n const resolvedScriptPath = await realpath(input.commandPath);\n const script = await readLaunchScriptInspection(resolvedScriptPath);\n const nodePath = await resolvePinnedNodePath({\n firstLine: script.firstLine,\n commandPath: input.commandPath,\n scriptPath: resolvedScriptPath,\n });\n const transientWrapper = isTransientPathWrapper({\n commandPath: input.commandPath,\n contents: script.contents,\n firstLine: script.firstLine,\n scriptPath: resolvedScriptPath,\n });\n const launchContract = nodePath\n ? {\n kind: \"node_script\",\n nodePath,\n // Keep the user-facing command entrypoint in the launch contract.\n // Managed CLIs such as cursor-agent update this symlink in place;\n // persisting its resolved version file would pin OpenMeld to the old\n // release forever even though the official command has moved on.\n scriptPath: input.commandPath,\n }\n : buildExecutableLaunchContract({\n commandPath: input.commandPath,\n });\n const canonicalLaunchContract = nodePath\n ? {\n kind: \"node_script\",\n nodePath,\n scriptPath: resolvedScriptPath,\n }\n : buildExecutableLaunchContract({\n commandPath: resolvedScriptPath,\n });\n return {\n dedupeId: buildLaunchCandidateInstallId(canonicalLaunchContract),\n launchCandidate: buildLaunchCandidate({\n commandPath: input.commandPath,\n launchContract,\n transientWrapper,\n }),\n ok: true,\n transientWrapper,\n };\n }\n catch (error) {\n return {\n errorMessage: `${input.displayName} is installed, but OpenMeld could not inspect its launch files: ${toErrorMessage(error)}`,\n ok: false,\n };\n }\n}\nexport function resolveInstalledCommandPath(input) {\n return resolveInstalledCommandPaths(input)[0] ?? null;\n}\nexport function resolveInstalledCommandPaths(input) {\n const configuredCommand = normalizeOptionalText(input.configuredCommand);\n if (configuredCommand) {\n if (isAbsolute(configuredCommand)) {\n return [configuredCommand];\n }\n if (configuredCommand.includes(\"/\") || configuredCommand.includes(\"\\\\\")) {\n return [];\n }\n return resolveExecutablePathsOnPath(configuredCommand);\n }\n return resolveExecutablePathsOnPath(input.commandName);\n}\nasync function resolveInstalledCommandPathsForLaunch(input) {\n const preferredCommandPath = normalizeOptionalText(input.preferredCommandPath);\n // A saved install may no longer be reachable through this Service process's\n // PATH. Treat it as one more discovery seed, never as trusted inventory:\n // every returned path is still inspected here and launch-verified by the\n // owning adapter.\n const preferredCommandPaths = preferredCommandPath && isAbsolute(preferredCommandPath)\n ? [preferredCommandPath]\n : [];\n const configuredCommand = normalizeOptionalText(input.configuredCommand);\n if (configuredCommand) {\n if (isAbsolute(configuredCommand)) {\n return mergeUniquePaths(preferredCommandPaths, [configuredCommand]);\n }\n if (configuredCommand.includes(\"/\") || configuredCommand.includes(\"\\\\\")) {\n return preferredCommandPaths;\n }\n return mergeUniquePaths(preferredCommandPaths, await resolveExecutablePathsFromSearchSurface({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: configuredCommand,\n }));\n }\n return mergeUniquePaths(preferredCommandPaths, await resolveExecutablePathsFromSearchSurface({\n additionalCommandDirectories: input.additionalCommandDirectories ?? null,\n commandName: input.commandName,\n }));\n}\nexport function resolveExecutableOnPath(commandName) {\n return resolveExecutablePathsOnPath(commandName)[0] ?? null;\n}\nexport function resolveExecutablePathsOnPath(commandName) {\n const normalizedCommandName = normalizeOptionalText(commandName);\n if (!normalizedCommandName) {\n return [];\n }\n const resolvedPaths = [];\n for (const directory of resolvePathDirectories()) {\n for (const candidateName of resolveCommandFileNameCandidates(normalizedCommandName)) {\n const candidate = join(directory, candidateName);\n if (pathLooksExecutable(candidate) &&\n !resolvedPaths.includes(candidate)) {\n resolvedPaths.push(candidate);\n }\n }\n }\n return resolvedPaths;\n}\nasync function resolveExecutablePathsFromSearchSurface(input) {\n const pathMatches = resolveExecutablePathsOnPath(input.commandName);\n const additionalDirectoryMatches = resolveExecutablePathsFromDirectories({\n commandName: input.commandName,\n directories: input.additionalCommandDirectories ?? [],\n });\n const knownInstallMatches = resolveExecutablePathsFromKnownInstallDirectories(input.commandName);\n const localMatches = mergeUniquePaths(mergeUniquePaths(pathMatches, additionalDirectoryMatches), knownInstallMatches);\n if (localMatches.length > 0) {\n return localMatches;\n }\n const loginShellPaths = await resolveExecutablePathsFromLoginShell(input.commandName);\n return mergeUniquePaths(localMatches, loginShellPaths);\n}\nfunction resolvePathDirectories() {\n const directories = [];\n const pathValue = normalizeOptionalText(process.env.PATH);\n for (const pathEntry of pathValue?.split(delimiter) ?? []) {\n addUniqueDirectory(directories, pathEntry);\n }\n return directories;\n}\nfunction resolveExecutablePathsFromKnownInstallDirectories(commandName) {\n return resolveExecutablePathsFromDirectories({\n commandName,\n directories: resolveKnownInstallDirectories(),\n });\n}\nfunction resolveExecutablePathsFromDirectories(input) {\n const normalizedCommandName = normalizeOptionalText(input.commandName);\n if (!normalizedCommandName) {\n return [];\n }\n const resolvedPaths = [];\n for (const directory of input.directories) {\n for (const candidateName of resolveCommandFileNameCandidates(normalizedCommandName)) {\n const candidate = join(directory, candidateName);\n if (pathLooksExecutable(candidate) &&\n !resolvedPaths.includes(candidate)) {\n resolvedPaths.push(candidate);\n }\n }\n }\n return resolvedPaths;\n}\nfunction resolveKnownInstallDirectories() {\n const directories = [];\n if (process.platform === \"win32\") {\n return directories;\n }\n const home = resolveHomeDirectory();\n const nvmDir = normalizeOptionalText(process.env.NVM_DIR) ?? join(home, \".nvm\");\n const pnpmHome = normalizeOptionalText(process.env.PNPM_HOME) ??\n (process.platform === \"darwin\"\n ? join(home, \"Library\", \"pnpm\")\n : join(home, \".local\", \"share\", \"pnpm\"));\n const bunHome = normalizeOptionalText(process.env.BUN_INSTALL) ?? join(home, \".bun\");\n const voltaHome = normalizeOptionalText(process.env.VOLTA_HOME) ?? join(home, \".volta\");\n const asdfHome = normalizeOptionalText(process.env.ASDF_DIR) ?? join(home, \".asdf\");\n const fnmHome = normalizeOptionalText(process.env.FNM_DIR) ?? join(home, \".fnm\");\n addUniqueDirectory(directories, join(home, \".local\", \"bin\"));\n addUniqueDirectory(directories, \"/usr/local/bin\");\n addUniqueDirectory(directories, \"/opt/homebrew/bin\");\n addUniqueDirectory(directories, join(bunHome, \"bin\"));\n addUniqueDirectory(directories, pnpmHome);\n addUniqueDirectory(directories, join(home, \".npm-global\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".yarn\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".config\", \"yarn\", \"global\", \"node_modules\", \".bin\"));\n addUniqueDirectory(directories, join(voltaHome, \"bin\"));\n addUniqueDirectory(directories, join(asdfHome, \"shims\"));\n addUniqueDirectory(directories, join(fnmHome, \"aliases\", \"default\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".local\", \"share\", \"fnm\", \"aliases\", \"default\", \"bin\"));\n addUniqueDirectory(directories, join(home, \".local\", \"share\", \"fnm\", \"current\", \"bin\"));\n for (const nvmBinDir of resolveNvmDefaultBinDirectories(nvmDir)) {\n addUniqueDirectory(directories, nvmBinDir);\n }\n const npmConfigPrefix = normalizeOptionalText(process.env.NPM_CONFIG_PREFIX);\n if (npmConfigPrefix) {\n addUniqueDirectory(directories, join(npmConfigPrefix, \"bin\"));\n }\n return directories;\n}\nfunction addUniqueDirectory(directories, value) {\n const directory = normalizeOptionalText(value);\n if (directory && !directories.includes(directory)) {\n directories.push(directory);\n }\n}\nasync function resolveExecutablePathsFromLoginShell(commandName) {\n const normalizedCommandName = normalizeOptionalText(commandName);\n if (!(normalizedCommandName && process.platform !== \"win32\")) {\n return [];\n }\n const shell = normalizeOptionalText(process.env.SHELL);\n if (!(shell && isAbsolute(shell) && pathLooksExecutable(shell))) {\n return [];\n }\n const cacheKey = [\n shell,\n normalizedCommandName,\n process.env.HOME ?? \"\",\n process.env.PATH ?? \"\",\n ].join(\"\\0\");\n let cached = loginShellExecutablePathsCache.get(cacheKey);\n if (!cached) {\n cached = runLoginShellExecutableLookup({\n commandName: normalizedCommandName,\n shell,\n });\n loginShellExecutablePathsCache.set(cacheKey, cached);\n }\n return await cached;\n}\nasync function runLoginShellExecutableLookup(input) {\n const timeoutMs = resolveLoginShellLookupTimeoutMs();\n return await new Promise((resolve) => {\n const child = spawn(input.shell, [\"-lic\", `command -v ${quotePosixShellToken(input.commandName)}`], {\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n windowsHide: true,\n });\n let stdout = \"\";\n let settled = false;\n const finish = (paths) => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timeout);\n resolve(paths);\n };\n const timeout = setTimeout(() => {\n child.kill();\n finish([]);\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.once(\"error\", () => {\n finish([]);\n });\n child.once(\"close\", (code) => {\n if (code !== 0) {\n finish([]);\n return;\n }\n finish(stdout\n .split(LOGIN_SHELL_OUTPUT_LINE_SPLIT_RE)\n .map((line) => normalizeOptionalText(line))\n .filter((line) => Boolean(line && isAbsolute(line) && pathLooksExecutable(line))));\n });\n });\n}\nfunction resolveNvmDefaultBinDirectories(nvmDir) {\n const version = resolveNvmDefaultVersion(nvmDir);\n if (!version) {\n return [];\n }\n return [join(nvmDir, \"versions\", \"node\", version, \"bin\")];\n}\nfunction resolveNvmDefaultVersion(nvmDir) {\n let value = readNvmAlias(nvmDir, \"default\");\n const seenAliases = new Set();\n for (let depth = 0; depth < 4; depth += 1) {\n const normalizedValue = normalizeOptionalText(value);\n if (!normalizedValue) {\n return null;\n }\n if (isNvmVersionValue(normalizedValue)) {\n return normalizedValue.startsWith(\"v\")\n ? normalizedValue\n : `v${normalizedValue}`;\n }\n if (seenAliases.has(normalizedValue)) {\n return null;\n }\n seenAliases.add(normalizedValue);\n value = readNvmAlias(nvmDir, normalizedValue);\n }\n return null;\n}\nfunction readNvmAlias(nvmDir, alias) {\n try {\n return normalizeOptionalText(readFileSync(join(nvmDir, \"alias\", alias), \"utf8\"));\n }\n catch {\n return null;\n }\n}\nfunction isNvmVersionValue(value) {\n return NVM_VERSION_VALUE_RE.test(value);\n}\nfunction resolveHomeDirectory() {\n return normalizeOptionalText(process.env.HOME) ?? homedir();\n}\nfunction resolveLoginShellLookupTimeoutMs() {\n const raw = normalizeOptionalText(process.env.OPENMELD_EXECUTABLE_LOGIN_SHELL_TIMEOUT_MS);\n if (!raw) {\n return DEFAULT_LOGIN_SHELL_LOOKUP_TIMEOUT_MS;\n }\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0\n ? parsed\n : DEFAULT_LOGIN_SHELL_LOOKUP_TIMEOUT_MS;\n}\nfunction mergeUniquePaths(left, right) {\n const merged = [...left];\n for (const path of right) {\n if (!merged.includes(path)) {\n merged.push(path);\n }\n }\n return merged;\n}\nfunction quotePosixShellToken(value) {\n if (SAFE_POSIX_SHELL_TOKEN_RE.test(value)) {\n return value;\n }\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\nexport function resolveSiblingCommandPath(input) {\n const normalizedCommandName = normalizeOptionalText(input.commandName);\n if (!normalizedCommandName) {\n return null;\n }\n const siblingDirectory = dirname(input.anchorPath);\n for (const candidateName of resolveCommandFileNameCandidates(normalizedCommandName)) {\n const candidate = join(siblingDirectory, candidateName);\n if (pathLooksExecutable(candidate)) {\n return candidate;\n }\n }\n return null;\n}\nasync function resolvePinnedNodePath(input) {\n const firstLine = normalizeOptionalText(input.firstLine);\n if (!firstLine) {\n return null;\n }\n if (firstLine === ENV_NODE_SHEBANG) {\n const nodeSiblings = [\n join(dirname(input.commandPath), \"node\"),\n join(dirname(input.scriptPath), \"node\"),\n ].filter((candidate, index, candidates) => {\n return candidates.indexOf(candidate) === index;\n });\n for (const nodeSibling of nodeSiblings) {\n if (await canAccessExecutablePath(nodeSibling)) {\n return nodeSibling;\n }\n }\n return null;\n }\n if (!firstLine.startsWith(\"#!\")) {\n return null;\n }\n const interpreter = normalizeOptionalText(firstLine.slice(2));\n if (!(interpreter && isAbsolute(interpreter))) {\n return null;\n }\n const normalizedInterpreter = interpreter.split(SHEBANG_ARGS_SPLIT_RE, 1)[0] ?? interpreter;\n try {\n await assertExecutablePath(normalizedInterpreter);\n return normalizedInterpreter;\n }\n catch {\n return null;\n }\n}\nasync function assertExecutablePath(path) {\n await access(path, resolveRunnablePathAccessMode());\n}\nasync function canAccessExecutablePath(path) {\n try {\n await assertExecutablePath(path);\n return true;\n }\n catch {\n return false;\n }\n}\nasync function assertReadablePath(path) {\n await access(path, constants.R_OK);\n}\nfunction pathLooksExecutable(path) {\n try {\n accessSync(path, resolveRunnablePathAccessMode());\n return true;\n }\n catch {\n return false;\n }\n}\nfunction commandPathRequiresShell(commandPath) {\n if (process.platform !== \"win32\") {\n return false;\n }\n const normalizedExtension = extname(commandPath).toLowerCase();\n return normalizedExtension === \".cmd\" || normalizedExtension === \".bat\";\n}\nfunction resolveCommandFileNameCandidates(commandName) {\n if (process.platform !== \"win32\") {\n return [commandName];\n }\n const normalizedExtension = extname(commandName).toLowerCase();\n if (normalizedExtension.length > 0) {\n return [commandName];\n }\n return [\n ...resolveWindowsPathExtensions(process.env.PATHEXT).map((extension) => `${commandName}${extension}`),\n commandName,\n ].filter((candidate, index, candidates) => {\n return candidates.indexOf(candidate) === index;\n });\n}\nfunction resolveRunnablePathAccessMode() {\n return process.platform === \"win32\" ? constants.F_OK : constants.X_OK;\n}\nfunction resolveWindowsPathExtensions(value) {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n return [...WINDOWS_PATHEXT];\n }\n return normalized\n .split(\";\")\n .map((entry) => entry.trim().toLowerCase())\n .filter((entry, index, values) => entry && values.indexOf(entry) === index)\n .map((entry) => (entry.startsWith(\".\") ? entry : `.${entry}`));\n}\nfunction normalizeOptionalText(value) {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\nfunction buildLaunchCandidate(input) {\n const installId = buildLaunchCandidateInstallId(input.launchContract);\n const sourceLabel = input.transientWrapper\n ? \"Temporary wrapper\"\n : resolveLaunchCandidateSourceLabel(input.commandPath);\n const detail = resolveLaunchCandidateDetail({\n commandPath: input.commandPath,\n launchContract: input.launchContract,\n transientWrapper: input.transientWrapper,\n });\n return {\n installId,\n label: sourceLabel,\n detail,\n commandPath: input.commandPath,\n launchContract: input.launchContract,\n };\n}\nfunction buildLaunchCandidateInstallId(launchContract) {\n const canonical = JSON.stringify(canonicalizeLaunchContract(launchContract));\n const digest = createHash(\"sha256\").update(canonical).digest(\"hex\");\n return `install_${digest.slice(0, 12)}`;\n}\nfunction canonicalizeLaunchContract(launchContract) {\n if (launchContract.kind === \"executable\") {\n return {\n kind: launchContract.kind,\n commandPath: launchContract.commandPath,\n argsPrefix: [...(launchContract.argsPrefix ?? [])],\n };\n }\n return {\n kind: launchContract.kind,\n nodePath: launchContract.nodePath,\n scriptPath: launchContract.scriptPath,\n argsPrefix: [...(launchContract.argsPrefix ?? [])],\n };\n}\nfunction finalizeLaunchCandidateDisplayMetadata(candidates) {\n const candidateIndexesByLabel = new Map();\n for (const [index, candidate] of candidates.entries()) {\n const currentIndexes = candidateIndexesByLabel.get(candidate.label) ?? [];\n currentIndexes.push(index);\n candidateIndexesByLabel.set(candidate.label, currentIndexes);\n }\n const nextCandidates = candidates.map((candidate) => ({ ...candidate }));\n for (const indexes of candidateIndexesByLabel.values()) {\n if (indexes.length < 2) {\n continue;\n }\n const duplicateCandidates = indexes\n .map((index) => nextCandidates[index])\n .filter((candidate) => Boolean(candidate));\n const labelSuffixes = resolveDistinctLaunchCandidateLabelSuffixes(duplicateCandidates);\n for (const [offset, index] of indexes.entries()) {\n const suffix = labelSuffixes[offset];\n if (!suffix) {\n continue;\n }\n const currentCandidate = nextCandidates[index];\n if (!currentCandidate) {\n continue;\n }\n currentCandidate.label = `${currentCandidate.label} (${suffix})`;\n }\n }\n return nextCandidates;\n}\nfunction resolveDistinctLaunchCandidateLabelSuffixes(candidates) {\n const directoryLabels = candidates.map((candidate) => resolveLaunchCandidateDirectoryLabel(candidate.commandPath));\n if (hasOnlyDistinctValues(directoryLabels)) {\n return directoryLabels;\n }\n const commandLabels = candidates.map((candidate) => shortenPathForDisplay(candidate.commandPath));\n if (hasOnlyDistinctValues(commandLabels)) {\n return commandLabels;\n }\n return candidates.map((candidate) => candidate.installId);\n}\nfunction hasOnlyDistinctValues(values) {\n return values.length === new Set(values).size;\n}\nfunction resolveLaunchCandidateSourceLabel(commandPath) {\n const normalizedPath = commandPath.toLowerCase();\n if (normalizedPath.includes(\".app/contents/\")) {\n return \"App install\";\n }\n if (normalizedPath.includes(\"/.nvm/\")) {\n return \"nvm install\";\n }\n if (normalizedPath.includes(\"/opt/homebrew/\") ||\n normalizedPath.includes(\"/cellar/\") ||\n normalizedPath.includes(\"/homebrew/\")) {\n return \"Homebrew install\";\n }\n if (normalizedPath.includes(\"/.asdf/\")) {\n return \"asdf install\";\n }\n if (normalizedPath.includes(\"/.volta/\")) {\n return \"Volta install\";\n }\n if (normalizedPath.includes(\"/.fnm/\")) {\n return \"fnm install\";\n }\n if (normalizedPath.includes(\"/.local/bin/\")) {\n return \"User install\";\n }\n if (normalizedPath.includes(\"/usr/local/bin/\")) {\n return \"System-wide install\";\n }\n if (normalizedPath.startsWith(\"/usr/bin/\") ||\n normalizedPath.startsWith(\"/bin/\")) {\n return \"System install\";\n }\n return \"Other install\";\n}\nfunction resolveLaunchCandidateDetail(input) {\n const nodeVersion = input.launchContract.kind === \"node_script\"\n ? resolveNodeVersionFromPath(input.launchContract.nodePath)\n : null;\n const commandDirectory = resolveLaunchCandidateDirectoryLabel(input.commandPath);\n if (input.transientWrapper) {\n return `Temporary PATH wrapper · ${commandDirectory}`;\n }\n if (nodeVersion) {\n return `Node ${nodeVersion} · ${commandDirectory}`;\n }\n return commandDirectory;\n}\nfunction resolveLaunchCandidateDirectoryLabel(commandPath) {\n return shortenPathForDisplay(dirname(commandPath));\n}\nfunction shortenPathForDisplay(path) {\n if (!(HOME_DIR && path.startsWith(HOME_DIR))) {\n return path;\n }\n if (path === HOME_DIR) {\n return \"~\";\n }\n return `~${path.slice(HOME_DIR.length)}`;\n}\nfunction resolveNodeVersionFromPath(path) {\n const match = path.match(NODE_VERSION_PATH_RE);\n return normalizeOptionalText(match?.[1]);\n}\nasync function readLaunchScriptInspection(path) {\n const file = await open(path, \"r\");\n let contents = \"\";\n try {\n const buffer = Buffer.allocUnsafe(MAX_LAUNCH_SCRIPT_INSPECTION_BYTES);\n const { bytesRead } = await file.read(buffer, 0, MAX_LAUNCH_SCRIPT_INSPECTION_BYTES, 0);\n contents = buffer.toString(\"utf8\", 0, bytesRead);\n }\n finally {\n await file.close();\n }\n const firstLine = contents.split(FIRST_LINE_SPLIT_RE, 1)[0] ?? \"\";\n return {\n contents,\n firstLine: normalizeOptionalText(firstLine),\n };\n}\nfunction isTransientPathWrapper(input) {\n if (!(isInsideTemporaryDirectory(input.commandPath) ||\n isInsideTemporaryDirectory(input.scriptPath))) {\n return false;\n }\n return (hasWrapperPathSegment(input.commandPath) ||\n hasWrapperPathSegment(input.scriptPath) ||\n shellScriptLooksLikeWrapper(input));\n}\nfunction isInsideTemporaryDirectory(path) {\n const normalizedPath = normalizePathForDetection(path);\n const normalizedTempDir = TEMP_DIR\n ? normalizePathForDetection(TEMP_DIR)\n : null;\n if (normalizedTempDir &&\n pathIsEqualOrDescendant(normalizedPath, normalizedTempDir)) {\n return true;\n }\n return (pathIsEqualOrDescendant(normalizedPath, \"/tmp\") ||\n pathIsEqualOrDescendant(normalizedPath, \"/private/tmp\") ||\n MACOS_TEMP_FOLDER_RE.test(normalizedPath));\n}\nfunction hasWrapperPathSegment(path) {\n return normalizePathForDetection(path)\n .split(\"/\")\n .filter((segment) => segment.length > 0)\n .slice(-4)\n .some((segment) => WRAPPER_PATH_SEGMENT_RE.test(segment));\n}\nfunction shellScriptLooksLikeWrapper(input) {\n const firstLine = normalizeOptionalText(input.firstLine)?.toLowerCase() ?? \"\";\n if (!(firstLine.includes(\"bash\") ||\n firstLine.includes(\"/sh\") ||\n firstLine.includes(\"zsh\"))) {\n return false;\n }\n const contents = input.contents.toLowerCase();\n return (contents.includes(\"wrapper_shim\") ||\n contents.includes(\"shim_root\") ||\n (contents.includes(\"\\nexec \") &&\n (contents.includes(\"wrapper\") || contents.includes(\"shim\"))));\n}\nfunction normalizePathForDetection(path) {\n return path.replaceAll(\"\\\\\", \"/\").replace(/\\/+/gu, \"/\").toLowerCase();\n}\nfunction pathIsEqualOrDescendant(path, parentPath) {\n return path === parentPath || path.startsWith(`${parentPath}/`);\n}\nfunction toErrorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\n","import { spawnAgentControllerProcess, } from \"./agent-controller-process.js\";\nimport { buildCliLaunchInvocation } from \"./launch-contract.js\";\nconst ACP_PROCESS_KILL_GRACE_MS = 1000;\nconst MAX_STDERR_CHARS = 16_000;\nexport class AcpProcessSession {\n #args;\n #createError;\n #cwd;\n #env;\n #launchContract;\n #mapJsonRpcError;\n #onClientRequest;\n #onLifecycleEvent;\n #onNotification;\n #consumeNonProtocolLine;\n #onProcessControlEvent;\n #pending = new Map();\n #processLabel;\n #timeoutMs;\n #child = null;\n #cleanupPromise = null;\n #forceKillTimeout = null;\n #lifecycle = {\n exitCode: null,\n exitObservedAtMs: null,\n exitSignal: null,\n firstStderrAtMs: null,\n firstStdoutAtMs: null,\n processId: null,\n processSpawnedAtMs: null,\n stdinClosedAtMs: null,\n timeoutTriggeredAtMs: null,\n };\n #lineBuffer = \"\";\n #nextRequestId = 1;\n #processTimeout = null;\n #runtimeProcess = null;\n #settledFailure = null;\n #stderr = \"\";\n #stderrLineBuffer = \"\";\n constructor(input) {\n this.#args = input.args;\n this.#createError = input.createError;\n this.#cwd = input.cwd;\n this.#env = input.env;\n this.#launchContract = input.launchContract;\n this.#mapJsonRpcError = input.mapJsonRpcError;\n this.#onClientRequest = input.onClientRequest;\n this.#onLifecycleEvent = input.onLifecycleEvent;\n this.#onNotification = input.onNotification;\n this.#consumeNonProtocolLine = input.consumeNonProtocolLine;\n this.#onProcessControlEvent = input.onProcessControlEvent;\n this.#processLabel = input.processLabel;\n this.#timeoutMs = input.timeoutMs;\n }\n start() {\n if (this.#child) {\n throw this.#error({\n code: \"protocol.invalid\",\n errorType: \"adapter\",\n message: `protocol.invalid: ${this.#processLabel} ACP process has already started`,\n });\n }\n const invocation = buildCliLaunchInvocation({\n args: [...this.#args],\n launchContract: this.#launchContract,\n });\n const runtimeProcess = spawnAgentControllerProcess({\n args: invocation.args,\n bin: invocation.bin,\n cwd: this.#cwd,\n env: {\n ...process.env,\n ...(this.#env ?? {}),\n },\n shell: invocation.shell ?? false,\n });\n const { child, processId, signalTarget } = runtimeProcess;\n this.#child = child;\n this.#runtimeProcess = runtimeProcess;\n const processSpawnedAtMs = Date.now();\n this.#lifecycle.processId = processId;\n this.#lifecycle.processSpawnedAtMs = processSpawnedAtMs;\n this.#onLifecycleEvent?.({\n phase: \"process_spawned\",\n processId,\n signalTarget,\n tsMs: processSpawnedAtMs,\n });\n this.#onProcessControlEvent?.({\n phase: \"process_spawned\",\n processId,\n signalTarget,\n });\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk) => {\n if (this.#lifecycle.firstStdoutAtMs === null) {\n const firstStdoutAtMs = Date.now();\n this.#lifecycle.firstStdoutAtMs = firstStdoutAtMs;\n this.#onLifecycleEvent?.({\n phase: \"first_stdout\",\n processId,\n tsMs: firstStdoutAtMs,\n });\n }\n this.#consumeStdoutText(String(chunk));\n });\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk) => {\n if (this.#lifecycle.firstStderrAtMs === null) {\n const firstStderrAtMs = Date.now();\n this.#lifecycle.firstStderrAtMs = firstStderrAtMs;\n this.#onLifecycleEvent?.({\n phase: \"first_stderr\",\n processId,\n tsMs: firstStderrAtMs,\n });\n }\n if (this.#consumeNonProtocolLine) {\n this.#stderrLineBuffer += String(chunk);\n let newline = this.#stderrLineBuffer.indexOf(\"\\n\");\n while (newline >= 0) {\n const line = this.#stderrLineBuffer.slice(0, newline).trim();\n this.#stderrLineBuffer = this.#stderrLineBuffer.slice(newline + 1);\n try {\n if (!this.#consumeNonProtocolLine(line)) {\n this.#stderr = `${this.#stderr}${line}\\n`.slice(-MAX_STDERR_CHARS);\n }\n }\n catch (error) {\n this.#failAll(error);\n }\n newline = this.#stderrLineBuffer.indexOf(\"\\n\");\n }\n this.#stderrLineBuffer = this.#stderrLineBuffer.slice(-MAX_STDERR_CHARS);\n }\n else {\n this.#stderr = `${this.#stderr}${String(chunk)}`.slice(-MAX_STDERR_CHARS);\n }\n });\n child.stdin.on(\"error\", (error) => {\n this.#failAll(this.#buildStdinWriteError(error));\n });\n child.on(\"error\", (error) => {\n this.#failAll(this.#error({\n cause: error,\n code: \"upstream_unreachable\",\n errorType: \"adapter\",\n message: `upstream_unreachable: failed to spawn ${this.#processLabel} ACP (${error.message})`,\n }));\n });\n child.on(\"close\", (exitCode, signal) => {\n this.#ensureRemainingDescendantsCleanup();\n this.#clearTimers();\n this.#lifecycle.exitCode = exitCode;\n this.#lifecycle.exitObservedAtMs = Date.now();\n this.#lifecycle.exitSignal = signal;\n this.#onLifecycleEvent?.({\n exitCode,\n phase: \"process_exit\",\n processId,\n signal,\n signalTarget,\n tsMs: this.#lifecycle.exitObservedAtMs,\n });\n this.#onProcessControlEvent?.({\n phase: \"process_exit\",\n processId,\n signalTarget,\n });\n if (this.#pending.size > 0) {\n this.#failAll(this.#error({\n code: \"upstream_unreachable\",\n errorType: \"adapter\",\n message: `upstream_unreachable: ${this.#processLabel} ACP exited before completing the request${this.formatStderrSuffix()}`,\n }));\n }\n });\n this.#processTimeout =\n this.#timeoutMs === null\n ? null\n : setTimeout(() => {\n const timeoutTriggeredAtMs = Date.now();\n this.#lifecycle.timeoutTriggeredAtMs = timeoutTriggeredAtMs;\n this.#onLifecycleEvent?.({\n phase: \"timeout_triggered\",\n processId,\n tsMs: timeoutTriggeredAtMs,\n });\n this.#failAll(this.#error({\n code: \"process.timeout\",\n errorType: \"timeout\",\n message: `process.timeout: ${this.#processLabel} ACP did not complete within ${this.#timeoutMs}ms`,\n }));\n this.#requestProcessTermination(\"SIGTERM\");\n }, this.#timeoutMs);\n }\n async request(method, params) {\n if (this.#settledFailure) {\n throw this.#settledFailure;\n }\n const id = this.#nextRequestId;\n this.#nextRequestId += 1;\n const result = new Promise((resolve, reject) => {\n this.#pending.set(id, { reject, resolve });\n });\n this.#write({\n id,\n jsonrpc: \"2.0\",\n method,\n params,\n });\n return await result;\n }\n notify(method, params) {\n this.#write({\n jsonrpc: \"2.0\",\n method,\n ...(params === undefined ? {} : { params }),\n });\n }\n fail(error) {\n this.#failAll(error);\n }\n readLifecycle() {\n return { ...this.#lifecycle };\n }\n readStderr() {\n return this.#stderr;\n }\n buildTelemetry(input) {\n return {\n completedAtMs: Date.now(),\n ...(this.#lifecycle.exitCode === null\n ? {}\n : { exitCode: this.#lifecycle.exitCode }),\n ...(this.#lifecycle.exitObservedAtMs === null\n ? {}\n : { exitObservedAtMs: this.#lifecycle.exitObservedAtMs }),\n ...(this.#lifecycle.exitSignal === null\n ? {}\n : { exitSignal: this.#lifecycle.exitSignal }),\n ...(input.firstOutputAtMs === null || input.firstOutputAtMs === undefined\n ? {}\n : { firstOutputAtMs: input.firstOutputAtMs }),\n ...(this.#lifecycle.firstStderrAtMs === null\n ? {}\n : { firstStderrAtMs: this.#lifecycle.firstStderrAtMs }),\n ...(this.#lifecycle.firstStdoutAtMs === null\n ? {}\n : { firstStdoutAtMs: this.#lifecycle.firstStdoutAtMs }),\n invokedAtMs: input.invokedAtMs,\n previewEmitted: input.previewEmitted,\n ...(this.#lifecycle.processId === null\n ? {}\n : { processId: this.#lifecycle.processId }),\n ...(this.#lifecycle.processSpawnedAtMs === null\n ? {}\n : { processSpawnedAtMs: this.#lifecycle.processSpawnedAtMs }),\n resumedContext: input.resumedContext,\n ...(this.#lifecycle.stdinClosedAtMs === null\n ? {}\n : { stdinClosedAtMs: this.#lifecycle.stdinClosedAtMs }),\n streamingMode: input.streamingMode,\n ...(this.#lifecycle.timeoutTriggeredAtMs === null\n ? {}\n : { timeoutTriggeredAtMs: this.#lifecycle.timeoutTriggeredAtMs }),\n };\n }\n async close(input) {\n this.#clearProcessTimeout();\n const child = this.#child;\n if (!child) {\n return;\n }\n if (this.#lifecycle.stdinClosedAtMs === null) {\n this.#lifecycle.stdinClosedAtMs = Date.now();\n this.#onLifecycleEvent?.({\n phase: \"stdin_closed\",\n processId: this.#lifecycle.processId,\n tsMs: this.#lifecycle.stdinClosedAtMs,\n });\n }\n if (!(child.stdin.destroyed || child.stdin.writableEnded)) {\n child.stdin.end();\n }\n if (this.#lifecycle.exitObservedAtMs !== null) {\n await this.#finishRemainingDescendantsCleanup();\n return;\n }\n const gracefulExitMs = input?.gracefulExitMs ?? 0;\n if (gracefulExitMs > 0 && (await this.#waitForClose(gracefulExitMs))) {\n await this.#finishRemainingDescendantsCleanup();\n return;\n }\n this.#requestProcessTermination(\"SIGTERM\");\n if (await this.#waitForClose(ACP_PROCESS_KILL_GRACE_MS)) {\n await this.#finishRemainingDescendantsCleanup();\n return;\n }\n this.#requestProcessTermination(\"SIGKILL\");\n await this.#waitForClose(ACP_PROCESS_KILL_GRACE_MS);\n await this.#finishRemainingDescendantsCleanup();\n }\n formatStderrSuffix() {\n const normalized = this.#stderr.trim();\n return normalized ? `: ${normalized}` : \"\";\n }\n #consumeStdoutText(text) {\n this.#lineBuffer += text;\n while (true) {\n const newlineIndex = this.#lineBuffer.indexOf(\"\\n\");\n if (newlineIndex < 0) {\n return;\n }\n const line = this.#lineBuffer.slice(0, newlineIndex).trim();\n this.#lineBuffer = this.#lineBuffer.slice(newlineIndex + 1);\n if (line) {\n this.#handleStdoutLine(line);\n }\n }\n }\n #handleStdoutLine(line) {\n try {\n if (this.#consumeNonProtocolLine?.(line)) {\n return;\n }\n }\n catch (error) {\n this.#failAll(error);\n return;\n }\n let message;\n try {\n const parsed = JSON.parse(line);\n if (!(parsed && typeof parsed === \"object\" && !Array.isArray(parsed))) {\n throw new TypeError(\"JSON-RPC message must be an object\");\n }\n message = parsed;\n }\n catch (error) {\n this.#failAll(this.#error({\n cause: error,\n code: \"protocol.invalid\",\n errorType: \"adapter\",\n message: `protocol.invalid: ${this.#processLabel} ACP emitted non-JSON-RPC output (${toErrorMessage(error)})`,\n }));\n return;\n }\n if (message.id !== undefined && message.method) {\n this.#handleClientRequest(message).catch((error) => {\n this.#failAll(error);\n });\n return;\n }\n if (message.id !== undefined) {\n this.#handleResponse(message);\n return;\n }\n if (message.method) {\n this.#onNotification?.({\n method: message.method,\n params: message.params,\n });\n }\n }\n #handleResponse(message) {\n const id = message.id;\n if (!(typeof id === \"number\" || typeof id === \"string\")) {\n return;\n }\n const pending = this.#pending.get(id);\n if (!pending) {\n return;\n }\n this.#pending.delete(id);\n if (message.error) {\n pending.reject(this.#toJsonRpcError(message.error));\n return;\n }\n pending.resolve(message.result);\n }\n async #handleClientRequest(message) {\n const id = message.id;\n const method = message.method;\n if (!((typeof id === \"number\" || typeof id === \"string\") && method)) {\n return;\n }\n const response = this.#onClientRequest\n ? await this.#onClientRequest({\n method,\n params: message.params,\n })\n : {\n error: {\n code: -32_601,\n message: `OpenMeld does not support ACP client method '${method}'.`,\n },\n };\n this.#write({\n id,\n jsonrpc: \"2.0\",\n ...response,\n });\n }\n #write(message) {\n const child = this.#child;\n if (this.#settledFailure) {\n throw this.#settledFailure;\n }\n if (!child ||\n this.#lifecycle.exitObservedAtMs !== null ||\n child.stdin.destroyed ||\n child.stdin.writableEnded ||\n !child.stdin.writable) {\n const error = this.#buildStdinWriteError();\n this.#failAll(error);\n throw error;\n }\n try {\n child.stdin.write(`${JSON.stringify(message)}\\n`, (error) => {\n if (error) {\n this.#failAll(this.#buildStdinWriteError(error));\n }\n });\n }\n catch (error) {\n const writeError = this.#buildStdinWriteError(error);\n this.#failAll(writeError);\n throw writeError;\n }\n }\n #buildStdinWriteError(cause) {\n const detail = cause instanceof Error && cause.message.trim()\n ? ` (${cause.message.trim()})`\n : \"\";\n return this.#error({\n cause,\n code: \"upstream_unreachable\",\n errorType: \"adapter\",\n message: `upstream_unreachable: ${this.#processLabel} ACP is not accepting responses${detail}`,\n });\n }\n #toJsonRpcError(error) {\n if (this.#mapJsonRpcError) {\n return this.#mapJsonRpcError(error);\n }\n let code = \"protocol.request_failed\";\n if (error.code === -32_601) {\n code = \"protocol.method_not_found\";\n }\n else if (error.code === -32_602) {\n code = \"protocol.invalid_params\";\n }\n const message = normalizeOptionalText(error.message) ?? \"ACP request failed\";\n return this.#error({\n code,\n errorType: \"adapter\",\n message: `${code}: ${message}`,\n });\n }\n #failAll(error) {\n if (!this.#settledFailure) {\n this.#settledFailure = error;\n }\n for (const pending of this.#pending.values()) {\n pending.reject(error);\n }\n this.#pending.clear();\n }\n #requestProcessTermination(signal) {\n const runtimeProcess = this.#runtimeProcess;\n if (!runtimeProcess || this.#lifecycle.exitObservedAtMs !== null) {\n return;\n }\n runtimeProcess.terminate(signal);\n if (signal === \"SIGTERM\") {\n this.#forceKillTimeout = setTimeout(() => {\n if (this.#lifecycle.exitObservedAtMs === null) {\n runtimeProcess.terminate(\"SIGKILL\");\n }\n }, ACP_PROCESS_KILL_GRACE_MS);\n this.#forceKillTimeout.unref?.();\n }\n }\n #ensureRemainingDescendantsCleanup() {\n this.#cleanupPromise ??=\n this.#runtimeProcess?.terminateRemainingDescendants() ??\n Promise.resolve({ ok: true, signalSent: false });\n return this.#cleanupPromise;\n }\n async #finishRemainingDescendantsCleanup() {\n const result = await this.#ensureRemainingDescendantsCleanup();\n if (result.ok) {\n return;\n }\n throw this.#error({\n cause: result.error,\n code: \"process.cleanup_failed\",\n errorType: \"adapter\",\n message: `process.cleanup_failed: OpenMeld could not stop every ${this.#processLabel} process`,\n });\n }\n async #waitForClose(timeoutMs) {\n const child = this.#child;\n if (!child || this.#lifecycle.exitObservedAtMs !== null) {\n return true;\n }\n return await new Promise((resolve) => {\n let settled = false;\n const onClose = () => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timeout);\n resolve(true);\n };\n const timeout = setTimeout(() => {\n if (settled) {\n return;\n }\n settled = true;\n child.off(\"close\", onClose);\n resolve(false);\n }, timeoutMs);\n timeout.unref?.();\n child.once(\"close\", onClose);\n });\n }\n #clearProcessTimeout() {\n if (this.#processTimeout !== null) {\n clearTimeout(this.#processTimeout);\n this.#processTimeout = null;\n }\n }\n #clearTimers() {\n this.#clearProcessTimeout();\n if (this.#forceKillTimeout !== null) {\n clearTimeout(this.#forceKillTimeout);\n this.#forceKillTimeout = null;\n }\n }\n #error(input) {\n return this.#createError(input);\n }\n}\nfunction normalizeOptionalText(value) {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\nfunction toErrorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\n","import { buildAgentControllerConversationRef, canonicalizeBuiltinAgentControllerRef, resolveBuiltinAgentControllerConversationKind, } from \"@openmeld/schemas\";\nconst normalizeText = (value) => {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n};\nexport const resolveBuiltinAdapterConversationBridgeSpec = (adapterId) => {\n const rawAgentControllerRef = normalizeText(adapterId);\n if (!rawAgentControllerRef) {\n return null;\n }\n const agentControllerRef = canonicalizeBuiltinAgentControllerRef(rawAgentControllerRef);\n if (!agentControllerRef) {\n return null;\n }\n const agentControllerConversationKind = resolveBuiltinAgentControllerConversationKind(agentControllerRef);\n if (!agentControllerConversationKind) {\n return null;\n }\n return {\n agentControllerRef,\n agentControllerConversationKind,\n };\n};\nexport const buildAdapterAgentControllerConversationRef = (input) => buildAgentControllerConversationRef({\n agentControllerRef: input.agentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n agentControllerConversationKind: input.agentControllerConversationKind,\n});\nexport const resolveBridgedAgentControllerConversationId = (input) => {\n const agentControllerConversationId = normalizeText(input.agentControllerConversationId);\n const agentControllerConversation = input.agentControllerConversation;\n if (!agentControllerConversation) {\n return agentControllerConversationId;\n }\n if (agentControllerConversation.agentControllerRef !==\n input.bridgeSpec.agentControllerRef) {\n throw new Error(`conversation.bridge.agent_controller_ref_mismatch: expected agentControllerRef=${input.bridgeSpec.agentControllerRef}, received agentControllerRef=${agentControllerConversation.agentControllerRef}`);\n }\n if (agentControllerConversation.agentControllerConversationKind !==\n input.bridgeSpec.agentControllerConversationKind) {\n throw new Error(`conversation.bridge.agent_controller_conversation_kind_mismatch: expected agentControllerConversationKind=${input.bridgeSpec.agentControllerConversationKind}, received agentControllerConversationKind=${agentControllerConversation.agentControllerConversationKind}`);\n }\n if (agentControllerConversationId &&\n agentControllerConversationId !==\n agentControllerConversation.agentControllerConversationId) {\n throw new Error(`conversation.bridge.agent_controller_conversation_id_mismatch: expected agentControllerConversationId=${agentControllerConversationId}, received agentControllerConversationId=${agentControllerConversation.agentControllerConversationId}`);\n }\n return agentControllerConversation.agentControllerConversationId;\n};\nexport const bridgeAgentControllerConversationRef = (input) => {\n const resolvedContextId = resolveBridgedAgentControllerConversationId(input);\n if (!resolvedContextId) {\n return null;\n }\n return buildAdapterAgentControllerConversationRef({\n agentControllerRef: input.bridgeSpec.agentControllerRef,\n agentControllerConversationId: resolvedContextId,\n agentControllerConversationKind: input.bridgeSpec.agentControllerConversationKind,\n });\n};\n","import { basename, isAbsolute } from \"node:path\";\nimport { DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV, isDispatchSpaceActionDeliveryOnly, } from \"./dispatch-space-tools.js\";\nconst SPACE_ACTION_CONTEXT_PATH_ENV = \"OPENMELD_SPACE_ACTION_CONTEXT_PATH\";\nconst USER_FACING_CLI_COMMAND_ENV = \"OPENMELD_USER_FACING_CLI_COMMAND\";\nconst SPACE_ACTION_TOOL_COMMAND_PATH_ENV = \"OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH\";\nexport const OPENMELD_SPACE_ACTION_MCP_SERVER_ID = \"openmeld_internal_dispatch_space_action\";\nexport const OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES = [\n \"working_copy\",\n \"read_file\",\n \"read_history\",\n \"read_evidence\",\n \"read_thread\",\n \"read_documents\",\n \"read_skills\",\n \"read_result\",\n \"open_direct_message\",\n \"list_tasks\",\n \"create_task\",\n \"start_task\",\n \"submit_task_result\",\n \"review_task\",\n \"cancel_task\",\n \"report_progress\",\n \"reply\",\n \"stay_silent\",\n \"read_receipt\",\n];\nconst FORWARDED_ENV_NAMES = [\n DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV,\n SPACE_ACTION_CONTEXT_PATH_ENV,\n SPACE_ACTION_TOOL_COMMAND_PATH_ENV,\n \"OPENMELD_DISPATCH_RUNTIME_MODE\",\n \"OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID\",\n \"OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID\",\n USER_FACING_CLI_COMMAND_ENV,\n \"OPENMELD_ENV_PRESET\",\n // The tool process must use the carrier's lane, not its host's default home.\n // This is an installation selector, not a credential or additional authority.\n \"OPENMELD_HOME\",\n \"OPENMELD_AUTH_URL\",\n \"OPENMELD_GATEWAY_URL\",\n];\nconst OPENMELD_CLI_COMMANDS = new Set([\n \"openmeld\",\n \"openmeld-dev\",\n \"openmeld-canary\",\n]);\nexport function resolveDispatchSpaceActionMcpServer(env) {\n if (!normalizeOptionalText(env?.[SPACE_ACTION_CONTEXT_PATH_ENV])) {\n return null;\n }\n const command = normalizeOptionalText(env?.[USER_FACING_CLI_COMMAND_ENV]);\n if (!(command && OPENMELD_CLI_COMMANDS.has(command))) {\n throw new Error(\"OpenMeld cannot start the dispatch Space Action tool because the active CLI command is invalid.\");\n }\n const commandPath = normalizeOptionalText(env?.[SPACE_ACTION_TOOL_COMMAND_PATH_ENV]);\n if (!(commandPath &&\n isAbsolute(commandPath) &&\n (basename(commandPath) === command ||\n basename(commandPath) === `${command}.exe`))) {\n throw new Error(\"OpenMeld cannot start the dispatch Space Action tool because its dispatch-owned CLI path is invalid.\");\n }\n return {\n args: [\"space\", \"action\", \"tool-server\"],\n command: command,\n commandPath,\n env: Object.fromEntries(FORWARDED_ENV_NAMES.flatMap((name) => {\n const value = normalizeOptionalText(env?.[name]);\n return value ? [[name, value]] : [];\n })),\n id: OPENMELD_SPACE_ACTION_MCP_SERVER_ID,\n toolNames: isDispatchSpaceActionDeliveryOnly(env)\n ? [\"reply\", \"stay_silent\", \"read_receipt\"]\n : OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES,\n };\n}\nexport function buildDispatchSpaceActionMcpToolIds(separator, env) {\n const names = isDispatchSpaceActionDeliveryOnly(env)\n ? [\"reply\", \"stay_silent\", \"read_receipt\"]\n : OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES;\n return names.map((toolName) => `${OPENMELD_SPACE_ACTION_MCP_SERVER_ID}${separator}${toolName}`);\n}\nexport function buildAcpDispatchSpaceActionMcpServers(env) {\n const config = resolveDispatchSpaceActionMcpServer(env);\n if (!config) {\n return [];\n }\n return [\n {\n args: [...config.args],\n command: config.commandPath,\n env: Object.entries(config.env).map(([name, value]) => ({ name, value })),\n name: config.id,\n },\n ];\n}\nfunction normalizeOptionalText(value) {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","export const RUNTIME_PERMISSION_DENIED_REASON_CODE = \"permission.denied.runtime\";\nconst ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\\\[[0-?]*[ -/]*[@-~]`, \"g\");\nconst OPENCODE_PERMISSION_KIND_RE = /permission requested:\\s*([a-z0-9_.:-]+)/i;\nconst OPENCLAW_PERMISSION_REQUIRED_RE = /\\b[a-z0-9_]+_permission_required\\b/;\nconst OPENCLAW_PERMISSION_KIND_RE = /\\b([a-z0-9_]+)_permission_required\\b/;\nconst UNSAFE_PERMISSION_KIND_CHARACTER_RE = /[^a-z0-9_.:-]+/g;\nconst EDGE_UNDERSCORE_RE = /^_+|_+$/g;\nexport function classifyRuntimePermissionDenialMessage(input) {\n const details = readRuntimePermissionDenialDetails(input.message);\n if (!details) {\n return null;\n }\n const source = input.source ?? details.source;\n const normalizedMessage = details.normalizedMessage;\n return {\n code: RUNTIME_PERMISSION_DENIED_REASON_CODE,\n details: {\n normalizedMessage,\n permissionKind: details.permissionKind,\n source,\n },\n errorType: \"adapter\",\n message: `${RUNTIME_PERMISSION_DENIED_REASON_CODE}: ${normalizedMessage}`,\n };\n}\nexport function looksLikeRuntimePermissionDenialMessage(value) {\n return readRuntimePermissionDenialDetails(value) !== null;\n}\nexport function readRuntimePermissionDenialDetails(value) {\n const normalizedMessage = normalizeRuntimePermissionMessage(value);\n if (!normalizedMessage) {\n return null;\n }\n const lowered = normalizedMessage.toLowerCase();\n if (isAntigravityPermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readAntigravityPermissionKind(lowered),\n source: \"antigravity\",\n };\n }\n if (isOpenCodePermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readOpenCodePermissionKind(normalizedMessage),\n source: \"opencode\",\n };\n }\n if (isClaudeCodePermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readClaudeCodePermissionKind(lowered),\n source: \"claude-code\",\n };\n }\n if (isCodexPermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readCodexPermissionKind(lowered),\n source: \"codex\",\n };\n }\n if (isOpenClawPermissionDenial(lowered)) {\n return {\n normalizedMessage,\n permissionKind: readOpenClawPermissionKind(lowered),\n source: \"openclaw\",\n };\n }\n return null;\n}\nfunction isAntigravityPermissionDenial(value) {\n return (value.includes(\"permission check failed\") ||\n value.includes(\"user denied permission to run command\") ||\n (value.includes(\"tool required the\") &&\n value.includes(\"permission\") &&\n value.includes(\"auto-denied\")));\n}\nfunction readAntigravityPermissionKind(value) {\n if (value.includes(\"command\")) {\n return \"command\";\n }\n if (value.includes(\"mcp\")) {\n return \"mcp\";\n }\n return \"tool_use\";\n}\nfunction normalizeRuntimePermissionMessage(value) {\n const normalized = String(value ?? \"\")\n .replace(ANSI_ESCAPE_RE, \"\")\n .trim();\n return normalized.length > 0 ? normalized : null;\n}\nfunction isOpenCodePermissionDenial(value) {\n return (value.includes(\"permission requested\") &&\n (value.includes(\"auto-reject\") ||\n value.includes(\"auto rejecting\") ||\n value.includes(\"auto rejected\") ||\n value.includes(\"rejecting\")));\n}\nfunction isClaudeCodePermissionDenial(value) {\n return (value.includes(\"permission for this tool use was denied\") ||\n value.includes(\"permission for this action was denied\") ||\n value.includes(\"permission for this action has been denied\") ||\n value.includes(\"denied by auto mode classifier\") ||\n value.includes(\"user rejected tool use\") ||\n (value.includes(\"permission request\") &&\n value.includes(\"not answered in time\")));\n}\nfunction isCodexPermissionDenial(value) {\n return (value.includes(\"command denied by sandbox:\") ||\n value.includes(\"sandbox denied exec error\") ||\n value.includes(\"this action was rejected due to unacceptable risk\") ||\n (value.includes(\"execution denied:\") &&\n (value.includes(\"policy\") ||\n value.includes(\"forbidden\") ||\n value.includes(\"approval\") ||\n value.includes(\"sandbox\"))) ||\n (value.includes(\"rejected:\") && value.includes(\"blocked by policy\")) ||\n (value.includes(\"requires approval\") && value.includes(\"policy\")) ||\n value.includes(\"policy forbids commands starting\"));\n}\nfunction isOpenClawPermissionDenial(value) {\n return (value.includes(\"system_run_denied:\") ||\n value.includes(\"system_run_disabled: security=deny\") ||\n value.includes(\"exec denied:\") ||\n value.includes(\"exec.denied\") ||\n value.includes(\"permission:screenrecording\") ||\n OPENCLAW_PERMISSION_REQUIRED_RE.test(value));\n}\nfunction readOpenCodePermissionKind(value) {\n const match = OPENCODE_PERMISSION_KIND_RE.exec(value);\n return normalizePermissionKind(match?.[1]);\n}\nfunction readClaudeCodePermissionKind(value) {\n if (value.includes(\"tool use\")) {\n return \"tool_use\";\n }\n if (value.includes(\"url\")) {\n return \"url_access\";\n }\n if (value.includes(\"auto mode classifier\")) {\n return \"auto_mode\";\n }\n return null;\n}\nfunction readCodexPermissionKind(value) {\n if (value.includes(\"sandbox\")) {\n return \"sandbox\";\n }\n if (value.includes(\"approval\")) {\n return \"approval\";\n }\n if (value.includes(\"policy\")) {\n return \"policy\";\n }\n return null;\n}\nfunction readOpenClawPermissionKind(value) {\n if (value.includes(\"system_run\")) {\n return \"system_run\";\n }\n if (value.includes(\"exec denied\") || value.includes(\"exec.denied\")) {\n return \"exec\";\n }\n if (value.includes(\"permission:screenrecording\")) {\n return \"screen_recording\";\n }\n const match = OPENCLAW_PERMISSION_KIND_RE.exec(value);\n return normalizePermissionKind(match?.[1]);\n}\nfunction normalizePermissionKind(value) {\n const normalized = String(value ?? \"\")\n .trim()\n .toLowerCase()\n .replace(UNSAFE_PERMISSION_KIND_CHARACTER_RE, \"_\")\n .replace(EDGE_UNDERSCORE_RE, \"\");\n return normalized.length > 0 ? normalized : null;\n}\n","// biome-ignore-all lint/performance/noBarrelFile: Package entrypoint intentionally exports stable adapter-core helpers.\n//\n// Provider runtime integrations must always go through adapter integration.\n// There is no parallel \"lightweight integration\" path outside adapter-core.\n//\n// Use a thin adapter when the provider only needs straightforward transport\n// wiring into the shared runtime shell. Escalate to a full adapter as soon as\n// the provider has any of the following:\n// - continuation-specific behavior\n// - bootstrap or readiness preparation\n// - gateway transport requirements\n// - provider-native workspace semantics\n// - non-trivial parser/codec logic\n// - provider-specific failure/diagnostics mapping\nimport { aiUsageObservationSchema, openMeldDaemonProviderAccessEvidenceSchema, } from \"@openmeld/schemas\";\nexport { agentExecutionSteerRequestSchema } from \"@openmeld/schemas\";\nexport { DISPATCH_SPACE_ACTION_DELIVERY_ONLY_ENV, describeDispatchSpaceTools, isDispatchSpaceActionDeliveryOnly, } from \"./dispatch-space-tools.js\";\nimport { createProviderOriginalError } from \"./provider-original-error.js\";\nexport { AcpProcessSession, } from \"./acp-process-session.js\";\nexport { createAcpToolActivityTracker, } from \"./acp-tool-activity.js\";\nimport { bridgeAgentControllerConversationRef, buildAdapterAgentControllerConversationRef, resolveBridgedAgentControllerConversationId, } from \"./conversation-bridge.js\";\nexport { createAgentControllerProcessDiscoveryDiagnosticAggregator, listAgentControllerDescendantProcessIds, listAgentControllerSupervisedProcessIds, resolveAgentControllerDescendantProcessIds, resolveAgentControllerProcessSignalId, resolveAgentControllerProcessSignalTarget, resolveAgentControllerSupervisedProcessIds, signalAgentControllerProcessTree, spawnAgentControllerProcess, terminateLiveAgentControllerProcesses, terminateRemainingAgentControllerProcesses, } from \"./agent-controller-process.js\";\nexport { bridgeAgentControllerConversationRef, buildAdapterAgentControllerConversationRef, resolveBridgedAgentControllerConversationId, resolveBuiltinAdapterConversationBridgeSpec, } from \"./conversation-bridge.js\";\nexport { buildAcpDispatchSpaceActionMcpServers, buildDispatchSpaceActionMcpToolIds, OPENMELD_SPACE_ACTION_MCP_SERVER_ID, OPENMELD_SPACE_ACTION_MCP_TOOL_NAMES, resolveDispatchSpaceActionMcpServer, } from \"./dispatch-space-action-mcp.js\";\nexport { buildCliLaunchInvocation, buildExecutableLaunchContract, materializeCliLaunchCommand, resolveExecutableOnPath, resolveExecutablePathsOnPath, resolveInstalledCommandPath, resolveInstalledCommandPaths, resolveInstalledNodeScriptLaunchCandidates, resolveInstalledNodeScriptLaunchContract, resolveLaunchCandidatesAfterVerification, resolveSiblingCommandPath, verifyCliLaunchContract, verifyLaunchContractFiles, } from \"./launch-contract.js\";\nexport { normalizeCommandEnvironment, WINDOWS_RUNTIME_ENV_KEYS, } from \"./process-environment.js\";\nexport { createProviderOriginalError } from \"./provider-original-error.js\";\nexport { createUnavailableProviderUsageLimits, createUnsupportedProviderUsageLimits, } from \"./provider-usage-limits.js\";\nexport { buildProviderExitError, classifyCliDriverTimeoutFailure, } from \"./runtime-failure.js\";\nexport { classifyRuntimePermissionDenialMessage, looksLikeRuntimePermissionDenialMessage, RUNTIME_PERMISSION_DENIED_REASON_CODE, readRuntimePermissionDenialDetails, } from \"./runtime-permission-denial.js\";\nexport { ADAPTER_TOOL_ACTIVITY_NAMES, resolveAdapterToolActivityName, resolveAdapterToolWorkActivity, } from \"./tool-activity.js\";\nexport const AGENT_CONTROLLER_CONVERSATION_OCCUPANCY_CONTRACT_VERSION = 1;\nexport function readAdapterAiUsageObservation(value) {\n const result = aiUsageObservationSchema.safeParse(value);\n return result.success ? result.data : null;\n}\nexport const DEFAULT_GRACEFUL_INTERRUPT_TIMEOUT_MS = 10_000;\nconst DEFAULT_INTERRUPT_REASON = \"service.interrupt\";\nconst DEFAULT_CANCEL_REASON = \"service.cancel\";\nconst TEST_DISABLE_DEFAULT_INVOKE = Symbol.for(\"openmeld.test.disableDefaultInvoke\");\nexport const createSharedDispatchShell = (input) => {\n const bridgeSpec = input.bridgeSpec ?? null;\n return async (dispatchInput) => {\n const transportMode = dispatchInput.transportMode ?? \"local-cli\";\n const transportInvoke = input.invokeByMode?.[transportMode];\n if (input.invokeByMode && !transportInvoke) {\n return {\n errorCode: \"adapter.unreachable\",\n errorMessage: `adapter.unreachable: ${input.adapterId} transport '${transportMode}' is not configured`,\n errorType: \"adapter\",\n status: \"failed\",\n };\n }\n const defaultInvoke = isDefaultInvokeDisabledForTests(input.runtimeOptions)\n ? null\n : (input.resolveDefaultInvoke() ?? null);\n const resolvedInvoke = transportInvoke ?? input.invoke ?? defaultInvoke;\n if (!resolvedInvoke) {\n return {\n errorCode: \"controller.runtime.missing\",\n errorMessage: `controller.runtime.missing: ${input.adapterId} invoke runtime is unavailable`,\n errorType: \"adapter\",\n status: \"failed\",\n };\n }\n try {\n const invokeRequest = input.resolveInvokeRequest?.({\n bridgeSpec,\n request: dispatchInput,\n }) ??\n buildDefaultInvokeRequest({\n bridgeSpec,\n request: dispatchInput,\n });\n const requiredRepairConversationId = resolveRequiredRepairConversationId({\n invokeRequest,\n policy: input.repairConversationPolicy,\n request: dispatchInput,\n });\n const result = await resolvedInvoke(invokeRequest);\n const contextDelta = input.resolveSuccessContextDelta?.({\n bridgeSpec,\n invokeRequest,\n request: dispatchInput,\n result,\n }) ??\n resolveCanonicalContextDelta({\n bridgeSpec,\n contextDelta: result.contextDelta,\n });\n const protectedContextDelta = requireCanonicalRepairConversation({\n canonicalConversationId: requiredRepairConversationId,\n contextDelta,\n });\n return {\n ...(protectedContextDelta\n ? { contextDelta: protectedContextDelta }\n : {}),\n ...(result.diagnostics ? { diagnostics: result.diagnostics } : {}),\n output: result.output,\n status: \"success\",\n ...(result.telemetry ? { telemetry: result.telemetry } : {}),\n };\n }\n catch (error) {\n return toAdapterDispatchFailure(error, \"adapter\");\n }\n };\n};\nclass AdapterRepairConversationMissingError extends Error {\n code = \"repair.conversation_missing\";\n errorType = \"adapter\";\n constructor() {\n super(\"repair.conversation_missing: repair requires an existing Agent Controller conversation\");\n this.name = \"AdapterRepairConversationMissingError\";\n }\n}\nclass AdapterRepairConversationError extends Error {\n code = \"repair.conversation_changed\";\n errorType = \"adapter\";\n constructor() {\n super(\"repair.conversation_changed: repair could not preserve the existing Agent Controller conversation\");\n this.name = \"AdapterRepairConversationError\";\n }\n}\nconst resolveRequiredRepairConversationId = (input) => {\n if (input.policy !== \"require_canonical\" ||\n input.request.executionMode !== \"repair\") {\n return null;\n }\n const canonicalConversationId = normalizeOptionalText(input.invokeRequest.agentControllerConversationId);\n if (!canonicalConversationId) {\n throw new AdapterRepairConversationMissingError();\n }\n return canonicalConversationId;\n};\nconst requireCanonicalRepairConversation = (input) => {\n if (!input.canonicalConversationId) {\n return input.contextDelta;\n }\n const observedConversationId = normalizeOptionalText(input.contextDelta?.agentControllerConversationId);\n if (input.contextDelta?.refreshed === true ||\n observedConversationId !== input.canonicalConversationId) {\n throw new AdapterRepairConversationError();\n }\n return input.contextDelta;\n};\nexport const createSharedControlShell = (input) => ({\n cancel: async (requestInput) => {\n const request = buildAdapterCancelRequest(requestInput);\n const sendCancelSignal = resolveCancelSignalSender({\n sendCancel: input.sendCancel,\n sendInterrupt: input.sendInterrupt,\n });\n if (!sendCancelSignal) {\n return buildUnsupportedCancelResult({\n taskId: request.taskId,\n });\n }\n try {\n await sendCancelSignal.send(request);\n return {\n accepted: true,\n deliveryPath: sendCancelSignal.deliveryPath,\n reasonCode: \"accepted\",\n signalDelivery: \"sent\",\n taskId: request.taskId,\n };\n }\n catch (error) {\n const reasonCode = resolveControlReasonCode(error) ?? \"signal.send_failed\";\n return buildUnsupportedCancelResult({\n reasonCode,\n reasonDetail: resolveControlReasonDetail(error, reasonCode),\n taskId: request.taskId,\n });\n }\n },\n interrupt: async (requestInput) => {\n const plan = buildInterruptPlan({\n gracefulTimeoutMs: requestInput.gracefulTimeoutMs ?? input.gracefulTimeoutMs,\n mode: requestInput.mode,\n reason: requestInput.reason,\n taskId: requestInput.taskId,\n });\n if (!input.sendInterrupt) {\n return buildUnsupportedInterruptResult({\n plan,\n reasonCode: \"adapter.unsupported\",\n taskId: requestInput.taskId,\n });\n }\n try {\n await executeInterruptPlan({\n plan,\n sendSignal: input.sendInterrupt,\n waitForMs: input.waitForMs,\n });\n return {\n accepted: true,\n plan,\n reasonCode: \"accepted\",\n signalDelivery: \"sent\",\n taskId: requestInput.taskId,\n };\n }\n catch (error) {\n const reasonCode = resolveControlReasonCode(error) ?? \"signal.send_failed\";\n return buildUnsupportedInterruptResult({\n plan,\n reasonCode,\n reasonDetail: resolveControlReasonDetail(error, reasonCode),\n taskId: requestInput.taskId,\n });\n }\n },\n});\nexport const invokeWithSingleContextHeal = async (input) => {\n try {\n const first = await input.invokeOnce(input.contextId);\n return {\n contextHealed: false,\n contextId: first.contextId,\n ...(first.diagnostics ? { diagnostics: first.diagnostics } : {}),\n output: first.output,\n telemetry: first.telemetry,\n };\n }\n catch (firstError) {\n if (!(input.contextId && input.isContextLostError(firstError))) {\n throw firstError;\n }\n if (input.contextLossPolicy === \"fail\") {\n throw firstError;\n }\n await input.onContextLost?.();\n try {\n const healed = await input.invokeOnce(null);\n return {\n contextHealed: true,\n contextId: healed.contextId,\n ...(healed.diagnostics ? { diagnostics: healed.diagnostics } : {}),\n output: healed.output,\n telemetry: healed.telemetry\n ? {\n ...healed.telemetry,\n contextHealed: true,\n resumedContext: input.contextId !== null,\n }\n : undefined,\n };\n }\n catch (healError) {\n throw input.createRebuildFailedError(healError);\n }\n }\n};\nexport const buildInterruptPlan = (input) => {\n const mode = input.mode ?? \"graceful\";\n const reason = input.reason ?? DEFAULT_INTERRUPT_REASON;\n if (mode === \"force\") {\n return {\n initial: {\n mode: \"force\",\n reason,\n taskId: input.taskId,\n },\n };\n }\n const delayMs = normalizeGracefulTimeoutMs(input.gracefulTimeoutMs);\n return {\n initial: {\n mode: \"graceful\",\n reason,\n taskId: input.taskId,\n },\n escalation: {\n delayMs,\n mode: \"force\",\n reason,\n taskId: input.taskId,\n },\n };\n};\nexport const executeInterruptPlan = async (input) => {\n await input.sendSignal(input.plan.initial);\n if (!input.plan.escalation) {\n return;\n }\n const waitForMs = input.waitForMs ?? defaultWaitForMs;\n await waitForMs(input.plan.escalation.delayMs);\n await input.sendSignal({\n mode: input.plan.escalation.mode,\n reason: input.plan.escalation.reason,\n taskId: input.plan.escalation.taskId,\n });\n};\nexport const buildUnsupportedInterruptResult = (input) => ({\n accepted: false,\n plan: input.plan,\n reasonCode: input.reasonCode ?? \"adapter.unsupported\",\n ...(input.reasonDetail ? { reasonDetail: input.reasonDetail } : {}),\n signalDelivery: \"not_sent\",\n taskId: input.taskId,\n});\nexport const buildUnsupportedCancelResult = (input) => ({\n accepted: false,\n reasonCode: input.reasonCode ?? \"adapter.unsupported\",\n ...(input.reasonDetail ? { reasonDetail: input.reasonDetail } : {}),\n signalDelivery: \"not_sent\",\n taskId: input.taskId,\n});\nexport const buildAdapterCancelRequest = (input) => ({\n reason: normalizeControlReason(input.reason, DEFAULT_CANCEL_REASON),\n taskId: input.taskId,\n});\nexport const toAdapterDispatchFailure = (error, defaultErrorType = \"adapter\") => {\n const errorCode = extractErrorCode(error);\n const agentControllerConversationOccupancy = extractAgentControllerConversationOccupancy(error);\n const errorType = extractErrorType(error) ?? defaultErrorType;\n const diagnostics = extractDispatchDiagnostics(error);\n const providerAccessEvidence = extractProviderAccessEvidence(error);\n const originalError = extractProviderOriginalError(error);\n const telemetry = extractDispatchTelemetry(error);\n return {\n ...(agentControllerConversationOccupancy\n ? { agentControllerConversationOccupancy }\n : {}),\n ...(diagnostics ? { diagnostics } : {}),\n ...(errorCode ? { errorCode } : {}),\n errorMessage: error instanceof Error ? error.message : \"adapter dispatch failed\",\n errorType,\n ...(originalError ? { originalError } : {}),\n ...(providerAccessEvidence ? { providerAccessEvidence } : {}),\n status: \"failed\",\n ...(telemetry ? { telemetry } : {}),\n };\n};\nconst extractAgentControllerConversationOccupancy = (error) => {\n if (!(error && typeof error === \"object\")) {\n return null;\n }\n const value = error\n .agentControllerConversationOccupancy;\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const occupancy = value;\n const agentControllerConversationId = typeof occupancy.agentControllerConversationId === \"string\"\n ? occupancy.agentControllerConversationId.trim()\n : \"\";\n if (!agentControllerConversationId ||\n occupancy.contractVersion !==\n AGENT_CONTROLLER_CONVERSATION_OCCUPANCY_CONTRACT_VERSION ||\n occupancy.state !== \"occupied\") {\n return null;\n }\n return {\n agentControllerConversationId,\n contractVersion: AGENT_CONTROLLER_CONVERSATION_OCCUPANCY_CONTRACT_VERSION,\n state: \"occupied\",\n };\n};\nconst extractProviderOriginalError = (error) => {\n if (!(error && typeof error === \"object\")) {\n return null;\n }\n return createProviderOriginalError(error.originalError);\n};\nconst extractDispatchTelemetry = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const telemetry = toUnknownRecord(error.telemetry);\n if (!(telemetry &&\n isFiniteNumber(telemetry.completedAtMs) &&\n isFiniteNumber(telemetry.invokedAtMs) &&\n typeof telemetry.resumedContext === \"boolean\")) {\n return null;\n }\n const tokenUsage = extractAdapterTokenUsage(telemetry.tokenUsage);\n return {\n completedAtMs: telemetry.completedAtMs,\n ...(typeof telemetry.contextCompactionObserved === \"boolean\"\n ? { contextCompactionObserved: telemetry.contextCompactionObserved }\n : {}),\n ...(typeof telemetry.contextHealed === \"boolean\"\n ? { contextHealed: telemetry.contextHealed }\n : {}),\n ...(isFiniteNumber(telemetry.exitCode)\n ? { exitCode: telemetry.exitCode }\n : {}),\n ...(isFiniteNumber(telemetry.exitObservedAtMs)\n ? { exitObservedAtMs: telemetry.exitObservedAtMs }\n : {}),\n ...(isNodeSignal(telemetry.exitSignal)\n ? { exitSignal: telemetry.exitSignal }\n : {}),\n ...(isFiniteNumber(telemetry.firstOutputAtMs)\n ? { firstOutputAtMs: telemetry.firstOutputAtMs }\n : {}),\n ...(isFiniteNumber(telemetry.firstStderrAtMs)\n ? { firstStderrAtMs: telemetry.firstStderrAtMs }\n : {}),\n ...(isFiniteNumber(telemetry.firstStdoutAtMs)\n ? { firstStdoutAtMs: telemetry.firstStdoutAtMs }\n : {}),\n invokedAtMs: telemetry.invokedAtMs,\n ...(typeof telemetry.previewEmitted === \"boolean\"\n ? { previewEmitted: telemetry.previewEmitted }\n : {}),\n ...(isFiniteNumber(telemetry.processId)\n ? { processId: telemetry.processId }\n : {}),\n ...(isFiniteNumber(telemetry.processSpawnedAtMs)\n ? { processSpawnedAtMs: telemetry.processSpawnedAtMs }\n : {}),\n resumedContext: telemetry.resumedContext,\n ...(isFiniteNumber(telemetry.stdinClosedAtMs)\n ? { stdinClosedAtMs: telemetry.stdinClosedAtMs }\n : {}),\n ...(telemetry.streamingMode === \"final\" ||\n telemetry.streamingMode === \"stream\"\n ? { streamingMode: telemetry.streamingMode }\n : {}),\n ...(isFiniteNumber(telemetry.timeoutTriggeredAtMs)\n ? { timeoutTriggeredAtMs: telemetry.timeoutTriggeredAtMs }\n : {}),\n ...(tokenUsage ? { tokenUsage } : {}),\n ...extractAiUsageTelemetry(telemetry.aiUsage),\n };\n};\nfunction extractAiUsageTelemetry(value) {\n const result = aiUsageObservationSchema.array().safeParse(value);\n return result.success ? { aiUsage: result.data } : {};\n}\nfunction extractAdapterTokenUsage(value) {\n const usage = toUnknownRecord(value);\n const last = extractAdapterTokenUsageBreakdown(usage?.last);\n const total = extractAdapterTokenUsageBreakdown(usage?.total);\n const modelContextWindow = usage?.modelContextWindow;\n if (!(usage &&\n last &&\n total &&\n (modelContextWindow === null || isNonNegativeInteger(modelContextWindow)))) {\n return null;\n }\n return { last, modelContextWindow, total };\n}\nfunction extractAdapterTokenUsageBreakdown(value) {\n const usage = toUnknownRecord(value);\n if (!(usage &&\n isNonNegativeInteger(usage.cachedInputTokens) &&\n isNonNegativeInteger(usage.inputTokens) &&\n isNonNegativeInteger(usage.outputTokens) &&\n isNonNegativeInteger(usage.reasoningOutputTokens) &&\n isNonNegativeInteger(usage.totalTokens) &&\n (usage.cacheWriteInputTokens === undefined ||\n isNonNegativeInteger(usage.cacheWriteInputTokens)))) {\n return null;\n }\n return {\n ...(usage.cacheWriteInputTokens === undefined\n ? {}\n : { cacheWriteInputTokens: usage.cacheWriteInputTokens }),\n cachedInputTokens: usage.cachedInputTokens,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n totalTokens: usage.totalTokens,\n };\n}\nfunction isNonNegativeInteger(value) {\n return Number.isInteger(value) && Number(value) >= 0;\n}\nfunction isFiniteNumber(value) {\n return typeof value === \"number\" && Number.isFinite(value);\n}\nfunction isNodeSignal(value) {\n return typeof value === \"string\" && value.startsWith(\"SIG\");\n}\nconst extractDispatchDiagnostics = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const diagnostics = error.diagnostics;\n const record = toUnknownRecord(diagnostics);\n const modelNegotiation = parseModelNegotiationDiagnostics(record?.modelNegotiation);\n return modelNegotiation ? { modelNegotiation } : null;\n};\nconst MODEL_DIAGNOSTIC_ID_LIMIT = 100;\nconst MODEL_DIAGNOSTIC_ID_MAX_LENGTH = 512;\nfunction parseModelNegotiationDiagnostics(value) {\n const record = toUnknownRecord(value);\n if (!record) {\n return null;\n }\n const configAvailableModelIds = parseBoundedModelIds(record.configAvailableModelIds);\n const legacyAvailableModelIds = parseBoundedModelIds(record.legacyAvailableModelIds);\n const configAvailableModelCount = parseModelCount(record.configAvailableModelCount, configAvailableModelIds?.length);\n const legacyAvailableModelCount = parseModelCount(record.legacyAvailableModelCount, legacyAvailableModelIds?.length);\n const configCurrentModelId = parseNullableModelId(record.configCurrentModelId);\n const currentModelId = parseNullableModelId(record.currentModelId);\n const legacyCurrentModelId = parseNullableModelId(record.legacyCurrentModelId);\n const requestedModelId = parseNullableModelId(record.requestedModelId);\n if ((record.checkAttempt !== 1 && record.checkAttempt !== 2) ||\n configAvailableModelIds === null ||\n configAvailableModelCount === null ||\n typeof record.configAvailableModelIdsTruncated !== \"boolean\" ||\n configCurrentModelId === undefined ||\n currentModelId === undefined ||\n legacyAvailableModelIds === null ||\n legacyAvailableModelCount === null ||\n typeof record.legacyAvailableModelIdsTruncated !== \"boolean\" ||\n legacyCurrentModelId === undefined ||\n record.protocol !== \"acp/v1\" ||\n requestedModelId === undefined ||\n typeof record.requestedPresentInConfigOptions !== \"boolean\" ||\n typeof record.requestedPresentInLegacyModels !== \"boolean\" ||\n (record.sessionOperation !== \"load\" &&\n record.sessionOperation !== \"new\" &&\n record.sessionOperation !== \"resume\") ||\n !isModelSourceState(record.sourceState)) {\n return null;\n }\n return {\n checkAttempt: record.checkAttempt,\n configAvailableModelCount,\n configAvailableModelIds,\n configAvailableModelIdsTruncated: record.configAvailableModelIdsTruncated,\n configCurrentModelId,\n currentModelId,\n legacyAvailableModelCount,\n legacyAvailableModelIds,\n legacyAvailableModelIdsTruncated: record.legacyAvailableModelIdsTruncated,\n legacyCurrentModelId,\n protocol: record.protocol,\n requestedModelId,\n requestedPresentInConfigOptions: record.requestedPresentInConfigOptions,\n requestedPresentInLegacyModels: record.requestedPresentInLegacyModels,\n sessionOperation: record.sessionOperation,\n sourceState: record.sourceState,\n };\n}\nfunction parseBoundedModelIds(value) {\n if (!Array.isArray(value) ||\n value.length > MODEL_DIAGNOSTIC_ID_LIMIT ||\n !value.every((modelId) => typeof modelId === \"string\" &&\n modelId.length > 0 &&\n modelId.length <= MODEL_DIAGNOSTIC_ID_MAX_LENGTH)) {\n return null;\n }\n return [...value];\n}\nfunction parseModelCount(value, visibleCount) {\n return typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= (visibleCount ?? Number.POSITIVE_INFINITY)\n ? value\n : null;\n}\nfunction parseNullableModelId(value) {\n if (value === null) {\n return null;\n }\n return typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= MODEL_DIAGNOSTIC_ID_MAX_LENGTH\n ? value\n : undefined;\n}\nfunction isModelSourceState(value) {\n return (value === \"config_options_only\" ||\n value === \"conflicting\" ||\n value === \"consistent\" ||\n value === \"legacy_models_only\" ||\n value === \"missing\");\n}\nfunction toUnknownRecord(value) {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? value\n : null;\n}\nexport const resolveAdapterAgentContext = (input) => {\n const env = input.env ?? {};\n const rawValue = env[input.spec.sourceField];\n const agentControllerConversationId = typeof rawValue === \"string\" && rawValue.trim().length > 0\n ? rawValue.trim()\n : null;\n const agentControllerConversation = input.bridgeSpec && agentControllerConversationId\n ? buildAdapterAgentControllerConversationRef({\n agentControllerRef: input.bridgeSpec.agentControllerRef,\n agentControllerConversationId,\n agentControllerConversationKind: input.bridgeSpec.agentControllerConversationKind,\n })\n : null;\n return {\n agentControllerConversationId,\n sourceField: input.spec.sourceField,\n mappingVersion: input.spec.mappingVersion,\n ...(agentControllerConversation ? { agentControllerConversation } : {}),\n };\n};\nconst defaultWaitForMs = async (delayMs) => {\n if (delayMs <= 0) {\n return;\n }\n await new Promise((resolve) => {\n setTimeout(() => {\n resolve();\n }, delayMs);\n });\n};\nconst normalizeGracefulTimeoutMs = (gracefulTimeoutMs) => {\n if (!Number.isInteger(gracefulTimeoutMs) || gracefulTimeoutMs === undefined) {\n return DEFAULT_GRACEFUL_INTERRUPT_TIMEOUT_MS;\n }\n return gracefulTimeoutMs > 0\n ? gracefulTimeoutMs\n : DEFAULT_GRACEFUL_INTERRUPT_TIMEOUT_MS;\n};\nconst extractErrorCode = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const code = error.code;\n if (typeof code !== \"string\") {\n return null;\n }\n const normalized = code.trim();\n return normalized.length > 0 ? normalized : null;\n};\nconst extractErrorType = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const errorType = error.errorType;\n if (typeof errorType !== \"string\") {\n return null;\n }\n const normalized = errorType.trim();\n switch (normalized) {\n case \"adapter\":\n return \"adapter\";\n case \"auth\":\n return \"auth\";\n case \"config\":\n return \"config\";\n case \"timeout\":\n return \"timeout\";\n case \"network\":\n return \"network\";\n case \"unknown\":\n return \"unknown\";\n default:\n return null;\n }\n};\nconst extractProviderAccessEvidence = (error) => {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const evidence = error\n .providerAccessEvidence;\n if (!evidence || typeof evidence !== \"object\") {\n return null;\n }\n const parsed = openMeldDaemonProviderAccessEvidenceSchema.safeParse(evidence);\n return parsed.success ? parsed.data : null;\n};\nconst normalizeControlReason = (reason, fallback) => {\n if (typeof reason !== \"string\") {\n return fallback;\n }\n const normalized = reason.trim();\n return normalized.length > 0 ? normalized : fallback;\n};\nconst resolveCanonicalContextDelta = (input) => {\n if (!input.contextDelta) {\n return undefined;\n }\n const canonicalContextDelta = {\n agentControllerConversationId: input.contextDelta.agentControllerConversationId,\n ...(input.contextDelta.refreshed === true ? { refreshed: true } : {}),\n ...(input.contextDelta.agentControllerConversation\n ? {\n agentControllerConversation: input.contextDelta.agentControllerConversation,\n }\n : {}),\n };\n if (!input.bridgeSpec) {\n return canonicalContextDelta;\n }\n const agentControllerConversation = bridgeAgentControllerConversationRef({\n agentControllerConversationId: canonicalContextDelta.agentControllerConversationId,\n bridgeSpec: input.bridgeSpec,\n agentControllerConversation: canonicalContextDelta.agentControllerConversation,\n });\n return {\n ...canonicalContextDelta,\n ...(agentControllerConversation ? { agentControllerConversation } : {}),\n };\n};\nconst buildDefaultInvokeRequest = (input) => {\n const agentControllerConversationId = input.bridgeSpec\n ? resolveBridgedAgentControllerConversationId({\n agentControllerConversationId: input.request.agentControllerConversationId,\n bridgeSpec: input.bridgeSpec,\n agentControllerConversation: input.request.agentControllerConversation,\n })\n : normalizeOptionalText(input.request.agentControllerConversationId);\n return {\n ...input.request,\n agentControllerConversationId,\n };\n};\nconst normalizeOptionalText = (value) => {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n};\nconst isDefaultInvokeDisabledForTests = (runtimeOptions) => runtimeOptions?.[TEST_DISABLE_DEFAULT_INVOKE] === true;\nconst resolveCancelSignalSender = (input) => {\n if (input.sendCancel) {\n return {\n deliveryPath: \"cancel\",\n send: input.sendCancel,\n };\n }\n if (!input.sendInterrupt) {\n return null;\n }\n return {\n deliveryPath: \"force_interrupt_fallback\",\n send: async (request) => {\n await input.sendInterrupt?.({\n mode: \"force\",\n reason: request.reason ?? DEFAULT_CANCEL_REASON,\n taskId: request.taskId,\n });\n },\n };\n};\nconst resolveControlReasonCode = (error) => {\n const code = extractErrorCode(error);\n switch (code) {\n case \"adapter.unsupported\":\n case \"signal.not_sent\":\n case \"signal.send_failed\":\n case \"task.not_found\":\n case \"task.not_running\":\n return code;\n default:\n return null;\n }\n};\nconst toUnknownErrorMessage = (error) => error instanceof Error ? error.message : \"unknown adapter control error\";\nconst resolveControlReasonDetail = (error, reasonCode) => reasonCode === \"adapter.unsupported\"\n ? undefined\n : toUnknownErrorMessage(error);\n"],"mappings":";;;;;;;;;;;;;;;;;;AAEA,SAAgB,2BAA2B,YAAY;CACnD,OAAO,WAAW,MAAM,KAAK,UAAU;EACnC,MAAM,KAAK;EACX,OAAO,KAAK,SAAS,KAAK;EAC1B,aAAa,KAAK;EAClB,aAAa,aAAa,KAAK,aAAa;GACxC,QAAQ;GACR,IAAI;EACR,CAAC;CACL,EAAE;AACN;AACA,MAAa,0CAA0C;AACvD,SAAgB,kCAAkC,KAAK;CACnD,OAAO,MAAM,6CAA6C;AAC9D;;;ACfA,SAAgB,4BAA4B,OAAO;CAC/C,IAAI,OAAO,UAAU,UACjB,OAAO;CAEX,MAAM,aAAa,MAAM,KAAK;CAC9B,IAAI,WAAW,WAAW,KACtB,CAAC,qCAAqC,UAAU,GAChD,OAAO;CAEX,OAAO,WAAW,MAAM,GAAG,kCAAkC;AACjE;;;ACFA,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,SAAgB,uBAAuB,OAAO;CAC1C,MAAM,MAAM,4BAA4B,MAAM,KAAK,OAAO;CAC1D,MAAM,aAAa,0BAA0B,MAAM,WAAW,KAAK,GA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