@tempad-dev/mcp 1.0.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +28 -10
  2. package/README.zh-Hans.md +24 -9
  3. package/dist/{acquire-DHwsqq0j.mjs → acquire-CCPjn86-.mjs} +4 -4
  4. package/dist/acquire-CCPjn86-.mjs.map +1 -0
  5. package/dist/{acquire-BtKFZ9Lz.mjs → acquire-C_qsbxdV.mjs} +1 -1
  6. package/dist/{bootstrap-B9-RyWlM.mjs → bootstrap-BkZ1dGkI.mjs} +33 -27
  7. package/dist/bootstrap-BkZ1dGkI.mjs.map +1 -0
  8. package/dist/cli.mjs +6 -6
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/client-binding-CvSSv9JC.mjs.map +1 -1
  11. package/dist/{cold-start-U3cW0q9T.mjs → cold-start-Cv4OAoez.mjs} +1 -1
  12. package/dist/{cold-start-DOy9JsIQ.mjs → cold-start-qMVT1cNu.mjs} +94 -47
  13. package/dist/cold-start-qMVT1cNu.mjs.map +1 -0
  14. package/dist/{config-Busa_Dqv.mjs → config-Qvh73WBD.mjs} +20 -73
  15. package/dist/config-Qvh73WBD.mjs.map +1 -0
  16. package/dist/{design-task-store-BHR54v8-.mjs → design-task-store-BQy2SO7l.mjs} +4 -3
  17. package/dist/design-task-store-BQy2SO7l.mjs.map +1 -0
  18. package/dist/durable-json-_WKesGDj.mjs.map +1 -1
  19. package/dist/{edge-BUf7gs4J.mjs → edge-DO3aAdn1.mjs} +9 -9
  20. package/dist/edge-DO3aAdn1.mjs.map +1 -0
  21. package/dist/{edge-CHzaTUFt.mjs → edge-DdEimtG9.mjs} +1 -1
  22. package/dist/{hook-receipts-QJU3AMoY.mjs → hook-receipts-BIUk86RJ.mjs} +2 -2
  23. package/dist/hook-receipts-BIUk86RJ.mjs.map +1 -0
  24. package/dist/host-context-9TVtjsSm.mjs.map +1 -1
  25. package/dist/{hub-control-UlA4Fncg.mjs → hub-control-C2jNTi3G.mjs} +3 -3
  26. package/dist/hub-control-C2jNTi3G.mjs.map +1 -0
  27. package/dist/{hub-runtime-DsEO9zvX.mjs → hub-runtime-ApgbrLQI.mjs} +500 -454
  28. package/dist/hub-runtime-ApgbrLQI.mjs.map +1 -0
  29. package/dist/{hub-runtime-DjdqIgGl.mjs → hub-runtime-BZ6Nrold.mjs} +1 -1
  30. package/dist/hub.mjs +2 -2
  31. package/dist/hub.mjs.map +1 -1
  32. package/dist/{identity-CCaDEwgc.mjs → identity-C80lcT6j.mjs} +2 -2
  33. package/dist/identity-C80lcT6j.mjs.map +1 -0
  34. package/dist/indexes-zYqwqnU6.mjs.map +1 -1
  35. package/dist/log-transport.mjs.map +1 -1
  36. package/dist/managed-runtime.mjs +12 -12
  37. package/dist/managed-runtime.mjs.map +1 -1
  38. package/dist/on-exit-leak-free-By20-eFK.mjs.map +1 -1
  39. package/dist/pino-BiEyUxFF.mjs.map +1 -1
  40. package/dist/pino-abstract-transport-BBwCGDga.mjs.map +1 -1
  41. package/dist/pino-file.mjs.map +1 -1
  42. package/dist/pino-worker.mjs.map +1 -1
  43. package/dist/{probe-BeWkMbzQ.mjs → probe-BBGkIAHT.mjs} +7 -15
  44. package/dist/probe-BBGkIAHT.mjs.map +1 -0
  45. package/dist/process-environment-DRRIdoL8.mjs.map +1 -1
  46. package/dist/{processes-CBoalzSk.mjs → processes-BL7g1Hvw.mjs} +1 -1
  47. package/dist/{processes-BCCE8As7.mjs → processes-BX-yLfvZ.mjs} +67 -36
  48. package/dist/processes-BX-yLfvZ.mjs.map +1 -0
  49. package/dist/proper-lockfile-BgKrOq5D.mjs.map +1 -1
  50. package/dist/{protocol-7m-E_iFu.mjs → protocol-DlkrVyMK.mjs} +2 -2
  51. package/dist/protocol-DlkrVyMK.mjs.map +1 -0
  52. package/dist/{protocol-COK3rM6m.mjs → protocol-G4tyEGD3.mjs} +1 -1
  53. package/dist/runtime-identity-D9V-g5M-.mjs.map +1 -1
  54. package/dist/runtime-installer.mjs +3 -3
  55. package/dist/runtime-installer.mjs.map +1 -1
  56. package/dist/runtime-manifest.json +96 -97
  57. package/dist/{runtime-platform-C-Yk9F3L.mjs → runtime-platform-CpunJOI4.mjs} +143 -43
  58. package/dist/runtime-platform-CpunJOI4.mjs.map +1 -0
  59. package/dist/{runtime-recovery-DaRaQ8qY.mjs → runtime-recovery-CPfCb3rY.mjs} +2 -2
  60. package/dist/runtime-recovery-CPfCb3rY.mjs.map +1 -0
  61. package/dist/{runtime-recovery-DAYSaVV2.mjs → runtime-recovery-CexhaHl_.mjs} +1 -1
  62. package/dist/runtime-verification.mjs +5 -5
  63. package/dist/schemas-ZDdPV7RQ.mjs.map +1 -1
  64. package/dist/{server-CsCpY0Ft.mjs → server-CyzfkzoZ.mjs} +2 -2
  65. package/dist/server-CyzfkzoZ.mjs.map +1 -0
  66. package/dist/{shared-S0dtOYq8.mjs → shared-BRxN9qqm.mjs} +1 -1
  67. package/dist/{shared--othnF1c.mjs → shared-avqQD-kX.mjs} +10 -7
  68. package/dist/shared-avqQD-kX.mjs.map +1 -0
  69. package/dist/src-BSnzZMvK.mjs.map +1 -1
  70. package/dist/{stable-edge-VAAxSYSS.mjs → stable-edge-C5C0Rx5t.mjs} +3 -3
  71. package/dist/stable-edge-C5C0Rx5t.mjs.map +1 -0
  72. package/dist/{startup-log-CYlFgdy5.mjs → startup-log-CVOxFwjV.mjs} +2 -2
  73. package/dist/startup-log-CVOxFwjV.mjs.map +1 -0
  74. package/dist/{startup-log-DqK2uwBd.mjs → startup-log-DUPFFTwJ.mjs} +1 -1
  75. package/dist/{state-6qFcvi-I.mjs → state-4Dz7r-_n.mjs} +2 -2
  76. package/dist/state-4Dz7r-_n.mjs.map +1 -0
  77. package/dist/{state-BrWBtYNG.mjs → state-DDpxeTVd.mjs} +1 -1
  78. package/dist/stdio-20SBFdww.mjs.map +1 -1
  79. package/dist/{supervisor-CesT-H5_.mjs → supervisor-IWbA-VOB.mjs} +40 -42
  80. package/dist/supervisor-IWbA-VOB.mjs.map +1 -0
  81. package/dist/{task-storage-recovery-I9lpYYX6.mjs → task-storage-recovery-CabVFMUg.mjs} +3 -3
  82. package/dist/task-storage-recovery-CabVFMUg.mjs.map +1 -0
  83. package/dist/thread-stream-worker.mjs.map +1 -1
  84. package/dist/types-kNTSQOnR.mjs.map +1 -1
  85. package/package.json +1 -1
  86. package/dist/acquire-DHwsqq0j.mjs.map +0 -1
  87. package/dist/bootstrap-B9-RyWlM.mjs.map +0 -1
  88. package/dist/cold-start-DOy9JsIQ.mjs.map +0 -1
  89. package/dist/config-Busa_Dqv.mjs.map +0 -1
  90. package/dist/design-task-store-BHR54v8-.mjs.map +0 -1
  91. package/dist/edge-BUf7gs4J.mjs.map +0 -1
  92. package/dist/hook-receipts-QJU3AMoY.mjs.map +0 -1
  93. package/dist/hub-control-UlA4Fncg.mjs.map +0 -1
  94. package/dist/hub-runtime-DsEO9zvX.mjs.map +0 -1
  95. package/dist/identity-CCaDEwgc.mjs.map +0 -1
  96. package/dist/probe-BeWkMbzQ.mjs.map +0 -1
  97. package/dist/processes-BCCE8As7.mjs.map +0 -1
  98. package/dist/protocol-7m-E_iFu.mjs.map +0 -1
  99. package/dist/runtime-platform-C-Yk9F3L.mjs.map +0 -1
  100. package/dist/runtime-recovery-DaRaQ8qY.mjs.map +0 -1
  101. package/dist/server-CsCpY0Ft.mjs.map +0 -1
  102. package/dist/shared--othnF1c.mjs.map +0 -1
  103. package/dist/stable-edge-VAAxSYSS.mjs.map +0 -1
  104. package/dist/startup-log-CYlFgdy5.mjs.map +0 -1
  105. package/dist/state-6qFcvi-I.mjs.map +0 -1
  106. package/dist/supervisor-CesT-H5_.mjs.map +0 -1
  107. package/dist/task-storage-recovery-I9lpYYX6.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared--othnF1c.mjs","names":["process","process","packageJson","pino"],"sources":["../../../agent-plugin/src/clients/shared/runtime-paths.mjs","../../../agent-plugin/src/clients/shared/runtime-profile.mjs","../package.json","../src/log-retention.ts","../src/shared.ts"],"sourcesContent":["import { lstatSync, mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\n\nfunction inspectRoot(path) {\n try {\n return lstatSync(path)\n } catch (error) {\n if (error.code !== 'ENOENT') throw error\n return null\n }\n}\n\nfunction isPrivateRoot(stat, uid) {\n return stat?.isDirectory() && stat.uid === uid && (stat.mode & 0o777) === 0o700\n}\n\nfunction hasHubFiles(root) {\n return (\n inspectRoot(join(root, 'run', 'mcp.sock')) !== null ||\n inspectRoot(join(root, 'run', 'hub.lock.lock')) !== null\n )\n}\n\nexport function resolveDefaultRoot(\n systemTmpDir = tmpdir(),\n platform = process.platform,\n uid = process.getuid?.()\n) {\n const legacyRoot = join(systemTmpDir, 'tempad-dev')\n if (platform !== 'linux') return legacyRoot\n const isolatedRoot = join(systemTmpDir, `tempad-dev-${uid}`)\n const legacy = inspectRoot(legacyRoot)\n const isolated = inspectRoot(isolatedRoot)\n const legacyPrivate = isPrivateRoot(legacy, uid)\n const isolatedPrivate = isPrivateRoot(isolated, uid)\n const legacyActive = legacy?.uid === uid && hasHubFiles(legacyRoot)\n const isolatedActive = isolated?.uid === uid && hasHubFiles(isolatedRoot)\n if (\n (legacyActive && !legacyPrivate) ||\n (isolatedActive && !isolatedPrivate) ||\n (legacyActive && isolatedActive)\n )\n throw new Error(\n `Ambiguous or unsafe Hub runtime roots: ${legacyRoot}, ${isolatedRoot}. Stop the existing runtimes and correct ownership/permissions before reconnecting; automatic migration is refused.`\n )\n if (isolatedPrivate && !legacyActive) return isolatedRoot\n if (legacyPrivate || !legacy) return legacyRoot\n return isolatedRoot\n}\n\nexport function prepareDefaultRoot(\n systemTmpDir = tmpdir(),\n platform = process.platform,\n uid = process.getuid?.()\n) {\n const selected = resolveDefaultRoot(systemTmpDir, platform, uid)\n if (platform !== 'linux' || selected !== join(systemTmpDir, 'tempad-dev')) return selected\n // Claim the released path atomically so old installed hooks still work after a reboot.\n try {\n mkdirSync(selected, { mode: 0o700 })\n } catch (error) {\n if (error.code !== 'EEXIST') throw error\n }\n return resolveDefaultRoot(systemTmpDir, platform, uid)\n}\n\nexport function assertTrustedSocket(\n socketPath,\n platform = process.platform,\n uid = process.getuid?.()\n) {\n if (platform === 'win32') return\n const parent = lstatSync(dirname(socketPath))\n const socket = lstatSync(socketPath)\n if (\n !parent.isDirectory() ||\n parent.uid !== uid ||\n (parent.mode & 0o077) !== 0 ||\n !socket.isSocket() ||\n socket.uid !== uid ||\n (socket.mode & 0o077) !== 0\n )\n throw new Error(\n `Refusing untrusted Hub socket: ${socketPath}. Check its owner and private permissions before reconnecting.`\n )\n}\n","import { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport { realpathSync, statSync } from 'node:fs'\nimport { homedir, tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { prepareDefaultRoot, resolveDefaultRoot } from './runtime-paths.mjs'\n\nfunction hash(value) {\n return createHash('sha256').update(value).digest('hex').slice(0, 16)\n}\n\nexport function checkoutProfile(checkout) {\n if (!isAbsolute(checkout)) throw new Error('TEMPAD_MCP_DEV_CHECKOUT must be an absolute path.')\n const root = realpathSync(checkout)\n if (!statSync(root).isDirectory()) throw new Error('The checkout must be a directory.')\n return { kind: 'checkout', id: hash(root) }\n}\n\nexport function resolveRuntimeProfile(env = process.env, entryUrl) {\n if (env.TEMPAD_MCP_DEV_CHECKOUT === undefined) return { kind: 'release' }\n const profile = checkoutProfile(env.TEMPAD_MCP_DEV_CHECKOUT)\n if (entryUrl) {\n const root = realpathSync(env.TEMPAD_MCP_DEV_CHECKOUT)\n const dist = join(root, 'packages/mcp-server/dist')\n for (const name of ['cli.mjs', 'hub.mjs']) {\n const path = join(dist, name)\n try {\n if (realpathSync(path) === path && statSync(path).isFile()) continue\n } catch (cause) {\n throw new Error(`Missing checkout runtime: ${path}. Run pnpm build:mcp in the checkout.`, {\n cause\n })\n }\n throw new Error(`Invalid checkout runtime: ${path}. Build the checkout before starting MCP.`)\n }\n if (dirname(realpathSync(fileURLToPath(entryUrl))) !== dist)\n throw new Error('The MCP entry point does not belong to TEMPAD_MCP_DEV_CHECKOUT.')\n }\n return profile\n}\n\nexport function runtimeDirectories(\n env = process.env,\n profile = resolveRuntimeProfile(env),\n options = {}\n) {\n const temporary = options.tmpdir ?? tmpdir()\n const home = options.homedir ?? homedir()\n const user = options.uid ?? process.getuid?.() ?? hash(home)\n const checkout = profile.kind === 'checkout'\n const needsRoot =\n !env.TEMPAD_MCP_RUNTIME_DIR || !env.TEMPAD_MCP_LOG_DIR || !env.TEMPAD_MCP_ASSET_DIR\n let root\n if (needsRoot) {\n root = checkout\n ? join(temporary, `tpd-${user}-${profile.id}`)\n : (options.prepare ? prepareDefaultRoot : resolveDefaultRoot)(temporary)\n }\n // Explicit directories remain usable for isolated tests, but never merge checkout and release.\n const directory = (override, name) => {\n if (!override) return join(root, name)\n return checkout ? join(override, `checkout-${profile.id}`) : override\n }\n const runtime = directory(env.TEMPAD_MCP_RUNTIME_DIR, 'run')\n let state\n if (!checkout && env.TEMPAD_MCP_STATE_DIR !== undefined) {\n state = env.TEMPAD_MCP_STATE_DIR\n } else if (env.TEMPAD_MCP_STATE_DIR) {\n state = directory(env.TEMPAD_MCP_STATE_DIR, 'state')\n } else if (env.TEMPAD_MCP_RUNTIME_DIR) {\n state = join(runtime, 'state')\n } else {\n state = checkout\n ? join(home, '.tempad-dev', 'checkouts', profile.id, 'state')\n : join(home, '.tempad-dev', 'state')\n }\n return {\n root,\n runtime,\n log: directory(env.TEMPAD_MCP_LOG_DIR, 'log'),\n assets: directory(env.TEMPAD_MCP_ASSET_DIR, 'assets'),\n state\n }\n}\n\nexport function runtimeSocketPath(\n runtime,\n profile = { kind: 'release' },\n platform = process.platform,\n home = homedir()\n) {\n if (platform !== 'win32') {\n const socket = join(runtime, 'mcp.sock')\n if (profile.kind === 'checkout' && Buffer.byteLength(socket) > 103)\n throw new Error('Checkout socket path is too long. Choose a shorter TEMPAD_MCP_RUNTIME_DIR.')\n return socket\n }\n return profile.kind === 'checkout'\n ? `\\\\\\\\.\\\\pipe\\\\tempad-mcp-${hash(home)}-${profile.id}`\n : '\\\\\\\\.\\\\pipe\\\\tempad-mcp'\n}\n","","import { lstatSync, readdirSync, unlinkSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000\nconst LOG_NAME = /^(?:startup-)?mcp-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z-([1-9]\\d*)\\.log$/\n\n/** Best-effort housekeeping: never remove a log a running process may still own. */\nexport function pruneExpiredLogs(directory: string, now = Date.now()): number {\n let names: string[]\n try {\n names = readdirSync(directory)\n } catch {\n return 0\n }\n let removed = 0\n for (const name of names) {\n const match = LOG_NAME.exec(name)\n if (!match) continue\n const pid = Number(match[1])\n if (!Number.isSafeInteger(pid) || pid > 2147483647 || pid === process.pid) continue\n try {\n const path = join(directory, name)\n const stat = lstatSync(path)\n if (\n !stat.isFile() ||\n stat.isSymbolicLink() ||\n (process.platform !== 'win32' && stat.uid !== process.getuid?.()) ||\n stat.mtimeMs > now - RETENTION_MS\n )\n continue\n try {\n process.kill(pid, 0)\n continue\n } catch (error) {\n // EPERM and platform-specific probe failures do not establish that a\n // process has exited. PID reuse deliberately favors keeping the log.\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') continue\n }\n unlinkSync(path)\n removed++\n } catch {\n // Concurrent cleanup, antivirus and storage failures must not block MCP.\n }\n }\n return removed\n}\n","import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport pino from 'pino'\n\nimport {\n resolveRuntimeProfile,\n runtimeDirectories,\n runtimeSocketPath\n} from '../../../agent-plugin/src/clients/shared/runtime-profile.mjs'\nimport packageJson from '../package.json' with { type: 'json' }\nimport { getRuntimeTimingConfig } from './config'\nimport { pruneExpiredLogs } from './log-retention'\nimport { ensurePrivateDirectory } from './runtime-platform'\n\nexport {\n assertTrustedSocket,\n resolveDefaultRoot\n} from '../../../agent-plugin/src/clients/shared/runtime-paths.mjs'\n\nexport function normalizePackageVersion(version: unknown): string {\n return typeof version === 'string' ? version : '0.0.0'\n}\n\nexport function ensureDir(dirPath: string): void {\n if (process.platform === 'win32') {\n ensurePrivateDirectory(dirPath)\n return\n }\n mkdirSync(dirPath, { recursive: true, mode: 0o700 })\n const stat = lstatSync(dirPath)\n if (\n !stat.isDirectory() ||\n stat.isSymbolicLink() ||\n stat.uid !== process.getuid?.() ||\n (stat.mode & 0o077) !== 0\n )\n throw new Error(`Refusing untrusted runtime directory: ${dirPath}`)\n}\n\nexport function getRecordProperty(record: unknown, key: string): unknown {\n if (!record || typeof record !== 'object') {\n return undefined\n }\n return Reflect.get(record, key)\n}\n\nexport const PACKAGE_VERSION = normalizePackageVersion(getRecordProperty(packageJson, 'version'))\nexport const RUNTIME_PROFILE = resolveRuntimeProfile(process.env, import.meta.url)\n\nexport function resolveRuntimeDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).runtime\n}\n\nexport function resolveLogDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).log\n}\n\nexport function resolveAssetDir(\n env: NodeJS.ProcessEnv = process.env,\n systemTmpDir: string = tmpdir()\n): string {\n return runtimeDirectories(env, undefined, { tmpdir: systemTmpDir }).assets\n}\n\nexport function resolveStateDir(env: NodeJS.ProcessEnv = process.env): string {\n return runtimeDirectories(env).state\n}\n\nexport function resolveLogLevel(\n debugValue: string | undefined = process.env.DEBUG\n): 'debug' | 'info' {\n return debugValue ? 'debug' : 'info'\n}\n\nexport function resolveSockPath(\n platform: NodeJS.Platform = process.platform,\n runtimeDir: string = RUNTIME_DIR\n): string {\n return runtimeSocketPath(runtimeDir, RUNTIME_PROFILE, platform)\n}\n\nconst directories = runtimeDirectories(process.env, RUNTIME_PROFILE, { prepare: true })\nexport const RUNTIME_DIR = directories.runtime\nexport const LOG_DIR = directories.log\nexport const ASSET_DIR = directories.assets\n\nif (directories.root) ensureDir(directories.root)\nensureDir(RUNTIME_DIR)\nensureDir(LOG_DIR)\nensureDir(ASSET_DIR)\n\nexport function ensureFile(filePath: string): void {\n const fd = openSync(filePath, 'a')\n closeSync(fd)\n}\n\nexport const LOCK_PATH = join(RUNTIME_DIR, 'mcp.lock')\nexport const HUB_LOCK_PATH = join(RUNTIME_DIR, 'hub.lock')\nexport const HUB_RUNTIME_IDENTITY_PATH = join(RUNTIME_DIR, 'hub-runtime.json')\nensureFile(LOCK_PATH)\nensureFile(HUB_LOCK_PATH)\n\nexport const HUB_BUSY_EXIT_CODE = 75\nconst runtimeTiming = getRuntimeTimingConfig()\nexport const HUB_LOCK_STALE_MS = runtimeTiming.hubLockStaleMs\nexport const HUB_LOCK_UPDATE_MS = runtimeTiming.hubLockUpdateMs\n\nconst timestamp = new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')\nconst pid = process.pid\nconst LOG_FILE = join(LOG_DIR, `mcp-${timestamp}-${pid}.log`)\n\npruneExpiredLogs(LOG_DIR)\n\nconst prettyTransport = pino.transport({\n // An ESM worker is a file, even when its parent was launched through --eval.\n ...(process.execArgv.some((arg) => arg === '--input-type' || arg.startsWith('--input-type='))\n ? { worker: { execArgv: [] } }\n : {}),\n target: fileURLToPath(\n import.meta.url.endsWith('.ts')\n ? new URL('./log-transport.ts', import.meta.url)\n : new URL('./log-transport.mjs', import.meta.url)\n ),\n options: {\n translateTime: 'SYS:HH:MM:ss',\n destination: LOG_FILE\n }\n})\n\nexport const log = pino(\n {\n level: resolveLogLevel(),\n msgPrefix: '[tempad-dev/mcp] '\n },\n prettyTransport\n)\n\nexport function endLogging(): void {\n // Shutdown must drain the worker even when its ready event is still pending.\n prettyTransport.end()\n}\n\nexport const SOCK_PATH = resolveSockPath()\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,MAAM;CACzB,IAAI;EACF,OAAO,UAAU,IAAI;CACvB,SAAS,OAAO;EACd,IAAI,MAAM,SAAS,UAAU,MAAM;EACnC,OAAO;CACT;AACF;AAEA,SAAS,cAAc,MAAM,KAAK;CAChC,OAAO,MAAM,YAAY,KAAK,KAAK,QAAQ,QAAQ,KAAK,OAAO,SAAW;AAC5E;AAEA,SAAS,YAAY,MAAM;CACzB,OACE,YAAY,KAAK,MAAM,OAAO,UAAU,CAAC,MAAM,QAC/C,YAAY,KAAK,MAAM,OAAO,eAAe,CAAC,MAAM;AAExD;AAEA,SAAgB,mBACd,eAAe,OAAO,GACtB,WAAWA,UAAQ,UACnB,MAAMA,UAAQ,SAAS,GACvB;CACA,MAAM,aAAa,KAAK,cAAc,YAAY;CAClD,IAAI,aAAa,SAAS,OAAO;CACjC,MAAM,eAAe,KAAK,cAAc,cAAc,KAAK;CAC3D,MAAM,SAAS,YAAY,UAAU;CACrC,MAAM,WAAW,YAAY,YAAY;CACzC,MAAM,gBAAgB,cAAc,QAAQ,GAAG;CAC/C,MAAM,kBAAkB,cAAc,UAAU,GAAG;CACnD,MAAM,eAAe,QAAQ,QAAQ,OAAO,YAAY,UAAU;CAClE,MAAM,iBAAiB,UAAU,QAAQ,OAAO,YAAY,YAAY;CACxE,IACG,gBAAgB,CAAC,iBACjB,kBAAkB,CAAC,mBACnB,gBAAgB,gBAEjB,MAAM,IAAI,MACR,0CAA0C,WAAW,IAAI,aAAa,oHACxE;CACF,IAAI,mBAAmB,CAAC,cAAc,OAAO;CAC7C,IAAI,iBAAiB,CAAC,QAAQ,OAAO;CACrC,OAAO;AACT;AAEA,SAAgB,mBACd,eAAe,OAAO,G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 +0,0 @@
1
- {"version":3,"file":"stable-edge-VAAxSYSS.mjs","names":["supportsUrlMode","delay"],"sources":["../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_supports-color@7.2.0_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_supports-color@7.2.0_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../scripts/runtime-contract.mjs","../src/stable-edge.ts"],"sourcesContent":["/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';\n/**\n * Experimental task features for MCP clients.\n *\n * Access via `client.experimental.tasks`:\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });\n * const task = await client.experimental.tasks.getTask(taskId);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalClientTasks {\n constructor(_client) {\n this._client = _client;\n }\n /**\n * Calls a tool and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to tool execution, allowing you to\n * observe intermediate task status updates for long-running tool calls.\n * Automatically validates structured output if the tool has an outputSchema.\n *\n * @example\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Tool execution started:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Tool status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Tool result:', message.result);\n * break;\n * case 'error':\n * console.error('Tool error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - Tool call parameters (name and arguments)\n * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n async *callToolStream(params, resultSchema = CallToolResultSchema, options) {\n // Access Client's internal methods\n const clientInternal = this._client;\n // Add task creation parameters if server supports it and not explicitly provided\n const optionsWithTask = {\n ...options,\n // We check if the tool is known to be a task during auto-configuration, but assume\n // the caller knows what they're doing if they pass this explicitly\n task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)\n };\n const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);\n // Get the validator for this tool (if it has an output schema)\n const validator = clientInternal.getToolOutputValidator(params.name);\n // Iterate through the stream and validate the final result if needed\n for await (const message of stream) {\n // If this is a result message and the tool has an output schema, validate it\n if (message.type === 'result' && validator) {\n const result = message.result;\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)\n };\n return;\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)\n };\n return;\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n yield { type: 'error', error };\n return;\n }\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)\n };\n return;\n }\n }\n }\n // Yield the message (either validated result or any other message type)\n yield message;\n }\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._client.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.cancelTask({ taskId }, options);\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._client.requestStream(request, resultSchema, options);\n }\n}\n//# sourceMappingURL=client.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getLiteralValue, getObjectShape, safeParse } from '../server/zod-compat.js';\nimport { ExperimentalClientTasks } from '../experimental/tasks/client.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * Elicitation default application helper. Applies defaults to the data based on the schema.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema, data) {\n if (!schema || data === null || typeof data !== 'object')\n return;\n // Handle object properties\n if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n const obj = data;\n const props = schema.properties;\n for (const key of Object.keys(props)) {\n const propSchema = props[key];\n // If missing or explicitly undefined, apply default if present\n if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n obj[key] = propSchema.default;\n }\n // Recurse into existing nested objects/arrays\n if (obj[key] !== undefined) {\n applyElicitationDefaults(propSchema, obj[key]);\n }\n }\n }\n if (Array.isArray(schema.anyOf)) {\n for (const sub of schema.anyOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n // Combine schemas\n if (Array.isArray(schema.oneOf)) {\n for (const sub of schema.oneOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n}\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities) {\n if (!capabilities) {\n return { supportsFormMode: false, supportsUrlMode: false };\n }\n const hasFormCapability = capabilities.form !== undefined;\n const hasUrlCapability = capabilities.url !== undefined;\n // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n const supportsUrlMode = hasUrlCapability;\n return { supportsFormMode, supportsUrlMode };\n}\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when connect() is called.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed client\n * const client = new Client<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomClient\",\n * version: \"1.0.0\"\n * })\n * ```\n */\nexport class Client extends Protocol {\n /**\n * Initializes this client with the given name and version information.\n */\n constructor(_clientInfo, options) {\n super(options);\n this._clientInfo = _clientInfo;\n this._cachedToolOutputValidators = new Map();\n this._cachedKnownTaskTools = new Set();\n this._cachedRequiredTaskTools = new Set();\n this._listChangedDebounceTimers = new Map();\n this._capabilities = options?.capabilities ?? {};\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n // Store list changed config for setup after connection (when we know server capabilities)\n if (options?.listChanged) {\n this._pendingListChangedConfig = options.listChanged;\n }\n }\n /**\n * Set up handlers for list changed notifications based on config and server capabilities.\n * This should only be called after initialization when server capabilities are known.\n * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n * @internal\n */\n _setupListChangedHandlers(config) {\n if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {\n const result = await this.listTools();\n return result.tools;\n });\n }\n if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {\n const result = await this.listPrompts();\n return result.prompts;\n });\n }\n if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {\n const result = await this.listResources();\n return result.resources;\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalClientTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce client-side validation for elicitation.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const methodValue = getLiteralValue(methodSchema);\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'elicitation/create') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(ElicitRequestSchema, request);\n if (!validatedRequest.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n params.mode = params.mode ?? 'form';\n const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n if (params.mode === 'form' && !supportsFormMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n }\n if (params.mode === 'url' && !supportsUrlMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n }\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against ElicitResultSchema\n const validationResult = safeParse(ElicitResultSchema, result);\n if (!validationResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);\n }\n const validatedResult = validationResult.data;\n const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;\n if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {\n if (this._capabilities.elicitation?.form?.applyDefaults) {\n try {\n applyElicitationDefaults(requestedSchema, validatedResult.content);\n }\n catch {\n // gracefully ignore errors in default application\n }\n }\n }\n return validatedResult;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n if (method === 'sampling/createMessage') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CreateMessageRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against appropriate schema based on tools presence\n const hasTools = params.tools || params.toolChoice;\n const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;\n const validationResult = safeParse(resultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapability(capability, method) {\n if (!this._serverCapabilities?.[capability]) {\n throw new Error(`Server does not support ${capability} (required for ${method})`);\n }\n }\n async connect(transport, options) {\n await super.connect(transport);\n // When transport sessionId is already set this means we are trying to reconnect.\n // In this case we don't need to initialize again.\n if (transport.sessionId !== undefined) {\n return;\n }\n try {\n const result = await this.request({\n method: 'initialize',\n params: {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n capabilities: this._capabilities,\n clientInfo: this._clientInfo\n }\n }, InitializeResultSchema, options);\n if (result === undefined) {\n throw new Error(`Server sent invalid initialize result: ${result}`);\n }\n if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n }\n this._serverCapabilities = result.capabilities;\n this._serverVersion = result.serverInfo;\n // HTTP transports must set the protocol version in each header after initialization.\n if (transport.setProtocolVersion) {\n transport.setProtocolVersion(result.protocolVersion);\n }\n this._instructions = result.instructions;\n await this.notification({\n method: 'notifications/initialized'\n });\n // Set up list changed handlers now that we know server capabilities\n if (this._pendingListChangedConfig) {\n this._setupListChangedHandlers(this._pendingListChangedConfig);\n this._pendingListChangedConfig = undefined;\n }\n }\n catch (error) {\n // Disconnect if initialization fails.\n void this.close();\n throw error;\n }\n }\n /**\n * After initialization has completed, this will be populated with the server's reported capabilities.\n */\n getServerCapabilities() {\n return this._serverCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the server's name and version.\n */\n getServerVersion() {\n return this._serverVersion;\n }\n /**\n * After initialization has completed, this may be populated with information about the server's instructions.\n */\n getInstructions() {\n return this._instructions;\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'logging/setLevel':\n if (!this._serverCapabilities?.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._serverCapabilities?.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n case 'resources/subscribe':\n case 'resources/unsubscribe':\n if (!this._serverCapabilities?.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n throw new Error(`Server does not support resource subscriptions (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._serverCapabilities?.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'completion/complete':\n if (!this._serverCapabilities?.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'initialize':\n // No specific capability required for initialize\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/roots/list_changed':\n if (!this._capabilities.roots?.listChanged) {\n throw new Error(`Client does not support roots list changed notifications (required for ${method})`);\n }\n break;\n case 'notifications/initialized':\n // No specific capability required for initialized\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!this._capabilities.sampling) {\n throw new Error(`Client does not support sampling capability (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._capabilities.elicitation) {\n throw new Error(`Client does not support elicitation capability (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._capabilities.roots) {\n throw new Error(`Client does not support roots capability (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Client does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertTaskCapability(method) {\n assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');\n }\n async ping(options) {\n return this.request({ method: 'ping' }, EmptyResultSchema, options);\n }\n async complete(params, options) {\n return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);\n }\n async setLoggingLevel(level, options) {\n return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);\n }\n async getPrompt(params, options) {\n return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);\n }\n async listPrompts(params, options) {\n return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);\n }\n async listResources(params, options) {\n return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);\n }\n async listResourceTemplates(params, options) {\n return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);\n }\n async readResource(params, options) {\n return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);\n }\n async subscribeResource(params, options) {\n return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);\n }\n async unsubscribeResource(params, options) {\n return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);\n }\n /**\n * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.\n *\n * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.\n */\n async callTool(params, resultSchema = CallToolResultSchema, options) {\n // Guard: required-task tools need experimental API\n if (this.isToolTaskRequired(params.name)) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool \"${params.name}\" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);\n }\n const result = await this.request({ method: 'tools/call', params }, resultSchema, options);\n // Check if the tool has an outputSchema\n const validator = this.getToolOutputValidator(params.name);\n if (validator) {\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n return result;\n }\n isToolTask(toolName) {\n if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {\n return false;\n }\n return this._cachedKnownTaskTools.has(toolName);\n }\n /**\n * Check if a tool requires task-based execution.\n * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.\n */\n isToolTaskRequired(toolName) {\n return this._cachedRequiredTaskTools.has(toolName);\n }\n /**\n * Cache validators for tool output schemas.\n * Called after listTools() to pre-compile validators for better performance.\n */\n cacheToolMetadata(tools) {\n this._cachedToolOutputValidators.clear();\n this._cachedKnownTaskTools.clear();\n this._cachedRequiredTaskTools.clear();\n for (const tool of tools) {\n // If the tool has an outputSchema, create and cache the validator\n if (tool.outputSchema) {\n const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);\n this._cachedToolOutputValidators.set(tool.name, toolValidator);\n }\n // If the tool supports task-based execution, cache that information\n const taskSupport = tool.execution?.taskSupport;\n if (taskSupport === 'required' || taskSupport === 'optional') {\n this._cachedKnownTaskTools.add(tool.name);\n }\n if (taskSupport === 'required') {\n this._cachedRequiredTaskTools.add(tool.name);\n }\n }\n }\n /**\n * Get cached validator for a tool\n */\n getToolOutputValidator(toolName) {\n return this._cachedToolOutputValidators.get(toolName);\n }\n async listTools(params, options) {\n const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);\n // Cache the tools and their output schemas for future validation\n this.cacheToolMetadata(result.tools);\n return result;\n }\n /**\n * Set up a single list changed handler.\n * @internal\n */\n _setupListChangedHandler(listType, notificationSchema, options, fetcher) {\n // Validate options using Zod schema (validates autoRefresh and debounceMs)\n const parseResult = ListChangedOptionsBaseSchema.safeParse(options);\n if (!parseResult.success) {\n throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n }\n // Validate callback\n if (typeof options.onChanged !== 'function') {\n throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);\n }\n const { autoRefresh, debounceMs } = parseResult.data;\n const { onChanged } = options;\n const refresh = async () => {\n if (!autoRefresh) {\n onChanged(null, null);\n return;\n }\n try {\n const items = await fetcher();\n onChanged(null, items);\n }\n catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n onChanged(error, null);\n }\n };\n const handler = () => {\n if (debounceMs) {\n // Clear any pending debounce timer for this list type\n const existingTimer = this._listChangedDebounceTimers.get(listType);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n // Set up debounced refresh\n const timer = setTimeout(refresh, debounceMs);\n this._listChangedDebounceTimers.set(listType, timer);\n }\n else {\n // No debounce, refresh immediately\n refresh();\n }\n };\n // Register notification handler\n this.setNotificationHandler(notificationSchema, handler);\n }\n async sendRootsListChanged() {\n return this.notification({ method: 'notifications/roots/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","import { createHash } from 'node:crypto'\n\nexport function canonicalJson(value) {\n return JSON.stringify(value, (_key, item) =>\n item && typeof item === 'object' && !Array.isArray(item)\n ? Object.fromEntries(\n Object.keys(item)\n .sort()\n .map((key) => [key, item[key]])\n )\n : item\n )\n}\n\nexport function digest(value) {\n return createHash('sha256').update(canonicalJson(value)).digest('hex')\n}\n\nconst SCHEMA_MAPS = new Set([\n 'properties',\n 'patternProperties',\n '$defs',\n 'definitions',\n 'dependentSchemas'\n])\nconst SCHEMA_LISTS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems'])\nconst SCHEMA_VALUES = new Set([\n 'items',\n 'additionalItems',\n 'additionalProperties',\n 'unevaluatedProperties',\n 'unevaluatedItems',\n 'contains',\n 'propertyNames',\n 'not',\n 'if',\n 'then',\n 'else',\n 'contentSchema'\n])\n\nfunction schemaContract(schema) {\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return schema\n return Object.fromEntries(\n Object.entries(schema)\n .filter(([key]) => !['description', 'title', '$comment'].includes(key))\n .map(([key, value]) => {\n if (SCHEMA_MAPS.has(key))\n value = Object.fromEntries(\n Object.entries(value).map(([name, child]) => [name, schemaContract(child)])\n )\n else if (SCHEMA_LISTS.has(key) || (key === 'items' && Array.isArray(value)))\n value = value.map(schemaContract)\n else if (SCHEMA_VALUES.has(key)) value = schemaContract(value)\n // Values under const, enum, default and extension keywords are data, not schemas.\n return [key, value]\n })\n )\n}\n\nfunction catalogContract(item) {\n const { description: _description, title: _title, inputSchema, outputSchema, ...wire } = item\n if (inputSchema !== undefined) wire.inputSchema = schemaContract(inputSchema)\n if (outputSchema !== undefined) wire.outputSchema = schemaContract(outputSchema)\n // Unknown fields and annotations stay wire-significant, even when only display-related.\n return wire\n}\n\nfunction ordered(items, key) {\n const names = items.map((item) => item[key])\n if (names.some((name) => typeof name !== 'string') || new Set(names).size !== names.length)\n throw new Error(`Catalog entries need unique ${key} values.`)\n return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0))\n}\n\n/** A conservative structural screen, never an activation or guidance-compatibility decision. */\nexport function runtimeContract(snapshot) {\n const { serverInfo, instructions, ...initialization } = snapshot.initialize\n const { version: _version, ...serverPresentation } = serverInfo\n const catalogs = Object.fromEntries(\n [\n ['tools', 'name'],\n ['resources', 'uri'],\n ['resourceTemplates', 'uriTemplate'],\n ['prompts', 'name']\n ].map(([name, key]) => [name, ordered(snapshot[name] ?? [], key)])\n )\n const wire = {\n initialize: initialization,\n ...Object.fromEntries(\n Object.entries(catalogs).map(([name, items]) => [name, items.map(catalogContract)])\n )\n }\n // Keep the full advertised snapshot for review; wire changes can also change this hash.\n const presentation = { serverInfo: serverPresentation, instructions, ...catalogs }\n return { wire, presentation, wireHash: digest(wire), presentationHash: digest(presentation) }\n}\n\nexport function compareContracts(before, after) {\n if (before.wireHash !== after.wireHash) return 'wire-changed'\n return before.presentationHash === after.presentationHash ? 'identical' : 'presentation-only'\n}\n\nexport function compareReleaseWindow(results) {\n return results.slice(0, -1).flatMap((before, start) =>\n results.slice(start + 1).map((after, offset) => {\n const intermediate = results.slice(start, start + offset + 2)\n const [fromMajor, fromMinor] = before.version.split('.').map(Number)\n const [toMajor, toMinor] = after.version.split('.').map(Number)\n return {\n from: before.version,\n to: after.version,\n adjacent: offset === 0,\n structural: compareContracts(before, after),\n wireUnchangedThroughout: intermediate.every((item) => item.wireHash === before.wireHash),\n breakingReleaseBoundary:\n fromMajor !== toMajor || (fromMajor === 0 && fromMinor !== toMinor),\n guidance: 'unreviewed',\n activation: 'not-established'\n }\n })\n )\n}\n\nexport function summarize(values) {\n if (!values.length || values.some((value) => !Number.isFinite(value)))\n throw new Error('Measurement samples must be nonempty and finite.')\n const sorted = [...values].sort((a, b) => a - b)\n const percentile = (p) => sorted[Math.ceil(sorted.length * p) - 1]\n return {\n samples: sorted.length,\n p50: percentile(0.5),\n p95: percentile(0.95),\n p99: percentile(0.99),\n max: sorted.at(-1)\n }\n}\n","import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'\nimport type {\n InitializeRequest,\n JSONRPCMessage,\n Notification,\n Request\n} from '@modelcontextprotocol/sdk/types.js'\n\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { STDIO_DEFAULT_MAX_BUFFER_SIZE } from '@modelcontextprotocol/sdk/shared/stdio.js'\nimport {\n ErrorCode,\n InitializeRequestSchema,\n ListToolsRequestSchema,\n ListToolsResultSchema,\n McpError,\n ResultSchema\n} from '@modelcontextprotocol/sdk/types.js'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport { runtimeContract } from '../scripts/runtime-contract.mjs'\nimport { ClientBindingUpdateSchema, type ClientBindingUpdate } from './client-binding'\nimport { isRuntimeUnavailable, unavailable } from './runtime-prototype/protocol'\n\nexport interface StableEdgeOptions {\n version: string\n requestTimeoutMs: number\n /** Retain only requests that the runtime has explicitly not dispatched. */\n runtimeWaitMs?: number\n open: (initialize: InitializeRequest, signal: AbortSignal) => Promise<Transport>\n register?: (client: Client) => Promise<void>\n onBinding?: (binding: ClientBindingUpdate) => void\n onError?: (error: Error) => void\n onBackendClose?: () => void\n onBackendReady?: () => Promise<void>\n validateContract?: (\n contract: RuntimeContract,\n version: string,\n previous?: RuntimeContract\n ) => void | Promise<void>\n}\ntype RuntimeContract = Awaited<ReturnType<typeof readRuntimeContract>>\n\nexport function contractHashes(contract: RuntimeContract) {\n return runtimeContract({\n initialize: {\n serverInfo: { ...contract.info, version: '0' },\n capabilities: contract.capabilities,\n instructions: contract.instructions\n },\n tools: [...contract.pages.values()].flatMap((page) => page.tools)\n })\n}\n\n/** Capture the observable contract before admitting a backend into a host session. */\nexport async function readRuntimeContract(client: Client, signal: AbortSignal, timeout: number) {\n const pages = new Map<string, Awaited<ReturnType<Client['listTools']>>>()\n let cursor: string | undefined\n let bytes = 0\n do {\n if (pages.has(cursor ?? '') || pages.size >= 64)\n throw new Error('Runtime returned a cyclic or oversized tool catalog.')\n const page = await client.request(\n { method: 'tools/list', ...(cursor === undefined ? {} : { params: { cursor } }) },\n ListToolsResultSchema,\n { signal, timeout }\n )\n bytes += Buffer.byteLength(JSON.stringify(page))\n if (bytes > STDIO_DEFAULT_MAX_BUFFER_SIZE)\n throw new Error('Runtime tool catalog exceeded the MCP buffer limit.')\n pages.set(cursor ?? '', page)\n cursor = page.nextCursor\n } while (cursor !== undefined)\n const { version: _version, ...info } = client.getServerVersion()!\n return {\n pages,\n info,\n capabilities: client.getServerCapabilities(),\n instructions: client.getInstructions()\n }\n}\n\n/** Own the host's MCP session without carrying any tool implementation or schema. */\nexport async function startStableEdge(host: Transport, options: StableEdgeOptions) {\n const lifetime = new AbortController()\n let backend: Client | undefined\n let initializedRequest: InitializeRequest | undefined\n let contract: Awaited<ReturnType<typeof readRuntimeContract>> | undefined\n let replacement: Promise<void> | undefined\n let server: Server | undefined\n let opening = false\n let openingId: string | number | undefined\n let failure: Error | undefined\n let bufferedBytes = 0\n const buffered: JSONRPCMessage[] = []\n let waitingRequests = 0\n let waitingBytes = 0\n let paused = false\n const forwarded = new Set<Promise<unknown>>()\n let resolveClosed: (error?: Error) => void\n const closed = new Promise<Error | undefined>((resolve) => (resolveClosed = resolve))\n\n async function close() {\n if (lifetime.signal.aborted) return\n lifetime.abort()\n buffered.length = 0\n await Promise.allSettled([backend?.close(), server?.close(), host.close()])\n resolveClosed(failure)\n }\n\n async function pause(signal: AbortSignal) {\n signal = AbortSignal.any([signal, lifetime.signal])\n signal.throwIfAborted()\n paused = true\n // Only attempts already sent to the backend participate. Locally queued\n // calls must remain queued until this barrier is released.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason)\n signal.addEventListener('abort', abort, { once: true })\n void Promise.allSettled([...forwarded]).then(() => {\n signal.removeEventListener('abort', abort)\n resolve()\n })\n if (signal.aborted) abort()\n })\n }\n\n function resume() {\n paused = false\n }\n\n function forward(\n target: Client | Server,\n request: Request,\n extra: RequestHandlerExtra<Request, Notification>,\n timeout = options.requestTimeoutMs\n ) {\n const progressToken = request.params?._meta?.progressToken\n return target.request(request, ResultSchema, {\n signal: extra.signal,\n timeout,\n ...(progressToken !== undefined\n ? {\n onprogress: (progress) => {\n void extra\n .sendNotification({\n method: 'notifications/progress',\n params: { ...progress, progressToken }\n })\n .catch(options.onError ?? (() => {}))\n }\n }\n : {})\n })\n }\n\n async function forwardToRuntime(\n request: Request,\n extra: RequestHandlerExtra<Request, Notification>\n ) {\n const started = performance.now()\n const deadline = started + options.requestTimeoutMs\n const waitUntil = Math.min(deadline, started + (options.runtimeWaitMs ?? 0))\n const signal = AbortSignal.any([extra.signal, lifetime.signal])\n let retainedBytes = 0\n let rejection: unknown = unavailable()\n try {\n for (;;) {\n signal.throwIfAborted()\n if (performance.now() >= deadline || (retainedBytes && performance.now() >= waitUntil))\n throw rejection\n const target = backend\n if (target && !paused) {\n try {\n const attempt = forward(\n target,\n request,\n extra,\n Math.max(1, deadline - performance.now())\n )\n forwarded.add(attempt)\n try {\n return await attempt\n } finally {\n forwarded.delete(attempt)\n }\n } catch (error) {\n // A dropped connection or any uncertain result may follow a write.\n // Only the transport's explicit pre-dispatch rejection permits retry.\n if (!isRuntimeUnavailable(error)) throw error\n rejection = error\n }\n }\n const remaining = waitUntil - performance.now()\n if (remaining <= 0) throw rejection\n if (!retainedBytes) {\n const bytes = Buffer.byteLength(JSON.stringify(request))\n if (waitingRequests >= 64 || waitingBytes + bytes > STDIO_DEFAULT_MAX_BUFFER_SIZE)\n throw unavailable('Runtime wait buffer is full; this call was not dispatched.')\n waitingRequests++\n waitingBytes += bytes\n retainedBytes = bytes\n }\n await delay(Math.min(50, remaining), undefined, { signal })\n }\n } finally {\n if (retainedBytes) {\n waitingRequests--\n waitingBytes -= retainedBytes\n }\n }\n }\n\n async function openBackend(request: InitializeRequest) {\n const client = new Client(request.params.clientInfo, {\n capabilities: request.params.capabilities\n })\n client.onerror = options.onError\n client.onclose = () => {\n if (backend !== client) return\n backend = undefined\n if (!lifetime.signal.aborted) options.onBackendClose?.()\n }\n client.fallbackRequestHandler = (request, extra) => {\n if (!server) throw new McpError(ErrorCode.InvalidRequest, 'Host is not initialized.')\n return forward(server, request, extra)\n }\n client.fallbackNotificationHandler = async (notification) => {\n if (notification.method === ClientBindingUpdateSchema.shape.method.value)\n options.onBinding?.(ClientBindingUpdateSchema.parse(notification).params)\n else if (notification.method !== 'notifications/tools/list_changed')\n await server?.notification(notification)\n }\n try {\n const transport = await options.open(request, lifetime.signal)\n if (lifetime.signal.aborted) {\n await transport.close()\n lifetime.signal.throwIfAborted()\n }\n await client.connect(transport, {\n signal: lifetime.signal,\n timeout: options.requestTimeoutMs\n })\n await options.register?.(client)\n const observed = await readRuntimeContract(client, lifetime.signal, options.requestTimeoutMs)\n await options.validateContract?.(observed, client.getServerVersion()!.version, contract)\n lifetime.signal.throwIfAborted()\n if (!client.transport) throw unavailable()\n return { client, observed }\n } catch (error) {\n await client.close()\n throw error\n }\n }\n\n async function replaceBackend(): Promise<void> {\n if (!initializedRequest || !server || !contract || lifetime.signal.aborted) throw unavailable()\n if (replacement) return replacement\n const replace = async () => {\n const previous = backend\n backend = undefined\n await previous?.close()\n const { client, observed } = await openBackend(initializedRequest!)\n if (!options.validateContract && !isDeepStrictEqual(contract, observed)) {\n await client.close()\n throw new McpError(\n -32002,\n 'MCP_RUNTIME_RESTART_REQUIRED: replacement runtime changed this session’s frozen contract.'\n )\n }\n backend = client\n await options.onBackendReady?.()\n }\n replacement = replace()\n try {\n await replacement\n } finally {\n replacement = undefined\n }\n }\n\n async function initialize(message: JSONRPCMessage) {\n if (!('method' in message) || message.method !== 'initialize' || !('id' in message)) {\n if ('id' in message)\n await host.send({\n jsonrpc: '2.0',\n id: message.id,\n error: { code: ErrorCode.InvalidRequest, message: 'Initialize the MCP session first.' }\n })\n return\n }\n opening = true\n openingId = message.id\n try {\n const request = InitializeRequestSchema.parse(message)\n const { client, observed } = await openBackend(request)\n backend = client\n initializedRequest = request\n contract = observed\n await options.onBackendReady?.()\n const runtimeInfo = backend.getServerVersion()!\n server = new Server(\n { ...runtimeInfo, version: options.version },\n {\n capabilities: contract.capabilities,\n instructions: contract.instructions\n }\n )\n server.onerror = options.onError\n server.setRequestHandler(ListToolsRequestSchema, ({ params }) => {\n const page = contract!.pages.get(params?.cursor ?? '')\n if (!page) throw new McpError(ErrorCode.InvalidParams, 'Unknown tool catalog cursor.')\n return structuredClone(page)\n })\n server.fallbackRequestHandler = forwardToRuntime\n server.fallbackNotificationHandler = async (notification) => {\n if (!backend) throw unavailable()\n await backend.notification(notification)\n }\n // The host transport already started while the runtime was being opened.\n const session: Transport = {\n start: async () => {},\n send: (value, sendOptions) => host.send(value, sendOptions),\n close: async () => {\n session.onclose?.()\n }\n }\n await server.connect(session)\n host.onmessage = (value, extra) => session.onmessage?.(value, extra)\n host.onmessage(message)\n for (const value of buffered.splice(0)) host.onmessage(value)\n bufferedBytes = 0\n } catch (error) {\n if (!lifetime.signal.aborted) {\n failure = error instanceof Error ? error : new Error(String(error))\n options.onError?.(failure)\n await host.send({\n jsonrpc: '2.0',\n id: message.id,\n error: {\n code: error instanceof McpError ? error.code : ErrorCode.InternalError,\n message: error instanceof Error ? error.message : String(error),\n ...(error instanceof McpError && error.data !== undefined ? { data: error.data } : {})\n }\n })\n }\n await close()\n }\n }\n\n host.onerror = options.onError\n host.onclose = () => void close()\n host.onmessage = (message) => {\n if (lifetime.signal.aborted) return\n if (\n opening &&\n 'method' in message &&\n message.method === 'notifications/cancelled' &&\n message.params?.requestId === openingId\n ) {\n void close()\n return\n }\n if (!opening) {\n void initialize(message).catch((error: Error) => {\n failure = error\n options.onError?.(error)\n void close()\n })\n return\n }\n bufferedBytes += Buffer.byteLength(JSON.stringify(message))\n if (buffered.length >= 64 || bufferedBytes > STDIO_DEFAULT_MAX_BUFFER_SIZE) {\n failure = new Error('Host initialization buffer exceeded the MCP buffer limit.')\n options.onError?.(failure)\n void close()\n } else buffered.push(message)\n }\n await host.start()\n return { close, closed, replaceBackend, pause, resume }\n}\n"],"ignoreList":[0,1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,0BAAb,M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IAAI,CAAC,SAAS;GACP,WAAW,OAAO,CAAC,CAAC,OAAO,UAAiB;IAC/C,UAAU;IACV,QAAQ,UAAU,KAAK;IAClB,MAAM;GACb,CAAC;GACD;EACF;EACA,iBAAiB,OAAO,WAAW,KAAK,UAAU,OAAO,CAAC;EAC1D,IAAI,SAAS,UAAU,MAAM,gBAAA,UAA+C;GAC1E,0BAAU,IAAI,MAAM,2DAA2D;GAC/E,QAAQ,UAAU,OAAO;GACpB,MAAM;EACb,OAAO,SAAS,KAAK,OAAO;CAC9B;CACA,MAAM,KAAK,MAAM;CACjB,OAAO;EAAE;EAAO;EAAQ;EAAgB;EAAO;CAAO;AACxD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"startup-log-CYlFgdy5.mjs","names":[],"sources":["../src/startup-log.ts"],"sourcesContent":["import { closeSync, openSync, writeFileSync, writeSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { LOG_DIR, PACKAGE_VERSION } from './shared'\n\nlet started = 0\nlet role = ''\nlet active = false\nlet descriptor: number | undefined\nlet bytes = 0\n\n/** Keep startup evidence available even if the host kills a logging worker. */\nfunction startupEvent(phase: string, event: string, durationMs?: number, error?: unknown): void {\n if (!active) return\n const line =\n JSON.stringify({\n time: new Date().toISOString(),\n pid: process.pid,\n role,\n version: PACKAGE_VERSION,\n node: process.version,\n elapsedMs: Math.round(performance.now() - started),\n phase,\n event,\n ...(error === undefined ? {} : { error: String(error).slice(0, 1000) }),\n ...(durationMs === undefined ? {} : { durationMs: Math.round(durationMs) })\n }) + '\\n'\n try {\n const size = Buffer.byteLength(line)\n if (bytes + size > 1024 * 1024) return\n descriptor ??= openSync(\n join(\n LOG_DIR,\n `startup-mcp-${new Date().toISOString().replaceAll(':', '-').replaceAll('.', '-')}-${process.pid}.log`\n ),\n 'wx',\n 0o600\n )\n writeFileSync(descriptor, line)\n bytes += size\n } catch {\n // Diagnostics must not prevent the runtime from starting.\n }\n if (\n role === 'cli' &&\n !process.stdin.isTTY &&\n process.argv.slice(2).every((arg) => arg.startsWith('--runtime-updates=')) &&\n (event === 'ready' || event === 'failed')\n ) {\n try {\n writeSync(2, `TemPad startup ${line}`)\n } catch {\n /* Host may have disconnected. */\n }\n }\n}\n\nexport function startStartup(processRole: string): void {\n role = processRole\n started = performance.now()\n active = true\n startupEvent(role, 'start')\n}\n\nexport function finishStartup(event: 'ready' | 'failed', error?: unknown): void {\n if (!active) return\n startupEvent(role, event, performance.now() - started, error)\n active = false\n try {\n if (descriptor !== undefined) closeSync(descriptor)\n } catch {\n /* Logging must not block readiness or error handling. */\n }\n descriptor = undefined\n}\n\nexport function startupPhase<T>(phase: string, action: () => T): T {\n if (!active) return action()\n const start = performance.now()\n startupEvent(phase, 'start')\n const complete = <V>(value: V): V => {\n startupEvent(phase, 'complete', performance.now() - start)\n return value\n }\n const failed = (error: unknown): never => {\n startupEvent(phase, 'failed', performance.now() - start, error)\n throw error\n }\n try {\n const result = action()\n if (result instanceof Promise) return result.then(complete, failed) as T\n return complete(result)\n } catch (error) {\n return failed(error)\n }\n}\n"],"mappings":";;;;;;;;;;AAKA,IAAI,UAAU;AACd,IAAI,OAAO;AACX,IAAI,SAAS;AACb,IAAI;AACJ,IAAI,QAAQ;;AAGZ,SAAS,aAAa,OAAe,OAAe,YAAqB,OAAuB;CAC9F,IAAI,CAAC,QAAQ;CACb,MAAM,OACJ,KAAK,UAAU;EACb,uBAAM,IAAI,KAAK,EAAA,CAAE,YAAY;EAC7B,KAAK,QAAQ;EACb;EACA,SAAS;EACT,MAAM,QAAQ;EACd,WAAW,KAAK,MAAM,YAAY,IAAI,IAAI,OAAO;EACjD;EACA;EACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,GAAI,EAAE;EACrE,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,KAAK,MAAM,UAAU,EAAE;CAC3E,CAAC,IAAI;CACP,IAAI;EACF,MAAM,O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,SAAS,MAAM;CACxB,SAAS,OAAO;EACd,OAAO,OAAO,KAAK;CACrB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"state-6qFcvi-I.mjs","names":["z\n .object","z.string","z\n .object","z.literal","z.uuid","z.number","z.enum","z.object","z.array"],"sources":["../src/runtime-prototype/state.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { isAbsolute, join } from 'node:path'\nimport { z } from 'zod'\n\nimport { writeDurableJson } from '../durable-json'\nimport { assertPrivatePath, assertPrivatePathAsync } from '../runtime-platform'\n\nexport const ArtifactSchema = z\n .object({\n entry: z.string().refine(isAbsolute),\n bundle: z.string().regex(/^[a-f0-9]{64}$/),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n release: z\n .object({\n directory: z.string().refine(isAbsolute),\n manifestHash: z.string().regex(/^[a-f0-9]{64}$/),\n integrity: z.string().optional()\n })\n .strict()\n .optional()\n })\n .strict()\nexport type Artifact = z.infer<typeof ArtifactSchema>\nexport const ConfigSchema = z\n .object({\n version: z.literal(1),\n entry: z.string().refine(isAbsolute),\n bundle: z.string().regex(/^[a-f0-9]{64}$/),\n secret: z.uuid(),\n directories: z\n .object({\n runtime: z.string().refine(isAbsolute),\n state: z.string().refine(isAbsolute),\n assets: z.string().refine(isAbsolute),\n log: z.string().refine(isAbsolute)\n })\n .strict()\n .optional(),\n release: ArtifactSchema.shape.release\n })\n .strict()\nexport type PrototypeConfig = z.infer<typeof ConfigSchema> & { root: string }\nexport const EndpointsSchema = z\n .object({\n wsPort: z.number().int().min(1).max(65535),\n httpPort: z.number().int().min(1).max(65535),\n accessToken: z.string().min(32),\n legacyAccessToken: z.string().min(32)\n })\n .strict()\nexport type Endpoints = z.infer<typeof EndpointsSchema>\nexport const JournalSchema = z\n .object({\n version: z.literal(1),\n revision: z.number().int().nonnegative(),\n phase: z.enum(['committed', 'preparing', 'old-stopped', 'candidate-ready']),\n coldStart: z.literal(true).optional(),\n active: ArtifactSchema,\n candidate: ArtifactSchema.optional(),\n previous: ArtifactSchema.optional(),\n oldHub: z.object({ id: z.uuid(), pid: z.number().int().positive() }).optional(),\n failedBundles: z.array(z.string()),\n failure: z.string().optional()\n })\n .strict()\nexport type Journal = z.infer<typeof JournalSchema>\n\nexport function readPrivateJson<T extends z.ZodType>(\n path: string,\n schema: T\n): z.output<T> | undefined {\n for (let attempt = 0; ; attempt++) {\n try {\n assertPrivatePath(path, 'file')\n return schema.parse(JSON.parse(readFileSync(path, 'utf8')))\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return\n // A writer can atomically replace a snapshot during Windows ACL inspection.\n // Retry once from a fresh trust check, never accept the unchecked replacement.\n if (attempt === 0 && code === 'ERUNTIMEPATHCHANGED') continue\n throw error\n }\n }\n}\n\nexport function readEndpoints(root: string) {\n return readPrivateJson(join(root, 'endpoints.json'), EndpointsSchema)\n}\n\nexport async function readPrivateJsonAsync<T extends z.ZodType>(\n path: string,\n schema: T\n): Promise<z.output<T> | undefined> {\n for (let attempt = 0; ; attempt++) {\n try {\n await assertPrivatePathAsync(path, 'file')\n return schema.parse(JSON.parse(readFileSync(path, 'utf8')))\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return\n if (attempt === 0 && code === 'ERUNTIMEPATHCHANGED') continue\n throw error\n }\n }\n}\n\nexport function readJournalAsync(root: string) {\n return readPrivateJsonAsync(join(root, 'switch.json'), JournalSchema)\n}\nexport function writeEndpoints(root: string, endpoints: Endpoints) {\n writeDurableJson(join(root, 'endpoints.json'), EndpointsSchema.parse(endpoints))\n}\nexport function readJournal(root: string) {\n return readPrivateJson(join(root, 'switch.json'), JournalSchema)\n}\nexport function writeJournal(root: string, journal: Journal) {\n writeDurableJson(join(root, 'switch.json'), JournalSchema.parse(journal))\n}\n\nexport function newerVersion(candidate: string, active: string) {\n const next = candidate.split('.').map(Number)\n const prior = active.split('.').map(Number)\n for (let index = 0; index < 3; index++) {\n if (next[index] !==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ACA,SAAgB,eAAe,MAAc,WAAsB;CACjE,iBAAiB,KAAK,MAAM,gBAAgB,GAAG,gBAAgB,MAAM,SAAS,CAAC;AACjF;AACA,SAAgB,YAAY,MAAc;CACxC,OAAO,gBAAgB,KAAK,MAAM,aAAa,GAAG,aAAa;AACjE;AACA,SAAgB,aAAa,MAAc,SAAkB;CAC3D,iBAAiB,KAAK,MAAM,aAAa,GAAG,cAAc,MAAM,OAAO,CAAC;AAC1E;AAEA,SAAgB,aAAa,WAAmB,QAAgB;CAC9D,MAAM,OAAO,UAAU,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC5C,MAAM,QAAQ,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC1C,KAAK,IAAI,QAAQ,GAAG,QAAQ,GAAG,SAC7B,IAAI,KAAK,WAAW,MAAM,QAAQ,OAAO,KAAK,SAAU,MAAM;CAEhE,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"supervisor-CesT-H5_.mjs","names":["z\n .object","z.literal","z.number","z.string","z.ZodError","z.array","z.object","z.uuid","z.number","z.literal","z.record","z.string","z.unknown","z.boolean","z.number","z.array","z.string","z.literal","z.uuid","lockfile","delay","z.object"],"sources":["../src/runtime-update/manager.ts","../src/runtime-prototype/hooks.ts","../src/runtime-prototype/status.ts","../src/runtime-prototype/supervisor.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport { z } from 'zod'\n\nimport { writeDurableJson } from '../durable-json'\nimport { hubEnvironment } from '../process-environment'\nimport { assertPrivatePath } from '../runtime-platform'\nimport { ArtifactSchema, readPrivateJson, type Artifact } from '../runtime-prototype/state'\nimport {\n AcquisitionResultSchema,\n SelectionSchema,\n type AcquisitionContext,\n type AcquisitionResult,\n type SelectionCursor\n} from './acquire'\nimport { VersionSchema } from './manifest'\n\nconst StateSchema = z\n .object({\n version: z.literal(2),\n nextCheck: z.number(),\n failures: z.number().int().nonnegative(),\n lastAttempt: z.number().optional(),\n candidate: ArtifactSchema.optional(),\n manualCandidate: ArtifactSchema.optional(),\n cacheWarning: z.string().max(2000).optional(),\n selection: SelectionSchema.optional(),\n error: z.string().optional()\n })\n .strict()\nconst INTERVAL = 6 * 60 * 60 * 1000\n\n/** Acquisition owns downloads; only the supervisor can activate a committed candidate. */\nexport class ReleaseUpdates {\n private state: z.infer<typeof StateSchema>\n private timer?: ReturnType<typeof setTimeout>\n private pending?: { selector: string; result: Promise<Artifact | undefined> }\n private abort?: AbortController\n private closed = false\n private explicit = false\n private disabled = false\n\n constructor(\n private readonly options: {\n root: string\n enrolled: () => boolean\n acquire: (\n selector: string,\n signal: AbortSignal,\n cursor?: SelectionCursor\n ) => Promise<AcquisitionResult>\n now?: () => number\n jitter?: () => number\n }\n ) {\n if (process.env.TEMPAD_MCP_DEV_CHECKOUT)\n throw new Error('Checkout runtimes cannot acquire releases.')\n this.state = { version: 2, nextCheck: 0, failures: 0 }\n try {\n this.state = readPrivateJson(join(options.root, 'updates.json'), StateSchema) ?? this.state\n } catch (error) {\n try {\n // Only this derived download/check state is reconstructible. Preserve\n // its bytes before replacing it; trust and I/O failures remain fatal.\n if (!(error instanceof SyntaxError || error instanceof z.ZodError)) throw error\n const path = join(options.root, 'updates.json')\n assertPrivatePath(path, 'file')\n const backup = join(options.root, `updates.invalid-${randomUUID()}.json`)\n writeFileSync(backup, readFileSync(path), { flag: 'wx', mode: 0o600, flush: true })\n this.save({\n version: 2,\n nextCheck: this.now() + 5 * 60 * 1000,\n failures: 1,\n error: `Update metadata was rebuilt; diagnostic copy: ${backup}. ${String(error)}`.slice(\n 0,\n 2000\n )\n })\n } catch (failure) {\n this.disabled = true\n this.state.error =\n `Update metadata is unreadable; checks are disabled: ${String(failure)}`.slice(0, 2000)\n }\n }\n }\n\n get status() {\n return { ...this.state, checking: !!this.pending, disabled: this.disabled }\n }\n private now() {\n return this.options.now?.() ?? Date.now()\n }\n private save(next: z.infer<typeof StateSchema>) {\n try {\n writeDurableJson(join(this.options.root, 'updates.json'), StateSchema.parse(next))\n } catch (error) {\n this.disabled = true\n clearTimeout(this.timer)\n this.state.error = (\n `Update metadata could not be saved; checks are disabled until MCP restarts: ${String(error)}` +\n (next.error ? ` (check error: ${next.error})` : '')\n ).slice(0, 2000)\n throw new Error(this.state.error, { cause: error })\n }\n // A downloaded candidate is visible to activation only after its metadata\n // commits. A failed fsync must not publish it or restore an older disk file.\n this.state = next\n }\n\n schedule() {\n clearTimeout(this.timer)\n if (this.closed || this.disabled) return\n if (!this.options.enrolled()) {\n if (!this.explicit) this.abort?.abort()\n return\n }\n if (this.pending) return\n this.timer = setTimeout(\n () => void this.check().catch(() => {}),\n Math.min(0x7fffffff, Math.max(0, this.state.nextCheck - this.now()))\n )\n this.timer.unref()\n }\n\n async check(selector = 'latest', explicit = false): Promise<Artifact | undefined> {\n if (this.disabled) throw new Error(this.state.error)\n if (selector !== 'latest') VersionSchema.parse(selector)\n if (this.closed || (!explicit && !this.options.enrolled())) return\n if (this.pending) {\n if (selector !== this.pending.selector)\n throw new Error('Another release selector is being checked; retry after it finishes.')\n return this.pending.result\n }\n clearTimeout(this.timer)\n // Persist the attempt before the worker starts. Crash/reconnect storms cannot\n // create an unbounded series of startup checks.\n const now = this.now()\n const stable = selector === 'latest'\n this.save({\n ...this.state,\n lastAttempt: now,\n ...(stable ? { nextCheck: now + 5 * 60 * 1000 } : {})\n })\n this.abort = new AbortController()\n this.explicit = explicit\n const signal = this.abort.signal\n const result = Promise.resolve()\n .then(() =>\n this.options.acquire(\n selector,\n signal,\n selector === 'latest' ? this.state.selection?.cursor : undefined\n )\n )\n .then((value) => {\n if (this.closed) return\n const { candidate, selection, cacheWarning } = AcquisitionResultSchema.parse(value)\n this.save({\n ...this.state,\n // A successful scan also revokes old staging when the stable tag rewinds.\n ...(stable\n ? {\n candidate,\n selection,\n failures: 0,\n nextCheck:\n this.now() +\n (selection?.cursor\n ? 30_000\n : INTERVAL +\n Math.floor(((this.options.jitter?.() ?? Math.random()) * INTERVAL) / 10))\n }\n : { manualCandidate: candidate }),\n cacheWarning,\n error: undefined\n })\n return candidate\n })\n .catch((error: unknown) => {\n if (!this.closed && !this.disabled) {\n const failures = Math.min(this.state.failures + 1, 10)\n this.save({\n ...this.state,\n ...(stable\n ? {\n failures,\n nextCheck: this.now() + Math.min(INTERVAL, 5 * 60 * 1000 * 2 ** (failures - 1))\n }\n : {}),\n error: String(error).slice(0, 2000)\n })\n }\n throw error\n })\n .finally(() => {\n this.pending = undefined\n this.abort = undefined\n this.explicit = false\n this.schedule()\n })\n this.pending = { selector, result }\n return result\n }\n\n close() {\n this.closed = true\n clearTimeout(this.timer)\n this.abort?.abort()\n }\n}\n\nexport async function acquireRelease(\n entry: string,\n cache: string,\n selector: string,\n context: AcquisitionContext,\n signal: AbortSignal,\n cursor?: SelectionCursor\n) {\n if (process.env.TEMPAD_MCP_DEV_CHECKOUT)\n throw new Error('Checkout runtimes cannot acquire releases.')\n const { stdout } = await promisify(execFile)(\n process.execPath,\n [\n entry,\n '--cache',\n cache,\n '--version',\n selector,\n '--context',\n JSON.stringify(context),\n ...(cursor ? ['--cursor', JSON.stringify(cursor)] : [])\n ],\n {\n env: hubEnvironment(process.env),\n windowsHide: true,\n signal,\n timeout: 240_000,\n maxBuffer: 1024 * 1024\n }\n )\n const result: unknown = JSON.parse(stdout)\n return AcquisitionResultSchema.parse(result)\n}\n","import {\n deserializeMessage,\n STDIO_DEFAULT_MAX_BUFFER_SIZE\n} from '@modelcontextprotocol/sdk/shared/stdio.js'\nimport { createServer } from 'node:net'\nimport { join } from 'node:path'\nimport { z } from 'zod'\n\nimport { ClientHookRequestSchema, type ClientHook } from '../agent-clients/hooks'\nimport { writeDurableJson } from '../durable-json'\nimport {\n ExpiredHookError,\n HOOK_RECEIPT_LIMIT,\n LEGACY_HOOK_EXHAUSTED_RESULT,\n LegacyHookCapacityError,\n hookCutoff,\n hookPressureCutoff,\n hookRetentionCutoff,\n hookSignature,\n isExpiredHookResult\n} from '../hook-receipts'\nimport { cleanupEndpoint, runtimeEndpoint } from '../runtime-platform'\nimport { listenPrivate } from './processes'\nimport { readPrivateJsonAsync } from './state'\n\nconst InboxSchema = z.array(\n z.object({\n input: ClientHookRequestSchema.shape.params,\n admittedHubId: z.uuid().optional(),\n recordedAt: z.number().optional(),\n retired: z.literal('expired').optional(),\n result: z.record(z.string(), z.unknown()).optional()\n })\n)\nconst ReceiverSchema = z.object({ hubId: z.uuid(), freshAfter: z.number().optional() })\nclass FutureHookError extends Error {}\n\n/** Keep the installed hook path alive while the data-plane Hub is stopped. */\nexport async function startHookGateway(\n root: string,\n deliver: (input: ClientHook, admittedHubId?: string) => Promise<Record<string, unknown>>,\n onFault: (error?: unknown) => void = () => {},\n socketPath = runtimeEndpoint(join(root, 'run'), 'mcp.sock'),\n retireLegacy: () => Promise<void> = async () => {\n throw new Error('Legacy lifecycle retirement requires a connected Hub.')\n },\n signal?: AbortSignal\n) {\n const path = join(root, 'hooks.json')\n const stored = await readPrivateJsonAsync(\n path,\n z.object({\n version: z.literal(2),\n cutoff: z.number(),\n entries: InboxSchema,\n receiver: ReceiverSchema.optional()\n })\n )\n signal?.throwIfAborted()\n let entries = stored?.entries ?? []\n let cutoff = stored?.cutoff ?? 0\n let receiver = stored?.receiver\n let flushing: Promise<void> | undefined\n let legacyRetiredFor: string | undefined\n let closed = false\n const sockets = new Set<import('node:net').Socket>()\n const pendingEntry = (entry: (typeof entries)[number]) => !entry.result && !entry.retired\n const capacityFailure = () =>\n entries.filter(pendingEntry).length >= HOOK_RECEIPT_LIMIT\n ? new Error('Hook inbox capacity reached.')\n : undefined\n const pending = () => entries.some(pendingEntry)\n const legacyExhausted = () =>\n entries.some((entry) => entry.result?.runtimeHookLegacyUpgradeRequired === true) ||\n entries.filter((entry) => entry.input.version === 1).length >= HOOK_RECEIPT_LIMIT\n const evidenceHub = (input: ClientHook) =>\n receiver &&\n (input.version !== 2 ||\n receiver.freshAfter === undefined ||\n input.issuedAt > receiver.freshAfter)\n ? receiver.hubId\n : undefined\n function save(next: typeof entries, nextReceiver = receiver, nextCutoff = cutoff) {\n if (closed) throw new Error('The hook inbox owner has closed.')\n try {\n writeDurableJson(path, {\n version: 2,\n cutoff: nextCutoff,\n entries: next,\n receiver: nextReceiver\n })\n entries = next\n receiver = nextReceiver\n cutoff = nextCutoff\n } catch (error) {\n onFault(error)\n throw error\n }\n }\n function compact(reserveResult = false) {\n let nextCutoff = hookRetentionCutoff(cutoff)\n const legacyCutoff = hookRetentionCutoff(0)\n if (reserveResult) {\n const completed: number[] = []\n const unresolved: number[] = []\n for (const entry of entries)\n if (entry.input.version === 2)\n (pendingEntry(entry) ? unresolved : completed).push(entry.input.issuedAt)\n nextCutoff = hookPressureCutoff(nextCutoff, completed, unresolved)\n }\n const next = entries.filter(\n (entry) =>\n pendingEntry(entry) || entry.input.version !== 2 || entry.input.issuedAt > nextCutoff\n )\n const compacted = next.map((entry) => {\n if (\n entry.input.version === 1 &&\n entry.result &&\n !entry.retired &&\n (entry.recordedAt === undefined || entry.recordedAt <= legacyCutoff)\n ) {\n // Legacy senders have no timestamp. Keep their identity as an old-reader-safe\n // tombstone: forgetting it would let a retry become fresh lifecycle evidence.\n return {\n input: entry.input,\n retired: 'expired' as const,\n ...(entry.result.runtimeHookLegacyUpgradeRequired\n ? { result: LEGACY_HOOK_EXHAUSTED_RESULT }\n : {})\n }\n }\n return entry\n })\n if (\n nextCutoff !== cutoff ||\n compacted.length !== entries.length ||\n compacted.some((entry, index) => entry !== entries[index])\n )\n save(compacted, receiver, nextCutoff)\n }\n async function flush() {\n if (flushing) return flushing\n const run = async () => {\n compact()\n while (true) {\n const entry = entries.find(pendingEntry)\n if (!entry) {\n // A later Stop (including one admitted during this drain) must commit\n // before an earlier delivery fault can reopen the data plane.\n const receiverId = receiver?.hubId ?? ''\n if (legacyExhausted() && legacyRetiredFor !== receiverId) {\n try {\n await retireLegacy()\n legacyRetiredFor = receiverId\n } catch (error) {\n onFault(error)\n throw error\n }\n }\n if (pending() || receiverId !== (receiver?.hubId ?? '')) continue\n onFault(undefined)\n return\n }\n const result = await deliver(\n entry.input,\n entry.admittedHubId === evidenceHub(entry.input) ? entry.admittedHubId : undefined\n ).catch((error: unknown) => {\n onFault(error)\n throw error\n })\n const retired = isExpiredHookResult(result)\n const outcome = retired ? { retired: 'expired' as const, result } : { result }\n save(\n entries.map((value) =>\n value === entry ? { ...value, ...outcome, recordedAt: Date.now() } : value\n ),\n receiver,\n retired && entry.input.version === 2 ? Math.max(cutoff, entry.input.issuedAt) : cutoff\n )\n }\n }\n flushing = run()\n try {\n await flushing\n } finally {\n flushing = undefined\n }\n }\n const server = createServer((socket) => {\n if (sockets.size >= 128) {\n socket.destroy()\n return\n }\n sockets.add(socket)\n socket.setEncoding('utf8')\n let buffer = ''\n let notifications = 0\n const timeout = setTimeout(() => socket.destroy(), 5000)\n socket.on('error', () => socket.destroy())\n socket.on('close', () => {\n clearTimeout(timeout)\n sockets.delete(socket)\n })\n socket.on('data', (chunk) => {\n buffer += chunk\n if (Buffer.byteLength(buffer) > STDIO_DEFAULT_MAX_BUFFER_SIZE) {\n socket.destroy()\n return\n }\n let newline\n while ((newline = buffer.indexOf('\\n')) >= 0) {\n let message\n try {\n message = deserializeMessage(buffer.slice(0, newline))\n } catch {\n socket.destroy()\n return\n }\n buffer = buffer.slice(newline + 1)\n // Old CLIs send identity notifications before initialize. Consume that\n // bounded prefix so the host receives an actionable initialize error.\n if (!('id' in message)) {\n if (++notifications > 16) {\n socket.destroy()\n return\n }\n continue\n }\n socket.removeAllListeners('data')\n void (async () => {\n const parsed = ClientHookRequestSchema.safeParse(message)\n if (!parsed.success) {\n socket.end(\n JSON.stringify({\n jsonrpc: '2.0',\n id: message.id,\n error: {\n code: -32002,\n message: 'MCP_RUNTIME_RESTART_REQUIRED: connect through the stable MCP edge.'\n }\n }) + '\\n'\n )\n return\n }\n const input = parsed.data.params\n if (input.version === 2 && input.profile.kind !== 'release')\n throw new Error('Lifecycle hook belongs to a different runtime profile.')\n const admittedAt = Date.now()\n const known = entries.some((entry) => entry.input.invocationId === input.invocationId)\n compact()\n hookCutoff(input, cutoff, admittedAt)\n if (input.version === 2 && !known) {\n // A retryable clock skew must not evict completed results before admission.\n if (input.issuedAt > admittedAt)\n throw new FutureHookError(\n 'Lifecycle invocation is ahead of the runtime clock; retry the same invocation.'\n )\n compact(true)\n hookCutoff(input, cutoff, admittedAt)\n }\n const existing = entries.find((entry) => entry.input.invocationId === input.invocationId)\n if (existing && hookSignature(existing.input) !== hookSignature(input))\n throw new Error('Lifecycle invocation identity changed.')\n if (existing?.retired) throw new ExpiredHookError(cutoff)\n if (!existing) {\n if (input.version === 1 && legacyExhausted()) {\n await flush()\n throw new LegacyHookCapacityError()\n }\n const error = capacityFailure()\n const historyFull =\n input.version === 2 &&\n entries.filter((entry) => entry.input.version === 2).length >= HOOK_RECEIPT_LIMIT\n if (error || historyFull) {\n const fault =\n error ??\n new Error('Hook result history is waiting for unresolved lifecycle effects.')\n onFault(fault)\n throw fault\n }\n save([...entries, { input, admittedHubId: evidenceHub(input) }])\n if (legacyExhausted()) onFault(new LegacyHookCapacityError())\n }\n if (input.version === 2) {\n void flush().catch(() => {})\n } else await flush()\n const result = entries.find(\n (entry) => entry.input.invocationId === input.invocationId\n )?.result\n if (result?.runtimeHookLegacyUpgradeRequired) throw new LegacyHookCapacityError()\n if (input.version === 1 && !result)\n throw new Error('Hook remains queued during runtime handoff.')\n socket.end(\n JSON.stringify({\n jsonrpc: '2.0',\n id: message.id,\n result:\n input.version === 2\n ? {\n ...result,\n receipt: {\n version: 2,\n invocationId: input.invocationId,\n state: result ? 'applied' : 'accepted'\n }\n }\n : result\n }) + '\\n'\n )\n })().catch((error: unknown) => {\n if (\n error instanceof ExpiredHookError ||\n error instanceof FutureHookError ||\n error instanceof LegacyHookCapacityError\n )\n socket.end(\n JSON.stringify({\n jsonrpc: '2.0',\n id: message.id,\n error: {\n code: -32001,\n message: error.message,\n ...(error instanceof FutureHookError || error instanceof LegacyHookCapacityError\n ? {\n data: {\n code:\n error instanceof FutureHookError\n ? 'MCP_HOOK_CLOCK_AHEAD'\n : 'MCP_HOOK_LEGACY_UPGRADE_REQUIRED'\n }\n }\n : {})\n }\n }) + '\\n'\n )\n else socket.destroy()\n })\n return\n }\n })\n })\n compact()\n cleanupEndpoint(socketPath)\n await listenPrivate(server, socketPath, signal)\n onFault(\n capacityFailure() ??\n (pending()\n ? new Error('Lifecycle hooks remain queued.')\n : legacyExhausted()\n ? new LegacyHookCapacityError()\n : undefined)\n )\n return {\n flush,\n setReceiver(hubId: string) {\n if (receiver?.hubId === hubId) return\n // A real Hub replacement requires new evidence. The first receiver still\n // accepts hooks issued while it was starting; reconnecting the same Hub\n // preserves its boundary and each invocation's original admission.\n save(\n entries,\n ReceiverSchema.parse({\n hubId,\n ...(receiver || stored !== undefined\n ? { freshAfter: Math.max(receiver?.freshAfter ?? 0, Date.now()) }\n : {})\n })\n )\n },\n get pending() {\n return pending()\n },\n get legacyExhausted() {\n return legacyExhausted()\n },\n close: async () => {\n closed = true\n for (const socket of sockets) socket.destroy()\n await new Promise<void>((resolve) => server.close(() => resolve()))\n cleanupEndpoint(socketPath)\n }\n }\n}\n","import type { Registration } from './protocol'\n\nimport { VersionSchema } from '../runtime-update/manifest'\nimport { newerVersion } from './state'\n\n/** Project version evidence only; registrations also contain private host context and capabilities. */\nexport function controlComponentStatus(\n supervisorVersion: string,\n registrations: Registration[],\n availableVersions: string[]\n) {\n const latest = availableVersions.reduce(\n (latest, version) => (newerVersion(version, latest) ? version : latest),\n supervisorVersion\n )\n const component = (value?: string) => {\n const version = VersionSchema.safeParse(value).data ?? null\n const pendingVersion = version && newerVersion(latest, version) ? latest : null\n return { version, pendingVersion, restartRequired: version ? pendingVersion !== null : null }\n }\n const supervisor = component(supervisorVersion)\n const edges = registrations.map((registration) => component(registration.updates?.version))\n const components = [supervisor, ...edges]\n return {\n supervisor,\n edges,\n restartRequired: components.some((value) => value.restartRequired === true)\n ? true\n : components.some((value) => value.restartRequired === null)\n ? null\n : false\n }\n}\n","import { ResultSchema } from '@modelcontextprotocol/sdk/types.js'\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { createServer } from 'node:net'\nimport { dirname, join } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport lockfile from 'proper-lockfile'\nimport { z } from 'zod'\n\nimport { writeDurableJson } from '../durable-json'\nimport { parseHubRuntimeIdentity } from '../runtime-identity'\nimport { cleanupEndpoint, runtimeEndpoint } from '../runtime-platform'\nimport { releaseManifest, verifyReleaseArtifact } from '../runtime-update/artifact'\nimport { pruneCache } from '../runtime-update/cache'\nimport { acquireRelease, ReleaseUpdates } from '../runtime-update/manager'\nimport {\n automaticCompatibilityReasons,\n coldCompatibilityReasons,\n compatibilityReasons\n} from '../runtime-update/manifest'\nimport { ensureDir, ensureFile, HUB_LOCK_STALE_MS, PACKAGE_VERSION, SOCK_PATH } from '../shared'\nimport { startHookGateway } from './hooks'\nimport { AUTOMATIC_IDLE_MS, LeaseSchema } from './hub-control'\nimport { probeArtifact } from './probe'\nimport {\n connectSocket,\n fingerprintBundle,\n hubSocketPath,\n isSocketPending,\n runtimePaths,\n supervisorSocketPath,\n launch,\n listenPrivate,\n waitForLaunchedSocket,\n waitForSocket,\n unavailableSocket,\n type PrototypeConfig\n} from './processes'\nimport {\n ControlPeer,\n CONTROL_VERSIONS,\n isRuntimeUnavailable,\n negotiate,\n RECOVER_MS,\n RegistrationSchema,\n RENEW_MS,\n SocketTransport,\n unavailable,\n type Registration\n} from './protocol'\nimport {\n newerVersion,\n readJournal,\n readJournalAsync,\n writeJournal,\n type Artifact,\n type Journal\n} from './state'\nimport { controlComponentStatus } from './status'\n\nconst InspectionSchema = ResultSchema.extend({\n drained: z.boolean(),\n deadline: z.number(),\n blockers: z.array(z.string()),\n version: z.string(),\n gated: z.boolean(),\n handoffVersion: z.literal(1),\n attachedSessions: z.array(z.uuid()).max(128),\n autoBlockers: z.array(z.string()).optional(),\n idleForMs: z.number().nonnegative().optional()\n})\nconst AUTOMATIC_RETRY_MS = 60_000\ntype Lease = z.infer<typeof LeaseSchema>\ntype Edge = {\n registration: Registration\n ready: boolean\n error?: string\n}\n\nfunction alive(pid: number) {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false\n throw error\n }\n}\n\nexport async function startSupervisor(config: PrototypeConfig) {\n const lockPath = join(config.root, 'supervisor.lock')\n ensureFile(lockPath)\n const unlock = await lockfile.lock(lockPath, { retries: 0, stale: 5000, update: 1000 })\n const socketPath = supervisorSocketPath(config)\n const paths = runtimePaths(config)\n const control: Artifact = {\n entry: config.entry,\n bundle: config.bundle,\n version: PACKAGE_VERSION,\n release: config.release\n }\n const peers = new Set<ControlPeer>()\n const edges = new Map<ControlPeer, Edge>()\n const pausedEdges = new Map<ControlPeer, string>()\n let hub: ControlPeer | undefined\n let lease: Lease | undefined\n let pendingHub:\n | { artifact: Artifact; child: ReturnType<typeof launch>; exited: boolean }\n | undefined\n let hooks: Awaited<ReturnType<typeof startHookGateway>> | undefined\n let journal: Journal = readJournal(config.root) ?? {\n version: 1,\n revision: 0,\n phase: 'committed',\n active: control,\n failedBundles: []\n }\n let closing = false\n let transitioning = false\n let renewing = false\n let recoveringDisconnected = false\n let automaticChecking = false\n let automaticRetryAt = 0\n let automaticError: string | undefined\n let hookFault: string | undefined\n let timer: ReturnType<typeof setInterval> | undefined\n const lifetime = new AbortController()\n const pause = (milliseconds: number) =>\n delay(milliseconds, undefined, { signal: lifetime.signal })\n const stop = () => void close()\n const updates: ReleaseUpdates | undefined = config.release\n ? new ReleaseUpdates({\n root: config.root,\n enrolled: () =>\n !transitioning &&\n [...edges.values()].some((edge) => edge.registration.updates?.policy === 'stable'),\n acquire: async (version, signal, cursor) => {\n await requireHub().request(\n { method: 'tempad/runtime-retain', params: { retained: true } },\n ResultSchema\n )\n try {\n const result = await acquireRelease(\n join(dirname(config.entry), 'runtime-installer.mjs'),\n join(config.root, 'cache'),\n version,\n {\n active: journal.active,\n control,\n previous: journal.previous,\n excludedBundles: journal.failedBundles\n },\n signal,\n cursor\n )\n await pruneCache(\n join(config.root, 'cache'),\n [\n control,\n journal.active,\n journal.previous,\n journal.candidate,\n result.candidate,\n updates?.status.candidate,\n updates?.status.manualCandidate\n ],\n signal\n )\n return result\n } finally {\n await hub\n ?.request(\n { method: 'tempad/runtime-retain', params: { retained: false } },\n ResultSchema\n )\n .catch(() => {})\n }\n }\n })\n : undefined\n\n function activationBlockers(candidate: Artifact, automatic = false) {\n let reasons: string[]\n try {\n const compare = automatic ? automaticCompatibilityReasons : compatibilityReasons\n const next = releaseManifest(candidate)\n reasons = [\n ...new Set([\n ...compare(releaseManifest(journal.active), next),\n ...compatibilityReasons(releaseManifest(control), next)\n ])\n ]\n } catch (error) {\n return [`Retained release verification failed: ${String(error)}`]\n }\n if (!newerVersion(candidate.version, journal.active.version))\n reasons.push('Candidate is not newer than the active runtime')\n if (journal.failedBundles.includes(candidate.bundle))\n reasons.push('Candidate was quarantined after a failed activation')\n if ([...edges.values()].some((edge) => edge.registration.updates?.policy !== 'stable'))\n reasons.push(\n 'An attached MCP client has not opted in; restart it with --runtime-updates=stable or close it'\n )\n if ([...edges.values()].some((edge) => !edge.ready))\n reasons.push('An attached MCP client has not finished initialization')\n return reasons\n }\n\n function automaticEnabled() {\n return (\n !!updates &&\n !updates.status.disabled &&\n edges.size > 0 &&\n [...edges.values()].every(\n (edge) => edge.registration.updates?.policy === 'stable' && edge.ready\n )\n )\n }\n\n function automaticBlockers(state: z.infer<typeof InspectionSchema>) {\n const reasons = [...state.blockers, ...connectionBlockers(state)]\n if (!automaticEnabled())\n reasons.push('All connected clients must opt in and support waiting through runtime switches')\n if (hookFault || hooks?.pending) reasons.push('Lifecycle events are awaiting durable delivery')\n if (!state.autoBlockers) reasons.push('Hub cannot verify automatic switch readiness')\n else reasons.push(...state.autoBlockers)\n if (state.idleForMs === undefined || state.idleForMs < AUTOMATIC_IDLE_MS)\n reasons.push(\n AUTOMATIC_IDLE_MS === 5000\n ? 'Waiting for five seconds without active work'\n : `Waiting for ${AUTOMATIC_IDLE_MS} ms without active work`\n )\n return reasons\n }\n\n function connectionBlockers(state: z.infer<typeof InspectionSchema>) {\n const controlled = new Set([...edges.values()].map((edge) => edge.registration.sessionId))\n return state.attachedSessions.some((id) => !controlled.has(id))\n ? ['An MCP data session is waiting for its control connection to reconnect']\n : []\n }\n\n // Reuse the existing lease heartbeat; do no artifact or readiness work without\n // a staged candidate. A busy Hub is never gated while waiting for an idle gap.\n async function maybeActivateAutomatically() {\n if (\n automaticChecking ||\n closing ||\n transitioning ||\n !automaticEnabled() ||\n updates?.status.checking ||\n journal.phase !== 'committed' ||\n performance.now() < automaticRetryAt\n )\n return\n const candidate = updates?.status.candidate\n if (\n !candidate ||\n !newerVersion(candidate.version, journal.active.version) ||\n journal.failedBundles.includes(candidate.bundle)\n )\n return\n automaticChecking = true\n try {\n if (activationBlockers(candidate, true).length) return\n const state = await inspect()\n if (state.gated || automaticBlockers(state).length) return\n automaticRetryAt = performance.now() + AUTOMATIC_RETRY_MS\n const result = await update(candidate.entry, candidate, true)\n automaticError = result.status === 'activated' ? undefined : result.reason\n } catch (error) {\n automaticRetryAt = performance.now() + AUTOMATIC_RETRY_MS\n automaticError = String(error).slice(0, 2000)\n } finally {\n automaticChecking = false\n }\n }\n\n function persist(next: Journal) {\n lifetime.signal.throwIfAborted()\n const value = { ...next, revision: journal.revision + 1 }\n writeJournal(config.root, value)\n journal = value\n }\n function requireHub() {\n if (closing || !hub || !lease)\n throw unavailable('The Hub is switching or recovering; no call was dispatched.')\n return hub\n }\n function inspect(timeout = 5000) {\n return requireHub().request({ method: 'tempad/runtime-inspect' }, InspectionSchema, {\n timeout\n })\n }\n async function gate(closed: boolean, timeout = 5000) {\n if (!closed && (hookFault || hooks?.pending))\n throw unavailable(\n `Lifecycle delivery remains uncertain: ${hookFault ?? 'hooks remain queued'}`\n )\n return requireHub().request(\n { method: 'tempad/runtime-gate', params: { closed } },\n InspectionSchema,\n { timeout }\n )\n }\n function publish() {\n writeDurableJson(join(config.root, 'supervisor.json'), {\n pid: process.pid,\n entry: config.entry,\n bundle: config.bundle,\n ...lease\n })\n }\n async function ensureHooks() {\n hooks ??= await startHookGateway(\n config.root,\n (input, admittedHubId) =>\n requireHub().request(\n { method: 'tempad/runtime-hook', params: { input, admittedHubId } },\n ResultSchema,\n {\n timeout: 5000\n }\n ),\n (error) => {\n const recovering = !!hookFault\n hookFault = error === undefined ? undefined : String(error)\n if (hookFault || (recovering && !transitioning)) void gate(!!hookFault).catch(() => {})\n },\n config.directories ? SOCK_PATH : runtimeEndpoint(paths.runtime, 'mcp.sock'),\n async () => {\n await requireHub().request({ method: 'tempad/runtime-retire-legacy-hooks' }, ResultSchema, {\n timeout: 5000,\n signal: lifetime.signal\n })\n },\n lifetime.signal\n )\n hooks.setReceiver(lease!.hubId)\n }\n\n async function waitForExit(pid: number, timeout = 15_000) {\n const deadline = performance.now() + timeout\n while (alive(pid)) {\n if (performance.now() >= deadline)\n throw new Error('The old Hub is still alive. Its writer ownership will not be replaced.')\n await pause(50)\n }\n }\n async function waitForWriters() {\n const deadline = performance.now() + HUB_LOCK_STALE_MS + 5000\n const writerLocks = [\n [join(paths.runtime, 'hub.lock'), undefined],\n [paths.state, join(paths.state, '.tempad-hub-writer.lock')],\n [paths.assets, join(paths.assets, '.tempad-hub-writer.lock')]\n ] as const\n while (true) {\n let locked = false\n for (const [path, lockfilePath] of writerLocks) {\n if (\n existsSync(path) &&\n (await lockfile.check(path, {\n stale: HUB_LOCK_STALE_MS,\n ...(lockfilePath ? { lockfilePath } : {})\n }))\n )\n locked = true\n }\n if (!locked) return\n if (performance.now() >= deadline)\n throw new Error('Hub writer locks remain owned; runtime recovery is deferred.')\n await pause(200)\n }\n }\n\n async function connectHub(\n artifact: Artifact,\n allowLaunch = true,\n deadline = performance.now() + RECOVER_MS\n ) {\n if (closing) throw unavailable('Runtime supervisor is closing.')\n let socket\n try {\n socket = await connectSocket(hubSocketPath(config.root, paths.runtime), lifetime.signal)\n } catch (error) {\n if (!isSocketPending(error) && !unavailableSocket(error)) throw error\n const presentEndpoint =\n isSocketPending(error) || (error as NodeJS.ErrnoException).code === 'EBUSY'\n const identityPath = join(paths.runtime, 'hub-runtime.json')\n const identity = existsSync(identityPath)\n ? parseHubRuntimeIdentity(JSON.parse(readFileSync(identityPath, 'utf8')))\n : undefined\n const liveIdentity = identity && alive(identity.processId)\n if (\n identity === null ||\n (liveIdentity &&\n (identity.packageVersion !== artifact.version ||\n dirname(identity.entryPath) !== dirname(artifact.entry))) ||\n (pendingHub && !pendingHub.exited && pendingHub.artifact.bundle !== artifact.bundle)\n )\n throw new Error('Hub process ownership is uncertain; no replacement was started.', {\n cause: error\n })\n if (!liveIdentity && !presentEndpoint && (!pendingHub || pendingHub.exited)) {\n if (!allowLaunch) throw error\n await waitForWriters()\n lifetime.signal.throwIfAborted()\n const pending = { artifact, child: launch(config, 'hub', artifact), exited: false }\n pendingHub = pending\n const exited = () => {\n pending.exited = true\n }\n pending.child.once('exit', exited)\n pending.child.once('error', exited)\n }\n const path = hubSocketPath(config.root, paths.runtime)\n const remaining = deadline - performance.now()\n socket =\n pendingHub && !pendingHub.exited\n ? await waitForLaunchedSocket(path, pendingHub.child, lifetime.signal, remaining)\n : await waitForSocket(\n path,\n lifetime.signal,\n remaining,\n liveIdentity ? identity.processId : undefined\n )\n }\n const peer = new ControlPeer()\n peer.onerror = () => void peer.close()\n try {\n await peer.connect(new SocketTransport(socket))\n const acquired = await peer.request(\n {\n method: 'tempad/runtime-acquire',\n params: { secret: config.secret, versions: [...CONTROL_VERSIONS] }\n },\n LeaseSchema,\n { timeout: 5000 }\n )\n const observed = await peer.request({ method: 'tempad/runtime-inspect' }, InspectionSchema, {\n timeout: 5000\n })\n const identity = parseHubRuntimeIdentity(\n JSON.parse(readFileSync(join(paths.runtime, 'hub-runtime.json'), 'utf8'))\n )\n if (\n !identity ||\n identity.processId !== acquired.hubPid ||\n dirname(identity.entryPath) !== dirname(artifact.entry) ||\n observed.version !== artifact.version ||\n fingerprintBundle(artifact.entry) !== artifact.bundle\n )\n throw new Error('The running Hub does not match the verified local artifact.')\n lifetime.signal.throwIfAborted()\n pendingHub = undefined\n hub = peer\n lease = acquired\n startRenewal()\n await ensureHooks()\n publish()\n peer.onclose = () => {\n if (hub !== peer) return\n hub = undefined\n recoverDisconnectedHub()\n }\n } catch (error) {\n await peer.close()\n // A failed startup can close its control pipe before its process exits\n // (for example, after WebSocket binding fails). Keep ownership until the\n // launched child has exited, within the original startup recovery budget.\n const starting = pendingHub\n while (\n starting?.artifact.bundle === artifact.bundle &&\n !starting.exited &&\n performance.now() < deadline\n ) {\n if (starting.child.exitCode != null || starting.child.signalCode != null)\n starting.exited = true\n else await pause(50)\n }\n throw error\n }\n }\n\n function recoverDisconnectedHub() {\n if (closing || transitioning || hub) return\n if (!edges.size) {\n void close()\n return\n }\n recoveringDisconnected = true\n void recover()\n .catch((error) => {\n if (!closing) process.stderr.write(`Runtime recovery failed: ${String(error)}\\n`)\n void close()\n })\n .finally(() => {\n recoveringDisconnected = false\n })\n }\n\n function startRenewal() {\n if (timer) return\n timer = setInterval(() => {\n if (renewing || !hub) return\n renewing = true\n const connection = hub\n void connection\n .request({ method: 'tempad/runtime-renew' }, ResultSchema, { timeout: RENEW_MS })\n .catch(() => connection.close())\n .finally(() => {\n renewing = false\n void maybeActivateAutomatically()\n })\n }, RENEW_MS)\n }\n\n async function register(edge: Edge) {\n const connection = requireHub()\n const current = lease!\n await connection.request(\n { method: 'tempad/runtime-register', params: edge.registration },\n ResultSchema,\n { timeout: 5000 }\n )\n if (connection !== hub) throw unavailable()\n return {\n ...current,\n version: negotiate(edge.registration.versions),\n supervisorPid: process.pid\n }\n }\n async function reattach() {\n await Promise.all(\n [...edges].map(async ([peer, edge]) => {\n edge.ready = false\n edge.error = undefined\n try {\n const grant = await register(edge)\n await peer.notification({\n method: 'notifications/tempad/runtime-replaced',\n params: grant\n })\n } catch (error) {\n if (edges.has(peer)) throw error\n }\n })\n )\n const deadline = performance.now() + 15_000\n while ([...edges.values()].some((edge) => !edge.ready)) {\n if (closing) throw unavailable('Runtime supervisor is closing.')\n const failure = [...edges.values()].find((edge) => edge.error)?.error\n if (failure) throw new Error(failure)\n if (performance.now() >= deadline)\n throw new Error('An edge could not verify the replacement runtime.')\n await pause(25)\n }\n }\n async function drain(automatic = false) {\n const observed = await inspect()\n const disconnected = connectionBlockers(observed)\n if (disconnected.length) throw new Error(disconnected.join('; '))\n const deadline = Math.min(Date.now() + 330_000, observed.deadline)\n const remaining = () => {\n const value = deadline - Date.now()\n if (value <= 0) throw unavailable('Runtime drain deadline expired; switching is deferred.')\n return Math.min(5000, value)\n }\n await pauseEdges(deadline)\n const state = await gate(true, remaining())\n remaining()\n const unpaused = connectionBlockers(state)\n if (unpaused.length) throw new Error(unpaused.join('; '))\n if (automatic) {\n const reasons = automaticBlockers(state)\n if (!state.drained || reasons.length)\n throw new Error(`Automatic runtime switch deferred: ${reasons.join(', ')}.`)\n return\n }\n let current = state\n while (!current.drained) {\n if (\n current.blockers.includes('Claude binding without receipt/retry hooks') ||\n Date.now() >= deadline\n )\n throw new Error(`Runtime switch deferred: ${current.blockers.join(', ')}.`)\n await pause(50)\n current = await inspect(remaining())\n }\n remaining()\n }\n\n async function pauseEdges(deadline: number) {\n const failed = new AbortController()\n const signal = AbortSignal.any([lifetime.signal, failed.signal])\n await Promise.allSettled(\n [...edges.keys()].map(async (peer) => {\n const hubId = lease!.hubId\n pausedEdges.set(peer, hubId)\n try {\n const remaining = deadline - Date.now()\n if (remaining <= 0) throw unavailable('Runtime admission barrier deadline expired.')\n await peer.request(\n { method: 'tempad/runtime-admission', params: { hubId, paused: true } },\n ResultSchema,\n { timeout: remaining, signal }\n )\n } catch (error) {\n if (edges.has(peer)) failed.abort(error)\n }\n })\n )\n lifetime.signal.throwIfAborted()\n failed.signal.throwIfAborted()\n }\n\n async function resumeEdges() {\n const pending = [...pausedEdges]\n pausedEdges.clear()\n await Promise.all(\n pending.map(async ([peer, hubId]) => {\n // A verified replacement or a new control registration releases its own\n // pause. Only a still-connected old backend needs this abort-path resume.\n if (!edges.has(peer) || hubId !== lease?.hubId) return\n try {\n await peer.request(\n { method: 'tempad/runtime-admission', params: { hubId, paused: false } },\n ResultSchema,\n { timeout: 5000, signal: lifetime.signal }\n )\n } catch {\n // A lost resume reply must recover through a fresh verified registration.\n await peer.close()\n }\n })\n )\n }\n async function stopHub(automatic = false) {\n const current = lease!\n await requireHub().request(\n {\n method: 'tempad/runtime-stop',\n params: {\n pausedSessions: [...pausedEdges].flatMap(([peer, hubId]) => {\n const edge = edges.get(peer)\n return edge && hubId === current.hubId ? [edge.registration.sessionId] : []\n }),\n ...(automatic ? { automatic: true } : {})\n }\n },\n ResultSchema,\n { timeout: 5000 }\n )\n await waitForExit(current.hubPid)\n hub = undefined\n await waitForWriters()\n }\n\n async function recoverHub(artifact: Artifact) {\n const deadline = performance.now() + RECOVER_MS\n while (true) {\n try {\n await connectHub(artifact, true, deadline)\n return\n } catch (error) {\n const identityPath = join(paths.runtime, 'hub-runtime.json')\n const identity = existsSync(identityPath)\n ? parseHubRuntimeIdentity(JSON.parse(readFileSync(identityPath, 'utf8')))\n : undefined\n // Retry a failed startup only after its process has exited. Never race\n // an unknown writer, change ports, or execute a changed local artifact.\n if (\n closing ||\n performance.now() >= deadline ||\n (existsSync(identityPath) && (!identity || alive(identity.processId))) ||\n fingerprintBundle(artifact.entry) !== artifact.bundle\n )\n throw error\n await pause(200)\n }\n }\n }\n\n async function activate(candidate: Artifact, automatic = false) {\n if (candidate.release) {\n const blockers = activationBlockers(candidate, automatic)\n if (blockers.length) throw new Error(blockers.join('; '))\n }\n await drain(automatic)\n persist({\n ...journal,\n phase: 'preparing',\n candidate,\n failure: undefined,\n oldHub: { id: lease!.hubId, pid: lease!.hubPid }\n })\n await stopHub(automatic)\n persist({ ...journal, phase: 'old-stopped' })\n await connectHub(candidate)\n persist({ ...journal, phase: 'candidate-ready' })\n await finishHandoff()\n }\n\n async function finishHandoff() {\n await reattach()\n await hooks?.flush()\n if (journal.candidate?.release && journal.phase !== 'committed') {\n const blockers = journal.coldStart\n ? coldCompatibilityReasons(\n releaseManifest(journal.active),\n releaseManifest(journal.candidate)\n )\n : activationBlockers(journal.candidate)\n if (blockers.length) throw new Error(blockers.join('; '))\n }\n if (journal.phase !== 'committed')\n persist({\n ...journal,\n phase: 'committed',\n coldStart: undefined,\n ...(journal.candidate\n ? {\n previous:\n journal.candidate.bundle === journal.active.bundle\n ? journal.previous\n : journal.active,\n active: journal.candidate,\n candidate: undefined,\n failure: undefined\n }\n : {}),\n oldHub: undefined\n })\n await gate(false)\n await resumeEdges()\n }\n\n async function rollback(error: unknown) {\n journal = (await readJournalAsync(config.root)) ?? journal\n const failed = journal.candidate ?? journal.active\n const fallback =\n journal.phase === 'committed' || journal.candidate?.bundle === journal.active.bundle\n ? journal.previous\n : journal.active\n if (!fallback) throw error\n if (hub && lease && alive(lease.hubPid)) {\n await drain()\n await stopHub()\n }\n const ownershipFailure = (cause = error) =>\n new Error('Hub process ownership is uncertain; the interrupted handoff remains gated.', {\n cause\n })\n if ((pendingHub && !pendingHub.exited) || (lease && alive(lease.hubPid)))\n throw ownershipFailure()\n const identityPath = join(paths.runtime, 'hub-runtime.json')\n const identity = existsSync(identityPath)\n ? parseHubRuntimeIdentity(JSON.parse(readFileSync(identityPath, 'utf8')))\n : undefined\n if (identity === null || (identity && alive(identity.processId))) throw ownershipFailure()\n let present\n try {\n present = await connectSocket(hubSocketPath(config.root, paths.runtime), lifetime.signal)\n } catch (cause) {\n if (!['ENOENT', 'ECONNREFUSED'].includes((cause as NodeJS.ErrnoException).code ?? ''))\n throw ownershipFailure(cause)\n }\n if (present) {\n present.destroy()\n throw ownershipFailure()\n }\n persist({\n ...journal,\n phase: 'old-stopped',\n coldStart: undefined,\n active: fallback,\n candidate: undefined,\n previous: undefined,\n oldHub: undefined,\n failedBundles: [...new Set([...journal.failedBundles, failed.bundle])],\n failure: String(error)\n })\n await recoverHub(fallback)\n await finishHandoff()\n }\n\n async function recover() {\n if (transitioning) return\n transitioning = true\n let observedPid: number | undefined\n try {\n const identityPath = join(paths.runtime, 'hub-runtime.json')\n const identity = existsSync(identityPath)\n ? parseHubRuntimeIdentity(JSON.parse(readFileSync(identityPath, 'utf8')))\n : undefined\n if (identity && alive(identity.processId)) {\n observedPid = identity.processId\n const candidates = [journal.active, journal.candidate, journal.previous].filter(\n (value): value is Artifact => !!value\n )\n const artifact = candidates.find(\n (value) =>\n value.version === identity.packageVersion &&\n dirname(value.entry) === dirname(identity.entryPath)\n )\n if (!artifact) throw new Error('An unknown Hub still owns this runtime.')\n // Socket closure can precede process exit. Reattaching must never\n // silently relaunch that artifact and bypass the crash rollback path.\n if (!hub?.transport || lease?.hubPid !== identity.processId)\n await connectHub(artifact, false)\n if (journal.phase === 'preparing' && artifact.bundle === journal.active.bundle) {\n persist({\n ...journal,\n phase: 'committed',\n candidate: updates ? undefined : journal.candidate,\n oldHub: undefined,\n failure:\n 'The supervisor stopped before the old Hub exited; the active runtime was retained.'\n })\n } else if (artifact.bundle !== journal.active.bundle) {\n persist({ ...journal, phase: 'candidate-ready' })\n }\n } else {\n if (journal.phase === 'committed' && identity && journal.previous) {\n await rollback(new Error('The active Hub exited unexpectedly.'))\n return\n }\n const candidate =\n journal.candidate &&\n !journal.failedBundles.includes(journal.candidate.bundle) &&\n journal.phase !== 'committed'\n ? journal.candidate\n : journal.active\n if (journal.phase !== 'committed') persist({ ...journal, phase: 'old-stopped' })\n await recoverHub(candidate)\n if (journal.phase !== 'committed') persist({ ...journal, phase: 'candidate-ready' })\n }\n await finishHandoff()\n } catch (error) {\n if (journal.phase !== 'committed' && journal.candidate) await rollback(error)\n else if (observedPid && journal.previous) {\n await waitForExit(observedPid)\n await rollback(error)\n } else throw error\n } finally {\n await resumeEdges()\n transitioning = false\n updates?.schedule()\n }\n }\n\n async function update(entry: string, released?: Artifact, automatic = false) {\n if (transitioning) throw unavailable('Another runtime transition is in progress.')\n if (updates?.status.checking)\n throw unavailable('Wait for release acquisition to finish before activating.')\n if (journal.phase !== 'committed')\n throw unavailable(\n 'An interrupted handoff must finish through --recover-runtime before offering another version.'\n )\n transitioning = true\n updates?.schedule()\n try {\n await requireHub().request(\n { method: 'tempad/runtime-retain', params: { retained: true } },\n ResultSchema\n )\n if ([...edges.values()].some((edge) => !edge.ready))\n throw new Error(\n 'An attached MCP client has not finished initialization; wait or reconnect it before switching.'\n )\n if (config.release && !released)\n throw new Error('Managed releases accept only a verified staged npm artifact.')\n if (released) verifyReleaseArtifact(released)\n const candidate = released\n ? { artifact: released, contract: undefined }\n : await probeArtifact(entry)\n if (!newerVersion(candidate.artifact.version, journal.active.version))\n throw new Error('Only a newer stable local runtime can be offered.')\n if (journal.failedBundles.includes(candidate.artifact.bundle))\n throw new Error('This runtime bundle is quarantined after a failed activation.')\n if (!released) {\n const active = await probeArtifact(journal.active.entry)\n if (candidate.contract !== active.contract)\n throw new Error(\n 'The local candidate changes the frozen MCP contract; restart MCP instead.'\n )\n }\n if (!updates) persist({ ...journal, candidate: candidate.artifact, failure: undefined })\n try {\n await activate(candidate.artifact, automatic)\n } catch (error) {\n journal = (await readJournalAsync(config.root)) ?? journal\n // A definite pre-shutdown refusal leaves the original writer intact.\n // Reopen it instead of draining newly arrived work for a rollback.\n const originalRetained =\n journal.phase === 'preparing' &&\n isRuntimeUnavailable(error) &&\n journal.oldHub?.id === lease?.hubId &&\n hub?.transport\n if (\n (journal.phase === 'committed' && journal.active.bundle !== candidate.artifact.bundle) ||\n originalRetained\n ) {\n persist({\n ...journal,\n phase: 'committed',\n candidate: updates ? undefined : journal.candidate,\n oldHub: undefined,\n failure: String(error)\n })\n await gate(false)\n return { status: 'staged', reason: String(error) }\n }\n await rollback(error)\n return { status: 'rolled-back', reason: String(error) }\n }\n return { status: 'activated', version: journal.active.version }\n } finally {\n await resumeEdges()\n transitioning = false\n await hub\n ?.request({ method: 'tempad/runtime-retain', params: { retained: false } }, ResultSchema)\n .catch(() => {})\n // onclose defers recovery while a switch owns the transition. A settled\n // journal can resume it without replaying the operator's update request;\n // an unfinished handoff still requires explicit recovery.\n if (journal.phase === 'committed') recoverDisconnectedHub()\n updates?.schedule()\n }\n }\n\n const server = createServer((socket) => {\n if (peers.size >= 128) {\n socket.destroy()\n return\n }\n const peer = new ControlPeer()\n peers.add(peer)\n const timeout = setTimeout(() => void peer.close(), 5000)\n peer.onerror = () => void peer.close()\n peer.onclose = () => {\n clearTimeout(timeout)\n peers.delete(peer)\n const detached = edges.delete(peer)\n // Data and control pipes can close in either order. Do not keep a probe\n // (or a departed host) alive recovering a Hub for an edge that just left.\n if (detached && !edges.size && recoveringDisconnected) void close()\n updates?.schedule()\n }\n peer.setRequestHandler(\n z.object({ method: z.literal('tempad/runtime-hello'), params: RegistrationSchema }),\n async ({ params }) => {\n if (edges.has(peer)) throw new Error('A runtime connection can register only once.')\n if (transitioning) throw unavailable('Runtime handoff in progress; retry attachment.')\n if (\n config.release &&\n params.updates?.policy === 'pinned' &&\n (params.updates?.version !== journal.active.version ||\n params.updates?.manifestHash !== journal.active.release?.manifestHash)\n )\n throw new Error(\n 'MCP_RUNTIME_RESTART_REQUIRED: this pinned client requests a different runtime; update/restart MCP or explicitly enroll it.'\n )\n const edge = { registration: params, ready: false }\n edges.set(peer, edge)\n const grant = await register(edge)\n clearTimeout(timeout)\n updates?.schedule()\n return grant\n }\n )\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-ready'),\n params: z.object({\n hubId: z.uuid(),\n error: z.string().optional()\n })\n }),\n ({ params }) => {\n const edge = edges.get(peer)\n if (!edge || params.hubId !== lease?.hubId)\n throw unavailable('Stale runtime readiness acknowledgment.')\n edge.error = params.error\n edge.ready = !params.error\n return {}\n }\n )\n peer.setRequestHandler(z.object({ method: z.literal('tempad/runtime-refresh') }), async () => {\n const edge = edges.get(peer)\n if (!edge) throw unavailable('Runtime session is not registered.')\n return register(edge)\n })\n peer.setRequestHandler(z.object({ method: z.literal('tempad/runtime-status') }), async () => {\n clearTimeout(timeout)\n const state = hub ? await inspect().catch(() => undefined) : undefined\n return {\n ...(state ?? { gated: true, unavailable: 'Hub recovery has not completed.' }),\n ...lease,\n supervisorPid: process.pid,\n phase: journal.phase,\n active: journal.active,\n candidate: journal.candidate,\n failure: journal.failure,\n hookFault,\n legacyHookWarning: hooks?.legacyExhausted\n ? 'Legacy lifecycle history is full. Update the TemPad Dev plugin to restore Claude lifecycle support.'\n : undefined,\n controlComponents: controlComponentStatus(\n PACKAGE_VERSION,\n [...edges.values()].map((edge) => edge.registration),\n [journal.active, journal.candidate, updates?.status.candidate]\n .filter(\n (artifact): artifact is Artifact =>\n !!artifact && !journal.failedBundles.includes(artifact.bundle)\n )\n .map((artifact) => artifact.version)\n ),\n updates: updates\n ? {\n ...updates.status,\n automaticActivation: automaticEnabled(),\n automaticError,\n automaticPendingReasons: updates.status.candidate\n ? [\n ...activationBlockers(updates.status.candidate, true),\n ...(state ? automaticBlockers(state) : ['Hub recovery has not completed.'])\n ]\n : [],\n pendingReasons: updates.status.candidate\n ? activationBlockers(updates.status.candidate)\n : []\n }\n : undefined\n }\n })\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-check'),\n params: z.object({ version: z.string() }).strict()\n }),\n async ({ params }) => {\n if (!updates)\n throw new Error('Release acquisition is unavailable in isolated/local runtimes.')\n if (transitioning) throw unavailable('Runtime handoff in progress.')\n clearTimeout(timeout)\n const candidate = await updates.check(params.version, true)\n return {\n candidate,\n selection: updates.status.selection,\n automaticActivation: automaticEnabled(),\n pendingReasons: candidate ? activationBlockers(candidate) : []\n }\n }\n )\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-activate'),\n params: z.object({ version: z.string(), integrity: z.string() }).strict()\n }),\n async ({ params }) => {\n const candidate = [updates?.status.manualCandidate, updates?.status.candidate].find(\n (value) =>\n value?.version === params.version && value.release?.integrity === params.integrity\n )\n if (!candidate)\n throw new Error(\n 'The staged artifact changed; check and confirm its version and integrity again.'\n )\n clearTimeout(timeout)\n const blockers = activationBlockers(candidate)\n if (blockers.length) return { status: 'staged', reasons: blockers }\n return update(candidate.entry, candidate)\n }\n )\n peer.setRequestHandler(z.object({ method: z.literal('tempad/runtime-recover') }), async () => {\n if (transitioning) throw unavailable('Another runtime transition is in progress.')\n clearTimeout(timeout)\n await recover()\n return { status: 'recovered', version: journal.active.version }\n })\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-update'),\n params: z.object({ entry: z.string() }).strict()\n }),\n async ({ params }) => {\n clearTimeout(timeout)\n return update(params.entry)\n }\n )\n void peer.connect(new SocketTransport(socket)).catch(() => void peer.close())\n })\n async function close() {\n if (closing) return\n closing = true\n updates?.close()\n lifetime.abort()\n process.off('SIGTERM', stop)\n process.off('SIGINT', stop)\n clearInterval(timer)\n server.close()\n await Promise.allSettled([...peers].map((peer) => peer.close()))\n await hooks?.close()\n await hub?.close()\n cleanupEndpoint(socketPath)\n rmSync(join(config.root, 'supervisor.json'), { force: true })\n await unlock()\n }\n try {\n persist(journal)\n ensureDir(paths.runtime)\n await recover()\n cleanupEndpoint(socketPath)\n await listenPrivate(server, socketPath, lifetime.signal)\n publish()\n process.once('SIGTERM', stop)\n process.once('SIGINT', stop)\n } catch (error) {\n await close()\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,cAAcA,OACV;CACN,SAASC,QAAU,CAAC;CACpB,WAAWC,OAAS;CACpB,UAAUA,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;CACvC,aAAaA,OAAS,CAAC,CAAC,SAAS;CACjC,WAAW,eAAe,SAAS;CACnC,iBAAiB,e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MAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,SAAS,KAAK,MAAM,CAAC,CAAC;EAC/D,MAAM,OAAO,MAAM;EACnB,MAAM,KAAK,MAAM;EACjB,gBAAgB,UAAU;EAC1B,OAAO,KAAK,OAAO,MAAM,iBAAiB,GAAG,EAAE,OAAO,KAAK,CAAC;EAC5D,MAAM,OAAO;CACf;CACA,IAAI;EACF,QAAQ,OAAO;EACf,UAAU,MAAM,OAAO;EACvB,MAAM,QAAQ;EACd,gBAAgB,UAAU;EAC1B,MAAM,cAAc,QAAQ,YAAY,SAAS,MAAM;EACvD,QAAQ;EACR,QAAQ,KAAK,WAAW,IAAI;EAC5B,QAAQ,KAAK,UAAU,IAAI;CAC7B,SAAS,OAAO;EACd,MAAM,MAAM;EACZ,MAAM;CACR;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"task-storage-recovery-I9lpYYX6.mjs","names":["lockfile"],"sources":["../src/task-storage-recovery.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n renameSync,\n writeFileSync\n} from 'node:fs'\nimport { basename, join } from 'node:path'\nimport lockfile from 'proper-lockfile'\n\nimport { DesignTaskStore } from './design-task-store'\nimport { HUB_LOCK_STALE_MS, HUB_LOCK_UPDATE_MS } from './shared'\n\n/** Explicit offline recovery retires every unknown old task; it never reconstructs Stop history. */\nexport async function recoverDesignTaskStorage(directory: string): Promise<{\n generation: string\n backupDirectory: string\n}> {\n const canonical = realpathSync(directory)\n const release = await lockfile.lock(canonical, {\n lockfilePath: join(canonical, '.tempad-hub-writer.lock'),\n retries: 0,\n stale: HUB_LOCK_STALE_MS,\n update: HUB_LOCK_UPDATE_MS\n })\n try {\n const path = join(canonical, 'design-tasks.json')\n const store = new DesignTaskStore(path)\n store.load()\n if (!store.recoveryError)\n throw new Error('Task storage is readable. No recovery was performed.')\n\n const generation = randomUUID()\n const backupDirectory = join(canonical, `design-tasks.recovery-${generation}`)\n mkdirSync(backupDirectory, { mode: 0o700 })\n for (const suffix of ['', '.corrupt', '.tmp']) {\n const source = `${path}${suffix}`\n if (existsSync(source))\n writeFileSync(join(backupDirectory, basename(source)), readFileSync(source), {\n flag: 'wx',\n mode: 0o600,\n flush: true\n })\n }\n\n // This marker is intentionally not a task record: older readers must block all writes.\n const snapshot = { revision: 0, current: {}, records: [{ recoveryGeneration: generation }] }\n const temporary = `${path}.recovery-${generation}.tmp`\n writeFileSync(temporary, JSON.stringify(snapshot), { flag: 'wx', mode: 0o600, flush: true })\n renameSync(temporary, path)\n return { generation, backupDirectory }\n } finally {\n await release()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,eAAsB,yBAAyB,WAG5C;CACD,MAAM,YAAY,aAAa,SAAS;CACxC,MAAM,UAAU,MAAMA,uBAAAA,QAAS,KAAK,WAAW;EAC7C,cAAc,KAAK,WAAW,yBAAyB;EACvD,SAAS;EACT,OAAO;EACP,QAAQ;CACV,CAAC;CACD,IAAI;EACF,MAAM,OAAO,KAAK,WAAW,mBAAmB;EAChD,MAAM,QAAQ,IAAI,gBAAgB,IAAI;EACtC,MAAM,KAAK;EACX,IAAI,CAAC,MAAM,eACT,MAAM,IAAI,MAAM,sDAAsD;EAExE,MAAM,aAAa,WAAW;EAC9B,MAAM,kBAAkB,KAAK,WAAW,yBAAyB,YAAY;EAC7E,UAAU,iBAAiB,EAAE,MAAM,IAAM,CAAC;EAC1C,KAAK,MAAM,UAAU;GAAC;GAAI;GAAY;EAAM,GAAG;GAC7C,MAAM,SAAS,GAAG,OAAO;GACzB,IAAI,WAAW,MAAM,GACnB,cAAc,KAAK,iBAAiB,SAAS,MAAM,CAAC,GAAG,aAAa,MAAM,GAAG;IAC3E,MAAM;IACN,MAAM;IACN,OAAO;GACT,CAAC;EACL;EAGA,MAAM,WAAW;GAAE,UAAU;GAAG,SAAS,CAAC;GAAG,SAAS,CAAC,EAAE,oBAAoB,WAAW,CAAC;EAAE;EAC3F,MAAM,YAAY,GAAG,KAAK,YAAY,WAAW;EACjD,cAAc,WAAW,KAAK,UAAU,QAAQ,GAAG;GAAE,MAAM;GAAM,MAAM;GAAO,OAAO;EAAK,CAAC;EAC3F,WAAW,WAAW,IAAI;EAC1B,OAAO;GAAE;GAAY;EAAgB;CACvC,UAAU;EACR,MAAM,QAAQ;CAChB;AACF"}