@tempad-dev/mcp 1.0.3 → 1.0.5

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 (111) hide show
  1. package/README.md +5 -1
  2. package/README.zh-Hans.md +3 -1
  3. package/dist/{acquire-TEiVy85j.mjs → acquire-C1v5UQB2.mjs} +1 -1
  4. package/dist/{acquire-DkkzoJ5Z.mjs → acquire-DK4Fg36-.mjs} +6 -7
  5. package/dist/{acquire-DkkzoJ5Z.mjs.map → acquire-DK4Fg36-.mjs.map} +1 -1
  6. package/dist/{bootstrap-Cz9cxf6f.mjs → bootstrap-CNJpiOAm.mjs} +14 -15
  7. package/dist/{bootstrap-Cz9cxf6f.mjs.map → bootstrap-CNJpiOAm.mjs.map} +1 -1
  8. package/dist/cli.mjs +12 -13
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/{client-binding-CuHY1-__.mjs → client-binding-CvSSv9JC.mjs} +4 -5
  11. package/dist/{client-binding-CuHY1-__.mjs.map → client-binding-CvSSv9JC.mjs.map} +1 -1
  12. package/dist/{cold-start-DnlXxs4o.mjs → cold-start-BOLlW_0n.mjs} +11 -12
  13. package/dist/{cold-start-DnlXxs4o.mjs.map → cold-start-BOLlW_0n.mjs.map} +1 -1
  14. package/dist/{cold-start-r07QQPSK.mjs → cold-start-DeFnhN3x.mjs} +1 -1
  15. package/dist/{config-CM4LsvW5.mjs → config-Busa_Dqv.mjs} +42 -31
  16. package/dist/config-Busa_Dqv.mjs.map +1 -0
  17. package/dist/{design-task-store-C9DJ_EQq.mjs → design-task-store-BHR54v8-.mjs} +8 -10
  18. package/dist/{design-task-store-C9DJ_EQq.mjs.map → design-task-store-BHR54v8-.mjs.map} +1 -1
  19. package/dist/{durable-json-dsqpwT93.mjs → durable-json-_WKesGDj.mjs} +2 -3
  20. package/dist/{durable-json-dsqpwT93.mjs.map → durable-json-_WKesGDj.mjs.map} +1 -1
  21. package/dist/{edge-C5SyBEy3.mjs → edge-DP-CwLYS.mjs} +1 -1
  22. package/dist/{edge-DBOKhsN4.mjs → edge-m9VuTeju.mjs} +14 -15
  23. package/dist/{edge-DBOKhsN4.mjs.map → edge-m9VuTeju.mjs.map} +1 -1
  24. package/dist/{hook-receipts-DcO9rRhi.mjs → hook-receipts-QJU3AMoY.mjs} +4 -5
  25. package/dist/{hook-receipts-DcO9rRhi.mjs.map → hook-receipts-QJU3AMoY.mjs.map} +1 -1
  26. package/dist/{host-context-CRMK5AI5.mjs → host-context-9TVtjsSm.mjs} +3 -4
  27. package/dist/{host-context-CRMK5AI5.mjs.map → host-context-9TVtjsSm.mjs.map} +1 -1
  28. package/dist/{hub-control-591ZGr_p.mjs → hub-control-UlA4Fncg.mjs} +7 -9
  29. package/dist/{hub-control-591ZGr_p.mjs.map → hub-control-UlA4Fncg.mjs.map} +1 -1
  30. package/dist/{hub-runtime-j_CZJnWz.mjs → hub-runtime-BBnfo1yd.mjs} +162 -158
  31. package/dist/hub-runtime-BBnfo1yd.mjs.map +1 -0
  32. package/dist/{hub-runtime-_GWa0RDc.mjs → hub-runtime-U3Set0EC.mjs} +1 -1
  33. package/dist/hub.mjs +3 -4
  34. package/dist/{identity-BgzOQE2L.mjs → identity-CCaDEwgc.mjs} +4 -5
  35. package/dist/{identity-BgzOQE2L.mjs.map → identity-CCaDEwgc.mjs.map} +1 -1
  36. package/dist/{indexes-CCA-CTcL.mjs → indexes-zYqwqnU6.mjs} +10 -12
  37. package/dist/{indexes-CCA-CTcL.mjs.map → indexes-zYqwqnU6.mjs.map} +1 -1
  38. package/dist/log-transport.mjs +234 -143
  39. package/dist/log-transport.mjs.map +1 -1
  40. package/dist/managed-runtime.mjs +15 -17
  41. package/dist/managed-runtime.mjs.map +1 -1
  42. package/dist/{on-exit-leak-free-BvimJ0rP.mjs → on-exit-leak-free-By20-eFK.mjs} +6 -8
  43. package/dist/{on-exit-leak-free-BvimJ0rP.mjs.map → on-exit-leak-free-By20-eFK.mjs.map} +1 -1
  44. package/dist/{pino-CLoB7tK6.mjs → pino-BiEyUxFF.mjs} +56 -82
  45. package/dist/pino-BiEyUxFF.mjs.map +1 -0
  46. package/dist/{pino-abstract-transport-B0ISte63.mjs → pino-abstract-transport-BBwCGDga.mjs} +4 -6
  47. package/dist/{pino-abstract-transport-B0ISte63.mjs.map → pino-abstract-transport-BBwCGDga.mjs.map} +1 -1
  48. package/dist/pino-file.mjs +3 -4
  49. package/dist/pino-worker.mjs +6 -8
  50. package/dist/pino-worker.mjs.map +1 -1
  51. package/dist/{probe-B6KQJxXU.mjs → probe-CqjOWdnP.mjs} +40 -55
  52. package/dist/probe-CqjOWdnP.mjs.map +1 -0
  53. package/dist/{process-environment-DJDtCcdv.mjs → process-environment-DRRIdoL8.mjs} +2 -3
  54. package/dist/{process-environment-DJDtCcdv.mjs.map → process-environment-DRRIdoL8.mjs.map} +1 -1
  55. package/dist/{processes-n0G2xAWb.mjs → processes-BnvaDi81.mjs} +1 -1
  56. package/dist/{processes-CQvuh1Sl.mjs → processes-DOmrri5n.mjs} +17 -23
  57. package/dist/{processes-CQvuh1Sl.mjs.map → processes-DOmrri5n.mjs.map} +1 -1
  58. package/dist/{proper-lockfile-CisPoFAZ.mjs → proper-lockfile-BgKrOq5D.mjs} +19 -32
  59. package/dist/{proper-lockfile-CisPoFAZ.mjs.map → proper-lockfile-BgKrOq5D.mjs.map} +1 -1
  60. package/dist/{protocol-DNswG6F2.mjs → protocol-7m-E_iFu.mjs} +57 -108
  61. package/dist/protocol-7m-E_iFu.mjs.map +1 -0
  62. package/dist/{protocol-0jvK718o.mjs → protocol-COK3rM6m.mjs} +1 -1
  63. package/dist/{rolldown-runtime-CLlik3RS.mjs → rolldown-runtime-BH1-_iVd.mjs} +2 -3
  64. package/dist/{runtime-identity-BiWIlGgw.mjs → runtime-identity-D9V-g5M-.mjs} +2 -3
  65. package/dist/{runtime-identity-BiWIlGgw.mjs.map → runtime-identity-D9V-g5M-.mjs.map} +1 -1
  66. package/dist/runtime-installer.mjs +4 -5
  67. package/dist/runtime-manifest.json +109 -109
  68. package/dist/{runtime-platform-EULgJm_w.mjs → runtime-platform-CpunJOI4.mjs} +144 -45
  69. package/dist/runtime-platform-CpunJOI4.mjs.map +1 -0
  70. package/dist/{runtime-recovery-Dq3hD3IT.mjs → runtime-recovery-DAYSaVV2.mjs} +1 -1
  71. package/dist/{runtime-recovery-DpqftTl9.mjs → runtime-recovery-DaRaQ8qY.mjs} +5 -6
  72. package/dist/{runtime-recovery-DpqftTl9.mjs.map → runtime-recovery-DaRaQ8qY.mjs.map} +1 -1
  73. package/dist/runtime-verification.mjs +6 -6
  74. package/dist/{schemas-BgOH6OcJ.mjs → schemas-ZDdPV7RQ.mjs} +23 -39
  75. package/dist/schemas-ZDdPV7RQ.mjs.map +1 -0
  76. package/dist/{server-C-tcoOT7.mjs → server-CsCpY0Ft.mjs} +645 -287
  77. package/dist/server-CsCpY0Ft.mjs.map +1 -0
  78. package/dist/{shared--CO_WPTx.mjs → shared-8_j_xlsJ.mjs} +20 -22
  79. package/dist/{shared--CO_WPTx.mjs.map → shared-8_j_xlsJ.mjs.map} +1 -1
  80. package/dist/{state-3mPLv7lh.mjs → shared-Bvmw_Pv0.mjs} +1 -1
  81. package/dist/{src-BGNQgTr6.mjs → src-BSnzZMvK.mjs} +3 -4
  82. package/dist/{src-BGNQgTr6.mjs.map → src-BSnzZMvK.mjs.map} +1 -1
  83. package/dist/{stable-edge-DQmYi4Mf.mjs → stable-edge-VAAxSYSS.mjs} +10 -14
  84. package/dist/stable-edge-VAAxSYSS.mjs.map +1 -0
  85. package/dist/{startup-log-iSoBU74r.mjs → startup-log-BI24ryBR.mjs} +3 -4
  86. package/dist/{startup-log-iSoBU74r.mjs.map → startup-log-BI24ryBR.mjs.map} +1 -1
  87. package/dist/{startup-log-C4DVL-6M.mjs → startup-log-isQ9Wv18.mjs} +1 -1
  88. package/dist/{state-CnkSwi5E.mjs → state-4Dz7r-_n.mjs} +5 -6
  89. package/dist/{state-CnkSwi5E.mjs.map → state-4Dz7r-_n.mjs.map} +1 -1
  90. package/dist/{shared-B8lb63iG.mjs → state-DDpxeTVd.mjs} +1 -1
  91. package/dist/{stdio-CZb1NNIa.mjs → stdio-20SBFdww.mjs} +3 -4
  92. package/dist/{stdio-CZb1NNIa.mjs.map → stdio-20SBFdww.mjs.map} +1 -1
  93. package/dist/{supervisor-B9lkK4ey.mjs → supervisor-Cu-xRt1k.mjs} +23 -27
  94. package/dist/{supervisor-B9lkK4ey.mjs.map → supervisor-Cu-xRt1k.mjs.map} +1 -1
  95. package/dist/{task-storage-recovery-_JdAWD5X.mjs → task-storage-recovery-fSo2eskS.mjs} +6 -7
  96. package/dist/{task-storage-recovery-_JdAWD5X.mjs.map → task-storage-recovery-fSo2eskS.mjs.map} +1 -1
  97. package/dist/thread-stream-worker.mjs +5 -6
  98. package/dist/thread-stream-worker.mjs.map +1 -1
  99. package/dist/{types-BEqvvpHh.mjs → types-C8GH0osr.mjs} +1 -1
  100. package/dist/{types-gJ5HkL66.mjs → types-kNTSQOnR.mjs} +4 -6
  101. package/dist/{types-gJ5HkL66.mjs.map → types-kNTSQOnR.mjs.map} +1 -1
  102. package/package.json +1 -1
  103. package/dist/config-CM4LsvW5.mjs.map +0 -1
  104. package/dist/hub-runtime-j_CZJnWz.mjs.map +0 -1
  105. package/dist/pino-CLoB7tK6.mjs.map +0 -1
  106. package/dist/probe-B6KQJxXU.mjs.map +0 -1
  107. package/dist/protocol-DNswG6F2.mjs.map +0 -1
  108. package/dist/runtime-platform-EULgJm_w.mjs.map +0 -1
  109. package/dist/schemas-BgOH6OcJ.mjs.map +0 -1
  110. package/dist/server-C-tcoOT7.mjs.map +0 -1
  111. package/dist/stable-edge-DQmYi4Mf.mjs.map +0 -1
