@feng0531/dsh-code-auto-debuger 0.0.0-stage → 0.1.2

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 (209) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/THIRD_PARTY_NOTICES.md +5 -0
  4. package/cordis.patch.yml +5 -0
  5. package/dist/bridge/win-x64/DOTNET-LICENSE.txt +23 -0
  6. package/dist/bridge/win-x64/DOTNET-THIRD-PARTY-NOTICES.txt +1272 -0
  7. package/dist/bridge/win-x64/Microsoft.CSharp.dll +0 -0
  8. package/dist/bridge/win-x64/Microsoft.DiaSymReader.Native.amd64.dll +0 -0
  9. package/dist/bridge/win-x64/Microsoft.VisualBasic.Core.dll +0 -0
  10. package/dist/bridge/win-x64/Microsoft.VisualBasic.dll +0 -0
  11. package/dist/bridge/win-x64/Microsoft.Win32.Primitives.dll +0 -0
  12. package/dist/bridge/win-x64/Microsoft.Win32.Registry.dll +0 -0
  13. package/dist/bridge/win-x64/System.AppContext.dll +0 -0
  14. package/dist/bridge/win-x64/System.Buffers.dll +0 -0
  15. package/dist/bridge/win-x64/System.Collections.Concurrent.dll +0 -0
  16. package/dist/bridge/win-x64/System.Collections.Immutable.dll +0 -0
  17. package/dist/bridge/win-x64/System.Collections.NonGeneric.dll +0 -0
  18. package/dist/bridge/win-x64/System.Collections.Specialized.dll +0 -0
  19. package/dist/bridge/win-x64/System.Collections.dll +0 -0
  20. package/dist/bridge/win-x64/System.ComponentModel.Annotations.dll +0 -0
  21. package/dist/bridge/win-x64/System.ComponentModel.DataAnnotations.dll +0 -0
  22. package/dist/bridge/win-x64/System.ComponentModel.EventBasedAsync.dll +0 -0
  23. package/dist/bridge/win-x64/System.ComponentModel.Primitives.dll +0 -0
  24. package/dist/bridge/win-x64/System.ComponentModel.TypeConverter.dll +0 -0
  25. package/dist/bridge/win-x64/System.ComponentModel.dll +0 -0
  26. package/dist/bridge/win-x64/System.Configuration.dll +0 -0
  27. package/dist/bridge/win-x64/System.Console.dll +0 -0
  28. package/dist/bridge/win-x64/System.Core.dll +0 -0
  29. package/dist/bridge/win-x64/System.Data.Common.dll +0 -0
  30. package/dist/bridge/win-x64/System.Data.DataSetExtensions.dll +0 -0
  31. package/dist/bridge/win-x64/System.Data.dll +0 -0
  32. package/dist/bridge/win-x64/System.Diagnostics.Contracts.dll +0 -0
  33. package/dist/bridge/win-x64/System.Diagnostics.Debug.dll +0 -0
  34. package/dist/bridge/win-x64/System.Diagnostics.DiagnosticSource.dll +0 -0
  35. package/dist/bridge/win-x64/System.Diagnostics.FileVersionInfo.dll +0 -0
  36. package/dist/bridge/win-x64/System.Diagnostics.Process.dll +0 -0
  37. package/dist/bridge/win-x64/System.Diagnostics.StackTrace.dll +0 -0
  38. package/dist/bridge/win-x64/System.Diagnostics.TextWriterTraceListener.dll +0 -0
  39. package/dist/bridge/win-x64/System.Diagnostics.Tools.dll +0 -0
  40. package/dist/bridge/win-x64/System.Diagnostics.TraceSource.dll +0 -0
  41. package/dist/bridge/win-x64/System.Diagnostics.Tracing.dll +0 -0
  42. package/dist/bridge/win-x64/System.Drawing.Primitives.dll +0 -0
  43. package/dist/bridge/win-x64/System.Drawing.dll +0 -0
  44. package/dist/bridge/win-x64/System.Dynamic.Runtime.dll +0 -0
  45. package/dist/bridge/win-x64/System.Formats.Asn1.dll +0 -0
  46. package/dist/bridge/win-x64/System.Formats.Tar.dll +0 -0
  47. package/dist/bridge/win-x64/System.Globalization.Calendars.dll +0 -0
  48. package/dist/bridge/win-x64/System.Globalization.Extensions.dll +0 -0
  49. package/dist/bridge/win-x64/System.Globalization.dll +0 -0
  50. package/dist/bridge/win-x64/System.IO.Compression.Brotli.dll +0 -0
  51. package/dist/bridge/win-x64/System.IO.Compression.FileSystem.dll +0 -0
  52. package/dist/bridge/win-x64/System.IO.Compression.Native.dll +0 -0
  53. package/dist/bridge/win-x64/System.IO.Compression.ZipFile.dll +0 -0
  54. package/dist/bridge/win-x64/System.IO.Compression.dll +0 -0
  55. package/dist/bridge/win-x64/System.IO.FileSystem.AccessControl.dll +0 -0
  56. package/dist/bridge/win-x64/System.IO.FileSystem.DriveInfo.dll +0 -0
  57. package/dist/bridge/win-x64/System.IO.FileSystem.Primitives.dll +0 -0
  58. package/dist/bridge/win-x64/System.IO.FileSystem.Watcher.dll +0 -0
  59. package/dist/bridge/win-x64/System.IO.FileSystem.dll +0 -0
  60. package/dist/bridge/win-x64/System.IO.IsolatedStorage.dll +0 -0
  61. package/dist/bridge/win-x64/System.IO.MemoryMappedFiles.dll +0 -0
  62. package/dist/bridge/win-x64/System.IO.Pipes.AccessControl.dll +0 -0
  63. package/dist/bridge/win-x64/System.IO.Pipes.dll +0 -0
  64. package/dist/bridge/win-x64/System.IO.UnmanagedMemoryStream.dll +0 -0
  65. package/dist/bridge/win-x64/System.IO.dll +0 -0
  66. package/dist/bridge/win-x64/System.Linq.Expressions.dll +0 -0
  67. package/dist/bridge/win-x64/System.Linq.Parallel.dll +0 -0
  68. package/dist/bridge/win-x64/System.Linq.Queryable.dll +0 -0
  69. package/dist/bridge/win-x64/System.Linq.dll +0 -0
  70. package/dist/bridge/win-x64/System.Memory.dll +0 -0
  71. package/dist/bridge/win-x64/System.Net.Http.Json.dll +0 -0
  72. package/dist/bridge/win-x64/System.Net.Http.dll +0 -0
  73. package/dist/bridge/win-x64/System.Net.HttpListener.dll +0 -0
  74. package/dist/bridge/win-x64/System.Net.Mail.dll +0 -0
  75. package/dist/bridge/win-x64/System.Net.NameResolution.dll +0 -0
  76. package/dist/bridge/win-x64/System.Net.NetworkInformation.dll +0 -0
  77. package/dist/bridge/win-x64/System.Net.Ping.dll +0 -0
  78. package/dist/bridge/win-x64/System.Net.Primitives.dll +0 -0
  79. package/dist/bridge/win-x64/System.Net.Quic.dll +0 -0
  80. package/dist/bridge/win-x64/System.Net.Requests.dll +0 -0
  81. package/dist/bridge/win-x64/System.Net.Security.dll +0 -0
  82. package/dist/bridge/win-x64/System.Net.ServicePoint.dll +0 -0
  83. package/dist/bridge/win-x64/System.Net.Sockets.dll +0 -0
  84. package/dist/bridge/win-x64/System.Net.WebClient.dll +0 -0
  85. package/dist/bridge/win-x64/System.Net.WebHeaderCollection.dll +0 -0
  86. package/dist/bridge/win-x64/System.Net.WebProxy.dll +0 -0
  87. package/dist/bridge/win-x64/System.Net.WebSockets.Client.dll +0 -0
  88. package/dist/bridge/win-x64/System.Net.WebSockets.dll +0 -0
  89. package/dist/bridge/win-x64/System.Net.dll +0 -0
  90. package/dist/bridge/win-x64/System.Numerics.Vectors.dll +0 -0
  91. package/dist/bridge/win-x64/System.Numerics.dll +0 -0
  92. package/dist/bridge/win-x64/System.ObjectModel.dll +0 -0
  93. package/dist/bridge/win-x64/System.Private.CoreLib.dll +0 -0
  94. package/dist/bridge/win-x64/System.Private.DataContractSerialization.dll +0 -0
  95. package/dist/bridge/win-x64/System.Private.Uri.dll +0 -0
  96. package/dist/bridge/win-x64/System.Private.Xml.Linq.dll +0 -0
  97. package/dist/bridge/win-x64/System.Private.Xml.dll +0 -0
  98. package/dist/bridge/win-x64/System.Reflection.DispatchProxy.dll +0 -0
  99. package/dist/bridge/win-x64/System.Reflection.Emit.ILGeneration.dll +0 -0
  100. package/dist/bridge/win-x64/System.Reflection.Emit.Lightweight.dll +0 -0
  101. package/dist/bridge/win-x64/System.Reflection.Emit.dll +0 -0
  102. package/dist/bridge/win-x64/System.Reflection.Extensions.dll +0 -0
  103. package/dist/bridge/win-x64/System.Reflection.Metadata.dll +0 -0
  104. package/dist/bridge/win-x64/System.Reflection.Primitives.dll +0 -0
  105. package/dist/bridge/win-x64/System.Reflection.TypeExtensions.dll +0 -0
  106. package/dist/bridge/win-x64/System.Reflection.dll +0 -0
  107. package/dist/bridge/win-x64/System.Resources.Reader.dll +0 -0
  108. package/dist/bridge/win-x64/System.Resources.ResourceManager.dll +0 -0
  109. package/dist/bridge/win-x64/System.Resources.Writer.dll +0 -0
  110. package/dist/bridge/win-x64/System.Runtime.CompilerServices.Unsafe.dll +0 -0
  111. package/dist/bridge/win-x64/System.Runtime.CompilerServices.VisualC.dll +0 -0
  112. package/dist/bridge/win-x64/System.Runtime.Extensions.dll +0 -0
  113. package/dist/bridge/win-x64/System.Runtime.Handles.dll +0 -0
  114. package/dist/bridge/win-x64/System.Runtime.InteropServices.JavaScript.dll +0 -0
  115. package/dist/bridge/win-x64/System.Runtime.InteropServices.RuntimeInformation.dll +0 -0
  116. package/dist/bridge/win-x64/System.Runtime.InteropServices.dll +0 -0
  117. package/dist/bridge/win-x64/System.Runtime.Intrinsics.dll +0 -0
  118. package/dist/bridge/win-x64/System.Runtime.Loader.dll +0 -0
  119. package/dist/bridge/win-x64/System.Runtime.Numerics.dll +0 -0
  120. package/dist/bridge/win-x64/System.Runtime.Serialization.Formatters.dll +0 -0
  121. package/dist/bridge/win-x64/System.Runtime.Serialization.Json.dll +0 -0
  122. package/dist/bridge/win-x64/System.Runtime.Serialization.Primitives.dll +0 -0
  123. package/dist/bridge/win-x64/System.Runtime.Serialization.Xml.dll +0 -0
  124. package/dist/bridge/win-x64/System.Runtime.Serialization.dll +0 -0
  125. package/dist/bridge/win-x64/System.Runtime.dll +0 -0
  126. package/dist/bridge/win-x64/System.Security.AccessControl.dll +0 -0
  127. package/dist/bridge/win-x64/System.Security.Claims.dll +0 -0
  128. package/dist/bridge/win-x64/System.Security.Cryptography.Algorithms.dll +0 -0
  129. package/dist/bridge/win-x64/System.Security.Cryptography.Cng.dll +0 -0
  130. package/dist/bridge/win-x64/System.Security.Cryptography.Csp.dll +0 -0
  131. package/dist/bridge/win-x64/System.Security.Cryptography.Encoding.dll +0 -0
  132. package/dist/bridge/win-x64/System.Security.Cryptography.OpenSsl.dll +0 -0
  133. package/dist/bridge/win-x64/System.Security.Cryptography.Primitives.dll +0 -0
  134. package/dist/bridge/win-x64/System.Security.Cryptography.X509Certificates.dll +0 -0
  135. package/dist/bridge/win-x64/System.Security.Cryptography.dll +0 -0
  136. package/dist/bridge/win-x64/System.Security.Principal.Windows.dll +0 -0
  137. package/dist/bridge/win-x64/System.Security.Principal.dll +0 -0
  138. package/dist/bridge/win-x64/System.Security.SecureString.dll +0 -0
  139. package/dist/bridge/win-x64/System.Security.dll +0 -0
  140. package/dist/bridge/win-x64/System.ServiceModel.Web.dll +0 -0
  141. package/dist/bridge/win-x64/System.ServiceProcess.dll +0 -0
  142. package/dist/bridge/win-x64/System.Text.Encoding.CodePages.dll +0 -0
  143. package/dist/bridge/win-x64/System.Text.Encoding.Extensions.dll +0 -0
  144. package/dist/bridge/win-x64/System.Text.Encoding.dll +0 -0
  145. package/dist/bridge/win-x64/System.Text.Encodings.Web.dll +0 -0
  146. package/dist/bridge/win-x64/System.Text.Json.dll +0 -0
  147. package/dist/bridge/win-x64/System.Text.RegularExpressions.dll +0 -0
  148. package/dist/bridge/win-x64/System.Threading.Channels.dll +0 -0
  149. package/dist/bridge/win-x64/System.Threading.Overlapped.dll +0 -0
  150. package/dist/bridge/win-x64/System.Threading.Tasks.Dataflow.dll +0 -0
  151. package/dist/bridge/win-x64/System.Threading.Tasks.Extensions.dll +0 -0
  152. package/dist/bridge/win-x64/System.Threading.Tasks.Parallel.dll +0 -0
  153. package/dist/bridge/win-x64/System.Threading.Tasks.dll +0 -0
  154. package/dist/bridge/win-x64/System.Threading.Thread.dll +0 -0
  155. package/dist/bridge/win-x64/System.Threading.ThreadPool.dll +0 -0
  156. package/dist/bridge/win-x64/System.Threading.Timer.dll +0 -0
  157. package/dist/bridge/win-x64/System.Threading.dll +0 -0
  158. package/dist/bridge/win-x64/System.Transactions.Local.dll +0 -0
  159. package/dist/bridge/win-x64/System.Transactions.dll +0 -0
  160. package/dist/bridge/win-x64/System.ValueTuple.dll +0 -0
  161. package/dist/bridge/win-x64/System.Web.HttpUtility.dll +0 -0
  162. package/dist/bridge/win-x64/System.Web.dll +0 -0
  163. package/dist/bridge/win-x64/System.Windows.dll +0 -0
  164. package/dist/bridge/win-x64/System.Xml.Linq.dll +0 -0
  165. package/dist/bridge/win-x64/System.Xml.ReaderWriter.dll +0 -0
  166. package/dist/bridge/win-x64/System.Xml.Serialization.dll +0 -0
  167. package/dist/bridge/win-x64/System.Xml.XDocument.dll +0 -0
  168. package/dist/bridge/win-x64/System.Xml.XPath.XDocument.dll +0 -0
  169. package/dist/bridge/win-x64/System.Xml.XPath.dll +0 -0
  170. package/dist/bridge/win-x64/System.Xml.XmlDocument.dll +0 -0
  171. package/dist/bridge/win-x64/System.Xml.XmlSerializer.dll +0 -0
  172. package/dist/bridge/win-x64/System.Xml.dll +0 -0
  173. package/dist/bridge/win-x64/System.dll +0 -0
  174. package/dist/bridge/win-x64/WindowsBase.dll +0 -0
  175. package/dist/bridge/win-x64/clretwrc.dll +0 -0
  176. package/dist/bridge/win-x64/clrgc.dll +0 -0
  177. package/dist/bridge/win-x64/clrjit.dll +0 -0
  178. package/dist/bridge/win-x64/coreclr.dll +0 -0
  179. package/dist/bridge/win-x64/createdump.exe +0 -0
  180. package/dist/bridge/win-x64/dsh-vs-bridge.deps.json +759 -0
  181. package/dist/bridge/win-x64/dsh-vs-bridge.dll +0 -0
  182. package/dist/bridge/win-x64/dsh-vs-bridge.exe +0 -0
  183. package/dist/bridge/win-x64/dsh-vs-bridge.runtimeconfig.json +16 -0
  184. package/dist/bridge/win-x64/hostfxr.dll +0 -0
  185. package/dist/bridge/win-x64/hostpolicy.dll +0 -0
  186. package/dist/bridge/win-x64/mscordaccore.dll +0 -0
  187. package/dist/bridge/win-x64/mscordaccore_amd64_amd64_8.0.3326.52219.dll +0 -0
  188. package/dist/bridge/win-x64/mscordbi.dll +0 -0
  189. package/dist/bridge/win-x64/mscorlib.dll +0 -0
  190. package/dist/bridge/win-x64/mscorrc.dll +0 -0
  191. package/dist/bridge/win-x64/msquic.dll +0 -0
  192. package/dist/bridge/win-x64/netstandard.dll +0 -0
  193. package/dist/bridge-info.json +767 -0
  194. package/dist/build-info.json +7 -0
  195. package/dist/client.js +858 -0
  196. package/dist/plugin.js +1259 -0
  197. package/dist/plugin.js.map +7 -0
  198. package/docs/ACCEPTANCE-0.1.0.md +44 -0
  199. package/docs/ACCEPTANCE-0.1.1.md +42 -0
  200. package/docs/RELEASE-0.1.1.md +22 -0
  201. package/docs/RELEASE-0.1.2.md +24 -0
  202. package/docs/architecture.md +26 -0
  203. package/docs/ci.md +33 -0
  204. package/docs/releasing.md +33 -0
  205. package/docs/security.md +31 -0
  206. package/docs/testing.md +35 -0
  207. package/locale/en.json +4 -0
  208. package/locale/zh-CN.json +4 -0
  209. package/package.json +67 -4