@@ -9,7 +9,7 @@ import { isAbsolute, join, resolve } from "node:path";
9
9
  import { tmpdir, userInfo } from "node:os";
10
10
  import { lstatSync, mkdirSync, realpathSync, rmSync } from "node:fs";
11
11
  import { createHash, randomUUID } from "node:crypto";
12
- //#region src/runtime-platform.ts
12
+ // src/runtime-platform.ts
13
13
  const PIPE_PREFIX = "\\\\.\\pipe\\";
14
14
  const checkedPermissions = /* @__PURE__ */ new Map();
15
15
  /** Runtime overrides must isolate pipes as well as files, including on one Windows account. */
@@ -75,7 +75,7 @@ async function assertPrivatePathAsync(path, kind) {
75
75
  if (!state) return;
76
76
  }
77
77
  }
78
- function ensurePrivateDirectory(path) {
78
+ function ensurePrivateDirectory(path, { recoverLegacyRoot = false } = {}) {
79
79
  if (!isAbsolute(path)) throw new Error("Runtime directory must be absolute.");
80
80
  if (process.platform !== "win32") {
81
81
  mkdirSync(path, {
@@ -87,10 +87,23 @@ function ensurePrivateDirectory(path) {
87
87
  }
88
88
  try {
89
89
  assertPrivatePath(path, "directory");
90
+ return;
90
91
  } catch (error) {
91
- if (error.code !== "ENOENT") throw error;
92
- windowsSecurity("ensure", path, "directory");
93
- rememberPermissions(path, inspectPath(path, "directory"));
92
+ const code = error.code;
93
+ if (recoverLegacyRoot && code === "EINHERITEDACL") retireLegacyDirectory(path);
94
+ else if (code !== "ENOENT") throw error;
95
+ }
96
+ windowsSecurity("ensure", path, "directory");
97
+ if (recoverLegacyRoot) assertPrivatePath(path, "directory");
98
+ else rememberPermissions(path, inspectPath(path, "directory"));
99
+ }
100
+ function retireLegacyDirectory(path) {
101
+ try {
102
+ windowsSecurity("retire", path, "directory");
103
+ } catch (cause) {
104
+ const code = cause.code;
105
+ if (code === "ENOENT" || code === "EBUSY") return;
106
+ throw new Error(`Cannot recover ${path}. Stop all TemPad MCP clients, rename the old directory, and restart. ${String(cause)}`, { cause });
94
107
  }
95
108
  }
96
109
  async function ensurePrivateDirectoryAsync(path) {
@@ -133,7 +146,7 @@ function securityCommand(action, path, kind) {
133
146
  "-NoProfile",
134
147
  "-NonInteractive",
135
148
  "-EncodedCommand",
136
- Buffer.from(SECURITY_SCRIPT, "utf16le").toString("base64")
149
+ Buffer.from(securityScript(action), "utf16le").toString("base64")
137
150
  ],
138
151
  options: {
139
152
  encoding: "utf8",
@@ -163,7 +176,7 @@ function windowsSecurity(action, path, kind) {
163
176
  ]
164
177
  });
165
178
  } catch (cause) {
166
- throw securityFailure(cause, path, kind);
179
+ throw securityFailure(cause, path, kind, action);
167
180
  }
168
181
  }
169
182
  async function windowsSecurityAsync(action, path, kind, signal) {
@@ -176,12 +189,12 @@ async function windowsSecurityAsync(action, path, kind, signal) {
176
189
  if (error) reject(securityFailure(Object.assign(error, {
177
190
  stdout,
178
191
  stderr
179
- }), path, kind));
192
+ }), path, kind, action));
180
193
  else resolve();
181
194
  }).stdin?.end();
182
195
  });
183
196
  }
184
- function securityFailure(cause, path, kind) {
197
+ function securityFailure(cause, path, kind, action) {
185
198
  const error = cause;
186
199
  const detail = [error.stdout, error.stderr].filter(Boolean).join("\n").trim();
187
200
  let code;
@@ -193,34 +206,57 @@ function securityFailure(cause, path, kind) {
193
206
  } catch {}
194
207
  const failure = new Error(`Refusing untrusted Windows runtime ${kind}: ${path}${detail ? ` (${detail})` : ""}`, { cause });
195
208
  if (code === 2 || code === 3) failure.code = "ENOENT";
196
- if (code === 231) failure.code = "EBUSY";
209
+ if (code === 231 || action === "retire" && code === 32) failure.code = "EBUSY";
197
210
  if (code === "EPIPEUNPROTECTED") failure.code = code;
211
+ if (kind === "directory" && code === "EINHERITEDACL") failure.code = code;
198
212
  if (!failure.code && kind === "pipe" && reportedFailure) failure.code = "EPIPEUNTRUSTED";
199
213
  return failure;
200
214
  }
201
- const SECURITY_SCRIPT = String.raw`
202
- $ErrorActionPreference = 'Stop'
203
- $ProgressPreference = 'SilentlyContinue'
204
- [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
205
- # Module autoload can stall with a filtered host environment. Use the trusted
206
- # built-in modules directly, without scanning host/user module locations.
207
- Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop
208
- Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" -ErrorAction Stop
209
- $PSModuleAutoloadingPreference = 'None'
210
- $failureCode = $null
211
- try {
212
- $request = $env:TEMPAD_RUNTIME_ACL_REQUEST | ConvertFrom-Json
213
- $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
214
- $allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544')
215
- if ($request.kind -eq 'pipe') {
216
- Add-Type -TypeDefinition @'
217
- using System;
218
- using System.ComponentModel;
219
- using System.Runtime.InteropServices;
220
- using Microsoft.Win32.SafeHandles;
221
- public static class TempadPipeSecurity {
215
+ const DIRECTORY_RECOVERY_METHODS = String.raw`
216
+ [DllImport("kernel32.dll", SetLastError=true)]
217
+ static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, byte[] info, uint size);
222
218
  [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
223
- static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
219
+ static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, System.Text.StringBuilder path, uint size, uint flags);
220
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
221
+ static extern uint GetLongPathName(string path, System.Text.StringBuilder expanded, uint size);
222
+ public static SafeFileHandle OpenLegacyDirectory(string path, bool retire) {
223
+ // FILE_READ_ATTRIBUTES, no share-delete, BACKUP_SEMANTICS | OPEN_REPARSE_POINT.
224
+ var handle = CreateFile(path, retire ? 0x10080u : 0x80u, 1, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
225
+ if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
226
+ try {
227
+ var final = new System.Text.StringBuilder(32768);
228
+ // Windows may supply an 8.3 profile name in TEMP. Expand only short names
229
+ // for the comparison; a junction still differs from the handle's final path.
230
+ var expanded = new System.Text.StringBuilder(32768);
231
+ uint length = GetLongPathName(path, expanded, (uint)expanded.Capacity);
232
+ uint count = GetFinalPathNameByHandle(handle, final, (uint)final.Capacity, 0);
233
+ if (length == 0 || length >= expanded.Capacity || count == 0 || count >= final.Capacity ||
234
+ !String.Equals(final.ToString(), @"\\?\" + expanded, StringComparison.OrdinalIgnoreCase) ||
235
+ (System.IO.File.GetAttributes(path) & (System.IO.FileAttributes.Directory | System.IO.FileAttributes.ReparsePoint)) != System.IO.FileAttributes.Directory)
236
+ throw new InvalidOperationException("Expected a canonical local runtime directory.");
237
+ return handle;
238
+ } catch { handle.Dispose(); throw; }
239
+ }
240
+ public static void Retire(SafeFileHandle handle, string path) {
241
+ foreach (string run in System.IO.Directory.GetFileSystemEntries(path, "run")) {
242
+ using (OpenLegacyDirectory(run, false)) {
243
+ foreach (string name in new[] { "hub.lock.lock", "mcp.lock.lock" }) {
244
+ if (System.IO.Directory.GetFileSystemEntries(run, name).Length != 0)
245
+ throw new InvalidOperationException("A runtime lock exists.");
246
+ }
247
+ }
248
+ }
249
+ // FILE_RENAME_INFO with ReplaceIfExists=false and RootDirectory=NULL.
250
+ byte[] nameBytes = System.Text.Encoding.Unicode.GetBytes(path + ".legacy");
251
+ int lengthOffset = 2 * IntPtr.Size;
252
+ byte[] info = new byte[lengthOffset + 4 + nameBytes.Length + 2];
253
+ BitConverter.GetBytes(nameBytes.Length).CopyTo(info, lengthOffset);
254
+ nameBytes.CopyTo(info, lengthOffset + 4);
255
+ if (!SetFileInformationByHandle(handle, 3, info, (uint)info.Length))
256
+ throw new Win32Exception(Marshal.GetLastWin32Error());
257
+ }
258
+ `;
259
+ const PIPE_SECURITY_METHODS = String.raw`
224
260
  [DllImport("advapi32.dll", SetLastError=true)]
225
261
  static extern uint GetSecurityInfo(SafeFileHandle handle, uint type, uint info, out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);
226
262
  [DllImport("advapi32.dll", SetLastError=true)]
@@ -261,25 +297,71 @@ public static class TempadPipeSecurity {
261
297
  } finally { LocalFree(descriptor); }
262
298
  }
263
299
  }