package/dist/plugin.js ADDED
@@ -0,0 +1,1259 @@
1
+ // src/plugin.ts
2
+ import path4 from "node:path";
3
+ import os from "node:os";
4
+ import { realpath as realpath3 } from "node:fs/promises";
5
+
6
+ // src/core/debug-service.ts
7
+ import path2 from "node:path";
8
+ import { randomUUID as randomUUID2 } from "node:crypto";
9
+ import { setTimeout as delay } from "node:timers/promises";
10
+
11
+ // src/bridge/client.ts
12
+ import { spawn } from "node:child_process";
13
+ import { randomUUID } from "node:crypto";
14
+ import { fileURLToPath } from "node:url";
15
+
16
+ // src/protocol/types.ts
17
+ var DebugError = class extends Error {
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.code = code;
21
+ }
22
+ };
23
+ function fail(code, message) {
24
+ throw new DebugError(code, message);
25
+ }
26
+ function object(value, keys) {
27
+ if (!value || typeof value !== "object" || Array.isArray(value))
28
+ return fail("INVALID_INPUT", "Expected object");
29
+ const o = value;
30
+ if (Object.keys(o).some((k) => !keys.includes(k)))
31
+ fail("INVALID_INPUT", "Unknown field");
32
+ return o;
33
+ }
34
+
35
+ // src/bridge/client.ts
36
+ var BridgeClient = class {
37
+ constructor(executable = fileURLToPath(
38
+ new URL("./bridge/win-x64/dsh-vs-bridge.exe", import.meta.url)
39
+ ), options = {}) {
40
+ this.executable = executable;
41
+ this.options = options;
42
+ }
43
+ child;
44
+ pending = /* @__PURE__ */ new Map();
45
+ buffer = "";
46
+ dead = false;
47
+ closePromise;
48
+ closed;
49
+ resolveClosed;
50
+ diagnostics = [];
51
+ start() {
52
+ if (this.dead)
53
+ throw new DebugError("BRIDGE_CLOSED", "Reconnect using a fresh bridge");
54
+ if (this.child) return;
55
+ if (process.platform !== "win32" && !this.options.spawnProcess)
56
+ throw new DebugError("UNSUPPORTED_PLATFORM", "Windows is required");
57
+ this.closed = new Promise((resolve) => {
58
+ this.resolveClosed = resolve;
59
+ });
60
+ const child = this.child = (this.options.spawnProcess ?? spawn)(
61
+ this.executable,
62
+ [],
63
+ { stdio: ["pipe", "pipe", "pipe"], windowsHide: true }
64
+ );
65
+ const streamError = () => this.abort(
66
+ "OUTCOME_UNKNOWN",
67
+ "Bridge transport failed; inspect external state before any mutation"
68
+ );
69
+ child.stdin.on("error", streamError);
70
+ child.stdout.on("error", streamError);
71
+ child.stderr.on("error", streamError);
72
+ child.stdin.on("close", () => {
73
+ if (this.pending.size)
74
+ this.abort("OUTCOME_UNKNOWN", "Bridge input closed during request");
75
+ });
76
+ child.stdout.setEncoding("utf8");
77
+ child.stderr.setEncoding("utf8");
78
+ child.stderr.on("data", (data) => {
79
+ for (const code of data.match(
80
+ /\b(?:BUSY|COM_ERROR|BRIDGE_ERROR|INVALID_REQUEST|TARGET_MISMATCH|OUTCOME_UNKNOWN)\b/g
81
+ ) ?? []) {
82
+ this.diagnostics.push(code);
83
+ if (this.diagnostics.length > 32) this.diagnostics.shift();
84
+ }
85
+ });
86
+ child.stdout.on("data", (data) => {
87
+ this.buffer += data;
88
+ if (Buffer.byteLength(this.buffer) > 2 * 1024 * 1024) {
89
+ this.abort("BRIDGE_PROTOCOL", "Oversized bridge output");
90
+ return;
91
+ }
92
+ let pos;
93
+ while ((pos = this.buffer.indexOf("\n")) >= 0) {
94
+ const line = this.buffer.slice(0, pos);
95
+ this.buffer = this.buffer.slice(pos + 1);
96
+ try {
97
+ const r = JSON.parse(line);
98
+ if (r.protocol !== 1 || typeof r.id !== "string" || typeof r.ok !== "boolean")
99
+ throw Error();
100
+ const p = this.pending.get(r.id);
101
+ if (!p) throw Error();
102
+ this.pending.delete(r.id);
103
+ p.cleanup();
104
+ if (r.ok) p.resolve(r.value);
105
+ else
106
+ p.reject(
107
+ new DebugError(
108
+ typeof r.error?.code === "string" ? r.error.code : "BRIDGE_ERROR",
109
+ typeof r.error?.message === "string" ? r.error.message : "Bridge request failed"
110
+ )
111
+ );
112
+ } catch {
113
+ this.abort("BRIDGE_PROTOCOL", "Invalid bridge response");
114
+ return;
115
+ }
116
+ }
117
+ });
118
+ child.on(
119
+ "error",
120
+ () => this.abort("BRIDGE_UNAVAILABLE", "Bridge executable could not start")
121
+ );
122
+ child.on(
123
+ "exit",
124
+ () => this.abort(
125
+ "BRIDGE_EXITED",
126
+ "Bridge exited; external VS state must be inspected",
127
+ false
128
+ )
129
+ );
130
+ child.on("close", () => {
131
+ this.dead = true;
132
+ this.resolveClosed?.();
133
+ });
134
+ }
135
+ abort(code, message, kill = true) {
136
+ this.dead = true;
137
+ for (const p of this.pending.values()) {
138
+ p.cleanup();
139
+ p.reject(new DebugError(code, message));
140
+ }
141
+ this.pending.clear();
142
+ if (kill && this.child && this.child.exitCode === null && this.child.signalCode === null)
143
+ this.child.kill();
144
+ }
145
+ diagnosticsSnapshot() {
146
+ return [...this.diagnostics];
147
+ }
148
+ async request(method, params = {}, signal) {
149
+ signal?.throwIfAborted();
150
+ const id = randomUUID(), line = JSON.stringify({ protocol: 1, id, method, params }) + "\n";
151
+ if (Buffer.byteLength(line) > 65536)
152
+ throw new DebugError("INVALID_INPUT", "Request exceeds 64KiB");
153
+ this.start();
154
+ if (this.pending.size)
155
+ throw new DebugError(
156
+ "BRIDGE_BUSY",
157
+ "Only one bridge request may be in flight"
158
+ );
159
+ return new Promise((resolve, reject) => {
160
+ const stop = () => this.abort(
161
+ "OUTCOME_UNKNOWN",
162
+ "Bridge request cancelled or timed out; do not replay mutations"
163
+ );
164
+ const timer = setTimeout(stop, this.options.timeoutMs ?? 15e3);
165
+ const cleanup = () => {
166
+ clearTimeout(timer);
167
+ signal?.removeEventListener("abort", stop);
168
+ };
169
+ this.pending.set(id, { resolve, reject, cleanup });
170
+ signal?.addEventListener("abort", stop, { once: true });
171
+ if (signal?.aborted) {
172
+ stop();
173
+ return;
174
+ }
175
+ try {
176
+ this.child.stdin.write(line, (error) => {
177
+ if (error)
178
+ this.abort(
179
+ "OUTCOME_UNKNOWN",
180
+ "Bridge write failed; inspect external state"
181
+ );
182
+ });
183
+ } catch {
184
+ this.abort(
185
+ "OUTCOME_UNKNOWN",
186
+ "Bridge write failed; inspect external state"
187
+ );
188
+ }
189
+ });
190
+ }
191
+ close() {
192
+ return this.closePromise ??= this.closeInternal();
193
+ }
194
+ async closeInternal() {
195
+ const child = this.child;
196
+ if (!child) {
197
+ this.dead = true;
198
+ return;
199
+ }
200
+ if (!this.dead && !this.pending.size) {
201
+ try {
202
+ await this.request("disconnect", {});
203
+ } catch {
204
+ }
205
+ }
206
+ this.abort("BRIDGE_CLOSED", "Bridge closed; VS was not terminated");
207
+ let timer;
208
+ try {
209
+ await Promise.race([
210
+ this.closed,
211
+ new Promise((_, reject) => {
212
+ timer = setTimeout(
213
+ () => reject(
214
+ new DebugError(
215
+ "BRIDGE_CLEANUP_UNCONFIRMED",
216
+ "Bridge stdio did not close; process cleanup unconfirmed"
217
+ )
218
+ ),
219
+ this.options.closeTimeoutMs ?? 5e3
220
+ );
221
+ })
222
+ ]);
223
+ } finally {
224
+ if (timer) clearTimeout(timer);
225
+ }
226
+ }
227
+ };
228
+
229
+ // src/policy/plan.ts
230
+ import path from "node:path";
231
+ import { realpath } from "node:fs/promises";
232
+ var fields = {
233
+ breakpointAdd: ["file", "line"],
234
+ breakpointRemove: ["breakpointId"],
235
+ launch: [],
236
+ attach: ["processId"],
237
+ continue: [],
238
+ pause: [],
239
+ step: ["kind"],
240
+ waitForBreak: ["timeoutMs"],
241
+ snapshot: [],
242
+ evaluate: ["expression"],
243
+ detach: [],
244
+ terminate: []
245
+ };
246
+ var mutating = /* @__PURE__ */ new Set([
247
+ "breakpointAdd",
248
+ "breakpointRemove",
249
+ "launch",
250
+ "attach",
251
+ "continue",
252
+ "pause",
253
+ "step",
254
+ "evaluate",
255
+ "detach",
256
+ "terminate"
257
+ ]);
258
+ async function canonicalInside(root, file) {
259
+ const [base, target] = await Promise.all([realpath(root), realpath(file)]);
260
+ const rel = path.relative(base, target);
261
+ if (rel.startsWith(".." + path.sep) || rel === ".." || path.isAbsolute(rel))
262
+ fail("OUTSIDE_WORKSPACE", "Target must be inside session workspace");
263
+ return target;
264
+ }
265
+ async function validatePlan(raw, cwd) {
266
+ const o = object(raw, [
267
+ "steps",
268
+ "maxSteps",
269
+ "timeoutMs",
270
+ "allowEvaluation",
271
+ "allowTerminate"
272
+ ]);
273
+ if (!Array.isArray(o.steps) || o.steps.length < 1 || o.steps.length > 64)
274
+ fail("INVALID_PLAN", "Plan requires 1..64 steps");
275
+ const maxSteps = o.maxSteps ?? 32, timeoutMs = o.timeoutMs ?? 6e4;
276
+ if (!Number.isSafeInteger(maxSteps) || maxSteps < 1 || maxSteps > 64 || o.steps.length > maxSteps || !Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 3e5)
277
+ fail("INVALID_PLAN", "Invalid execution budget");
278
+ if (o.allowEvaluation !== void 0 && typeof o.allowEvaluation !== "boolean" || o.allowTerminate !== void 0 && typeof o.allowTerminate !== "boolean")
279
+ fail("INVALID_PLAN", "Risk switches must be booleans");
280
+ const steps = [];
281
+ for (const value of o.steps) {
282
+ const s = object(value, ["action", "params"]);
283
+ if (typeof s.action !== "string" || !Object.hasOwn(fields, s.action))
284
+ fail("INVALID_PLAN", "Unknown action");
285
+ const p = object(s.params ?? {}, fields[s.action]);
286
+ if (s.action === "breakpointAdd") {
287
+ if (typeof p.file !== "string" || !Number.isSafeInteger(p.line) || p.line < 1 || p.line > 1e7)
288
+ fail("INVALID_PLAN", "Invalid breakpoint");
289
+ p.file = await canonicalInside(cwd, path.resolve(cwd, p.file));
290
+ }
291
+ if (s.action === "breakpointRemove" && (typeof p.breakpointId !== "string" || p.breakpointId.length > 256))
292
+ fail("INVALID_PLAN", "Invalid breakpoint id");
293
+ if (s.action === "attach" && (!Number.isSafeInteger(p.processId) || p.processId <= 0))
294
+ fail("INVALID_PLAN", "Invalid process id");
295
+ if (s.action === "step" && !["over", "into", "out"].includes(p.kind))
296
+ fail("INVALID_PLAN", "Invalid step kind");
297
+ if (s.action === "waitForBreak" && (!Number.isSafeInteger(p.timeoutMs) || p.timeoutMs < 100 || p.timeoutMs > timeoutMs))
298
+ fail("INVALID_PLAN", "Invalid wait budget");
299
+ if (s.action === "evaluate") {
300
+ if (o.allowEvaluation !== true)
301
+ fail(
302
+ "RISK_NOT_AUTHORIZED",
303
+ "Expression evaluation can run target code; explicitly opt in"
304
+ );
305
+ if (typeof p.expression !== "string" || !p.expression.trim() || p.expression.length > 2048)
306
+ fail("INVALID_PLAN", "Invalid expression");
307
+ }
308
+ if (s.action === "terminate" && o.allowTerminate !== true)
309
+ fail("RISK_NOT_AUTHORIZED", "Termination requires explicit opt in");
310
+ steps.push({ action: s.action, params: structuredClone(p) });
311
+ }
312
+ return {
313
+ steps,
314
+ maxSteps,
315
+ timeoutMs,
316
+ allowEvaluation: o.allowEvaluation === true,
317
+ allowTerminate: o.allowTerminate === true
318
+ };
319
+ }
320
+
321
+ // src/core/debug-service.ts
322
+ var targetLocks = /* @__PURE__ */ new Map();
323
+ var key = (o) => JSON.stringify(o);
324
+ var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
325
+ var DebugService = class {
326
+ constructor(store, factory = () => new BridgeClient(), authorize = async () => {
327
+ }) {
328
+ this.store = store;
329
+ this.factory = factory;
330
+ this.authorize = authorize;
331
+ }
332
+ connections = /* @__PURE__ */ new Map();
333
+ previews = /* @__PURE__ */ new Map();
334
+ active = /* @__PURE__ */ new Map();
335
+ closed = false;
336
+ backendId = randomUUID2();
337
+ completed = /* @__PURE__ */ new Map();
338
+ requests = /* @__PURE__ */ new Map();
339
+ pendingConnections = /* @__PURE__ */ new Map();
340
+ transient = /* @__PURE__ */ new Map();
341
+ capabilities() {
342
+ return {
343
+ version: "0.1.2",
344
+ backendId: this.backendId,
345
+ protocol: 1,
346
+ available: process.platform === "win32",
347
+ verified: false,
348
+ limitations: [
349
+ "External COM only; no VSIX",
350
+ "Windows x64 / VS2022 baseline; real-host acceptance recorded separately",
351
+ "No implicit evaluation, no source editing, no mutation replay",
352
+ "Cancel stops automation, not debuggee"
353
+ ]
354
+ };
355
+ }
356
+ connection(owner) {
357
+ if (this.closed) fail("CLOSED", "Service disposed");
358
+ return this.connections.get(key(owner)) ?? fail("NOT_CONNECTED", "Select and connect a Visual Studio instance");
359
+ }
360
+ idle(c) {
361
+ if (c.busy) fail("BUSY", "A task or lifecycle operation owns this target");
362
+ }
363
+ async exclusive(c, work) {
364
+ this.idle(c);
365
+ c.busy = true;
366
+ try {
367
+ return await work();
368
+ } finally {
369
+ c.busy = false;
370
+ }
371
+ }
372
+ async discover(signal) {
373
+ if (this.closed) fail("CLOSED", "Service disposed");
374
+ const bridge = this.factory();
375
+ let settled;
376
+ const lifetime = new Promise((resolve) => {
377
+ settled = resolve;
378
+ });
379
+ this.transient.set(bridge, lifetime);
380
+ try {
381
+ return await bridge.request("discover", {}, signal);
382
+ } finally {
383
+ try {
384
+ await bridge.close();
385
+ } finally {
386
+ this.transient.delete(bridge);
387
+ settled();
388
+ }
389
+ }
390
+ }
391
+ async connect(owner, raw, signal) {
392
+ await this.authorize(owner);
393
+ const k = key(owner);
394
+ if (this.closed) fail("CLOSED", "Service disposed");
395
+ if (this.pendingConnections.has(k))
396
+ fail("ALREADY_CONNECTED", "Connection in progress");
397
+ const work = this.connectInternal(owner, raw, signal);
398
+ this.pendingConnections.set(k, work);
399
+ try {
400
+ return await work;
401
+ } finally {
402
+ this.pendingConnections.delete(k);
403
+ }
404
+ }
405
+ async connectInternal(owner, raw, signal) {
406
+ const p = object(raw, ["instanceId", "solutionPath"]);
407
+ if (typeof p.instanceId !== "string" || p.instanceId.length > 1024 || typeof p.solutionPath !== "string")
408
+ fail("INVALID_INPUT", "Explicit instance and solution required");
409
+ const solutionPath = await canonicalInside(
410
+ owner.cwd,
411
+ path2.resolve(owner.cwd, p.solutionPath)
412
+ );
413
+ if (this.closed) fail("CLOSED", "Service disposed");
414
+ if (this.connections.has(key(owner)))
415
+ fail("ALREADY_CONNECTED", "Disconnect previous instance first");
416
+ if (targetLocks.has(p.instanceId))
417
+ fail("TARGET_BUSY", "Instance controlled by another session");
418
+ targetLocks.set(p.instanceId, key(owner));
419
+ const bridge = this.factory();
420
+ try {
421
+ const value = await bridge.request(
422
+ "connect",
423
+ { instanceId: p.instanceId, solutionPath },
424
+ signal
425
+ );
426
+ const target = value.target;
427
+ if (!target || target.instanceId !== p.instanceId || !Number.isSafeInteger(target.pid) || typeof target.startTime !== "string" || typeof target.solutionPath !== "string" || !same(
428
+ (await canonicalInside(owner.cwd, target.solutionPath)).toLowerCase(),
429
+ solutionPath.toLowerCase()
430
+ ))
431
+ fail("TARGET_MISMATCH", "Bridge target identity mismatch");
432
+ if (this.closed) fail("CLOSED", "Service disposed during connect");
433
+ this.connections.set(key(owner), {
434
+ bridge,
435
+ target: structuredClone(target),
436
+ busy: false,
437
+ owner
438
+ });
439
+ return value;
440
+ } catch (e) {
441
+ targetLocks.delete(p.instanceId);
442
+ await bridge.close();
443
+ throw e;
444
+ }
445
+ }
446
+ async verified(c, signal) {
447
+ await this.authorize(c.owner);
448
+ let v;
449
+ for (let attempt = 0; ; attempt++) {
450
+ try {
451
+ await this.authorize(c.owner);
452
+ v = await c.bridge.request("status", {}, signal);
453
+ break;
454
+ } catch (e) {
455
+ if (e.code !== "BUSY" || attempt >= 20) throw e;
456
+ await delay(150, void 0, { signal });
457
+ }
458
+ }
459
+ if (!same(v.target, c.target))
460
+ fail("TARGET_CHANGED", "Target changed; reconnect and preview again");
461
+ return v;
462
+ }
463
+ async status(owner, signal) {
464
+ const c = this.connection(owner);
465
+ return this.exclusive(c, () => this.verified(c, signal));
466
+ }
467
+ async ownedBreakpoints(owner, signal) {
468
+ const c = this.connection(owner);
469
+ return this.exclusive(c, async () => {
470
+ await this.verified(c, signal);
471
+ await this.authorize(owner);
472
+ return c.bridge.request("listOwnedBreakpoints", {}, signal);
473
+ });
474
+ }
475
+ async snapshot(owner, signal) {
476
+ const c = this.connection(owner);
477
+ return this.exclusive(c, async () => {
478
+ await this.verified(c, signal);
479
+ return c.bridge.request("snapshot", {}, signal);
480
+ });
481
+ }
482
+ async preview(owner, raw, signal) {
483
+ const c = this.connection(owner);
484
+ if (c.uncertain)
485
+ fail(
486
+ "RECONNECT_REQUIRED",
487
+ "Previous outcome unknown; inspect VS and explicitly reconnect before new preview"
488
+ );
489
+ return this.exclusive(c, async () => {
490
+ const plan = await validatePlan(structuredClone(raw), owner.cwd);
491
+ const debugState = await this.verified(c, signal);
492
+ for (const step of plan.steps) {
493
+ if (step.action === "attach") {
494
+ const process2 = await c.bridge.request(
495
+ "processDescribe",
496
+ { processId: step.params.processId },
497
+ signal
498
+ );
499
+ if (typeof process2.startTime !== "string")
500
+ fail("TARGET_CHANGED", "Process identity unavailable");
501
+ step.params.expectedStartTime = process2.startTime;
502
+ }
503
+ }
504
+ for (const [id, p] of this.previews)
505
+ if (p.expiresAt <= Date.now() || same(p.owner, owner))
506
+ this.previews.delete(id);
507
+ if (this.previews.size >= 128)
508
+ fail("CAPACITY", "Preview capacity reached");
509
+ const previewId = randomUUID2(), expiresAt = Date.now() + 12e4;
510
+ this.previews.set(previewId, {
511
+ owner: structuredClone(owner),
512
+ connection: c,
513
+ target: structuredClone(c.target),
514
+ debugState: structuredClone(debugState),
515
+ plan,
516
+ expiresAt
517
+ });
518
+ return {
519
+ previewId,
520
+ target: structuredClone(c.target),
521
+ debugState: structuredClone(debugState),
522
+ ...structuredClone(plan),
523
+ expiresAt,
524
+ warnings: [
525
+ "Controls and launch may affect external systems",
526
+ "Cancel does not pause or terminate the target",
527
+ ...plan.allowEvaluation ? ["Expression evaluation may execute target code"] : [],
528
+ ...plan.allowTerminate ? ["Plan explicitly permits terminating debuggee processes"] : []
529
+ ]
530
+ };
531
+ });
532
+ }
533
+ async execute(owner, raw, signal, wait = true) {
534
+ const p = object(raw, ["previewId", "confirmed", "requestId"]);
535
+ if (p.requestId === void 0)
536
+ return this.executeNew(owner, p, signal, wait);
537
+ if (typeof p.requestId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(p.requestId))
538
+ fail("INVALID_INPUT", "Invalid requestId");
539
+ const requestKey = JSON.stringify([owner.sessionId, p.requestId]);
540
+ const signature = JSON.stringify([owner.cwd, p.previewId, p.confirmed]);
541
+ const previous = this.requests.get(requestKey);
542
+ if (previous) {
543
+ if (previous.signature !== signature)
544
+ fail("REQUEST_CONFLICT", "requestId parameters changed");
545
+ const jobId = await previous.result;
546
+ if (!jobId)
547
+ fail(
548
+ "REQUEST_FAILED",
549
+ "Original request failed; no automatic replay permitted"
550
+ );
551
+ return this.jobStatus(owner, { jobId });
552
+ }
553
+ if (this.requests.size >= 1024)
554
+ fail(
555
+ "CAPACITY",
556
+ "Request retention capacity reached; no replay permitted"
557
+ );
558
+ const result = (async () => {
559
+ const previous2 = (await this.store.list(owner)).find(
560
+ (j) => j.requestId === p.requestId
561
+ );
562
+ if (previous2) {
563
+ if (previous2.owner.cwd !== owner.cwd || previous2.previewId !== p.previewId || p.confirmed !== true)
564
+ fail("REQUEST_CONFLICT", "requestId parameters changed");
565
+ return this.store.read(previous2.jobId, owner);
566
+ }
567
+ return this.executeNew(owner, p, signal, wait);
568
+ })();
569
+ this.requests.set(requestKey, {
570
+ signature,
571
+ result: result.then(
572
+ (job) => job.jobId,
573
+ () => ""
574
+ )
575
+ });
576
+ return result;
577
+ }
578
+ async executeNew(owner, p, signal, wait = true) {
579
+ if (p.confirmed !== true)
580
+ fail(
581
+ "CONFIRMATION_REQUIRED",
582
+ "Execute only explicitly authorized matching preview"
583
+ );
584
+ const preview = this.previews.get(p.previewId);
585
+ if (!preview || !same(preview.owner, owner) || preview.expiresAt <= Date.now())
586
+ fail("PREVIEW_EXPIRED", "Preview expired or foreign");
587
+ await this.authorize(owner);
588
+ const c = this.connection(owner);
589
+ this.idle(c);
590
+ if (c.uncertain)
591
+ fail(
592
+ "RECONNECT_REQUIRED",
593
+ "Previous outcome or persistence uncertain; reconnect explicitly"
594
+ );
595
+ while (this.active.size + this.completed.size >= 128) {
596
+ const evict = [...this.completed].find(
597
+ ([, j]) => j.persistence?.status !== "failed"
598
+ );
599
+ if (evict) this.completed.delete(evict[0]);
600
+ else fail("CAPACITY", "Retained task capacity reached");
601
+ }
602
+ if (preview.connection !== c || !same(c.target, preview.target))
603
+ fail("TARGET_CHANGED", "Reconnect requires fresh preview");
604
+ this.previews.delete(p.previewId);
605
+ c.busy = true;
606
+ const controller = new AbortController();
607
+ const abort = () => controller.abort(signal?.reason);
608
+ if (wait) {
609
+ signal?.addEventListener("abort", abort, { once: true });
610
+ if (signal?.aborted) abort();
611
+ }
612
+ const record = {
613
+ jobId: randomUUID2(),
614
+ owner: structuredClone(owner),
615
+ target: c.target,
616
+ status: "queued",
617
+ steps: preview.plan.steps,
618
+ results: [],
619
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
620
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
621
+ externalState: "unconfirmed",
622
+ persistence: { status: "pending" },
623
+ requestId: p.requestId,
624
+ previewId: p.previewId
625
+ };
626
+ const active = { record, controller, done: Promise.resolve() };
627
+ this.active.set(record.jobId, active);
628
+ active.done = this.run(c, preview, active).catch((error) => {
629
+ this.persistenceFailure(c, record, error);
630
+ }).finally(() => {
631
+ c.busy = false;
632
+ signal?.removeEventListener("abort", abort);
633
+ this.completed.set(record.jobId, record);
634
+ this.active.delete(record.jobId);
635
+ });
636
+ if (wait) await active.done;
637
+ return structuredClone(record);
638
+ }
639
+ async run(c, p, a) {
640
+ let inFlightMutation = false;
641
+ const r = a.record;
642
+ const timer = setTimeout(
643
+ () => a.controller.abort(new Error("Task budget exceeded")),
644
+ p.plan.timeoutMs
645
+ );
646
+ const signal = a.controller.signal;
647
+ try {
648
+ await this.persist(c, r);
649
+ signal.throwIfAborted();
650
+ const current = await this.verified(c, signal);
651
+ if (current.state !== p.debugState.state || !same(current.debuggees ?? [], p.debugState.debuggees ?? []))
652
+ fail(
653
+ "TARGET_CHANGED",
654
+ "Debugger state or debuggee identity changed after preview"
655
+ );
656
+ r.status = "running";
657
+ await this.persist(c, r);
658
+ let expectedDebuggees = current.debuggees ?? [];
659
+ let awaitingLaunch = false;
660
+ for (let i = 0; i < p.plan.steps.length; i++) {
661
+ signal.throwIfAborted();
662
+ const s = p.plan.steps[i];
663
+ const observed = await this.verified(c, signal);
664
+ if (awaitingLaunch && expectedDebuggees.length === 0)
665
+ expectedDebuggees = observed.debuggees ?? [];
666
+ if (!same(observed.debuggees ?? [], expectedDebuggees))
667
+ fail(
668
+ "TARGET_CHANGED",
669
+ "Debuggee identity changed between plan steps"
670
+ );
671
+ if (s.action === "breakpointAdd")
672
+ await canonicalInside(r.owner.cwd, s.params.file);
673
+ await this.authorize(r.owner);
674
+ signal.throwIfAborted();
675
+ inFlightMutation = mutating.has(s.action);
676
+ let value;
677
+ if (s.action === "waitForBreak") {
678
+ const until = Date.now() + s.params.timeoutMs;
679
+ do {
680
+ signal.throwIfAborted();
681
+ value = await this.verified(c, signal);
682
+ if (awaitingLaunch && expectedDebuggees.length === 0)
683
+ expectedDebuggees = value.debuggees ?? [];
684
+ if (!same(value.debuggees ?? [], expectedDebuggees))
685
+ fail("TARGET_CHANGED", "Debuggee changed during wait");
686
+ if (value.state === "break") {
687
+ awaitingLaunch = false;
688
+ break;
689
+ }
690
+ if (value.state === "design" && !awaitingLaunch)
691
+ fail("TARGET_EXITED", "Target is not running");
692
+ await delay(100, void 0, { signal });
693
+ } while (Date.now() < until);
694
+ if (value.state !== "break")
695
+ fail("WAIT_TIMEOUT", "Target did not pause within budget");
696
+ } else value = await c.bridge.request(s.action, s.params, signal);
697
+ if (["launch", "attach", "detach", "terminate"].includes(s.action)) {
698
+ const after = await this.verified(c, signal);
699
+ expectedDebuggees = after.debuggees ?? [];
700
+ awaitingLaunch = s.action === "launch";
701
+ }
702
+ inFlightMutation = false;
703
+ const encoded = JSON.stringify(value);
704
+ if (Buffer.byteLength(encoded) > 256 * 1024)
705
+ value = {
706
+ truncated: true,
707
+ bytes: Buffer.byteLength(encoded),
708
+ notice: "Evidence omitted; not complete"
709
+ };
710
+ r.results.push({
711
+ index: i,
712
+ action: s.action,
713
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
714
+ value
715
+ });
716
+ r.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
717
+ await this.persist(c, r);
718
+ }
719
+ r.status = "succeeded";
720
+ r.externalState = "last_observed_not_stopped";
721
+ } catch (e) {
722
+ const error = e;
723
+ if (r.persistence?.status === "failed") return;
724
+ r.status = inFlightMutation ? "unknown" : signal.aborted ? "cancelled" : "failed";
725
+ r.externalState = "unknown";
726
+ if (inFlightMutation) c.uncertain = true;
727
+ r.error = {
728
+ code: inFlightMutation ? "OUTCOME_UNKNOWN" : error.code ?? "DEBUG_FAILED",
729
+ message: error.message.slice(0, 2048)
730
+ };
731
+ } finally {
732
+ clearTimeout(timer);
733
+ r.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
734
+ if (r.persistence?.status !== "failed") {
735
+ try {
736
+ await this.persist(c, r);
737
+ } catch {
738
+ }
739
+ }
740
+ }
741
+ }
742
+ persistenceFailure(c, r, error) {
743
+ const e = error;
744
+ if (r.status !== "persistence_failed") r.outcome = r.status;
745
+ r.status = "persistence_failed";
746
+ r.persistence = {
747
+ status: "failed",
748
+ error: {
749
+ code: e.code ?? "PERSISTENCE_FAILED",
750
+ message: String(e.message ?? error).slice(0, 2048)
751
+ }
752
+ };
753
+ r.error = {
754
+ code: "PERSISTENCE_FAILED",
755
+ message: "Job evidence could not be saved; inspect VS, do not replay"
756
+ };
757
+ c.uncertain = true;
758
+ }
759
+ async persist(c, r) {
760
+ r.persistence = { status: "pending" };
761
+ try {
762
+ await this.store.save({ ...r, persistence: { status: "saved" } });
763
+ r.persistence = { status: "saved" };
764
+ } catch (e) {
765
+ this.persistenceFailure(c, r, e);
766
+ throw e;
767
+ }
768
+ }
769
+ async jobStatus(owner, raw) {
770
+ const p = object(raw, ["jobId"]);
771
+ const a = this.active.get(p.jobId);
772
+ if (a) {
773
+ if (a.record.owner.sessionId !== owner.sessionId)
774
+ fail("FOREIGN_JOB", "Foreign task");
775
+ return structuredClone(a.record);
776
+ }
777
+ const retained = this.completed.get(p.jobId);
778
+ if (retained) {
779
+ if (retained.owner.sessionId !== owner.sessionId)
780
+ fail("FOREIGN_JOB", "Foreign task");
781
+ return structuredClone(retained);
782
+ }
783
+ return this.store.read(p.jobId, owner);
784
+ }
785
+ async cancel(owner, raw) {
786
+ const p = object(raw, ["jobId"]);
787
+ const a = this.active.get(p.jobId);
788
+ if (!a) return this.jobStatus(owner, p);
789
+ if (a.record.owner.sessionId !== owner.sessionId)
790
+ fail("FOREIGN_JOB", "Foreign task");
791
+ a.controller.abort(new Error("Automation cancelled; debuggee not stopped"));
792
+ await a.done;
793
+ return structuredClone(a.record);
794
+ }
795
+ async listJobs(owner, raw = {}) {
796
+ const p = object(raw, ["limit", "offset", "requestId"]);
797
+ const limit = p.limit ?? 20, offset = p.offset ?? 0;
798
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0 || offset > 4096 || p.requestId !== void 0 && (typeof p.requestId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(p.requestId)))
799
+ fail("INVALID_INPUT", "Invalid job list filter");
800
+ const jobs = /* @__PURE__ */ new Map();
801
+ let storageError;
802
+ try {
803
+ for (const job of await this.store.list(owner)) jobs.set(job.jobId, job);
804
+ } catch (error) {
805
+ const e = error;
806
+ storageError = {
807
+ code: e?.code ?? "STORAGE_UNAVAILABLE",
808
+ message: String(e?.message ?? error).slice(0, 2048)
809
+ };
810
+ }
811
+ for (const j of [
812
+ ...this.completed.values(),
813
+ ...[...this.active.values()].map((a) => a.record)
814
+ ])
815
+ if (j.owner.sessionId === owner.sessionId) jobs.set(j.jobId, j);
816
+ const sorted = [...jobs.values()].filter((j) => p.requestId === void 0 || j.requestId === p.requestId).sort(
817
+ (a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? "") || a.jobId.localeCompare(b.jobId)
818
+ );
819
+ return {
820
+ jobs: structuredClone(
821
+ sorted.slice(offset, offset + limit).map((j) => ({ ...j, steps: [], results: [] }))
822
+ ),
823
+ total: sorted.length,
824
+ storageUnavailable: storageError !== void 0,
825
+ incomplete: storageError !== void 0,
826
+ ...storageError ? { error: storageError } : {},
827
+ offset,
828
+ limit,
829
+ hasMore: offset + limit < sorted.length
830
+ };
831
+ }
832
+ async currentJob(owner) {
833
+ const listed = await this.listJobs(owner, { limit: 1 });
834
+ if (!listed.jobs.length && listed.storageUnavailable)
835
+ fail(
836
+ "STORAGE_UNAVAILABLE",
837
+ "No in-memory task found; persisted tasks could not be listed"
838
+ );
839
+ return listed.jobs[0] ?? null;
840
+ }
841
+ async disconnect(owner) {
842
+ if (!this.connections.has(key(owner))) {
843
+ const old = [...this.connections.values()].filter(
844
+ (c2) => c2.owner.sessionId === owner.sessionId
845
+ );
846
+ for (const c2 of old) await this.disconnect(c2.owner);
847
+ return { disconnected: true, debuggeeStopped: false };
848
+ }
849
+ const c = this.connection(owner);
850
+ return this.exclusive(c, async () => {
851
+ try {
852
+ await c.bridge.close();
853
+ } finally {
854
+ this.connections.delete(key(owner));
855
+ targetLocks.delete(c.target.instanceId);
856
+ for (const [id, p] of this.previews)
857
+ if (same(p.owner, owner)) this.previews.delete(id);
858
+ }
859
+ return { disconnected: true, debuggeeStopped: false };
860
+ });
861
+ }
862
+ async dispose() {
863
+ this.closed = true;
864
+ for (const a of this.active.values())
865
+ a.controller.abort(new Error("Plugin disposed"));
866
+ await Promise.allSettled(
867
+ [...this.transient.keys()].map((bridge) => bridge.close())
868
+ );
869
+ await Promise.allSettled([...this.transient.values()]);
870
+ await Promise.allSettled([...this.pendingConnections.values()]);
871
+ await Promise.allSettled([...this.active.values()].map((a) => a.done));
872
+ for (const c of this.connections.values()) {
873
+ await c.bridge.close();
874
+ targetLocks.delete(c.target.instanceId);
875
+ }
876
+ this.connections.clear();
877
+ this.previews.clear();
878
+ }
879
+ };
880
+
881
+ // src/jobs/store.ts
882
+ import {
883
+ mkdir,
884
+ writeFile,
885
+ rename,
886
+ lstat,
887
+ realpath as realpath2,
888
+ opendir,
889
+ open,
890
+ unlink
891
+ } from "node:fs/promises";
892
+ import path3 from "node:path";
893
+ import { randomUUID as randomUUID3, createHash } from "node:crypto";
894
+ async function projectedPath(value) {
895
+ let current = path3.resolve(value);
896
+ const suffix = [];
897
+ for (; ; ) {
898
+ try {
899
+ return path3.join(await realpath2(current), ...suffix);
900
+ } catch (e) {
901
+ if (e.code !== "ENOENT") throw e;
902
+ try {
903
+ if ((await lstat(current)).isSymbolicLink())
904
+ fail("UNSAFE_STORE", "Dangling store symlink");
905
+ } catch (inner) {
906
+ if (inner.code !== "ENOENT") throw inner;
907
+ }
908
+ const parent = path3.dirname(current);
909
+ if (parent === current) throw e;
910
+ suffix.unshift(path3.basename(current));
911
+ current = parent;
912
+ }
913
+ }
914
+ }
915
+ var JobStore = class {
916
+ constructor(directory) {
917
+ this.directory = directory;
918
+ }
919
+ canonical;
920
+ async dir(owner, recovery = false) {
921
+ const dir = await projectedPath(this.directory), workspace = recovery ? void 0 : await realpath2(owner.cwd);
922
+ const rel = workspace === void 0 ? ".." : path3.relative(workspace, dir);
923
+ if (!rel || rel !== ".." && !rel.startsWith(".." + path3.sep) && !path3.isAbsolute(rel))
924
+ fail("UNSAFE_STORE", "Job store must be outside target workspace");
925
+ if (this.canonical && dir !== this.canonical)
926
+ fail("UNSAFE_STORE", "Store location changed");
927
+ await mkdir(dir, { recursive: true, mode: 448 });
928
+ if ((await lstat(this.directory)).isSymbolicLink() || await realpath2(this.directory) !== dir)
929
+ fail("UNSAFE_STORE", "Store path changed");
930
+ this.canonical = dir;
931
+ const scoped = path3.join(
932
+ dir,
933
+ createHash("sha256").update(owner.sessionId).digest("hex")
934
+ );
935
+ await mkdir(scoped, { recursive: true, mode: 448 });
936
+ if ((await lstat(scoped)).isSymbolicLink() || await realpath2(scoped) !== scoped)
937
+ fail("UNSAFE_STORE", "Invalid session store");
938
+ return scoped;
939
+ }
940
+ async save(job) {
941
+ this.id(job.jobId);
942
+ const dir = await this.dir(job.owner), file = path3.join(dir, job.jobId + ".json"), tmp = path3.join(dir, randomUUID3() + ".tmp");
943
+ const text = JSON.stringify(job);
944
+ if (Buffer.byteLength(text) > 20 * 1024 * 1024)
945
+ fail("STORE_LIMIT", "Job exceeds storage budget");
946
+ try {
947
+ await writeFile(tmp, text, { flag: "wx", mode: 384 });
948
+ await this.dir(job.owner);
949
+ await rename(tmp, file);
950
+ } finally {
951
+ await unlink(tmp).catch(() => {
952
+ });
953
+ }
954
+ }
955
+ id(id) {
956
+ if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id))
957
+ fail("INVALID_JOB", "Invalid job id");
958
+ }
959
+ async read(id, owner) {
960
+ this.id(id);
961
+ const scoped = await this.dir(owner, true);
962
+ let file = path3.join(scoped, id + ".json");
963
+ let stat;
964
+ try {
965
+ stat = await lstat(file);
966
+ } catch (e) {
967
+ if (e.code !== "ENOENT") throw e;
968
+ file = path3.join(path3.dirname(scoped), id + ".json");
969
+ stat = await lstat(file);
970
+ }
971
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
972
+ fail("UNSAFE_STORE", "Invalid job file");
973
+ const handle = await open(file, "r");
974
+ let text;
975
+ try {
976
+ const opened = await handle.stat();
977
+ if (!opened.isFile() || opened.size > 20 * 1024 * 1024 || opened.ino !== stat.ino || opened.dev !== stat.dev)
978
+ fail("UNSAFE_STORE", "Job file changed");
979
+ const buffer = Buffer.alloc(opened.size + 1);
980
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
981
+ if (bytesRead > 20 * 1024 * 1024)
982
+ fail("STORE_LIMIT", "Job file too large");
983
+ text = buffer.subarray(0, bytesRead).toString("utf8");
984
+ } finally {
985
+ await handle.close();
986
+ }
987
+ const job = JSON.parse(text);
988
+ if (!job || typeof job !== "object" || job.jobId !== id || !job.owner || typeof job.owner.sessionId !== "string" || typeof job.owner.cwd !== "string" || !path3.isAbsolute(job.owner.cwd) || typeof job.status !== "string" || ![
989
+ "queued",
990
+ "running",
991
+ "succeeded",
992
+ "failed",
993
+ "cancelled",
994
+ "unknown",
995
+ "interrupted",
996
+ "persistence_failed"
997
+ ].includes(job.status) || job.createdAt !== void 0 && typeof job.createdAt !== "string" || job.updatedAt !== void 0 && typeof job.updatedAt !== "string" || job.requestId !== void 0 && (typeof job.requestId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(job.requestId)) || !Array.isArray(job.steps) || job.steps.length > 100 || !Array.isArray(job.results) || job.results.length > 100)
998
+ fail("UNSAFE_STORE", "Malformed job record");
999
+ if (job.owner.sessionId !== owner.sessionId)
1000
+ fail("FOREIGN_JOB", "Job belongs to another owner");
1001
+ if (["running", "queued"].includes(job.status)) {
1002
+ job.status = "interrupted";
1003
+ job.externalState = "unknown";
1004
+ job.error = {
1005
+ code: "INTERRUPTED",
1006
+ message: "Host restarted; inspect VS state, never replay mutations"
1007
+ };
1008
+ }
1009
+ return job;
1010
+ }
1011
+ async list(owner) {
1012
+ const scoped = await this.dir(owner, true);
1013
+ const jobs = [];
1014
+ let scanned = 0, bytes = 0;
1015
+ for (const location of [scoped, path3.dirname(scoped)]) {
1016
+ const directory = await opendir(location);
1017
+ for await (const entry of directory) {
1018
+ if (++scanned > 4096)
1019
+ fail("STORE_LIMIT", "Too many stored jobs; narrow store offline");
1020
+ if (!/^[a-f0-9-]{36}\.json$/.test(entry.name) || !entry.isFile() || entry.isSymbolicLink())
1021
+ continue;
1022
+ try {
1023
+ bytes += (await lstat(path3.join(location, entry.name))).size;
1024
+ if (bytes > 64 * 1024 * 1024)
1025
+ fail("STORE_LIMIT", "Job listing exceeds scan byte budget");
1026
+ const job = await this.read(entry.name.slice(0, -5), owner);
1027
+ jobs.push({ ...job, steps: [], results: [] });
1028
+ } catch (e) {
1029
+ const code = e.code;
1030
+ if (code === "UNSAFE_STORE" || code === "FOREIGN_JOB" || code === "ENOENT" || e instanceof SyntaxError)
1031
+ continue;
1032
+ throw e;
1033
+ }
1034
+ }
1035
+ }
1036
+ return jobs;
1037
+ }
1038
+ };
1039
+
1040
+ // src/plugin.ts
1041
+ var name = "dsh-code-auto-debuger";
1042
+ var inject = ["tools", "connection", "sessions", "sessionPersistence"];
1043
+ var actions = [
1044
+ "capabilities",
1045
+ "discover",
1046
+ "connect",
1047
+ "status",
1048
+ "snapshot",
1049
+ "preview",
1050
+ "execute",
1051
+ "jobStatus",
1052
+ "cancel",
1053
+ "disconnect",
1054
+ "listJobs",
1055
+ "breakpoints"
1056
+ ];
1057
+ function apply(ctx, config = {}) {
1058
+ const directory = typeof config.storageDirectory === "string" ? config.storageDirectory : path4.join(os.homedir(), ".dsh", "auto-debug", "jobs");
1059
+ const service = new DebugService(
1060
+ new JobStore(directory),
1061
+ void 0,
1062
+ async (expected) => {
1063
+ const current = await owner(expected.sessionId);
1064
+ if (current.cwd !== expected.cwd)
1065
+ fail(
1066
+ "OWNER_CHANGED",
1067
+ "Session workspace changed; further debug controls are revoked"
1068
+ );
1069
+ }
1070
+ );
1071
+ async function owner(sessionId, recovery = false) {
1072
+ if (typeof sessionId !== "string" || !sessionId || sessionId.length > 256 || /[\\/\0]/.test(sessionId))
1073
+ fail("INVALID_OWNER", "Valid session required");
1074
+ const live = ctx.sessions.get(sessionId);
1075
+ const header = live?.header ?? (await ctx.sessionPersistence.stat(sessionId))?.header;
1076
+ if (!header?.cwd) fail("INVALID_OWNER", "Session unavailable");
1077
+ const cwd = recovery ? path4.resolve(header.cwd) : await realpath3(header.cwd);
1078
+ if (recovery) return { sessionId, cwd };
1079
+ const store = await projectedPath(directory);
1080
+ const rel = path4.relative(cwd, store);
1081
+ if (!rel || !rel.startsWith(".." + path4.sep) && rel !== ".." && !path4.isAbsolute(rel))
1082
+ fail("UNSAFE_STORE", "State directory cannot be in target workspace");
1083
+ return { sessionId, cwd };
1084
+ }
1085
+ async function dispatch(action, args, who, signal, wait = true) {
1086
+ signal?.throwIfAborted();
1087
+ switch (action) {
1088
+ case "capabilities":
1089
+ object(args, []);
1090
+ return service.capabilities();
1091
+ case "discover":
1092
+ object(args, []);
1093
+ return service.discover(signal);
1094
+ case "connect":
1095
+ return service.connect(who, args, signal);
1096
+ case "status":
1097
+ object(args, []);
1098
+ return service.status(who, signal);
1099
+ case "snapshot":
1100
+ object(args, []);
1101
+ return service.snapshot(who, signal);
1102
+ case "preview":
1103
+ return service.preview(who, args, signal);
1104
+ case "execute":
1105
+ return service.execute(who, args, signal, wait);
1106
+ case "listJobs":
1107
+ return service.listJobs(who, args);
1108
+ case "breakpoints":
1109
+ object(args, []);
1110
+ return service.ownedBreakpoints(who, signal);
1111
+ case "jobStatus":
1112
+ return service.jobStatus(who, args);
1113
+ case "cancel":
1114
+ return service.cancel(who, args);
1115
+ case "disconnect":
1116
+ object(args, []);
1117
+ return service.disconnect(who);
1118
+ default:
1119
+ return fail("UNKNOWN_ACTION", "Unknown action");
1120
+ }
1121
+ }
1122
+ const schemas = {
1123
+ capabilities: {},
1124
+ discover: {},
1125
+ connect: {
1126
+ instanceId: { type: "string" },
1127
+ solutionPath: { type: "string" }
1128
+ },
1129
+ status: {},
1130
+ snapshot: {},
1131
+ preview: {
1132
+ steps: {
1133
+ type: "array",
1134
+ minItems: 1,
1135
+ maxItems: 64,
1136
+ items: {
1137
+ type: "object",
1138
+ additionalProperties: false,
1139
+ properties: {
1140
+ action: {
1141
+ type: "string",
1142
+ enum: [
1143
+ "breakpointAdd",
1144
+ "breakpointRemove",
1145
+ "launch",
1146
+ "attach",
1147
+ "continue",
1148
+ "pause",
1149
+ "step",
1150
+ "waitForBreak",
1151
+ "snapshot",
1152
+ "evaluate",
1153
+ "detach",
1154
+ "terminate"
1155
+ ]
1156
+ },
1157
+ params: { type: "object" }
1158
+ },
1159
+ required: ["action"]
1160
+ }
1161
+ },
1162
+ maxSteps: { type: "integer", minimum: 1, maximum: 64 },
1163
+ timeoutMs: { type: "integer", minimum: 100, maximum: 3e5 },
1164
+ allowEvaluation: { type: "boolean" },
1165
+ allowTerminate: { type: "boolean" }
1166
+ },
1167
+ execute: {
1168
+ previewId: { type: "string" },
1169
+ confirmed: { type: "boolean" },
1170
+ requestId: { type: "string", maxLength: 128 }
1171
+ },
1172
+ listJobs: {
1173
+ offset: { type: "integer", minimum: 0 },
1174
+ limit: { type: "integer", minimum: 1, maximum: 50 },
1175
+ requestId: { type: "string", maxLength: 128 }
1176
+ },
1177
+ breakpoints: {},
1178
+ jobStatus: { jobId: { type: "string" } },
1179
+ cancel: { jobId: { type: "string" } },
1180
+ disconnect: {}
1181
+ };
1182
+ for (const action of actions)
1183
+ ctx.tools.register({
1184
+ name: "auto_debug_" + action.replace(/[A-Z]/g, (s) => "_" + s.toLowerCase()),
1185
+ description: action === "execute" ? "Execute a matching explicitly authorized finite Visual Studio debug preview. confirmed is an assertion, not independent human approval. Waits for task settlement; never replay unknown mutations. Does not edit source." : action === "preview" ? "Preview bounded external Visual Studio actions without running them. Requires selected instance. Evaluation and termination need explicit risk opt-ins." : action === "cancel" ? "Cancel owned automation; does NOT guarantee pausing, detaching or terminating the debuggee." : "External Visual Studio debugging: " + action + ". Operates only on current DSH session target; no VSIX.",
1186
+ parameters: {
1187
+ type: "object",
1188
+ additionalProperties: false,
1189
+ properties: schemas[action],
1190
+ ...action === "execute" ? { required: ["previewId", "confirmed"] } : action === "listJobs" ? {} : Object.keys(schemas[action]).length && action !== "preview" ? { required: Object.keys(schemas[action]) } : action === "preview" ? { required: ["steps"] } : {}
1191
+ },
1192
+ output: {
1193
+ schema: { type: "object" },
1194
+ render: (_args, value) => [
1195
+ { type: "text", text: JSON.stringify(value) }
1196
+ ]
1197
+ },
1198
+ async execute(args, exec) {
1199
+ const session = exec?.agent?.session;
1200
+ const who = await owner(
1201
+ session?.header?.id ?? session?.id,
1202
+ ["jobStatus", "cancel", "listJobs", "disconnect"].includes(action)
1203
+ );
1204
+ return dispatch(action, args, who, exec.signal, true);
1205
+ }
1206
+ });
1207
+ ctx.connection.register(
1208
+ ctx,
1209
+ "/auto-debug-rpc",
1210
+ async (endpoint, payload, signal) => {
1211
+ try {
1212
+ const o = object(payload, [
1213
+ "sessionId",
1214
+ "instanceId",
1215
+ "solutionPath",
1216
+ "steps",
1217
+ "maxSteps",
1218
+ "timeoutMs",
1219
+ "allowEvaluation",
1220
+ "allowTerminate",
1221
+ "previewId",
1222
+ "confirmed",
1223
+ "jobId",
1224
+ "requestId",
1225
+ "offset",
1226
+ "limit"
1227
+ ]);
1228
+ const { sessionId, ...args } = o;
1229
+ const who = await owner(
1230
+ sessionId,
1231
+ ["jobStatus", "cancel", "listJobs", "disconnect"].includes(endpoint)
1232
+ );
1233
+ return {
1234
+ ok: true,
1235
+ value: await dispatch(endpoint, args, who, signal, false)
1236
+ };
1237
+ } catch (e) {
1238
+ const error = e;
1239
+ return {
1240
+ ok: false,
1241
+ error: {
1242
+ code: error.code ?? "DEBUG_ERROR",
1243
+ message: error.message.slice(0, 2048)
1244
+ }
1245
+ };
1246
+ }
1247
+ }
1248
+ );
1249
+ ctx.on("dispose", () => service.dispose());
1250
+ return service;
1251
+ }
1252
+ export {
1253
+ DebugService,
1254
+ JobStore,
1255
+ apply,
1256
+ inject,
1257
+ name
1258
+ };
1259
+ //# sourceMappingURL=plugin.js.map