300
+ `;
301
+ function securityScript(action) {
302
+ return String.raw`
303
+ $ErrorActionPreference = 'Stop'
304
+ $ProgressPreference = 'SilentlyContinue'
305
+ [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
306
+ # Module autoload can stall with a filtered host environment. Use the trusted
307
+ # built-in modules directly, without scanning host/user module locations.
308
+ Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop
309
+ Import-Module "$PSHOME\Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1" -ErrorAction Stop
310
+ $PSModuleAutoloadingPreference = 'None'
311
+ $failureCode = $null
312
+ $legacy = $null
313
+ $compilerTemp = $null
314
+ function New-PrivateDirectory($path) {
315
+ $security = New-Object System.Security.AccessControl.DirectorySecurity
316
+ $security.SetOwner($user)
317
+ $security.SetAccessRuleProtection($true, $false)
318
+ foreach ($sid in $allowed) {
319
+ $principal = New-Object System.Security.Principal.SecurityIdentifier($sid)
320
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
321
+ $security.AddAccessRule($rule)
322
+ }
323
+ [void][IO.Directory]::CreateDirectory($path, $security)
324
+ }
325
+ try {
326
+ $request = $env:TEMPAD_RUNTIME_ACL_REQUEST | ConvertFrom-Json
327
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
328
+ $allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544')
329
+ if ($request.action -eq 'retire') {
330
+ # Windows PowerShell's Add-Type compiles via temporary files. Temp itself
331
+ # may be sandbox-writable in precisely the migration we are handling.
332
+ $local = [Environment]::GetFolderPath('LocalApplicationData')
333
+ if (![IO.Path]::IsPathRooted($local)) { throw 'Missing local application data directory.' }
334
+ $scratch = [IO.Path]::Combine($local, 'tempad-acl-' + [Guid]::NewGuid().ToString('N'))
335
+ New-PrivateDirectory $scratch
336
+ $compilerTemp = $scratch
337
+ $env:TMP = $env:TEMP = $scratch
338
+ }
339
+ if ($request.kind -eq 'pipe' -or $request.action -eq 'retire') {
340
+ Add-Type -TypeDefinition @'
341
+ using System;
342
+ using System.ComponentModel;
343
+ using System.Runtime.InteropServices;
344
+ using Microsoft.Win32.SafeHandles;
345
+ public static class TempadSecurity {
346
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
347
+ static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
348
+ ${action === "retire" ? DIRECTORY_RECOVERY_METHODS : PIPE_SECURITY_METHODS}
264
349
  }
265
350
  '@
351
+ }
352
+ if ($request.kind -eq 'pipe') {
266
353
  $sddl = $null
267
354
  if ($request.action -eq 'protect') {
268
355
  $sddl = 'D:P(D;;GA;;;NU)(A;;GA;;;' + $user.Value + ')(A;;GA;;;SY)(A;;GA;;;BA)'
269
356
  }
270
- $bytes = [TempadPipeSecurity]::Inspect($request.path, $sddl)
357
+ $bytes = [TempadSecurity]::Inspect($request.path, $sddl)
271
358
  $descriptor = New-Object System.Security.AccessControl.RawSecurityDescriptor($bytes, 0)
272
359
  } else {
360
+ if ($request.action -eq 'retire') {
361
+ $legacy = [TempadSecurity]::OpenLegacyDirectory($request.path, $true)
362
+ }
273
363
  if ($request.action -eq 'ensure' -and ![IO.Directory]::Exists($request.path)) {
274
- $security = New-Object System.Security.AccessControl.DirectorySecurity
275
- $security.SetOwner($user)
276
- $security.SetAccessRuleProtection($true, $false)
277
- foreach ($sid in $allowed) {
278
- $principal = New-Object System.Security.Principal.SecurityIdentifier($sid)
279
- $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
280
- $security.AddAccessRule($rule)
281
- }
282
- [void][IO.Directory]::CreateDirectory($request.path, $security)
364
+ New-PrivateDirectory $request.path
283
365
  }
284
366
  try {
285
367
  $acl = Get-Acl -LiteralPath $request.path
@@ -294,11 +376,13 @@ public static class TempadPipeSecurity {
294
376
  }
295
377
  $ownAccess = $false
296
378
  $foreignAccess = $false
379
+ $inheritedOnly = $request.kind -eq 'directory' -and $descriptor.Owner.Value -eq $user.Value -and !$acl.AreAccessRulesProtected
297
380
  $pendingProtection = $request.kind -eq 'pipe' -and $request.action -eq 'inspect'
298
381
  foreach ($ace in $descriptor.DiscretionaryAcl) {
299
382
  if ($ace.AceType -eq 'AccessAllowed') {
300
383
  if ($allowed -notcontains $ace.SecurityIdentifier.Value) {
301
384
  $foreignAccess = $true
385
+ if (!$ace.AceFlags.HasFlag([Security.AccessControl.AceFlags]::Inherited)) { $inheritedOnly = $false }
302
386
  # Windows' initial pipe descriptor can be owned by Administrators and omit
303
387
  # the user's ACE. Only its default reader grants are retryable, never trusted.
304
388
  $defaultReader = @('S-1-1-0', 'S-1-5-7') -contains $ace.SecurityIdentifier.Value
@@ -306,13 +390,22 @@ public static class TempadPipeSecurity {
306
390
  $pendingProtection = $pendingProtection -and $defaultReader -and $readOnly
307
391
  }
308
392
  if ($ace.SecurityIdentifier.Value -eq $user.Value) { $ownAccess = $true }
309
- } elseif ($ace.AceType -ne 'AccessDenied') {
393
+ } elseif ($ace.AceType -eq 'AccessDenied') {
394
+ $inheritedOnly = $false
395
+ } else {
310
396
  throw 'Unsupported ACL entry.'
311
397
  }
312
398
  }
313
399
  if ($foreignAccess -and $pendingProtection) { $failureCode = 'EPIPEUNPROTECTED' }
314
400
  if (!$ownAccess) { throw 'ACL does not explicitly grant the current user access.' }
315
401
  if ($foreignAccess) {
402
+ if ($inheritedOnly -and $request.action -eq 'retire') {
403
+ # Tightening the old DACL cannot revoke open handles or authenticate existing files.
404
+ # Leave the entire tree untouched and recreate the private root at the enrolled path.
405
+ [TempadSecurity]::Retire($legacy, $request.path)
406
+ return
407
+ }
408
+ if ($inheritedOnly) { $failureCode = 'EINHERITEDACL' }
316
409
  throw 'ACL grants another account access.'
317
410
  }
318
411
  } catch {
@@ -321,9 +414,15 @@ public static class TempadPipeSecurity {
321
414
  if (!$failureCode) { $failureCode = $failure.NativeErrorCode }
322
415
  [Console]::Error.WriteLine((@{ message = $failure.Message; code = $failureCode } | ConvertTo-Json -Compress))
323
416
  exit 1
417
+ } finally {
418
+ if ($null -ne $legacy) { $legacy.Dispose() }
419
+ if ($null -ne $compilerTemp) {
420
+ # A scanner can still hold compiler output. Never let scratch cleanup undo a completed rename.
421
+ try { [IO.Directory]::Delete($compilerTemp, $true) } catch [IO.IOException] {}
422
+ }
324
423
  }
325
424
  `;
326
- //#endregion
425
+ }
327
426
  export { createPrivateTempDirectory as a, isPipe as c, cleanupEndpoint as i, protectPipeAsync as l, assertPrivatePath as n, ensurePrivateDirectory as o, assertPrivatePathAsync as r, ensurePrivateDirectoryAsync as s, assertPrivateEndpointAsync as t, runtimeEndpoint as u };
328
427
 
329
- //# sourceMappingURL=runtime-platform-EULgJm_w.mjs.map
428
+ //# sourceMappingURL=runtime-platform-CpunJOI4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-platform-CpunJOI4.mjs","names":[],"sources":["../src/runtime-platform.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process'\nimport { createHash, randomUUID } from 'node:crypto'\nimport { lstatSync, mkdirSync, realpathSync, rmSync } from 'node:fs'\nimport { tmpdir, userInfo } from 'node:os'\nimport { isAbsolute, join, resolve } from 'node:path'\n\nconst PIPE_PREFIX = '\\\\\\\\.\\\\pipe\\\\'\nconst checkedPermissions = new Map<string, ReturnType<typeof inspectPath>>()\n\n/** Runtime overrides must isolate pipes as well as files, including on one Windows account. */\nexport function runtimeEndpoint(\n directory: string,\n name: string,\n platform: NodeJS.Platform = process.platform,\n user = userInfo().username\n) {\n if (platform !== 'win32') return join(directory, name)\n const identity = createHash('sha256')\n .update(user)\n .update('\\0')\n .update(directory.replaceAll('/', '\\\\').toLowerCase())\n .update('\\0')\n .update(name)\n .digest('hex')\n .slice(0, 32)\n return `${PIPE_PREFIX}tempad-runtime-${identity}`\n}\n\nexport function isPipe(path: string) {\n return path.startsWith(PIPE_PREFIX)\n}\n\nfunction canonical(path: string) {\n const actual = realpathSync(path)\n return process.platform === 'win32'\n ? actual.toLowerCase() === resolve(path).toLowerCase()\n : actual === path\n}\n\n/** Check real Windows ACLs; chmod and stat.mode do not establish Windows privacy. */\nfunction inspectPath(path: string, kind: 'file' | 'directory') {\n if (!isAbsolute(path)) throw new Error('Runtime path must be absolute.')\n const stat = lstatSync(path, { bigint: true })\n if (\n stat.isSymbolicLink() ||\n !(kind === 'file' ? stat.isFile() : stat.isDirectory()) ||\n !canonical(path) ||\n (process.platform !== 'win32' && (stat.uid !== BigInt(process.getuid!()) || stat.mode & 0o077n))\n )\n throw new Error(`Refusing untrusted runtime ${kind}: ${path}`)\n return {\n identity: `${stat.dev}:${stat.ino}:${stat.birthtimeNs}:${kind}`,\n revision: stat.ctimeNs\n }\n}\n\nfunction rememberPermissions(path: string, state: ReturnType<typeof inspectPath>) {\n if (checkedPermissions.size >= 1024) checkedPermissions.clear()\n checkedPermissions.set(path, state)\n}\n\nfunction uncheckedPath(path: string, kind: 'file' | 'directory') {\n const state = inspectPath(path, kind)\n if (process.platform !== 'win32') return\n const cached = checkedPermissions.get(path)\n if (cached?.identity === state.identity && cached.revision === state.revision) return\n checkedPermissions.delete(path)\n return state\n}\n\nfunction checkedPath(\n path: string,\n kind: 'file' | 'directory',\n state: ReturnType<typeof inspectPath>\n) {\n const next = inspectPath(path, kind)\n if (next.identity !== state.identity)\n throw Object.assign(new Error(`Runtime ${kind} changed during its permission check: ${path}`), {\n code: 'ERUNTIMEPATHCHANGED'\n })\n if (next.revision === state.revision) {\n rememberPermissions(path, next)\n return\n }\n return next\n}\n\nexport function assertPrivatePath(path: string, kind: 'file' | 'directory') {\n let state = uncheckedPath(path, kind)\n if (!state) return\n for (let attempt = 0; attempt < 2; attempt++) {\n windowsSecurity('inspect', path, kind)\n // ChangeTime covers ACL edits and ordinary child creation. Recheck once when it\n // changes, rejecting replacement but leaving an actively changing object uncached.\n state = checkedPath(path, kind, state)\n if (!state) return\n }\n}\n\n/** Serving processes must let control leases renew while Windows checks permissions. */\nexport async function assertPrivatePathAsync(path: string, kind: 'file' | 'directory') {\n let state = uncheckedPath(path, kind)\n if (!state) return\n for (let attempt = 0; attempt < 2; attempt++) {\n await windowsSecurityAsync('inspect', path, kind)\n state = checkedPath(path, kind, state)\n if (!state) return\n }\n}\n\nexport function ensurePrivateDirectory(path: string, { recoverLegacyRoot = false } = {}) {\n if (!isAbsolute(path)) throw new Error('Runtime directory must be absolute.')\n if (process.platform !== 'win32') {\n mkdirSync(path, { recursive: true, mode: 0o700 })\n assertPrivatePath(path, 'directory')\n return\n }\n try {\n assertPrivatePath(path, 'directory')\n return\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (recoverLegacyRoot && code === 'EINHERITEDACL') retireLegacyDirectory(path)\n else if (code !== 'ENOENT') throw error\n }\n windowsSecurity('ensure', path, 'directory')\n if (recoverLegacyRoot) assertPrivatePath(path, 'directory')\n else rememberPermissions(path, inspectPath(path, 'directory'))\n}\n\nfunction retireLegacyDirectory(path: string) {\n try {\n windowsSecurity('retire', path, 'directory')\n } catch (cause) {\n // Another launcher may already be replacing the root. Its successor still\n // has to pass ensurePrivateDirectory's independent ACL and identity checks.\n const code = (cause as NodeJS.ErrnoException).code\n if (code === 'ENOENT' || code === 'EBUSY') return\n throw new Error(\n `Cannot recover ${path}. Stop all TemPad MCP clients, rename the old directory, and restart. ${String(cause)}`,\n { cause }\n )\n }\n}\n\nexport async function ensurePrivateDirectoryAsync(path: string) {\n if (process.platform !== 'win32') return ensurePrivateDirectory(path)\n try {\n await assertPrivatePathAsync(path, 'directory')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await windowsSecurityAsync('ensure', path, 'directory')\n rememberPermissions(path, inspectPath(path, 'directory'))\n }\n}\n\nexport function createPrivateTempDirectory(prefix: string) {\n // macOS's per-user temp path leaves too little room for Unix socket names.\n const directory = process.platform === 'win32' ? tmpdir() : '/tmp'\n const path = join(realpathSync(directory), `${prefix}${randomUUID()}`)\n ensurePrivateDirectory(path)\n return path\n}\n\nexport function cleanupEndpoint(path: string) {\n if (!isPipe(path)) rmSync(path, { force: true })\n}\n\nexport function assertPrivateEndpoint(path: string) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n windowsSecurity('inspect', path, 'pipe')\n}\n\nexport function protectPipe(path: string) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n windowsSecurity('protect', path, 'pipe')\n}\n\nexport async function assertPrivateEndpointAsync(path: string, signal?: AbortSignal) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n await windowsSecurityAsync('inspect', path, 'pipe', signal)\n}\n\nexport async function protectPipeAsync(path: string, signal?: AbortSignal) {\n if (!isPipe(path)) throw new Error('Expected a Windows runtime pipe.')\n await windowsSecurityAsync('protect', path, 'pipe', signal)\n}\n\nexport function windowsPowerShellEnvironment(env: NodeJS.ProcessEnv = process.env) {\n // PowerShell 7's module paths can load incompatible modules in Windows PowerShell 5.\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => key.toLowerCase() !== 'psmodulepath')\n )\n}\n\n// Built-in Windows PowerShell supplies the platform ACL API without an npm/native dependency.\n// JSON stays in a child-only environment value, never executable source or shell arguments.\n// Helper input is independent of host stdio and the Windows console's input code page.\ntype SecurityAction = 'ensure' | 'inspect' | 'protect' | 'retire'\n\nfunction securityCommand(action: SecurityAction, path: string, kind: string) {\n const systemRoot = process.env.SystemRoot\n if (!systemRoot || !isAbsolute(systemRoot))\n throw new Error('Windows SystemRoot is required to verify private runtime storage.')\n return {\n file: join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),\n args: [\n '-NoLogo',\n '-NoProfile',\n '-NonInteractive',\n '-EncodedCommand',\n Buffer.from(securityScript(action), 'utf16le').toString('base64')\n ],\n options: {\n encoding: 'utf8' as const,\n timeout: 15_000,\n maxBuffer: 64 * 1024,\n windowsHide: true,\n env: {\n ...windowsPowerShellEnvironment(),\n TEMPAD_RUNTIME_ACL_REQUEST: JSON.stringify({ action, path, kind })\n }\n }\n }\n}\n\nfunction windowsSecurity(action: SecurityAction, path: string, kind: string) {\n const { file, args, options } = securityCommand(action, path, kind)\n try {\n execFileSync(file, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] })\n } catch (cause) {\n throw securityFailure(cause, path, kind, action)\n }\n}\n\nasync function windowsSecurityAsync(\n action: 'ensure' | 'inspect' | 'protect',\n path: string,\n kind: string,\n signal?: AbortSignal\n) {\n const { file, args, options } = securityCommand(action, path, kind)\n await new Promise<void>((resolve, reject) => {\n const child = execFile(file, args, { ...options, signal }, (error, stdout, stderr) => {\n if (error)\n reject(securityFailure(Object.assign(error, { stdout, stderr }), path, kind, action))\n else resolve()\n })\n child.stdin?.end()\n })\n}\n\nfunction securityFailure(cause: unknown, path: string, kind: string, action: SecurityAction) {\n const error = cause as { stdout?: string; stderr?: string }\n const detail = [error.stdout, error.stderr].filter(Boolean).join('\\n').trim()\n let code: number | string | undefined\n let reportedFailure = false\n try {\n const report = JSON.parse(error.stderr ?? '{}')\n code = report.code\n reportedFailure = typeof report.message === 'string'\n } catch {\n // Startup and policy failures need not be JSON; they still fail closed.\n }\n const failure = new Error(\n `Refusing untrusted Windows runtime ${kind}: ${path}${detail ? ` (${detail})` : ''}`,\n {\n cause\n }\n ) as NodeJS.ErrnoException\n if (code === 2 || code === 3) failure.code = 'ENOENT'\n if (code === 231 || (action === 'retire' && code === 32)) failure.code = 'EBUSY'\n if (code === 'EPIPEUNPROTECTED') failure.code = code\n if (kind === 'directory' && code === 'EINHERITEDACL') failure.code = code\n if (!failure.code && kind === 'pipe' && reportedFailure) failure.code = 'EPIPEUNTRUSTED'\n return failure\n}\n\nconst DIRECTORY_RECOVERY_METHODS = String.raw`\n [DllImport(\"kernel32.dll\", SetLastError=true)]\n static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, byte[] info, uint size);\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern uint GetFinalPathNameByHandle(SafeFileHandle handle, System.Text.StringBuilder path, uint size, uint flags);\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern uint GetLongPathName(string path, System.Text.StringBuilder expanded, uint size);\n public static SafeFileHandle OpenLegacyDirectory(string path, bool retire) {\n // FILE_READ_ATTRIBUTES, no share-delete, BACKUP_SEMANTICS | OPEN_REPARSE_POINT.\n var handle = CreateFile(path, retire ? 0x10080u : 0x80u, 1, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);\n if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());\n try {\n var final = new System.Text.StringBuilder(32768);\n // Windows may supply an 8.3 profile name in TEMP. Expand only short names\n // for the comparison; a junction still differs from the handle's final path.\n var expanded = new System.Text.StringBuilder(32768);\n uint length = GetLongPathName(path, expanded, (uint)expanded.Capacity);\n uint count = GetFinalPathNameByHandle(handle, final, (uint)final.Capacity, 0);\n if (length == 0 || length >= expanded.Capacity || count == 0 || count >= final.Capacity ||\n !String.Equals(final.ToString(), @\"\\\\?\\\" + expanded, StringComparison.OrdinalIgnoreCase) ||\n (System.IO.File.GetAttributes(path) & (System.IO.FileAttributes.Directory | System.IO.FileAttributes.ReparsePoint)) != System.IO.FileAttributes.Directory)\n throw new InvalidOperationException(\"Expected a canonical local runtime directory.\");\n return handle;\n } catch { handle.Dispose(); throw; }\n }\n public static void Retire(SafeFileHandle handle, string path) {\n foreach (string run in System.IO.Directory.GetFileSystemEntries(path, \"run\")) {\n using (OpenLegacyDirectory(run, false)) {\n foreach (string name in new[] { \"hub.lock.lock\", \"mcp.lock.lock\" }) {\n if (System.IO.Directory.GetFileSystemEntries(run, name).Length != 0)\n throw new InvalidOperationException(\"A runtime lock exists.\");\n }\n }\n }\n // FILE_RENAME_INFO with ReplaceIfExists=false and RootDirectory=NULL.\n byte[] nameBytes = System.Text.Encoding.Unicode.GetBytes(path + \".legacy\");\n int lengthOffset = 2 * IntPtr.Size;\n byte[] info = new byte[lengthOffset + 4 + nameBytes.Length + 2];\n BitConverter.GetBytes(nameBytes.Length).CopyTo(info, lengthOffset);\n nameBytes.CopyTo(info, lengthOffset + 4);\n if (!SetFileInformationByHandle(handle, 3, info, (uint)info.Length))\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n`\n\nconst PIPE_SECURITY_METHODS = String.raw`\n [DllImport(\"advapi32.dll\", SetLastError=true)]\n static extern uint GetSecurityInfo(SafeFileHandle handle, uint type, uint info, out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);\n [DllImport(\"advapi32.dll\", SetLastError=true)]\n static extern uint SetSecurityInfo(SafeFileHandle handle, uint type, uint info, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl);\n [DllImport(\"advapi32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string value, uint revision, out IntPtr descriptor, out uint length);\n [DllImport(\"advapi32.dll\", SetLastError=true)]\n static extern bool GetSecurityDescriptorDacl(IntPtr descriptor, out bool present, out IntPtr dacl, out bool defaulted);\n [DllImport(\"advapi32.dll\")]\n static extern uint GetSecurityDescriptorLength(IntPtr descriptor);\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr LocalFree(IntPtr memory);\n public static byte[] Inspect(string path, string sddl) {\n // PowerShell converts a null string argument to an empty string.\n bool protect = !String.IsNullOrEmpty(sddl);\n SafeFileHandle opened = CreateFile(path, 0x20000u | (protect ? 0x40000u : 0u), 7, IntPtr.Zero, 3, 0x40000000, IntPtr.Zero);\n int openError = Marshal.GetLastWin32Error();\n using (SafeFileHandle handle = opened) {\n if (handle.IsInvalid) throw new Win32Exception(openError, \"CreateFile failed for the runtime pipe.\");\n if (protect) {\n IntPtr replacement; uint length;\n if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, out replacement, out length)) throw new Win32Exception(Marshal.GetLastWin32Error(), \"ConvertStringSecurityDescriptorToSecurityDescriptor failed.\");\n try {\n bool present, defaulted; IntPtr acl;\n if (!GetSecurityDescriptorDacl(replacement, out present, out acl, out defaulted)) throw new Win32Exception(Marshal.GetLastWin32Error(), \"GetSecurityDescriptorDacl failed.\");\n if (!present || acl == IntPtr.Zero) throw new InvalidOperationException(\"The replacement pipe descriptor has no discretionary ACL.\");\n uint changed = SetSecurityInfo(handle, 6, 4u | 0x80000000u, IntPtr.Zero, IntPtr.Zero, acl, IntPtr.Zero);\n if (changed != 0) throw new Win32Exception((int)changed, \"SetSecurityInfo failed for the runtime pipe.\");\n } finally { LocalFree(replacement); }\n }\n IntPtr owner, group, dacl, sacl, descriptor;\n uint result = GetSecurityInfo(handle, 6, 5, out owner, out group, out dacl, out sacl, out descriptor);\n if (result != 0) throw new Win32Exception((int)result, \"GetSecurityInfo failed for the runtime pipe.\");\n try {\n byte[] bytes = new byte[GetSecurityDescriptorLength(descriptor)];\n Marshal.Copy(descriptor, bytes, 0, bytes.Length);\n return bytes;\n } finally { LocalFree(descriptor); }\n }\n }\n`\n\nfunction securityScript(action: SecurityAction) {\n return String.raw`\n$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)\n# Module autoload can stall with a filtered host environment. Use the trusted\n# built-in modules directly, without scanning host/user module locations.\nImport-Module \"$PSHOME\\Modules\\Microsoft.PowerShell.Utility\\Microsoft.PowerShell.Utility.psd1\" -ErrorAction Stop\nImport-Module \"$PSHOME\\Modules\\Microsoft.PowerShell.Security\\Microsoft.PowerShell.Security.psd1\" -ErrorAction Stop\n$PSModuleAutoloadingPreference = 'None'\n$failureCode = $null\n$legacy = $null\n$compilerTemp = $null\nfunction New-PrivateDirectory($path) {\n $security = New-Object System.Security.AccessControl.DirectorySecurity\n $security.SetOwner($user)\n $security.SetAccessRuleProtection($true, $false)\n foreach ($sid in $allowed) {\n $principal = New-Object System.Security.Principal.SecurityIdentifier($sid)\n $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($principal, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')\n $security.AddAccessRule($rule)\n }\n [void][IO.Directory]::CreateDirectory($path, $security)\n}\ntry {\n $request = $env:TEMPAD_RUNTIME_ACL_REQUEST | ConvertFrom-Json\n $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User\n $allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544')\n if ($request.action -eq 'retire') {\n # Windows PowerShell's Add-Type compiles via temporary files. Temp itself\n # may be sandbox-writable in precisely the migration we are handling.\n $local = [Environment]::GetFolderPath('LocalApplicationData')\n if (![IO.Path]::IsPathRooted($local)) { throw 'Missing local application data directory.' }\n $scratch = [IO.Path]::Combine($local, 'tempad-acl-' + [Guid]::NewGuid().ToString('N'))\n New-PrivateDirectory $scratch\n $compilerTemp = $scratch\n $env:TMP = $env:TEMP = $scratch\n }\n if ($request.kind -eq 'pipe' -or $request.action -eq 'retire') {\n Add-Type -TypeDefinition @'\nusing System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing Microsoft.Win32.SafeHandles;\npublic static class TempadSecurity {\n [DllImport(\"kernel32.dll\", CharSet=CharSet.Unicode, SetLastError=true)]\n static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);\n${action === 'retire' ? DIRECTORY_RECOVERY_METHODS : PIPE_SECURITY_METHODS}\n}\n'@\n }\n if ($request.kind -eq 'pipe') {\n $sddl = $null\n if ($request.action -eq 'protect') {\n $sddl = 'D:P(D;;GA;;;NU)(A;;GA;;;' + $user.Value + ')(A;;GA;;;SY)(A;;GA;;;BA)'\n }\n $bytes = [TempadSecurity]::Inspect($request.path, $sddl)\n $descriptor = New-Object System.Security.AccessControl.RawSecurityDescriptor($bytes, 0)\n } else {\n if ($request.action -eq 'retire') {\n $legacy = [TempadSecurity]::OpenLegacyDirectory($request.path, $true)\n }\n if ($request.action -eq 'ensure' -and ![IO.Directory]::Exists($request.path)) {\n New-PrivateDirectory $request.path\n }\n try {\n $acl = Get-Acl -LiteralPath $request.path\n } catch [System.Management.Automation.ItemNotFoundException], [IO.FileNotFoundException], [IO.DirectoryNotFoundException] {\n $failureCode = 2\n throw\n }\n $descriptor = New-Object System.Security.AccessControl.RawSecurityDescriptor($acl.Sddl)\n }\n if ($allowed -notcontains $descriptor.Owner.Value -or $null -eq $descriptor.DiscretionaryAcl) {\n throw 'Unexpected owner or absent discretionary ACL.'\n }\n $ownAccess = $false\n $foreignAccess = $false\n $inheritedOnly = $request.kind -eq 'directory' -and $descriptor.Owner.Value -eq $user.Value -and !$acl.AreAccessRulesProtected\n $pendingProtection = $request.kind -eq 'pipe' -and $request.action -eq 'inspect'\n foreach ($ace in $descriptor.DiscretionaryAcl) {\n if ($ace.AceType -eq 'AccessAllowed') {\n if ($allowed -notcontains $ace.SecurityIdentifier.Value) {\n $foreignAccess = $true\n if (!$ace.AceFlags.HasFlag([Security.AccessControl.AceFlags]::Inherited)) { $inheritedOnly = $false }\n # Windows' initial pipe descriptor can be owned by Administrators and omit\n # the user's ACE. Only its default reader grants are retryable, never trusted.\n $defaultReader = @('S-1-1-0', 'S-1-5-7') -contains $ace.SecurityIdentifier.Value\n $readOnly = ($ace.AccessMask -band 0x7fedff76) -eq 0\n $pendingProtection = $pendingProtection -and $defaultReader -and $readOnly\n }\n if ($ace.SecurityIdentifier.Value -eq $user.Value) { $ownAccess = $true }\n } elseif ($ace.AceType -eq 'AccessDenied') {\n $inheritedOnly = $false\n } else {\n throw 'Unsupported ACL entry.'\n }\n }\n if ($foreignAccess -and $pendingProtection) { $failureCode = 'EPIPEUNPROTECTED' }\n if (!$ownAccess) { throw 'ACL does not explicitly grant the current user access.' }\n if ($foreignAccess) {\n if ($inheritedOnly -and $request.action -eq 'retire') {\n # Tightening the old DACL cannot revoke open handles or authenticate existing files.\n # Leave the entire tree untouched and recreate the private root at the enrolled path.\n [TempadSecurity]::Retire($legacy, $request.path)\n return\n }\n if ($inheritedOnly) { $failureCode = 'EINHERITEDACL' }\n throw 'ACL grants another account access.'\n }\n} catch {\n $failure = $_.Exception\n while ($failure.InnerException) { $failure = $failure.InnerException }\n if (!$failureCode) { $failureCode = $failure.NativeErrorCode }\n [Console]::Error.WriteLine((@{ message = $failure.Message; code = $failureCode } | ConvertTo-Json -Compress))\n exit 1\n} finally {\n if ($null -ne $legacy) { $legacy.Dispose() }\n if ($null -ne $compilerTemp) {\n # A scanner can still hold compiler output. Never let scratch cleanup undo a completed rename.\n try { [IO.Directory]::Delete($compilerTemp, $true) } catch [IO.IOException] {}\n }\n}\n`\n}\n"],"mappings":";;;;;;;;;;;;AAMA,MAAM,cAAc;AACpB,MAAM,qCAAqB,IAAI,IAA4C;;AAG3E,SAAgB,gBACd,WACA,MACA,WAA4B,QAAQ,UACpC,OAAO,SAAS,CAAC,CAAC,UAClB;CACA,IAAI,aAAa,SAAS,OAAO,KAAK,WAAW,IAAI;CACrD,MAAM,WAAW,WAAW,QAAQ,CAAC,CAClC,OAAO,IAAI,CAAC,CACZ,OAAO,IAAI,CAAC,CACZ,OAAO,UAAU,WAAW,KAAK,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,CACrD,OAAO,IAAI,CAAC,CACZ,OAAO,IAAI,CAAC,CACZ,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;CACd,OAAO,GAAG,YAAY,iBAAiB;AACzC;AAEA,SAAgB,OAAO,MAAc;CACnC,OAAO,KAAK,WAAW,WAAW;AACpC;AAEA,SAAS,UAAU,MAAc;CAC/B,MAAM,SAAS,aAAa,IAAI;CAChC,OAAO,QAAQ,aAAa,UACxB,OAAO,YAAY,MAAM,QAAQ,IAAI,CAAC,CAAC,YAAY,IACnD,WAAW;AACjB;;AAGA,SAAS,YAAY,MAAc,MAA4B;CAC7D,IAAI,CAAC,WAAW,IAAI,GAAG,MAAM,IAAI,MA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,OAAO,KAAK,MAChF,EACE,MACF,CACF;CACA,IAAI,SAAS,KAAK,SAAS,GAAG,QAAQ,OAAO;CAC7C,IAAI,SAAS,OAAQ,WAAW,YAAY,SAAS,IAAK,QAAQ,OAAO;CACzE,IAAI,SAAS,oBAAoB,QAAQ,OAAO;CAChD,IAAI,SAAS,eAAe,SAAS,iBAAiB,QAAQ,OAAO;CACrE,IAAI,CAAC,QAAQ,QAAQ,SAAS,UAAU,iBAAiB,QAAQ,OAAO;CACxE,OAAO;AACT;AAEA,MAAM,6BAA6B,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C7C,MAAM,wBAAwB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CxC,SAAS,eAAe,QAAwB;CAC9C,OAAO,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8CjB,WAAW,WAAW,6BAA6B,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6E3E"}
@@ -4,4 +4,4 @@ globalThis.__bundlerPathsOverrides = {
4
4
  'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
5
5
  'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
6
6
  };
7
- export { r as runRuntimeRecovery } from "./runtime-recovery-DpqftTl9.mjs";
7
+ export { r as runRuntimeRecovery } from "./runtime-recovery-DaRaQ8qY.mjs";
@@ -4,12 +4,12 @@ globalThis.__bundlerPathsOverrides = {
4
4
  'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
5
5
  'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
6
6
  };
7
- import { S as uuid, d as literal, m as object, o as array, p as number, v as string } from "./schemas-BgOH6OcJ.mjs";
8
- import { tn as ResultSchema } from "./types-gJ5HkL66.mjs";
9
- import { f as SocketTransport, n as ControlPeer } from "./protocol-DNswG6F2.mjs";
7
+ import { S as uuid, d as literal, m as object, o as array, p as number, v as string } from "./schemas-ZDdPV7RQ.mjs";
8
+ import { tn as ResultSchema } from "./types-kNTSQOnR.mjs";
9
+ import { f as SocketTransport, n as ControlPeer } from "./protocol-7m-E_iFu.mjs";
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { createInterface } from "node:readline/promises";
12
- //#region src/runtime-recovery.ts
12
+ // src/runtime-recovery.ts
13
13
  const BlockSchema = object({
14
14
  id: string(),
15
15
  revision: uuid(),
@@ -120,7 +120,6 @@ async function runRuntimeRecovery(args, connect, io = {
120
120
  await peer.close();
121
121
  }
122
122
  }
123
- //#endregion
124
123
  export { attachRuntimeRecovery as n, runRuntimeRecovery as r, RECOVERY_METHODS as t };
125
124
 
126
- //# sourceMappingURL=runtime-recovery-DpqftTl9.mjs.map
125
+ //# sourceMappingURL=runtime-recovery-DaRaQ8qY.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-recovery-DpqftTl9.mjs","names":["z.object","z.string","z.uuid","z.number","z.array","z.literal"],"sources":["../src/runtime-recovery.ts"],"sourcesContent":["import type { Socket } from 'node:net'\n\nimport { ResultSchema } from '@modelcontextprotocol/sdk/types.js'\nimport { randomUUID } from 'node:crypto'\nimport { createInterface } from 'node:readline/promises'\nimport { z } from 'zod'\n\nimport type { TerminalReceipts } from './terminal-receipts'\n\nimport { ControlPeer, SocketTransport } from './runtime-prototype/protocol'\n\nconst BlockSchema = z.object({\n id: z.string(),\n revision: z.uuid(),\n fileKey: z.string(),\n browserId: z.string(),\n tabId: z.number().optional(),\n documentId: z.string().optional(),\n recordedAt: z.number()\n})\nconst StatusSchema = ResultSchema.extend({ blocks: z.array(BlockSchema) })\nconst PreparedSchema = ResultSchema.extend({ block: BlockSchema, challenge: z.uuid() })\nexport const RECOVERY_METHODS = ['tempad/runtime-status', 'tempad/runtime-prepare-resolution']\n\n/** Private same-user socket only; never registered in the MCP tool catalog. */\nexport async function attachRuntimeRecovery(\n socket: Socket,\n receipts: TerminalReceipts,\n resolved: (record: NonNullable<ReturnType<TerminalReceipts['abandon']>>) => void\n) {\n const peer = new ControlPeer()\n let confirmation: { id: string; revision: string; challenge: string; expires: number } | undefined\n const timeout = setTimeout(() => void peer.close(), 120_000)\n timeout.unref()\n peer.onclose = () => {\n clearTimeout(timeout)\n confirmation = undefined\n }\n peer.onerror = () => void peer.close()\n peer.setRequestHandler(z.object({ method: z.literal('tempad/runtime-status') }), () => ({\n blocks: receipts.status()\n }))\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-prepare-resolution'),\n params: z.object({ id: z.string() }).strict()\n }),\n ({ params }) => {\n const block = receipts.status().find((record) => record.id === params.id)\n if (!block)\n throw new Error('No unresolved execution with this ID. Inspect --runtime-status again.')\n confirmation = {\n id: block.id,\n revision: block.revision,\n challenge: randomUUID(),\n expires: performance.now() + 120_000\n }\n return { block, challenge: confirmation.challenge }\n }\n )\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-resolve-block'),\n params: z.object({ challenge: z.uuid(), stopped: z.literal(true) }).strict()\n }),\n ({ params }) => {\n const selected = confirmation\n confirmation = undefined\n if (\n !selected ||\n selected.challenge !== params.challenge ||\n performance.now() >= selected.expires\n )\n throw new Error('Recovery confirmation expired or was already used.')\n const record = receipts.abandon(selected.id, selected.revision)\n if (record) resolved(record)\n return { resolved: selected.id, readRequired: true }\n }\n )\n await peer.connect(new SocketTransport(socket))\n return peer\n}\n\nexport async function runRuntimeRecovery(\n args: string[],\n connect: () => Promise<Socket>,\n io = {\n interactive: !!process.stdin.isTTY && !!process.stdout.isTTY,\n write: (value: string) => process.stdout.write(value),\n confirm: async (prompt: string) => {\n const terminal = createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await terminal.question(prompt)\n } finally {\n terminal.close()\n }\n }\n }\n): Promise<void> {\n const status = args.length === 1 && args[0] === '--runtime-status'\n const id = args.length === 2 && args[0] === '--resolve-runtime-block' ? args[1] : undefined\n if (!status && !id) throw new Error('Use --runtime-status or --resolve-runtime-block <block-id>.')\n if (id && !io.interactive)\n throw new Error(\n 'Runtime recovery requires an interactive terminal and confirmation that the original execution environment has stopped.'\n )\n const peer = new ControlPeer()\n peer.onerror = () => void peer.close()\n try {\n await peer.connect(new SocketTransport(await connect()))\n if (status) {\n const result = await peer.request({ method: 'tempad/runtime-status' }, StatusSchema)\n io.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n const prepared = await peer.request(\n { method: 'tempad/runtime-prepare-resolution', params: { id } },\n PreparedSchema\n )\n io.write(JSON.stringify(prepared.block, null, 2) + '\\n')\n const answer = await io.confirm(\n 'This cannot stop remote code. Close the original Figma page/browser first. Type the exact block ID to attest that its execution environment has stopped: '\n )\n if (answer !== id) throw new Error('Recovery cancelled; execution remains blocked.')\n await peer.request(\n {\n method: 'tempad/runtime-resolve-block',\n params: { challenge: prepared.challenge, stopped: true }\n },\n ResultSchema\n )\n io.write(\n 'Execution retired. Stop fences remain; explicitly resume an eligible task and reread the original target before writing.\\n'\n )\n } finally {\n await peer.close()\n }\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,cAAcA,OAAS;CAC3B,IAAIC,OAAS;CACb,UAAUC,KAAO;CACjB,SAASD,OAAS;CAClB,WAAWA,OAAS;CACpB,OAAOE,OAAS,CAAC,CAAC,SAAS;CAC3B,YAAYF,OAAS,CAAC,CAAC,SAAS;CAChC,YAAYE,OAAS;AACvB,CAAC;AACD,MAAM,eAAe,aAAa,OAAO,EAAE,QAAQC,MAAQ,WAAW,EAAE,CAAC;AACzE,MAAM,iBAAiB,aAAa,OAAO;CAAE,OAAO;CAAa,WAAWF,KAAO;AAAE,CAAC;AACtF,MAAa,mBAAmB,CAAC,yBAAyB,mCAAmC;;AAG7F,eAAsB,sBACpB,QACA,UACA,UACA;CACA,MAAM,OAAO,IAAI,YAAY;CAC7B,IAAI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EACzD,GACA,YACF;EACA,GAAG,MACD,4HACF;CACF,UAAU;EACR,MAAM,KAAK,MAAM;CACnB;AACF"}
1
+ {"version":3,"file":"runtime-recovery-DaRaQ8qY.mjs","names":["z.object","z.string","z.uuid","z.number","z.array","z.literal"],"sources":["../src/runtime-recovery.ts"],"sourcesContent":["import type { Socket } from 'node:net'\n\nimport { ResultSchema } from '@modelcontextprotocol/sdk/types.js'\nimport { randomUUID } from 'node:crypto'\nimport { createInterface } from 'node:readline/promises'\nimport { z } from 'zod'\n\nimport type { TerminalReceipts } from './terminal-receipts'\n\nimport { ControlPeer, SocketTransport } from './runtime-prototype/protocol'\n\nconst BlockSchema = z.object({\n id: z.string(),\n revision: z.uuid(),\n fileKey: z.string(),\n browserId: z.string(),\n tabId: z.number().optional(),\n documentId: z.string().optional(),\n recordedAt: z.number()\n})\nconst StatusSchema = ResultSchema.extend({ blocks: z.array(BlockSchema) })\nconst PreparedSchema = ResultSchema.extend({ block: BlockSchema, challenge: z.uuid() })\nexport const RECOVERY_METHODS = ['tempad/runtime-status', 'tempad/runtime-prepare-resolution']\n\n/** Private same-user socket only; never registered in the MCP tool catalog. */\nexport async function attachRuntimeRecovery(\n socket: Socket,\n receipts: TerminalReceipts,\n resolved: (record: NonNullable<ReturnType<TerminalReceipts['abandon']>>) => void\n) {\n const peer = new ControlPeer()\n let confirmation: { id: string; revision: string; challenge: string; expires: number } | undefined\n const timeout = setTimeout(() => void peer.close(), 120_000)\n timeout.unref()\n peer.onclose = () => {\n clearTimeout(timeout)\n confirmation = undefined\n }\n peer.onerror = () => void peer.close()\n peer.setRequestHandler(z.object({ method: z.literal('tempad/runtime-status') }), () => ({\n blocks: receipts.status()\n }))\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-prepare-resolution'),\n params: z.object({ id: z.string() }).strict()\n }),\n ({ params }) => {\n const block = receipts.status().find((record) => record.id === params.id)\n if (!block)\n throw new Error('No unresolved execution with this ID. Inspect --runtime-status again.')\n confirmation = {\n id: block.id,\n revision: block.revision,\n challenge: randomUUID(),\n expires: performance.now() + 120_000\n }\n return { block, challenge: confirmation.challenge }\n }\n )\n peer.setRequestHandler(\n z.object({\n method: z.literal('tempad/runtime-resolve-block'),\n params: z.object({ challenge: z.uuid(), stopped: z.literal(true) }).strict()\n }),\n ({ params }) => {\n const selected = confirmation\n confirmation = undefined\n if (\n !selected ||\n selected.challenge !== params.challenge ||\n performance.now() >= selected.expires\n )\n throw new Error('Recovery confirmation expired or was already used.')\n const record = receipts.abandon(selected.id, selected.revision)\n if (record) resolved(record)\n return { resolved: selected.id, readRequired: true }\n }\n )\n await peer.connect(new SocketTransport(socket))\n return peer\n}\n\nexport async function runRuntimeRecovery(\n args: string[],\n connect: () => Promise<Socket>,\n io = {\n interactive: !!process.stdin.isTTY && !!process.stdout.isTTY,\n write: (value: string) => process.stdout.write(value),\n confirm: async (prompt: string) => {\n const terminal = createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await terminal.question(prompt)\n } finally {\n terminal.close()\n }\n }\n }\n): Promise<void> {\n const status = args.length === 1 && args[0] === '--runtime-status'\n const id = args.length === 2 && args[0] === '--resolve-runtime-block' ? args[1] : undefined\n if (!status && !id) throw new Error('Use --runtime-status or --resolve-runtime-block <block-id>.')\n if (id && !io.interactive)\n throw new Error(\n 'Runtime recovery requires an interactive terminal and confirmation that the original execution environment has stopped.'\n )\n const peer = new ControlPeer()\n peer.onerror = () => void peer.close()\n try {\n await peer.connect(new SocketTransport(await connect()))\n if (status) {\n const result = await peer.request({ method: 'tempad/runtime-status' }, StatusSchema)\n io.write(JSON.stringify(result, null, 2) + '\\n')\n return\n }\n const prepared = await peer.request(\n { method: 'tempad/runtime-prepare-resolution', params: { id } },\n PreparedSchema\n )\n io.write(JSON.stringify(prepared.block, null, 2) + '\\n')\n const answer = await io.confirm(\n 'This cannot stop remote code. Close the original Figma page/browser first. Type the exact block ID to attest that its execution environment has stopped: '\n )\n if (answer !== id) throw new Error('Recovery cancelled; execution remains blocked.')\n await peer.request(\n {\n method: 'tempad/runtime-resolve-block',\n params: { challenge: prepared.challenge, stopped: true }\n },\n ResultSchema\n )\n io.write(\n 'Execution retired. Stop fences remain; explicitly resume an eligible task and reread the original target before writing.\\n'\n )\n } finally {\n await peer.close()\n }\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,cAAcA,OAAS;CAC3B,IAAIC,OAAS;CACb,UAAUC,KAAO;CACjB,SAASD,OAAS;CAClB,WAAWA,OAAS;CACpB,OAAOE,OAAS,CAAC,CAAC,SAAS;CAC3B,YAAYF,OAAS,CAAC,CAAC,SAAS;CAChC,YAAYE,OAAS;AACvB,CAAC;AACD,MAAM,eAAe,aAAa,OAAO,EAAE,QAAQC,MAAQ,WAAW,EAAE,CAAC;AACzE,MAAM,iBAAiB,aAAa,OAAO;CAAE,OAAO;CAAa,WAAWF,KAAO;AAAE,CAAC;AACtF,MAAa,mBAAmB,CAAC,yBAAyB,mCAAmC;;AAG7F,eAAsB,sBACpB,QACA,UACA,UACA;CACA,MAAM,OAAO,IAAI,YAAY;CAC7B,IAAI;CACJ,MAAM,UAAU,iBAAiB,KAAK,KAAK,MAAM,GAAG,IAAO;CAC3D,QAAQ,MAAM;CACd,KAAK,gBAAgB;EACnB,aAAa,OAAO;EACpB,eAAe,KAAA;CACjB;CACA,KAAK,gBAAgB,KAAK,KAAK,MAAM;CACrC,KAAK,kBAAkBF,OAAS,EAAE,QAAQK,QAAU,uBAAuB,EAAE,CAAC,UAAU,EACtF,QAAQ,SAAS,OAAO,EAC1B,EAAE;CACF,KAAK,kBACHL,OAAS;EACP,QAAQK,QAAU,mCAAmC;EACrD,QAAQL,OAAS,EAAE,IAAIC,OAAS,EAAE,CAAC,CAAC,CAAC,OAAO;CAC9C,CAAC,IACA,EAAE,aAAa;EACd,MAAM,QAAQ,SAAS,OAAO,CAAC,CAAC,MAAM,WAAW,OAAO,OAAO,OAAO,EAAE;EACxE,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,uEA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MAAM,CAAC,GAAG,aACZ,MAAM,IAAI,MACR,yHACF;CACF,MAAM,OAAO,IAAI,YAAY;CAC7B,KAAK,gBAAgB,KAAK,KAAK,MAAM;CACrC,IAAI;EACF,MAAM,KAAK,QAAQ,IAAI,gBAAgB,MAAM,QAAQ,CAAC,CAAC;EACvD,IAAI,QAAQ;GACV,MAAM,SAAS,MAAM,KAAK,QAAQ,EAAE,QAAQ,wBAAwB,GAAG,YAAY;GACnF,GAAG,MAAM,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,IAAI;GAC/C;EACF;EACA,MAAM,WAAW,MAAM,KAAK,QAC1B;GAAE,QAAQ;GAAqC,QAAQ,EAAE,GAAG;EAAE,GAC9D,cACF;EACA,GAAG,MAAM,KAAK,UAAU,SAAS,OAAO,MAAM,CAAC,IAAI,IAAI;EAIvD,IAAI,MAHiB,GAAG,QACtB,2JACF,MACe,IAAI,MAAM,IAAI,MAAM,gDAAgD;EACnF,MAAM,KAAK,QACT;GACE,QAAQ;GACR,QAAQ;IAAE,WAAW,SAAS;IAAW,SAAS;GAAK;EACzD,GACA,YACF;EACA,GAAG,MACD,4HACF;CACF,UAAU;EACR,MAAM,KAAK,MAAM;CACnB;AACF"}
@@ -4,10 +4,10 @@ globalThis.__bundlerPathsOverrides = {
4
4
  'pino-worker': runtimeFilePath(new URL('./pino-worker.mjs', import.meta.url)),
5
5
  'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
6
6
  };
7
- import { tn as ResultSchema } from "./types-gJ5HkL66.mjs";
8
- import { J as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS } from "./config-CM4LsvW5.mjs";
9
- import { f as endLogging } from "./shared--CO_WPTx.mjs";
10
- import { d as RuntimeDataTransport, f as SocketTransport, n as ControlPeer, t as CONTROL_VERSIONS } from "./protocol-DNswG6F2.mjs";
11
- import { A as MANIFEST_PATH, C as sha256, D as readArchive, N as PolicySchema, O as verifyIntegrity, T as verifyPackage, V as validatePolicyBaseline, j as ManifestSchema, t as connectSocket, w as verifyArchive } from "./processes-CQvuh1Sl.mjs";
12
- import { i as resolveRelease, n as downloadRelease, t as probeArtifact } from "./probe-B6KQJxXU.mjs";
7
+ import { A as MANIFEST_PATH, C as sha256, D as readArchive, N as PolicySchema, O as verifyIntegrity, T as verifyPackage, V as validatePolicyBaseline, j as ManifestSchema, t as connectSocket, w as verifyArchive } from "./processes-DOmrri5n.mjs";
8
+ import { i as resolveRelease, n as downloadRelease, t as probeArtifact } from "./probe-CqjOWdnP.mjs";
9
+ import { f as endLogging } from "./shared-8_j_xlsJ.mjs";
10
+ import { d as RuntimeDataTransport, f as SocketTransport, n as ControlPeer, t as CONTROL_VERSIONS } from "./protocol-7m-E_iFu.mjs";
11
+ import { tn as ResultSchema } from "./types-kNTSQOnR.mjs";
12
+ import { J as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS } from "./config-Busa_Dqv.mjs";
13
13
  export { CONTROL_VERSIONS, ControlPeer, MANIFEST_PATH, ManifestSchema, PolicySchema, ResultSchema, RuntimeDataTransport, SocketTransport, TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, connectSocket, downloadRelease, endLogging, probeArtifact, readArchive, resolveRelease, sha256, validatePolicyBaseline, verifyArchive, verifyIntegrity, verifyPackage };