larness 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/app.js +122 -0
  4. package/apps/server/dist/address-BE25lU9-.js +94 -0
  5. package/apps/server/dist/client-Co1thYbK.js +120 -0
  6. package/apps/server/dist/doctor-ClvbJZvj.js +127 -0
  7. package/apps/server/dist/doctor.js +12 -0
  8. package/apps/server/dist/index.js +27349 -0
  9. package/apps/server/dist/lock-DyEoZgG_.js +101 -0
  10. package/apps/server/dist/managed-CLFUiDbj.js +2138 -0
  11. package/apps/server/dist/paths-BHryFHwq.js +2337 -0
  12. package/apps/server/dist/status-idXF0pm6.js +49 -0
  13. package/apps/server/dist/status.js +30 -0
  14. package/apps/server/dist/tui.js +1626 -0
  15. package/apps/server/drizzle/0001_auth.sql +110 -0
  16. package/apps/server/drizzle/0002_projects.sql +13 -0
  17. package/apps/server/drizzle/0003_workspace.sql +81 -0
  18. package/apps/server/drizzle/0004_models.sql +30 -0
  19. package/apps/server/drizzle/0005_resources.sql +54 -0
  20. package/apps/server/drizzle/0006_commands.sql +24 -0
  21. package/apps/server/drizzle/0007_terminals.sql +42 -0
  22. package/apps/server/drizzle/0008_resource_actions.sql +24 -0
  23. package/apps/server/drizzle/0009_terminal_title.sql +1 -0
  24. package/apps/server/drizzle/0010_services.sql +32 -0
  25. package/apps/server/drizzle/0011_deployments.sql +88 -0
  26. package/apps/server/drizzle/0012_deployment_authorizations.sql +67 -0
  27. package/apps/server/drizzle/0013_service_ops.sql +64 -0
  28. package/apps/server/drizzle/0014_service_actions.sql +36 -0
  29. package/apps/server/drizzle/0015_model_catalog.sql +17 -0
  30. package/apps/server/drizzle/0016_multi_provider.sql +2 -0
  31. package/apps/server/drizzle/0017_model_visibility.sql +10 -0
  32. package/apps/server/drizzle/0018_model_defaults.sql +9 -0
  33. package/apps/server/drizzle/0019_credential_endpoint.sql +1 -0
  34. package/apps/server/drizzle/0020_compatible_context.sql +1 -0
  35. package/apps/server/drizzle/0021_context_summaries.sql +13 -0
  36. package/apps/server/drizzle/0022_scheduler.sql +58 -0
  37. package/apps/server/drizzle/0023_turn_terminal_reason.sql +1 -0
  38. package/apps/server/drizzle/0024_turn_checkpoints.sql +4 -0
  39. package/apps/server/drizzle/0025_turn_resume.sql +1 -0
  40. package/apps/server/drizzle/0026_session_pin.sql +1 -0
  41. package/apps/server/drizzle/0027_project_sort_order.sql +2 -0
  42. package/apps/server/drizzle/meta/0001_snapshot.json +705 -0
  43. package/apps/server/drizzle/meta/0002_snapshot.json +784 -0
  44. package/apps/server/drizzle/meta/0003_snapshot.json +1300 -0
  45. package/apps/server/drizzle/meta/0004_snapshot.json +1489 -0
  46. package/apps/server/drizzle/meta/0005_snapshot.json +1794 -0
  47. package/apps/server/drizzle/meta/0006_snapshot.json +1953 -0
  48. package/apps/server/drizzle/meta/0007_snapshot.json +2232 -0
  49. package/apps/server/drizzle/meta/0008_snapshot.json +2391 -0
  50. package/apps/server/drizzle/meta/0009_snapshot.json +2398 -0
  51. package/apps/server/drizzle/meta/0010_snapshot.json +2601 -0
  52. package/apps/server/drizzle/meta/0015_snapshot.json +4332 -0
  53. package/apps/server/drizzle/meta/0016_snapshot.json +4346 -0
  54. package/apps/server/drizzle/meta/0017_snapshot.json +4408 -0
  55. package/apps/server/drizzle/meta/0018_snapshot.json +4468 -0
  56. package/apps/server/drizzle/meta/0019_snapshot.json +4475 -0
  57. package/apps/server/drizzle/meta/0020_snapshot.json +4482 -0
  58. package/apps/server/drizzle/meta/0021_snapshot.json +4565 -0
  59. package/apps/server/drizzle/meta/0022_snapshot.json +4960 -0
  60. package/apps/server/drizzle/meta/0023_snapshot.json +4967 -0
  61. package/apps/server/drizzle/meta/0024_snapshot.json +4994 -0
  62. package/apps/server/drizzle/meta/0025_snapshot.json +5001 -0
  63. package/apps/server/drizzle/meta/0026_snapshot.json +5008 -0
  64. package/apps/server/drizzle/meta/0027_snapshot.json +5021 -0
  65. package/apps/server/drizzle/meta/_journal.json +195 -0
  66. package/apps/server/package.json +57 -0
  67. package/apps/web/dist/assets/FileEditor-twkRcPR8.js +1 -0
  68. package/apps/web/dist/assets/FileViewer-B6J1gfWW.js +1 -0
  69. package/apps/web/dist/assets/abap-08VXUWAP.js +1 -0
  70. package/apps/web/dist/assets/apex-BWPQTe0t.js +1 -0
  71. package/apps/web/dist/assets/azcli-Bc_sGQ0U.js +1 -0
  72. package/apps/web/dist/assets/bat-i0X4ZdIN.js +1 -0
  73. package/apps/web/dist/assets/bicep-B5-_aFwp.js +2 -0
  74. package/apps/web/dist/assets/cameligo-DMUM7wLl.js +1 -0
  75. package/apps/web/dist/assets/clojure-Cm7r79vr.js +1 -0
  76. package/apps/web/dist/assets/codicon-DF1abBS2.ttf +0 -0
  77. package/apps/web/dist/assets/coffee-Ba7i2nA0.js +1 -0
  78. package/apps/web/dist/assets/cpp-C7h46wYY.js +1 -0
  79. package/apps/web/dist/assets/csharp-BKxtCVv1.js +1 -0
  80. package/apps/web/dist/assets/csp-bTuwJoIa.js +1 -0
  81. package/apps/web/dist/assets/css-DIMkf-bt.js +3 -0
  82. package/apps/web/dist/assets/css.worker-C5TGqYcS.js +96 -0
  83. package/apps/web/dist/assets/cssMode-B2gCrV51.js +1 -0
  84. package/apps/web/dist/assets/cypher-CVaqCwHa.js +1 -0
  85. package/apps/web/dist/assets/dart-onAF5SnQ.js +1 -0
  86. package/apps/web/dist/assets/dockerfile-DZFCIeNp.js +1 -0
  87. package/apps/web/dist/assets/ecl-94qehhXe.js +1 -0
  88. package/apps/web/dist/assets/editor-B8GMDV7_.css +1 -0
  89. package/apps/web/dist/assets/editor.api-TQGsXQVT.js +908 -0
  90. package/apps/web/dist/assets/editor.worker-uJzjfcWc.js +33 -0
  91. package/apps/web/dist/assets/elixir-6RTg0lbw.js +1 -0
  92. package/apps/web/dist/assets/flow9-C5_-GSwl.js +1 -0
  93. package/apps/web/dist/assets/freemarker2-Due01FLd.js +3 -0
  94. package/apps/web/dist/assets/fsharp-C8Ef5oNN.js +1 -0
  95. package/apps/web/dist/assets/go-C-y9NEjX.js +1 -0
  96. package/apps/web/dist/assets/graphql-fmXr3nnJ.js +1 -0
  97. package/apps/web/dist/assets/handlebars-Cbmho-0R.js +1 -0
  98. package/apps/web/dist/assets/hcl-CpzslTdj.js +1 -0
  99. package/apps/web/dist/assets/html-1Ke8CI8o.js +1 -0
  100. package/apps/web/dist/assets/html.worker-DthhmbAk.js +509 -0
  101. package/apps/web/dist/assets/htmlMode-KxcipU--.js +1 -0
  102. package/apps/web/dist/assets/index-BvfzAW2A.js +158 -0
  103. package/apps/web/dist/assets/index-DxcI8GSl.css +1 -0
  104. package/apps/web/dist/assets/ini-sBoK_t0W.js +1 -0
  105. package/apps/web/dist/assets/java-BEtHBSE6.js +1 -0
  106. package/apps/web/dist/assets/javascript-DMPkDcJu.js +1 -0
  107. package/apps/web/dist/assets/json.worker-BGaEIa3n.js +65 -0
  108. package/apps/web/dist/assets/jsonMode-CLqudskm.js +7 -0
  109. package/apps/web/dist/assets/julia-Bri6UV-V.js +1 -0
  110. package/apps/web/dist/assets/kotlin-BOotOW0E.js +1 -0
  111. package/apps/web/dist/assets/less-B9JPFI3C.js +2 -0
  112. package/apps/web/dist/assets/lexon-CfSJPG6W.js +1 -0
  113. package/apps/web/dist/assets/liquid-bIUiAHG1.js +1 -0
  114. package/apps/web/dist/assets/lspLanguageFeatures-CplKbdW4.js +4 -0
  115. package/apps/web/dist/assets/lua-CsQS60Ue.js +1 -0
  116. package/apps/web/dist/assets/m3-D-oSqn_W.js +1 -0
  117. package/apps/web/dist/assets/markdown-Cimd5fb3.js +1 -0
  118. package/apps/web/dist/assets/mdx-DiInMCu3.js +1 -0
  119. package/apps/web/dist/assets/mips-CIPQ_RoX.js +1 -0
  120. package/apps/web/dist/assets/monaco-D_A7VB90.js +68 -0
  121. package/apps/web/dist/assets/monaco-n7clI0si.css +1 -0
  122. package/apps/web/dist/assets/msdax-DauUninz.js +1 -0
  123. package/apps/web/dist/assets/mysql-SOo6toE5.js +1 -0
  124. package/apps/web/dist/assets/objective-c-FvmIjYaQ.js +1 -0
  125. package/apps/web/dist/assets/pascal-DrH0SRf2.js +1 -0
  126. package/apps/web/dist/assets/pascaligo-D-ptJ9y-.js +1 -0
  127. package/apps/web/dist/assets/perl-oz_6vUea.js +1 -0
  128. package/apps/web/dist/assets/pgsql-DTj74zXo.js +1 -0
  129. package/apps/web/dist/assets/php-nr791fC2.js +1 -0
  130. package/apps/web/dist/assets/pla-CopQ2nXW.js +1 -0
  131. package/apps/web/dist/assets/postiats-43DmfD33.js +1 -0
  132. package/apps/web/dist/assets/powerquery-D3hlyOfw.js +1 -0
  133. package/apps/web/dist/assets/powershell-DmHpPYUd.js +1 -0
  134. package/apps/web/dist/assets/protobuf-C531GsRP.js +2 -0
  135. package/apps/web/dist/assets/pug-Z5eAx3Zn.js +1 -0
  136. package/apps/web/dist/assets/python-O93J5sRJ.js +1 -0
  137. package/apps/web/dist/assets/qsharp-DkqhCAOL.js +1 -0
  138. package/apps/web/dist/assets/r-BwWrilGY.js +1 -0
  139. package/apps/web/dist/assets/razor-DpA8sAYd.js +1 -0
  140. package/apps/web/dist/assets/redis-ClamHrr6.js +1 -0
  141. package/apps/web/dist/assets/redshift-DT7zqm-g.js +1 -0
  142. package/apps/web/dist/assets/restructuredtext-BYgofb2h.js +1 -0
  143. package/apps/web/dist/assets/ruby-DezsRK8O.js +1 -0
  144. package/apps/web/dist/assets/rust-DdL9SqIa.js +1 -0
  145. package/apps/web/dist/assets/sb-CcwsVR0C.js +1 -0
  146. package/apps/web/dist/assets/scala-DHpiXF5c.js +1 -0
  147. package/apps/web/dist/assets/scheme-BeGwcela.js +1 -0
  148. package/apps/web/dist/assets/scss-gp-XZpBa.js +3 -0
  149. package/apps/web/dist/assets/shell-CC2rA5mh.js +1 -0
  150. package/apps/web/dist/assets/solidity-BEEn4gHE.js +1 -0
  151. package/apps/web/dist/assets/sophia-CRfGWb83.js +1 -0
  152. package/apps/web/dist/assets/sparql-D_Lu-MrJ.js +1 -0
  153. package/apps/web/dist/assets/sql-NEE52Syq.js +1 -0
  154. package/apps/web/dist/assets/st-DbInun42.js +1 -0
  155. package/apps/web/dist/assets/swift-Bxkupp3x.js +1 -0
  156. package/apps/web/dist/assets/systemverilog-Bz4Y3fRF.js +1 -0
  157. package/apps/web/dist/assets/tcl-DISqw1ZD.js +1 -0
  158. package/apps/web/dist/assets/ts.worker-CUR_zL4j.js +67741 -0
  159. package/apps/web/dist/assets/tsMode-qBmFN2NS.js +11 -0
  160. package/apps/web/dist/assets/twig-De2hgUGE.js +1 -0
  161. package/apps/web/dist/assets/typescript-BjR2yH8S.js +1 -0
  162. package/apps/web/dist/assets/typespec-B8J7ngcE.js +1 -0
  163. package/apps/web/dist/assets/vb-DV3o63ZY.js +1 -0
  164. package/apps/web/dist/assets/wgsl-DpFanUEy.js +298 -0
  165. package/apps/web/dist/assets/workers-x9_8y1ur.js +1 -0
  166. package/apps/web/dist/assets/xml-CL70_TAY.js +1 -0
  167. package/apps/web/dist/assets/yaml-qno5z39m.js +1 -0
  168. package/apps/web/dist/favicon.svg +4 -0
  169. package/apps/web/dist/index.html +15 -0
  170. package/docs/README.md +26 -0
  171. package/docs/guides/install.md +88 -0
  172. package/package.json +95 -4
@@ -0,0 +1,2138 @@
1
+ import { Fn as MAX_EDITABLE_FILE_BYTES, _n as OriginUrlSchema, kn as FilePathSchema } from "./paths-BHryFHwq.js";
2
+ import { constants, existsSync, readFileSync, realpathSync, statSync, watch } from "node:fs";
3
+ import path from "node:path";
4
+ import { execFile, spawn } from "node:child_process";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import { promisify } from "node:util";
7
+ import { createHash, randomInt, randomUUID } from "node:crypto";
8
+ import { access, lstat, mkdir, open, opendir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
9
+ import { z } from "zod";
10
+ import { applyPatch, diffLines, parsePatch } from "diff";
11
+ import { tmpdir } from "node:os";
12
+ // ../../packages/resources/src/commands/redactor.ts
13
+ const PREFIX = /(authorization|api[_-]?key|token|password|cookie|secret)["']?\s{0,16}[:=]\s{0,16}(["']?)/i;
14
+ const DELIMITER = /[\s"'&;,}]/;
15
+ var OutputRedactor = class {
16
+ #pending = "";
17
+ #suppress = false;
18
+ #quote = "";
19
+ #escaped = false;
20
+ #header = false;
21
+ #awaitValue = false;
22
+ #secrets;
23
+ constructor(secrets) {
24
+ if (secrets.some((secret) => secret.length > 65536)) throw new Error("Unsupported secret size");
25
+ this.#secrets = secrets.filter(Boolean);
26
+ }
27
+ #safeLength() {
28
+ let held = 0;
29
+ for (const secret of this.#secrets) for (let length = Math.min(this.#pending.length, secret.length - 1); length > held; length--) if (this.#pending.endsWith(secret.slice(0, length))) {
30
+ held = length;
31
+ break;
32
+ }
33
+ const tail = this.#pending.slice(-64).toLowerCase();
34
+ for (let index = 0; index < tail.length; index++) {
35
+ const suffix = tail.slice(index);
36
+ if ([
37
+ "authorization",
38
+ "apikey",
39
+ "api_key",
40
+ "api-key",
41
+ "token",
42
+ "password",
43
+ "cookie",
44
+ "secret"
45
+ ].some((label) => label.startsWith(suffix) || suffix.startsWith(label) && /^["']?\s{0,16}(?:[:=]\s{0,16}["']?)?$/.test(suffix.slice(label.length)))) {
46
+ held = Math.max(held, suffix.length);
47
+ break;
48
+ }
49
+ }
50
+ return this.#pending.length - held;
51
+ }
52
+ push(text, final = false) {
53
+ this.#pending += text;
54
+ let output = "";
55
+ while (this.#pending.length) {
56
+ if (this.#suppress) {
57
+ if (this.#awaitValue) {
58
+ this.#pending = this.#pending.replace(/^[ \t]+/, "");
59
+ if (!this.#pending.length) break;
60
+ this.#awaitValue = false;
61
+ const first = this.#pending[0];
62
+ if (first === "\"" || first === "'") {
63
+ this.#quote = first;
64
+ output += `${first}[Redacted]`;
65
+ this.#pending = this.#pending.slice(1);
66
+ } else if (first === "\r" || first === "\n") {
67
+ this.#suppress = false;
68
+ continue;
69
+ } else output += "[Redacted]";
70
+ }
71
+ let end = -1;
72
+ if (this.#quote) for (let i = 0; i < this.#pending.length; i++) {
73
+ const char = this.#pending[i];
74
+ if (this.#escaped) {
75
+ this.#escaped = false;
76
+ continue;
77
+ }
78
+ if (char === "\\") {
79
+ this.#escaped = true;
80
+ continue;
81
+ }
82
+ if (char === this.#quote) {
83
+ end = i;
84
+ break;
85
+ }
86
+ }
87
+ else end = this.#pending.search(this.#header ? /[\r\n]/ : DELIMITER);
88
+ if (end < 0) {
89
+ this.#pending = "";
90
+ break;
91
+ }
92
+ this.#pending = this.#pending.slice(end);
93
+ this.#suppress = false;
94
+ }
95
+ const safe = final ? this.#pending.length : this.#safeLength();
96
+ const prefix = PREFIX.exec(this.#pending);
97
+ let index = prefix?.index ?? Infinity;
98
+ let length = prefix?.[0].length ?? 0;
99
+ let field = !!prefix;
100
+ for (const secret of this.#secrets) {
101
+ const found = this.#pending.indexOf(secret);
102
+ if (found >= 0 && (found < index || found === index && !field && secret.length > length)) {
103
+ index = found;
104
+ length = secret.length;
105
+ field = false;
106
+ }
107
+ }
108
+ if (index >= safe && !(field && index === 0)) {
109
+ if (!safe) break;
110
+ output += this.#pending.slice(0, safe);
111
+ this.#pending = this.#pending.slice(safe);
112
+ continue;
113
+ }
114
+ const awaiting = !final && field && !prefix?.[2] && index + length === this.#pending.length;
115
+ let label = field ? this.#pending.slice(index, index + length) : "";
116
+ for (const secret of this.#secrets) label = label.replaceAll(secret, "[Redacted]");
117
+ output += `${this.#pending.slice(0, index)}${label}${awaiting ? "" : "[Redacted]"}`;
118
+ this.#pending = this.#pending.slice(index + length);
119
+ this.#suppress = field;
120
+ this.#awaitValue = awaiting;
121
+ this.#quote = field ? prefix?.[2] ?? "" : "";
122
+ this.#header = field && /^(authorization|cookie)$/i.test(prefix?.[1] ?? "");
123
+ this.#escaped = false;
124
+ }
125
+ return output;
126
+ }
127
+ };
128
+ // ../../packages/resources/src/platform/environment.ts
129
+ const POSIX_KEYS = [
130
+ "PATH",
131
+ "HOME",
132
+ "TMPDIR",
133
+ "TMP",
134
+ "TEMP",
135
+ "LANG",
136
+ "LC_ALL",
137
+ "LC_CTYPE",
138
+ "TERM"
139
+ ];
140
+ const WINDOWS_KEYS = [
141
+ "PATH",
142
+ "PATHEXT",
143
+ "SystemRoot",
144
+ "SystemDrive",
145
+ "windir",
146
+ "COMSPEC",
147
+ "ComSpec",
148
+ "USERPROFILE",
149
+ "APPDATA",
150
+ "LOCALAPPDATA",
151
+ "HOMEDRIVE",
152
+ "HOMEPATH",
153
+ "USERNAME",
154
+ "USERDOMAIN",
155
+ "TEMP",
156
+ "TMP",
157
+ "TMPDIR",
158
+ "NUMBER_OF_PROCESSORS",
159
+ "PROCESSOR_ARCHITECTURE",
160
+ "PROGRAMDATA",
161
+ "PROGRAMFILES",
162
+ "PROGRAMFILES(X86)",
163
+ "PSModulePath",
164
+ "LANG",
165
+ "LC_ALL",
166
+ "LC_CTYPE",
167
+ "TERM"
168
+ ];
169
+ /**
170
+ * Build the deliberately small environment every managed child receives.
171
+ * Callers may add scoped variables (PM2_HOME, TZ, job ids) on top.
172
+ */
173
+ function commandEnvironment(source = process.env) {
174
+ const env = {};
175
+ const keys = process.platform === "win32" ? WINDOWS_KEYS : POSIX_KEYS;
176
+ const seen = /* @__PURE__ */ new Set();
177
+ for (const key of keys) {
178
+ const identity = process.platform === "win32" ? key.toLowerCase() : key;
179
+ if (seen.has(identity)) continue;
180
+ if (source[key] !== void 0) {
181
+ seen.add(identity);
182
+ env[key] = source[key];
183
+ }
184
+ }
185
+ return env;
186
+ }
187
+ /** Absolute Windows PowerShell 5.1 path, which ships with Windows 10/11. */
188
+ function windowsPowerShell() {
189
+ return `${process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
190
+ }
191
+ /** Quote a value as a PowerShell single-quoted literal. */
192
+ function powerShellLiteral(value) {
193
+ return `'${value.replaceAll("'", "''")}'`;
194
+ }
195
+ /** Encode a PowerShell script without cmd/PowerShell command-line quoting. */
196
+ function powerShellEncodedCommand(script) {
197
+ return Buffer.from(script, "utf16le").toString("base64");
198
+ }
199
+ /** Arguments for a non-interactive PowerShell invocation. */
200
+ function powerShellArguments(script, noExit = false) {
201
+ return [
202
+ "-NoLogo",
203
+ "-NoProfile",
204
+ "-NonInteractive",
205
+ ...noExit ? ["-NoExit"] : [],
206
+ "-ExecutionPolicy",
207
+ "Bypass",
208
+ "-EncodedCommand",
209
+ powerShellEncodedCommand(script)
210
+ ];
211
+ }
212
+ // ../../packages/resources/src/platform/process.ts
213
+ const exec$3 = promisify(execFile);
214
+ async function runPowerShell(script, timeoutMs = 1e4) {
215
+ const { stdout } = await exec$3(windowsPowerShell(), powerShellArguments(script), {
216
+ timeout: timeoutMs,
217
+ maxBuffer: 16777216,
218
+ windowsHide: true,
219
+ env: commandEnvironment()
220
+ });
221
+ return stdout;
222
+ }
223
+ async function posixSnapshot() {
224
+ const { stdout } = await exec$3("/bin/ps", ["-axo", "pid=,ppid=,pgid=,sess=,stat=,lstart="], {
225
+ timeout: 5e3,
226
+ maxBuffer: 8388608,
227
+ env: {
228
+ ...commandEnvironment(),
229
+ LC_ALL: "C"
230
+ }
231
+ });
232
+ const entries = [];
233
+ for (const line of stdout.split("\n")) {
234
+ const fields = line.trim().split(/\s+/);
235
+ if (fields.length < 10 || fields[4]?.startsWith("Z")) continue;
236
+ entries.push({
237
+ pid: Number(fields[0]),
238
+ ppid: Number(fields[1]),
239
+ pgid: Number(fields[2]),
240
+ session: Number(fields[3]),
241
+ birth: fields.slice(5).join(" "),
242
+ command: ""
243
+ });
244
+ }
245
+ return entries;
246
+ }
247
+ const WINDOWS_SNAPSHOT = String.raw`
248
+ $ErrorActionPreference = 'Stop'
249
+ Get-CimInstance Win32_Process | ForEach-Object {
250
+ $born = if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().Ticks } else { 0 }
251
+ $command = if ($_.CommandLine) { $_.CommandLine -replace "[\r\n]+", " " } else { "" }
252
+ [Console]::Out.WriteLine(("{0}|{1}|{2}|{3}" -f $_.ProcessId, $_.ParentProcessId, $born, $command))
253
+ }
254
+ `;
255
+ async function windowsSnapshot() {
256
+ const stdout = await runPowerShell(WINDOWS_SNAPSHOT, 15e3);
257
+ const entries = [];
258
+ for (const line of stdout.split(/\r?\n/)) {
259
+ if (!line) continue;
260
+ const first = line.indexOf("|");
261
+ const second = line.indexOf("|", first + 1);
262
+ const third = line.indexOf("|", second + 1);
263
+ if (first < 0 || second < 0 || third < 0) continue;
264
+ const pid = Number(line.slice(0, first));
265
+ const ppid = Number(line.slice(first + 1, second));
266
+ const birth = line.slice(second + 1, third);
267
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(ppid)) continue;
268
+ entries.push({
269
+ pid,
270
+ ppid,
271
+ pgid: 0,
272
+ session: 0,
273
+ birth,
274
+ command: line.slice(third + 1)
275
+ });
276
+ }
277
+ return entries;
278
+ }
279
+ let snapshotCache = null;
280
+ let snapshotInFlight = null;
281
+ /**
282
+ * Snapshot every live process. Windows uses CIM because `ps` is unavailable;
283
+ * repeated CIM calls are expensive, so a very short cache coalesces the
284
+ * per-second reconciliation probes without hiding a stopped process for long.
285
+ */
286
+ function processSnapshot() {
287
+ if (process.platform !== "win32") return posixSnapshot();
288
+ if (snapshotCache && Date.now() - snapshotCache.at < 300) return Promise.resolve(snapshotCache.entries);
289
+ if (snapshotInFlight) return snapshotInFlight;
290
+ snapshotInFlight = windowsSnapshot().catch(async () => {
291
+ await new Promise((resolve) => setTimeout(resolve, 100));
292
+ return windowsSnapshot();
293
+ }).then((entries) => {
294
+ snapshotCache = {
295
+ at: Date.now(),
296
+ entries
297
+ };
298
+ return entries;
299
+ }).finally(() => {
300
+ snapshotInFlight = null;
301
+ });
302
+ return snapshotInFlight;
303
+ }
304
+ function processAlive(pid) {
305
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
306
+ try {
307
+ process.kill(pid, 0);
308
+ return true;
309
+ } catch (error) {
310
+ return error.code === "EPERM";
311
+ }
312
+ }
313
+ /** Descendants of `pid` in parent-before-child order, including `pid` itself. */
314
+ async function processTreePids(pid) {
315
+ const entries = await processSnapshot();
316
+ const byParent = /* @__PURE__ */ new Map();
317
+ for (const entry of entries) {
318
+ const children = byParent.get(entry.ppid) ?? [];
319
+ children.push(entry.pid);
320
+ byParent.set(entry.ppid, children);
321
+ }
322
+ const result = [];
323
+ const queue = [pid];
324
+ const seen = /* @__PURE__ */ new Set();
325
+ while (queue.length) {
326
+ const current = queue.shift();
327
+ if (seen.has(current)) continue;
328
+ seen.add(current);
329
+ result.push(current);
330
+ for (const child of byParent.get(current) ?? []) queue.push(child);
331
+ }
332
+ return result;
333
+ }
334
+ async function taskkill(args) {
335
+ try {
336
+ await exec$3("taskkill", args, {
337
+ timeout: 5e3,
338
+ maxBuffer: 1048576,
339
+ windowsHide: true,
340
+ env: commandEnvironment()
341
+ });
342
+ } catch {}
343
+ }
344
+ /**
345
+ * Force-stop a process tree on Windows. taskkill walks the live parent/child
346
+ * tree; known descendants are then retried individually so a parent exiting
347
+ * first cannot leave an orphan behind.
348
+ */
349
+ async function terminateProcessTree(pid, graceMs = 2e3) {
350
+ if (process.platform !== "win32") throw new Error("Windows process termination only");
351
+ if (pid === process.pid || !Number.isSafeInteger(pid) || pid <= 0) return false;
352
+ const known = await processTreePids(pid).catch(() => [pid]);
353
+ await taskkill([
354
+ "/PID",
355
+ String(pid),
356
+ "/T",
357
+ "/F"
358
+ ]);
359
+ const deadline = Date.now() + graceMs;
360
+ while (Date.now() < deadline) {
361
+ for (const target of known) if (target !== pid && processAlive(target)) await taskkill([
362
+ "/PID",
363
+ String(target),
364
+ "/T",
365
+ "/F"
366
+ ]);
367
+ if (!processAlive(pid) && known.every((target) => !processAlive(target))) return true;
368
+ await new Promise((resolve) => setTimeout(resolve, 50));
369
+ }
370
+ return !processAlive(pid) && known.every((target) => !processAlive(target));
371
+ }
372
+ async function processCommandLine(pid) {
373
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;
374
+ if (process.platform === "win32") {
375
+ const script = String.raw`
376
+ $ErrorActionPreference = 'Stop'
377
+ $process = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"
378
+ if ($process -and $process.CommandLine) { [Console]::Out.Write($process.CommandLine) }
379
+ `;
380
+ try {
381
+ const value = (await runPowerShell(script, 5e3)).trim();
382
+ return value.length ? value : null;
383
+ } catch {
384
+ return null;
385
+ }
386
+ }
387
+ try {
388
+ const { stdout } = await exec$3("/bin/ps", [
389
+ "-ww",
390
+ "-p",
391
+ String(pid),
392
+ "-o",
393
+ "command="
394
+ ], {
395
+ timeout: 2e3,
396
+ maxBuffer: 262144,
397
+ env: {
398
+ ...commandEnvironment(),
399
+ LC_ALL: "C"
400
+ }
401
+ });
402
+ const value = stdout.trim();
403
+ return value.length ? value : null;
404
+ } catch {
405
+ return null;
406
+ }
407
+ }
408
+ const listenerCache = /* @__PURE__ */ new Map();
409
+ const listenerInFlight = /* @__PURE__ */ new Map();
410
+ /** TCP listeners for a loopback-relevant port on Windows. */
411
+ async function windowsTcpListeners(port) {
412
+ if (process.platform !== "win32") throw new Error("Windows listener lookup only");
413
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) return [];
414
+ const cached = listenerCache.get(port);
415
+ if (cached && Date.now() - cached.at < 1e3) return cached.listeners;
416
+ const pending = listenerInFlight.get(port);
417
+ if (pending) return pending;
418
+ const script = String.raw`
419
+ $ErrorActionPreference = 'Stop'
420
+ Get-NetTCPConnection -State Listen -LocalPort ${port} | ForEach-Object {
421
+ [Console]::Out.WriteLine(("{0}|{1}|{2}" -f $_.OwningProcess, $_.LocalAddress, $_.LocalPort))
422
+ }
423
+ `;
424
+ const task = (async () => {
425
+ for (let attempt = 0; attempt < 5; attempt += 1) {
426
+ let stdout;
427
+ try {
428
+ stdout = await runPowerShell(script, 8e3);
429
+ } catch {
430
+ if (attempt < 4) await new Promise((resolve) => setTimeout(resolve, 150));
431
+ continue;
432
+ }
433
+ const listeners = [];
434
+ for (const line of stdout.split(/\r?\n/)) {
435
+ if (!line) continue;
436
+ const first = line.indexOf("|");
437
+ const second = line.indexOf("|", first + 1);
438
+ if (first < 0 || second < 0) continue;
439
+ const pid = Number(line.slice(0, first));
440
+ const address = line.slice(first + 1, second);
441
+ const value = Number(line.slice(second + 1));
442
+ if (!Number.isSafeInteger(pid) || !address || !Number.isInteger(value)) continue;
443
+ listeners.push({
444
+ pid,
445
+ address,
446
+ port: value
447
+ });
448
+ }
449
+ if (listeners.length > 0 || attempt === 4) return listeners;
450
+ await new Promise((resolve) => setTimeout(resolve, 150));
451
+ }
452
+ return [];
453
+ })().then((listeners) => {
454
+ listenerCache.set(port, {
455
+ at: Date.now(),
456
+ listeners
457
+ });
458
+ return listeners;
459
+ }).finally(() => {
460
+ listenerInFlight.delete(port);
461
+ });
462
+ listenerInFlight.set(port, task);
463
+ return task;
464
+ }
465
+ // ../../packages/resources/src/commands/windows.ts
466
+ function fileExists(candidate) {
467
+ try {
468
+ return statSync(candidate).isFile();
469
+ } catch {
470
+ return false;
471
+ }
472
+ }
473
+ function extensions() {
474
+ return (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((entry) => entry.trim().toLowerCase()).filter(Boolean);
475
+ }
476
+ function withExtensions(candidate) {
477
+ if (path.extname(candidate)) return [candidate];
478
+ return extensions().map((extension) => `${candidate}${extension}`);
479
+ }
480
+ /** Resolve a Windows executable without invoking cmd.exe. */
481
+ function resolveWindowsExecutable(executable, cwd) {
482
+ const hasSeparator = executable.includes("\\") || executable.includes("/");
483
+ if (path.isAbsolute(executable) || hasSeparator) {
484
+ const base = path.resolve(cwd, executable);
485
+ for (const candidate of withExtensions(base)) if (fileExists(candidate)) return candidate;
486
+ return base;
487
+ }
488
+ for (const directory of (process.env.PATH ?? "").split(";")) {
489
+ const trimmed = directory.trim().replace(/^"(.*)"$/, "$1");
490
+ if (!trimmed) continue;
491
+ for (const candidate of withExtensions(path.join(trimmed, executable))) if (fileExists(candidate)) return candidate;
492
+ }
493
+ return executable;
494
+ }
495
+ function scriptInvocation(target, args) {
496
+ const script = [
497
+ "$ErrorActionPreference = 'Stop'",
498
+ [`& ${powerShellLiteral(target)}`, ...args.map(powerShellLiteral)].join(" "),
499
+ "if ($null -eq $LASTEXITCODE) { exit 0 } else { exit $LASTEXITCODE }"
500
+ ].join("\n");
501
+ return {
502
+ executable: windowsPowerShell(),
503
+ args: powerShellArguments(script),
504
+ shim: true
505
+ };
506
+ }
507
+ /**
508
+ * Windows cannot CreateProcess a .cmd/.bat shim directly. Launch those (and
509
+ * .ps1 scripts) through an encoded PowerShell script so every argument stays a
510
+ * literal instead of being interpolated into a shell command line.
511
+ */
512
+ function windowsLaunch(executable, args, cwd) {
513
+ const target = resolveWindowsExecutable(executable, cwd);
514
+ const extension = path.extname(target).toLowerCase();
515
+ if (extension === ".cmd" || extension === ".bat" || extension === ".ps1") return scriptInvocation(target, args);
516
+ return {
517
+ executable: target,
518
+ args,
519
+ shim: false
520
+ };
521
+ }
522
+ // ../../packages/resources/src/commands/runner.ts
523
+ const exec$2 = promisify(execFile);
524
+ const MAX_COMMAND_OUTPUT_BYTES = 1048576;
525
+ async function groupMembers(pgid) {
526
+ const { stdout } = await exec$2("/bin/ps", ["-axo", "pid=,pgid=,stat=,lstart=,comm="], {
527
+ timeout: 2e3,
528
+ maxBuffer: 2097152,
529
+ env: {
530
+ ...commandEnvironment(),
531
+ LC_ALL: "C"
532
+ }
533
+ });
534
+ const members = [];
535
+ for (const line of stdout.split("\n")) {
536
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/.exec(line);
537
+ if (match && Number(match[2]) === pgid && !match[3].startsWith("Z")) members.push({
538
+ pid: Number(match[1]),
539
+ birth: match[4]
540
+ });
541
+ }
542
+ return members;
543
+ }
544
+ async function groupAlive(pid) {
545
+ return (await groupMembers(pid)).length > 0;
546
+ }
547
+ function signalGroup(pid, signal) {
548
+ try {
549
+ process.kill(-pid, signal);
550
+ } catch (error) {
551
+ if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) throw new Error("Process stop failed");
552
+ }
553
+ }
554
+ const delay$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
555
+ async function stopCommandGroup(pid, graceMs = 300, authorizeSignal) {
556
+ try {
557
+ const initial = await groupMembers(pid);
558
+ if (!initial.length) return true;
559
+ if (!await authorizeSignal?.(initial)) return false;
560
+ signalGroup(pid, "SIGTERM");
561
+ const deadline = Date.now() + graceMs;
562
+ while (Date.now() < deadline) {
563
+ if (!await groupAlive(pid)) return true;
564
+ await delay$1(20);
565
+ }
566
+ const remaining = await groupMembers(pid);
567
+ if (!remaining.length) return true;
568
+ if (!await authorizeSignal?.(remaining)) return false;
569
+ signalGroup(pid, "SIGKILL");
570
+ const hardDeadline = Date.now() + 2e3;
571
+ while (Date.now() < hardDeadline) {
572
+ if (!await groupAlive(pid)) return true;
573
+ await delay$1(20);
574
+ }
575
+ return false;
576
+ } catch {
577
+ return false;
578
+ }
579
+ }
580
+ async function stopWindowsTree(pid, captured, graceMs, authorizeSignal) {
581
+ const known = new Set(captured);
582
+ known.add(pid);
583
+ if (![...known].some((target) => processAlive(target))) return true;
584
+ if (authorizeSignal && !await authorizeSignal()) return false;
585
+ if (!await terminateProcessTree(pid, Math.max(2e3, graceMs + 2e3))) return false;
586
+ return [...known].every((target) => !processAlive(target));
587
+ }
588
+ async function runCommand(options) {
589
+ if (!Number.isInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > 6e5) throw new Error("Invalid command timeout");
590
+ if (options.signal?.aborted) return {
591
+ exitCode: null,
592
+ reasonCode: "CANCELLED",
593
+ truncated: false,
594
+ stopped: true
595
+ };
596
+ const streams = {
597
+ stdout: {
598
+ decoder: new StringDecoder("utf8"),
599
+ redact: new OutputRedactor(options.secrets ?? [])
600
+ },
601
+ stderr: {
602
+ decoder: new StringDecoder("utf8"),
603
+ redact: new OutputRedactor(options.secrets ?? [])
604
+ }
605
+ };
606
+ let reason = null, truncated = false, used = 0;
607
+ let stop;
608
+ let exitCode = null;
609
+ let finishStop;
610
+ const stopFinished = new Promise((resolve) => {
611
+ finishStop = resolve;
612
+ });
613
+ const windows = process.platform === "win32";
614
+ const owned = /* @__PURE__ */ new Map();
615
+ const windowsOwned = /* @__PURE__ */ new Set();
616
+ let birthCapture = Promise.resolve();
617
+ let windowsCapture = Promise.resolve();
618
+ const authorizeSignal = async () => {
619
+ if (windows) {
620
+ await windowsCapture;
621
+ if (!child.pid) return false;
622
+ return processAlive(child.pid) || [...windowsOwned].some((pid) => processAlive(pid));
623
+ }
624
+ await birthCapture;
625
+ if (!child.pid) return false;
626
+ const members = await groupMembers(child.pid);
627
+ if (!members.some((member) => owned.get(member.pid) === member.birth)) return false;
628
+ if (child.exitCode === null && child.signalCode === null && members.some((member) => member.pid === child.pid && owned.get(member.pid) === member.birth)) for (const member of members) owned.set(member.pid, member.birth);
629
+ return true;
630
+ };
631
+ const startStop = () => {
632
+ if (!child.pid || stop) return;
633
+ stop = windows ? stopWindowsTree(child.pid, windowsOwned, options.stopGraceMs ?? 300, authorizeSignal) : stopCommandGroup(child.pid, options.stopGraceMs, authorizeSignal);
634
+ stop.then(() => {
635
+ setTimeout(() => finishStop?.(), 200);
636
+ });
637
+ };
638
+ const launch = windows ? windowsLaunch(options.executable, options.args, options.cwd) : {
639
+ executable: options.executable,
640
+ args: options.args
641
+ };
642
+ const child = spawn(launch.executable, launch.args, {
643
+ cwd: options.cwd,
644
+ env: {
645
+ ...commandEnvironment(options.env),
646
+ ...options.pm2Home ? {
647
+ PM2_HOME: options.pm2Home,
648
+ PM2_NO_INTERACTION: "true",
649
+ PM2_DISABLE_MODULES: "true"
650
+ } : {}
651
+ },
652
+ shell: false,
653
+ detached: !windows,
654
+ windowsHide: true,
655
+ stdio: [
656
+ "ignore",
657
+ "pipe",
658
+ "pipe"
659
+ ]
660
+ });
661
+ const requestStop = (code) => {
662
+ reason ??= code;
663
+ startStop();
664
+ };
665
+ const emit = (channel, text) => {
666
+ let bytes = Buffer.from(text);
667
+ while (bytes.length) {
668
+ const room = MAX_COMMAND_OUTPUT_BYTES - used;
669
+ if (room <= 0) {
670
+ truncated = true;
671
+ return;
672
+ }
673
+ let length = Math.min(bytes.length, 16384, room);
674
+ while (length > 0 && length < bytes.length && (bytes[length] & 192) === 128) length--;
675
+ if (!length) {
676
+ truncated = true;
677
+ return;
678
+ }
679
+ used += length;
680
+ try {
681
+ options.onOutput?.({
682
+ channel,
683
+ data: bytes.subarray(0, length).toString("utf8"),
684
+ timestamp: Date.now()
685
+ });
686
+ } catch {
687
+ truncated = true;
688
+ requestStop("OUTPUT_FAILED");
689
+ }
690
+ bytes = bytes.subarray(length);
691
+ }
692
+ };
693
+ for (const channel of ["stdout", "stderr"]) child[channel].on("data", (bytes) => {
694
+ const stream = streams[channel];
695
+ emit(channel, stream.redact.push(stream.decoder.write(bytes)));
696
+ });
697
+ const abort = () => requestStop("CANCELLED");
698
+ options.signal?.addEventListener("abort", abort, { once: true });
699
+ if (options.signal?.aborted) abort();
700
+ const timeout = setTimeout(() => requestStop("TIMED_OUT"), options.timeoutMs);
701
+ const closed = new Promise((resolve) => {
702
+ child.once("close", (code) => {
703
+ exitCode = code;
704
+ resolve();
705
+ });
706
+ });
707
+ child.once("error", () => {
708
+ reason ??= "SPAWN_FAILED";
709
+ });
710
+ child.once("spawn", () => {
711
+ if (child.pid) {
712
+ if (windows) windowsCapture = processTreePids(child.pid).then((pids) => {
713
+ if (child.exitCode === null && child.signalCode === null) for (const pid of pids) windowsOwned.add(pid);
714
+ }).catch(() => {});
715
+ else birthCapture = groupMembers(child.pid).then((members) => {
716
+ if (child.exitCode === null && child.signalCode === null) for (const member of members) owned.set(member.pid, member.birth);
717
+ }).catch(() => {});
718
+ }
719
+ try {
720
+ if (child.pid) options.onSpawn?.(child.pid);
721
+ } catch {
722
+ requestStop("START_RECORD_FAILED");
723
+ }
724
+ });
725
+ child.once("exit", () => {
726
+ startStop();
727
+ });
728
+ const pipesClosed = await Promise.race([closed.then(() => true), stopFinished.then(() => false)]);
729
+ if (!pipesClosed) {
730
+ truncated = true;
731
+ child.stdout.destroy();
732
+ child.stderr.destroy();
733
+ child.unref();
734
+ }
735
+ clearTimeout(timeout);
736
+ options.signal?.removeEventListener("abort", abort);
737
+ const stopped = pipesClosed && (child.pid ? await (stop ?? (windows ? stopWindowsTree(child.pid, windowsOwned, options.stopGraceMs ?? 300, authorizeSignal) : stopCommandGroup(child.pid, options.stopGraceMs, authorizeSignal))) : true);
738
+ for (const channel of ["stdout", "stderr"]) {
739
+ const stream = streams[channel];
740
+ emit(channel, stream.redact.push(stream.decoder.end(), true));
741
+ }
742
+ return {
743
+ exitCode,
744
+ reasonCode: !stopped ? "STOP_UNCONFIRMED" : reason ?? (exitCode === 0 ? null : "NONZERO_EXIT"),
745
+ truncated,
746
+ stopped
747
+ };
748
+ }
749
+ // ../../packages/resources/src/files/pathGuard.ts
750
+ var PathGuardError = class extends Error {
751
+ code;
752
+ constructor(code, message) {
753
+ super(message);
754
+ this.name = "PathGuardError";
755
+ this.code = code;
756
+ }
757
+ };
758
+ function validateInput(input) {
759
+ if (input.trim().length === 0 || input.includes("\0")) throw new PathGuardError("INVALID_PATH", "path must be non-empty and must not contain NUL");
760
+ }
761
+ function isInsideRoot(rootReal, candidateReal) {
762
+ const relative = path.relative(rootReal, candidateReal);
763
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
764
+ }
765
+ function assertInsideRoot(rootReal, candidateReal) {
766
+ if (!isInsideRoot(rootReal, candidateReal)) throw new PathGuardError("PATH_OUTSIDE_PROJECT", "path escapes the authorized project root");
767
+ return candidateReal;
768
+ }
769
+ async function canonicalDirectory(input) {
770
+ validateInput(input);
771
+ let resolved;
772
+ try {
773
+ resolved = await realpath(input);
774
+ } catch (error) {
775
+ const code = error.code;
776
+ throw new PathGuardError(code === "ENOENT" ? "NOT_FOUND" : "INVALID_PATH", `cannot resolve directory: ${code ?? "unknown"}`);
777
+ }
778
+ if (!(await stat(resolved)).isDirectory()) throw new PathGuardError("INVALID_PATH", "path is not a directory");
779
+ try {
780
+ await access(resolved, constants.R_OK);
781
+ } catch {
782
+ throw new PathGuardError("INVALID_PATH", "directory is not readable");
783
+ }
784
+ return resolved;
785
+ }
786
+ async function resolveInsideRoot(rootReal, input) {
787
+ validateInput(input);
788
+ if (!path.isAbsolute(rootReal)) throw new PathGuardError("INVALID_PATH", "project root must be absolute");
789
+ const absolute = path.isAbsolute(input) ? path.normalize(input) : path.resolve(rootReal, input);
790
+ const missing = [];
791
+ let current = absolute;
792
+ for (;;) {
793
+ try {
794
+ const existing = await realpath(current);
795
+ return assertInsideRoot(rootReal, path.join(existing, ...missing));
796
+ } catch (error) {
797
+ if (!(error instanceof PathGuardError)) {
798
+ const code = error.code;
799
+ if (code !== "ENOENT") throw new PathGuardError("INVALID_PATH", `cannot resolve path: ${code ?? "unknown"}`);
800
+ } else throw error;
801
+ }
802
+ const parent = path.dirname(current);
803
+ if (parent === current) throw new PathGuardError("INVALID_PATH", "path cannot be resolved");
804
+ missing.unshift(path.basename(current));
805
+ current = parent;
806
+ }
807
+ }
808
+ // ../../packages/resources/src/files/fileService.ts
809
+ const MAX_TOOL_OUTPUT_BYTES = 1048576;
810
+ const MAX_TOOL_OUTPUT_LINES = 2e3;
811
+ const MAX_READ_BYTES = 1048576;
812
+ const MAX_WRITE_BYTES = 1048576;
813
+ const DEFAULT_IGNORED = /* @__PURE__ */ new Set([
814
+ ".git",
815
+ "node_modules",
816
+ ".larness"
817
+ ]);
818
+ var FileError = class extends Error {
819
+ code;
820
+ details;
821
+ constructor(code, message, details) {
822
+ super(message);
823
+ this.name = "FileError";
824
+ this.code = code;
825
+ this.details = details;
826
+ }
827
+ };
828
+ function toPosix(relative) {
829
+ return relative.split(path.sep).join("/");
830
+ }
831
+ function fromPosix(relative) {
832
+ return relative.split("/").join(path.sep);
833
+ }
834
+ function isIgnoredFile(relativePath, name, extra) {
835
+ if (DEFAULT_IGNORED.has(name)) return true;
836
+ return extra.some((raw) => {
837
+ const pattern = raw.trim().replace(/^\.?\/+/, "").replace(/\/+$/, "");
838
+ if (pattern.length === 0) return false;
839
+ if (pattern.includes("/")) return relativePath === pattern || relativePath.startsWith(`${pattern}/`);
840
+ return name === pattern;
841
+ });
842
+ }
843
+ function assertNotBinary(buffer, displayPath) {
844
+ if (buffer.includes(0)) throw new FileError("VALIDATION_ERROR", `file is not text: ${displayPath}`);
845
+ }
846
+ function mapPathError(error) {
847
+ if (error instanceof PathGuardError) {
848
+ if (error.code === "NOT_FOUND") throw new FileError("NOT_FOUND", error.message);
849
+ if (error.code === "PATH_OUTSIDE_PROJECT") throw new FileError("PATH_OUTSIDE_PROJECT", error.message);
850
+ throw new FileError("VALIDATION_ERROR", error.message);
851
+ }
852
+ throw error;
853
+ }
854
+ function mapFsError(error) {
855
+ const code = error.code;
856
+ if (code === "ENOENT") throw new FileError("NOT_FOUND", "path not found");
857
+ if (code === "EACCES" || code === "EPERM" || code === "ENOTDIR" || code === "EISDIR") throw new FileError("VALIDATION_ERROR", `path is not accessible: ${code}`);
858
+ throw new FileError("INTERNAL", `file operation failed: ${code ?? "unknown"}`);
859
+ }
860
+ async function statOrThrow(target) {
861
+ try {
862
+ return await stat(target);
863
+ } catch (error) {
864
+ mapFsError(error);
865
+ }
866
+ }
867
+ async function readFileOrThrow(target) {
868
+ try {
869
+ return await readFile(target);
870
+ } catch (error) {
871
+ mapFsError(error);
872
+ }
873
+ }
874
+ async function readDirOrThrow(dir, options) {
875
+ try {
876
+ return await readdir(dir, options);
877
+ } catch (error) {
878
+ mapFsError(error);
879
+ }
880
+ }
881
+ async function writeFileOrThrow(target, content) {
882
+ try {
883
+ await writeFile(target, content, "utf8");
884
+ } catch (error) {
885
+ mapFsError(error);
886
+ }
887
+ }
888
+ async function resolveInput(rootReal, input) {
889
+ try {
890
+ return await resolveInsideRoot(rootReal, fromPosix(input));
891
+ } catch (error) {
892
+ mapPathError(error);
893
+ }
894
+ }
895
+ async function listFiles(rootReal, options = {}) {
896
+ const base = await resolveInput(rootReal, options.path ?? ".");
897
+ if (!(await statOrThrow(base)).isDirectory()) throw new FileError("VALIDATION_ERROR", "path is not a directory");
898
+ const depth = Math.min(Math.max(Math.trunc(options.depth ?? 3), 1), 10);
899
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 500), 1), 2e3);
900
+ const ignore = options.ignore ?? [];
901
+ const files = [];
902
+ let truncated = false;
903
+ const walk = async (dir, level) => {
904
+ if (truncated) return;
905
+ const entries = await readDirOrThrow(dir, { withFileTypes: true });
906
+ entries.sort((left, right) => left.name.localeCompare(right.name));
907
+ for (const entry of entries) {
908
+ if (truncated) return;
909
+ const absolute = path.join(dir, entry.name);
910
+ const relativePath = toPosix(path.relative(rootReal, absolute));
911
+ if (isIgnoredFile(relativePath, entry.name, ignore) || entry.isSymbolicLink()) continue;
912
+ if (entry.isDirectory()) {
913
+ files.push({
914
+ path: relativePath,
915
+ name: entry.name,
916
+ type: "directory"
917
+ });
918
+ if (files.length > limit) {
919
+ truncated = true;
920
+ return;
921
+ }
922
+ if (level < depth) await walk(absolute, level + 1);
923
+ } else if (entry.isFile()) {
924
+ const info = await statOrThrow(absolute);
925
+ files.push({
926
+ path: relativePath,
927
+ name: entry.name,
928
+ type: "file",
929
+ size: info.size
930
+ });
931
+ if (files.length > limit) {
932
+ truncated = true;
933
+ return;
934
+ }
935
+ }
936
+ }
937
+ };
938
+ await walk(base, 1);
939
+ if (files.length > limit) {
940
+ files.pop();
941
+ truncated = true;
942
+ }
943
+ return {
944
+ files,
945
+ truncated
946
+ };
947
+ }
948
+ function hashContent(buffer) {
949
+ return createHash("sha256").update(buffer).digest("hex");
950
+ }
951
+ async function readTextFile(rootReal, options) {
952
+ const target = await resolveInput(rootReal, options.path);
953
+ const info = await statOrThrow(target);
954
+ if (!info.isFile()) throw new FileError("VALIDATION_ERROR", "path is not a file");
955
+ if (info.size > 1048576) throw new FileError("TOO_LARGE", `file exceeds ${MAX_READ_BYTES} bytes`, { size: info.size });
956
+ const buffer = await readFileOrThrow(target);
957
+ const version = hashContent(buffer);
958
+ assertNotBinary(buffer, options.path);
959
+ const lines = buffer.toString("utf8").split(/\r?\n/);
960
+ const offset = Math.max(Math.trunc(options.offset ?? 1), 1);
961
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 2e3), 1), MAX_TOOL_OUTPUT_LINES);
962
+ const selected = lines.slice(offset - 1, offset - 1 + limit);
963
+ const fitted = options.maxChars === void 0 ? {
964
+ lines: selected,
965
+ clipped: false
966
+ } : fitLines(selected, options.maxChars);
967
+ const kept = fitted.lines;
968
+ const content = kept.join("\n");
969
+ const byteLength = Buffer.byteLength(content, "utf8");
970
+ const truncated = fitted.clipped || offset - 1 + kept.length < lines.length || byteLength > 1048576;
971
+ return {
972
+ path: toPosix(path.relative(rootReal, target)),
973
+ version,
974
+ content: byteLength > 1048576 ? Buffer.from(content, "utf8").subarray(0, MAX_TOOL_OUTPUT_BYTES).toString("utf8") : content,
975
+ truncated,
976
+ totalLines: lines.length,
977
+ offset,
978
+ nextOffset: Math.min(lines.length + 1, offset + kept.length)
979
+ };
980
+ }
981
+ /**
982
+ * Whole-line page that fits `maxChars` (joined with newlines). At least one
983
+ * line is returned; a single line longer than the budget is cut and counted as
984
+ * consumed, so paging always advances. A cut line is reported as `clipped`.
985
+ */
986
+ function fitLines(lines, maxChars) {
987
+ const budget = Math.max(1e3, Math.trunc(maxChars));
988
+ let used = 0;
989
+ let count = 0;
990
+ let clipped = false;
991
+ for (const line of lines) {
992
+ if (count === 0) {
993
+ used = Math.min(line.length, budget);
994
+ clipped = line.length > budget;
995
+ count = 1;
996
+ continue;
997
+ }
998
+ const next = used + 1 + line.length;
999
+ if (next > budget) break;
1000
+ used = next;
1001
+ count += 1;
1002
+ }
1003
+ const kept = lines.slice(0, Math.max(1, count));
1004
+ if (clipped && kept[0] !== void 0) kept[0] = kept[0].slice(0, budget);
1005
+ return {
1006
+ lines: kept,
1007
+ clipped
1008
+ };
1009
+ }
1010
+ function globToRegExp(glob) {
1011
+ let pattern = "";
1012
+ for (let index = 0; index < glob.length; index += 1) {
1013
+ const char = glob[index] ?? "";
1014
+ if (char === "*") {
1015
+ if (glob[index + 1] === "*" && glob[index + 2] === "/") {
1016
+ pattern += "(?:.*/)?";
1017
+ index += 2;
1018
+ } else if (glob[index + 1] === "*") {
1019
+ pattern += ".*";
1020
+ index += 1;
1021
+ } else pattern += "[^/]*";
1022
+ } else if (char === "?") pattern += "[^/]";
1023
+ else pattern += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
1024
+ }
1025
+ return new RegExp(`^${pattern}$`);
1026
+ }
1027
+ async function searchCode(rootReal, options) {
1028
+ const query = options.query.trim();
1029
+ if (query.length === 0 || query.length > 500) throw new FileError("VALIDATION_ERROR", "query must be 1-500 characters");
1030
+ const base = await resolveInput(rootReal, options.path ?? ".");
1031
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 100), 1), 500);
1032
+ const ignore = options.ignore ?? [];
1033
+ const needle = options.caseSensitive === true ? query : query.toLowerCase();
1034
+ const contextLines = Math.min(Math.max(Math.trunc(options.contextLines ?? 0), 0), 5);
1035
+ const maxFiles = Math.min(Math.max(Math.trunc(options.maxFiles ?? 2e3), 1), 2e4);
1036
+ const globPattern = options.glob === void 0 ? void 0 : globToRegExp(options.glob);
1037
+ const matches = [];
1038
+ let scannedFiles = 0;
1039
+ let truncated = false;
1040
+ let scanBudgetExhausted = false;
1041
+ const searchFile = async (file) => {
1042
+ if (truncated || scanBudgetExhausted) return;
1043
+ const info = await statOrThrow(file);
1044
+ if (!info.isFile() || info.size > 262144) return;
1045
+ const buffer = await readFileOrThrow(file);
1046
+ if (buffer.includes(0)) return;
1047
+ const relativePath = toPosix(path.relative(rootReal, file));
1048
+ if (globPattern !== void 0 && !globPattern.test(relativePath)) return;
1049
+ scannedFiles += 1;
1050
+ if (scannedFiles >= maxFiles) scanBudgetExhausted = true;
1051
+ const lines = buffer.toString("utf8").split(/\r?\n/);
1052
+ for (let index = 0; index < lines.length; index += 1) {
1053
+ const line = lines[index] ?? "";
1054
+ if (!(options.caseSensitive === true ? line : line.toLowerCase()).includes(needle)) continue;
1055
+ const context = contextLines === 0 ? void 0 : lines.slice(Math.max(0, index - contextLines), index + contextLines + 1).join("\n").slice(0, 2e3);
1056
+ matches.push({
1057
+ path: relativePath,
1058
+ line: index + 1,
1059
+ preview: line.trim().slice(0, 240),
1060
+ ...context === void 0 ? {} : { context }
1061
+ });
1062
+ if (matches.length > limit) {
1063
+ truncated = true;
1064
+ return;
1065
+ }
1066
+ }
1067
+ };
1068
+ if ((await statOrThrow(base)).isFile()) {
1069
+ await searchFile(base);
1070
+ if (matches.length > limit) {
1071
+ matches.pop();
1072
+ truncated = true;
1073
+ }
1074
+ return {
1075
+ matches,
1076
+ truncated,
1077
+ scannedFiles,
1078
+ scanBudgetExhausted
1079
+ };
1080
+ }
1081
+ const walk = async (dir) => {
1082
+ if (truncated) return;
1083
+ const entries = await readDirOrThrow(dir, { withFileTypes: true });
1084
+ entries.sort((left, right) => left.name.localeCompare(right.name));
1085
+ for (const entry of entries) {
1086
+ if (truncated) return;
1087
+ const absolute = path.join(dir, entry.name);
1088
+ if (isIgnoredFile(toPosix(path.relative(rootReal, absolute)), entry.name, ignore) || entry.isSymbolicLink()) continue;
1089
+ if (entry.isDirectory()) await walk(absolute);
1090
+ else if (entry.isFile()) await searchFile(absolute);
1091
+ }
1092
+ };
1093
+ await walk(base);
1094
+ if (matches.length > limit) {
1095
+ matches.pop();
1096
+ truncated = true;
1097
+ }
1098
+ return {
1099
+ matches,
1100
+ truncated,
1101
+ scannedFiles,
1102
+ scanBudgetExhausted
1103
+ };
1104
+ }
1105
+ /**
1106
+ * Models regularly wrap diffs in code fences, escape newlines twice, or omit
1107
+ * the ---/+++ headers. Normalize those shapes before parsing instead of
1108
+ * rejecting an otherwise correct diff. Context matching stays exact
1109
+ * (fuzzFactor 0); only the envelope is repaired.
1110
+ */
1111
+ function normalizePatchText(patch, filePath) {
1112
+ let text = patch.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1113
+ const fenced = text.match(/^\s*```[a-zA-Z]*\s*\n([\s\S]*?)\n```\s*$/);
1114
+ if (fenced !== null && fenced[1] !== void 0) text = fenced[1];
1115
+ if (!text.includes("\n") && text.includes("\\n")) text = text.replace(/\\n/g, "\n").replace(/\\t/g, " ");
1116
+ const lines = text.split("\n");
1117
+ const start = lines.findIndex((line) => /^(--- |\+\+\+ |@@ |diff --git )/.test(line));
1118
+ if (start > 0) text = lines.slice(start).join("\n");
1119
+ if (/^@@ /m.test(text) && (!/^--- /m.test(text) || !/^\+\+\+ /m.test(text))) text = `--- a/${filePath}\n+++ b/${filePath}\n${text}`;
1120
+ return repairHunkEnvelope(text);
1121
+ }
1122
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/;
1123
+ /**
1124
+ * The model often miscounts `@@ -a,b +c,d @@`, drops the leading space of a
1125
+ * context line, or sends a blank line where a context line belongs. The body
1126
+ * is authoritative: recompute the counts from it and prefix bare lines as
1127
+ * context. Application still matches context exactly (fuzzFactor 0), so a
1128
+ * wrong repair fails closed instead of writing a different file.
1129
+ */
1130
+ function repairHunkEnvelope(text) {
1131
+ const lines = text.split("\n");
1132
+ const output = [];
1133
+ let index = 0;
1134
+ while (index < lines.length) {
1135
+ const line = lines[index] ?? "";
1136
+ const header = HUNK_HEADER.exec(line);
1137
+ if (header === null) {
1138
+ output.push(line);
1139
+ index += 1;
1140
+ continue;
1141
+ }
1142
+ const oldStart = header[1] ?? "0";
1143
+ const newStart = header[3] ?? "0";
1144
+ const tail = header[5] ?? "";
1145
+ index += 1;
1146
+ const body = [];
1147
+ let oldLines = 0;
1148
+ let newLines = 0;
1149
+ while (index < lines.length) {
1150
+ const bodyLine = lines[index] ?? "";
1151
+ if (bodyLine.startsWith("@@ ") || bodyLine.startsWith("diff --git ") || bodyLine.startsWith("Index: ") || bodyLine.startsWith("--- ") && (lines[index + 1] ?? "").startsWith("+++ ")) break;
1152
+ if (bodyLine.startsWith("\\ No newline")) {
1153
+ body.push(bodyLine);
1154
+ index += 1;
1155
+ continue;
1156
+ }
1157
+ if (bodyLine.length === 0) {
1158
+ if (index === lines.length - 1) {
1159
+ index += 1;
1160
+ break;
1161
+ }
1162
+ body.push(" ");
1163
+ oldLines += 1;
1164
+ newLines += 1;
1165
+ index += 1;
1166
+ continue;
1167
+ }
1168
+ const marker = bodyLine[0];
1169
+ if (marker === "+") {
1170
+ body.push(bodyLine);
1171
+ newLines += 1;
1172
+ } else if (marker === "-") {
1173
+ body.push(bodyLine);
1174
+ oldLines += 1;
1175
+ } else if (marker === " ") {
1176
+ body.push(bodyLine);
1177
+ oldLines += 1;
1178
+ newLines += 1;
1179
+ } else {
1180
+ body.push(` ${bodyLine}`);
1181
+ oldLines += 1;
1182
+ newLines += 1;
1183
+ }
1184
+ index += 1;
1185
+ }
1186
+ if (body.length === 0) {
1187
+ output.push(line);
1188
+ continue;
1189
+ }
1190
+ output.push(`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@${tail}`, ...body);
1191
+ }
1192
+ return output.join("\n");
1193
+ }
1194
+ function diagnosePatch(text, error) {
1195
+ if (!/^@@ /m.test(text)) return "missing @@ hunk header";
1196
+ if (!/^--- /m.test(text) || !/^\+\+\+ /m.test(text)) return "missing ---/+++ file headers";
1197
+ return (error instanceof Error ? error.message : "").trim().slice(0, 160) || "unrecognized diff format";
1198
+ }
1199
+ async function createTextFile(rootReal, options) {
1200
+ if (options.content.includes("\0")) throw new FileError("VALIDATION_ERROR", "content must be text");
1201
+ const bytes = Buffer.byteLength(options.content, "utf8");
1202
+ if (bytes > 1048576) throw new FileError("TOO_LARGE", `content exceeds ${MAX_WRITE_BYTES} bytes`, { bytes });
1203
+ const target = await resolveInput(rootReal, options.path);
1204
+ await mkdir(path.dirname(target), { recursive: true });
1205
+ try {
1206
+ await writeFile(target, options.content, {
1207
+ encoding: "utf8",
1208
+ flag: "wx",
1209
+ mode: 420
1210
+ });
1211
+ } catch (error) {
1212
+ const code = error.code;
1213
+ if (code === "EEXIST") throw new FileError("VERSION_CONFLICT", "file already exists; read it and use apply_patch to change it", { currentVersion: hashContent(await readFile(target)) });
1214
+ throw new FileError("INTERNAL", `cannot write file: ${code ?? "unknown"}`);
1215
+ }
1216
+ const buffer = await readFile(target);
1217
+ return {
1218
+ path: toPosix(path.relative(rootReal, target)),
1219
+ version: hashContent(buffer),
1220
+ bytes,
1221
+ lines: options.content.split("\n").length,
1222
+ created: true
1223
+ };
1224
+ }
1225
+ async function applyPatch$1(rootReal, options) {
1226
+ if (options.expectedVersion.trim().length === 0) throw new FileError("VALIDATION_ERROR", "expectedVersion is required");
1227
+ if (options.patch.trim().length === 0) throw new FileError("VALIDATION_ERROR", "patch must not be empty");
1228
+ const target = await resolveInput(rootReal, options.path);
1229
+ if (!(await statOrThrow(target)).isFile()) throw new FileError("VALIDATION_ERROR", "path is not a file");
1230
+ const originalBuffer = await readFileOrThrow(target);
1231
+ if (originalBuffer.includes(0)) throw new FileError("VALIDATION_ERROR", "file is not text");
1232
+ const previousVersion = hashContent(originalBuffer);
1233
+ if (previousVersion !== options.expectedVersion) throw new FileError("VERSION_CONFLICT", "file version does not match", { currentVersion: previousVersion });
1234
+ const original = originalBuffer.toString("utf8");
1235
+ const normalized = normalizePatchText(options.patch, options.path);
1236
+ try {
1237
+ const parsedPatches = parsePatch(normalized);
1238
+ if (parsedPatches.length === 0 || parsedPatches.every((parsed) => parsed.hunks.length === 0)) throw new FileError("INVALID_PATCH", `patch has no hunks: ${diagnosePatch(normalized, void 0)}`);
1239
+ } catch (error) {
1240
+ if (error instanceof FileError) throw error;
1241
+ throw new FileError("INVALID_PATCH", `patch could not be parsed: ${diagnosePatch(normalized, error)}`);
1242
+ }
1243
+ let patched;
1244
+ try {
1245
+ patched = applyPatch(original, normalized, { fuzzFactor: 0 });
1246
+ } catch {
1247
+ throw new FileError("INVALID_PATCH", "patch could not be applied");
1248
+ }
1249
+ if (patched === false) throw new FileError("INVALID_PATCH", "patch does not match the file");
1250
+ const currentBuffer = await readFileOrThrow(target);
1251
+ if (hashContent(currentBuffer) !== previousVersion) throw new FileError("VERSION_CONFLICT", "file changed while applying the patch", { currentVersion: hashContent(currentBuffer) });
1252
+ const changes = diffLines(original, patched, { newlineIsToken: false });
1253
+ let additions = 0;
1254
+ let deletions = 0;
1255
+ for (const change of changes) if (change.added === true) additions += change.count ?? 0;
1256
+ else if (change.removed === true) deletions += change.count ?? 0;
1257
+ await writeFileOrThrow(target, patched);
1258
+ return {
1259
+ path: toPosix(path.relative(rootReal, target)),
1260
+ version: hashContent(Buffer.from(patched, "utf8")),
1261
+ previousVersion,
1262
+ additions,
1263
+ deletions
1264
+ };
1265
+ }
1266
+ // ../../packages/resources/src/files/fileManager.ts
1267
+ var FileManagerError = class extends Error {
1268
+ code;
1269
+ details;
1270
+ requiresReconciliation;
1271
+ constructor(code, message, details, requiresReconciliation = false) {
1272
+ super(message);
1273
+ this.code = code;
1274
+ this.details = details;
1275
+ this.requiresReconciliation = requiresReconciliation;
1276
+ this.name = "FileManagerError";
1277
+ }
1278
+ };
1279
+ function reject(code, message) {
1280
+ throw new FileManagerError(code, message);
1281
+ }
1282
+ function filesystemError(error) {
1283
+ if (error instanceof FileManagerError) throw error;
1284
+ const code = z.object({ code: z.string() }).safeParse(error);
1285
+ if (code.success && ["ENOENT", "ENOTDIR"].includes(code.data.code)) reject("NOT_FOUND", "File is unavailable");
1286
+ if (code.success && [
1287
+ "EACCES",
1288
+ "EPERM",
1289
+ "ELOOP"
1290
+ ].includes(code.data.code)) reject("FORBIDDEN", "File access denied");
1291
+ reject("INTERNAL", "File operation failed");
1292
+ }
1293
+ function normalizeFilePath(value) {
1294
+ const parsed = FilePathSchema.safeParse(value);
1295
+ if (!parsed.success) reject("VALIDATION_ERROR", "Invalid relative file path");
1296
+ const parts = parsed.data.split("/").filter((item) => item && item !== ".");
1297
+ if (parts.some((part) => /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part) || /[. ]$/.test(part))) reject("VALIDATION_ERROR", "Unsupported file path");
1298
+ return parts.join("/") || ".";
1299
+ }
1300
+ async function resolveFilePath(root, relative) {
1301
+ try {
1302
+ const normalized = normalizeFilePath(relative);
1303
+ if (await realpath(root) !== root) reject("PATH_OUTSIDE_PROJECT", "Authorized root changed");
1304
+ let target = root;
1305
+ for (const part of normalized === "." ? [] : normalized.split("/")) {
1306
+ target = path.join(target, part);
1307
+ if ((await lstat(target)).isSymbolicLink()) reject("PATH_OUTSIDE_PROJECT", "Symbolic link access denied");
1308
+ }
1309
+ if (!isInsideRoot(root, await realpath(target))) reject("PATH_OUTSIDE_PROJECT", "Path outside authorized root");
1310
+ return target;
1311
+ } catch (error) {
1312
+ filesystemError(error);
1313
+ }
1314
+ }
1315
+ function encodeEditableContent(content) {
1316
+ const bytes = Buffer.from(content, "utf8");
1317
+ if (bytes.length > 524288) reject("PAYLOAD_TOO_LARGE", "File exceeds editing limit");
1318
+ if (bytes.includes(0)) reject("FILE_NOT_EDITABLE", "File is not UTF-8 text");
1319
+ try {
1320
+ if (new TextDecoder("utf-8", {
1321
+ fatal: true,
1322
+ ignoreBOM: true
1323
+ }).decode(bytes) !== content) reject("FILE_NOT_EDITABLE", "Invalid UTF-8 text");
1324
+ } catch {
1325
+ reject("FILE_NOT_EDITABLE", "Invalid UTF-8 text");
1326
+ }
1327
+ return bytes;
1328
+ }
1329
+ async function readEditableFile(root, relative, afterOpen) {
1330
+ try {
1331
+ const normalized = normalizeFilePath(relative);
1332
+ const target = await resolveFilePath(root, normalized);
1333
+ if (!(await lstat(target)).isFile()) reject("FILE_NOT_EDITABLE", "Only regular files are editable");
1334
+ const fd = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1335
+ try {
1336
+ const before = await fd.stat();
1337
+ if (!before.isFile()) reject("FILE_NOT_EDITABLE", "Only regular files are editable");
1338
+ if (before.size > 524288) reject("PAYLOAD_TOO_LARGE", "File exceeds editing limit");
1339
+ await afterOpen?.();
1340
+ const bytes = Buffer.alloc(MAX_EDITABLE_FILE_BYTES + 1);
1341
+ let size = 0;
1342
+ while (size < bytes.length) {
1343
+ const read = await fd.read(bytes, size, bytes.length - size, size);
1344
+ if (read.bytesRead === 0) break;
1345
+ size += read.bytesRead;
1346
+ }
1347
+ if (size > 524288) reject("PAYLOAD_TOO_LARGE", "File exceeds editing limit");
1348
+ const snapshot = await stat(await resolveFilePath(root, normalized));
1349
+ const after = await fd.stat();
1350
+ if (snapshot.ino !== before.ino || snapshot.dev !== before.dev || snapshot.size !== size || before.size !== after.size || before.mtimeMs !== after.mtimeMs) reject("CONFLICT", "File identity changed while reading");
1351
+ const buffer = bytes.subarray(0, size);
1352
+ if (buffer.includes(0)) reject("FILE_NOT_EDITABLE", "File is not UTF-8 text");
1353
+ let content;
1354
+ try {
1355
+ content = new TextDecoder("utf-8", {
1356
+ fatal: true,
1357
+ ignoreBOM: true
1358
+ }).decode(buffer);
1359
+ } catch {
1360
+ reject("FILE_NOT_EDITABLE", "File is not UTF-8 text");
1361
+ }
1362
+ return {
1363
+ path: normalized,
1364
+ realPath: target,
1365
+ content,
1366
+ version: hashContent(buffer),
1367
+ size,
1368
+ encoding: "utf-8",
1369
+ inode: before.ino,
1370
+ device: before.dev,
1371
+ mode: before.mode,
1372
+ mtime: before.mtimeMs
1373
+ };
1374
+ } finally {
1375
+ await fd.close();
1376
+ }
1377
+ } catch (error) {
1378
+ filesystemError(error);
1379
+ }
1380
+ }
1381
+ async function saveEditableFile(root, input, hooks) {
1382
+ const bytes = encodeEditableContent(input.content);
1383
+ const original = await readEditableFile(root, input.path);
1384
+ if (original.version !== input.expectedVersion) throw new FileManagerError("VERSION_CONFLICT", "File version changed", { currentVersion: original.version });
1385
+ const name = hooks.temporaryName ?? `.larness-save-${randomUUID()}`;
1386
+ if (!/^\.larness-save-[a-zA-Z0-9_-]+$/.test(name)) reject("INTERNAL", "Invalid save operation identity");
1387
+ const temporary = path.join(path.dirname(original.realPath), name);
1388
+ let result;
1389
+ let failed = false;
1390
+ let failure;
1391
+ let temporaryCreated = false;
1392
+ let temporaryIdentity;
1393
+ try {
1394
+ hooks.assertFence?.();
1395
+ const fd = await open(temporary, "wx", 384);
1396
+ temporaryCreated = true;
1397
+ try {
1398
+ temporaryIdentity = await fd.stat();
1399
+ hooks.assertFence?.();
1400
+ await fd.writeFile(bytes);
1401
+ await fd.chmod(original.mode & 511);
1402
+ await fd.sync();
1403
+ } finally {
1404
+ await fd.close();
1405
+ }
1406
+ await hooks.beforeCommit();
1407
+ const current = await readEditableFile(root, input.path);
1408
+ if (current.version !== original.version) throw new FileManagerError("VERSION_CONFLICT", "File version changed", { currentVersion: current.version });
1409
+ if (current.inode !== original.inode || current.device !== original.device) reject("CONFLICT", "File identity changed");
1410
+ hooks.assertFence?.();
1411
+ await rename(temporary, original.realPath);
1412
+ hooks.onReplaced?.();
1413
+ result = {
1414
+ path: original.path,
1415
+ realPath: original.realPath,
1416
+ content: input.content,
1417
+ version: hashContent(bytes),
1418
+ size: bytes.length,
1419
+ encoding: "utf-8"
1420
+ };
1421
+ } catch (error) {
1422
+ failed = true;
1423
+ failure = error;
1424
+ }
1425
+ try {
1426
+ if (temporaryCreated) {
1427
+ const current = await lstat(temporary);
1428
+ if (!temporaryIdentity || current.ino !== temporaryIdentity.ino || current.dev !== temporaryIdentity.dev) reject("RESOURCE_UNAVAILABLE", "Temporary save identity changed");
1429
+ await rm(temporary);
1430
+ }
1431
+ } catch (error) {
1432
+ if (!z.object({ code: z.literal("ENOENT") }).safeParse(error).success) throw new FileManagerError("RESOURCE_UNAVAILABLE", "File save cleanup requires reconciliation", void 0, true);
1433
+ }
1434
+ if (failed) filesystemError(failure);
1435
+ if (!result) reject("INTERNAL", "File save did not produce a result");
1436
+ return result;
1437
+ }
1438
+ const CursorSchema = z.object({
1439
+ directory: z.string(),
1440
+ revision: z.string(),
1441
+ offset: z.number().int().nonnegative()
1442
+ }).strict();
1443
+ async function listDirectory(root, input) {
1444
+ try {
1445
+ const relative = normalizeFilePath(input.path);
1446
+ const target = await resolveFilePath(root, relative);
1447
+ if (!(await stat(target)).isDirectory()) reject("VALIDATION_ERROR", "Expected directory");
1448
+ const identity = await stat(target);
1449
+ const entries = [];
1450
+ const stamps = [];
1451
+ for (const entry of await readdir(target, { withFileTypes: true })) {
1452
+ const file = path.posix.join(relative, entry.name);
1453
+ if (!entry.isFile() && !entry.isDirectory() || isIgnoredFile(file, entry.name, input.ignore ?? [])) continue;
1454
+ if (input.exclude?.(path.join(target, entry.name))) continue;
1455
+ const resolved = await resolveFilePath(root, file);
1456
+ const info = await lstat(resolved);
1457
+ const type = info.isDirectory() ? "directory" : info.isFile() ? "file" : null;
1458
+ if (type === null) continue;
1459
+ entries.push({
1460
+ name: entry.name,
1461
+ path: file,
1462
+ type,
1463
+ ...type === "file" ? { size: info.size } : {}
1464
+ });
1465
+ stamps.push([
1466
+ file,
1467
+ info.ino,
1468
+ info.size,
1469
+ info.mtimeMs
1470
+ ]);
1471
+ }
1472
+ const after = await stat(await resolveFilePath(root, relative));
1473
+ if (identity.ino !== after.ino || identity.dev !== after.dev || identity.mtimeMs !== after.mtimeMs) reject("CONFLICT", "Directory changed during listing");
1474
+ entries.sort((a, b) => (a.type === b.type ? 0 : a.type === "directory" ? -1 : 1) || a.name.localeCompare(b.name));
1475
+ const revision = hashContent(Buffer.from(JSON.stringify(stamps.sort())));
1476
+ const directory = hashContent(Buffer.from(target));
1477
+ let offset = 0;
1478
+ if (input.cursor) {
1479
+ let cursor;
1480
+ try {
1481
+ cursor = CursorSchema.parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
1482
+ } catch {
1483
+ reject("VALIDATION_ERROR", "Invalid file cursor");
1484
+ }
1485
+ if (cursor.directory !== directory || cursor.revision !== revision || cursor.offset > entries.length) reject("CONFLICT", "Directory snapshot changed");
1486
+ offset = cursor.offset;
1487
+ }
1488
+ const end = offset + input.limit;
1489
+ return {
1490
+ items: entries.slice(offset, end),
1491
+ revision,
1492
+ nextCursor: end < entries.length ? Buffer.from(JSON.stringify({
1493
+ directory,
1494
+ revision,
1495
+ offset: end
1496
+ })).toString("base64url") : null
1497
+ };
1498
+ } catch (error) {
1499
+ filesystemError(error);
1500
+ }
1501
+ }
1502
+ // ../../packages/resources/src/files/watchSnapshot.ts
1503
+ async function scanWatchPath(root, relative, options) {
1504
+ let target;
1505
+ try {
1506
+ target = await resolveFilePath(root, relative);
1507
+ } catch (error) {
1508
+ if (error instanceof FileManagerError && error.code === "NOT_FOUND") return {
1509
+ nodes: /* @__PURE__ */ new Map(),
1510
+ identity: "missing",
1511
+ partial: false
1512
+ };
1513
+ throw error;
1514
+ }
1515
+ const before = await lstat(target);
1516
+ const nodes = /* @__PURE__ */ new Map();
1517
+ let partial = false;
1518
+ if (options.directory && before.isDirectory()) {
1519
+ const directory = await opendir(target);
1520
+ let scanned = 0;
1521
+ for await (const entry of directory) {
1522
+ if (++scanned > options.limit) {
1523
+ partial = true;
1524
+ break;
1525
+ }
1526
+ if (!entry.isDirectory() && !entry.isFile()) continue;
1527
+ const child = path.posix.join(relative, entry.name);
1528
+ if (isIgnoredFile(child, entry.name, options.ignore) || entry.name.startsWith(".larness-save-")) continue;
1529
+ if (options.exclude?.(path.join(target, entry.name))) continue;
1530
+ const real = await resolveFilePath(root, child);
1531
+ const info = await lstat(real);
1532
+ if (!info.isFile() && !info.isDirectory()) continue;
1533
+ nodes.set(child, {
1534
+ type: info.isDirectory() ? "directory" : "file",
1535
+ size: info.size,
1536
+ mtime: info.mtimeMs,
1537
+ inode: info.ino,
1538
+ device: info.dev
1539
+ });
1540
+ }
1541
+ } else if (!options.directory && before.isFile()) {
1542
+ let version;
1543
+ try {
1544
+ version = (await readEditableFile(root, relative)).version;
1545
+ } catch (error) {
1546
+ if (!(error instanceof FileManagerError) || !["FILE_NOT_EDITABLE", "PAYLOAD_TOO_LARGE"].includes(error.code)) throw error;
1547
+ }
1548
+ nodes.set(relative, {
1549
+ type: "file",
1550
+ size: before.size,
1551
+ mtime: before.mtimeMs,
1552
+ inode: before.ino,
1553
+ device: before.dev,
1554
+ version
1555
+ });
1556
+ } else throw new FileManagerError("CONFLICT", "Watched path type changed");
1557
+ const after = await stat(await resolveFilePath(root, relative));
1558
+ if (before.ino !== after.ino || before.dev !== after.dev || before.mtimeMs !== after.mtimeMs) throw new FileManagerError("CONFLICT", "Watched path changed during scan");
1559
+ return {
1560
+ nodes,
1561
+ identity: `${before.dev}:${before.ino}`,
1562
+ partial
1563
+ };
1564
+ }
1565
+ const createDirectoryWatcher = (directory, changed, failed) => {
1566
+ const watcher = watch(directory, changed);
1567
+ watcher.on("error", failed);
1568
+ return watcher;
1569
+ };
1570
+ // ../../packages/resources/src/git/index.ts
1571
+ const exec$1 = promisify(execFile);
1572
+ var GitError = class extends Error {
1573
+ code;
1574
+ constructor(code, message) {
1575
+ super(message);
1576
+ this.code = code;
1577
+ this.name = "GitError";
1578
+ }
1579
+ };
1580
+ const MAX_OUTPUT = 2097152;
1581
+ function gitEnvironment() {
1582
+ const env = {
1583
+ ...commandEnvironment(),
1584
+ ...process.env.USER !== void 0 ? { USER: process.env.USER } : {},
1585
+ LC_ALL: "C",
1586
+ GIT_TERMINAL_PROMPT: "0",
1587
+ GIT_PAGER: "cat",
1588
+ GIT_OPTIONAL_LOCKS: "0",
1589
+ GIT_MERGE_AUTOEDIT: "no"
1590
+ };
1591
+ if (process.platform !== "win32") {
1592
+ env.GIT_ASKPASS = "/bin/false";
1593
+ env.SSH_ASKPASS = "/bin/false";
1594
+ }
1595
+ return env;
1596
+ }
1597
+ function classify(stderr, readOnly) {
1598
+ const text = stderr.toLowerCase();
1599
+ if (text.includes("authentication failed") || text.includes("could not read username") || text.includes("permission denied") || text.includes("terminal prompts disabled")) return new GitError("GIT_AUTH_REQUIRED", "Git host authentication is required");
1600
+ if (text.includes("not possible to fast-forward") || text.includes("diverging branches")) return new GitError("GIT_CONFLICT", "Git operation cannot be applied without a merge");
1601
+ if (text.includes("not a git repository")) return new GitError("GIT_UNAVAILABLE", "Git repository is unavailable");
1602
+ return new GitError(readOnly ? "GIT_UNAVAILABLE" : "GIT_CONFLICT", readOnly ? "Git command failed" : "Git operation was rejected");
1603
+ }
1604
+ async function runGit(root, args, options = {}) {
1605
+ try {
1606
+ const { stdout, stderr } = await exec$1("git", args, {
1607
+ cwd: root,
1608
+ env: gitEnvironment(),
1609
+ timeout: options.timeoutMs ?? 15e3,
1610
+ maxBuffer: options.maxBuffer ?? MAX_OUTPUT,
1611
+ encoding: "buffer",
1612
+ windowsHide: true
1613
+ });
1614
+ return {
1615
+ stdout: stdout.toString("utf8"),
1616
+ stderr: stderr.toString("utf8")
1617
+ };
1618
+ } catch (error) {
1619
+ if (!(error instanceof Error)) throw new GitError("GIT_UNAVAILABLE", "Git command failed");
1620
+ const value = error;
1621
+ if (value.code === "ENOENT") throw new GitError("GIT_UNAVAILABLE", "Git is not installed");
1622
+ if (value.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") throw new GitError("PAYLOAD_TOO_LARGE", "Git output exceeds the limit");
1623
+ if (value.killed || value.code === "ETIMEDOUT") throw new GitError("GIT_CONFLICT", "Git command timed out");
1624
+ throw classify(value.stderr?.toString("utf8") ?? "", options.readOnly === true);
1625
+ }
1626
+ }
1627
+ function validateGitPath(root, value) {
1628
+ if (!value || value.length > 4096 || value.includes("\0")) throw new GitError("GIT_CONFLICT", "Invalid Git path");
1629
+ if (path.isAbsolute(value)) throw new GitError("GIT_CONFLICT", "Git path must be relative");
1630
+ const normalized = value.replaceAll("\\", "/");
1631
+ const segments = normalized.split("/");
1632
+ if (segments.some((segment) => segment === "" || segment === "." || segment === "..") || segments[0] === ".git") throw new GitError("GIT_CONFLICT", "Invalid Git path");
1633
+ if (!isInsideRoot(root, path.resolve(root, normalized))) throw new GitError("GIT_CONFLICT", "Git path escapes root");
1634
+ return normalized;
1635
+ }
1636
+ function parseStatus(raw) {
1637
+ const tokens = raw.split("\0");
1638
+ const status = {
1639
+ branch: "HEAD",
1640
+ head: null,
1641
+ upstream: null,
1642
+ ahead: 0,
1643
+ behind: 0,
1644
+ staged: [],
1645
+ unstaged: [],
1646
+ untracked: [],
1647
+ conflicts: []
1648
+ };
1649
+ for (let index = 0; index < tokens.length; index++) {
1650
+ const token = tokens[index] ?? "";
1651
+ if (!token) continue;
1652
+ if (token.startsWith("# branch.oid ")) status.head = token.slice(13).trim();
1653
+ else if (token.startsWith("# branch.head ")) status.branch = token.slice(14).trim();
1654
+ else if (token.startsWith("# branch.upstream ")) status.upstream = token.slice(18).trim();
1655
+ else if (token.startsWith("# branch.ab ")) {
1656
+ const match = /^\+(\d+) -(\d+)$/.exec(token.slice(12).trim());
1657
+ if (match) {
1658
+ status.ahead = Number(match[1]);
1659
+ status.behind = Number(match[2]);
1660
+ }
1661
+ } else if (token.startsWith("? ")) status.untracked.push(token.slice(2));
1662
+ else if (token.startsWith("1 ")) {
1663
+ const fields = token.split(" ");
1664
+ const pathValue = fields.slice(8).join(" ");
1665
+ pushEntry(status, fields[1] ?? "..", pathValue, null);
1666
+ } else if (token.startsWith("2 ")) {
1667
+ const fields = token.split(" ");
1668
+ const pathValue = fields.slice(9).join(" ");
1669
+ const origPath = tokens[index + 1] ?? null;
1670
+ index += 1;
1671
+ pushEntry(status, fields[1] ?? "..", pathValue, origPath);
1672
+ } else if (token.startsWith("u ")) {
1673
+ const fields = token.split(" ");
1674
+ pushEntry(status, fields[1] ?? "UU", fields.slice(10).join(" "), null, true);
1675
+ }
1676
+ }
1677
+ return status;
1678
+ }
1679
+ function pushEntry(status, codes, pathValue, origPath, conflict = false) {
1680
+ const indexCode = codes[0] ?? ".";
1681
+ const worktreeCode = codes[1] ?? ".";
1682
+ if (conflict) {
1683
+ status.conflicts.push({
1684
+ path: pathValue,
1685
+ origPath,
1686
+ status: "conflicted",
1687
+ staged: false
1688
+ });
1689
+ return;
1690
+ }
1691
+ if (indexCode !== ".") status.staged.push({
1692
+ path: pathValue,
1693
+ origPath,
1694
+ status: codeName(indexCode),
1695
+ staged: true
1696
+ });
1697
+ if (worktreeCode !== ".") status.unstaged.push({
1698
+ path: pathValue,
1699
+ origPath,
1700
+ status: codeName(worktreeCode),
1701
+ staged: false
1702
+ });
1703
+ }
1704
+ function codeName(code) {
1705
+ switch (code) {
1706
+ case "A": return "added";
1707
+ case "M": return "modified";
1708
+ case "D": return "deleted";
1709
+ case "R": return "renamed";
1710
+ case "C": return "copied";
1711
+ case "T": return "typechange";
1712
+ case "U": return "conflicted";
1713
+ default: return "unknown";
1714
+ }
1715
+ }
1716
+ function snapshotOf(status, raw) {
1717
+ return createHash("sha256").update(JSON.stringify({
1718
+ head: status.head,
1719
+ branch: status.branch,
1720
+ upstream: status.upstream,
1721
+ ahead: status.ahead,
1722
+ behind: status.behind,
1723
+ raw
1724
+ })).digest("hex");
1725
+ }
1726
+ function parseLog(raw) {
1727
+ return raw.split("").map((record) => record.trim()).filter(Boolean).map((record) => {
1728
+ const [hash = "", shortHash = "", author = "", email = "", timestamp = "0", subject = ""] = record.split("");
1729
+ return {
1730
+ hash,
1731
+ shortHash,
1732
+ author,
1733
+ email,
1734
+ timestamp: Number(timestamp) * 1e3,
1735
+ subject
1736
+ };
1737
+ });
1738
+ }
1739
+ function parseBranches(raw) {
1740
+ return raw.split("\n").map((record) => record.trim()).filter(Boolean).map((record) => {
1741
+ const [name = "", head = "", current = ""] = record.split(" ");
1742
+ return {
1743
+ name,
1744
+ head,
1745
+ current: current.trim() === "*"
1746
+ };
1747
+ });
1748
+ }
1749
+ // ../../packages/resources/src/terminals/process.ts
1750
+ const exec = promisify(execFile);
1751
+ async function snapshot() {
1752
+ const { stdout } = await exec("/bin/ps", ["-axo", "pid=,ppid=,pgid=,sess=,stat=,lstart="], {
1753
+ timeout: 2e3,
1754
+ maxBuffer: 2097152,
1755
+ env: {
1756
+ ...commandEnvironment(),
1757
+ LC_ALL: "C"
1758
+ }
1759
+ });
1760
+ return stdout.split("\n").flatMap((line) => {
1761
+ const fields = line.trim().split(/\s+/);
1762
+ if (fields.length !== 10 || fields[4].startsWith("Z")) return [];
1763
+ return [{
1764
+ pid: Number(fields[0]),
1765
+ ppid: Number(fields[1]),
1766
+ pgid: Number(fields[2]),
1767
+ session: fields[3],
1768
+ birth: fields.slice(5).join(" ")
1769
+ }];
1770
+ });
1771
+ }
1772
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1773
+ var ManagedPty = class {
1774
+ native;
1775
+ output;
1776
+ ready;
1777
+ done;
1778
+ #owned = /* @__PURE__ */ new Map();
1779
+ #session;
1780
+ #exited = false;
1781
+ #controlAvailable = true;
1782
+ #exitCode = null;
1783
+ #stop;
1784
+ #redactor;
1785
+ #timer;
1786
+ #poll;
1787
+ #resolve;
1788
+ constructor(native, secrets, output) {
1789
+ this.native = native;
1790
+ this.output = output;
1791
+ this.#redactor = new OutputRedactor(secrets);
1792
+ this.done = new Promise((resolve) => {
1793
+ this.#resolve = resolve;
1794
+ });
1795
+ if (process.platform === "win32") {
1796
+ this.ready = Promise.resolve();
1797
+ this.#timer = setInterval(() => void 0, 6e4);
1798
+ } else {
1799
+ this.ready = this.#capture();
1800
+ this.#timer = setInterval(() => {
1801
+ if (!this.#poll) this.#poll = this.#capture().catch(() => {
1802
+ this.#controlAvailable = false;
1803
+ this.stop();
1804
+ }).finally(() => {
1805
+ this.#poll = void 0;
1806
+ });
1807
+ }, 250);
1808
+ }
1809
+ this.#timer.unref();
1810
+ native.onData((data) => {
1811
+ try {
1812
+ this.#emit(this.#redactor.push(data));
1813
+ } catch {
1814
+ this.stop();
1815
+ }
1816
+ });
1817
+ native.onExit((event) => {
1818
+ this.#exited = true;
1819
+ this.#exitCode = event.exitCode;
1820
+ this.stop();
1821
+ });
1822
+ }
1823
+ #emit(text) {
1824
+ let buffer = Buffer.from(text);
1825
+ while (buffer.length) {
1826
+ let length = Math.min(buffer.length, 16384);
1827
+ while (length < buffer.length && (buffer[length] & 192) === 128) length--;
1828
+ this.output(buffer.subarray(0, length).toString("utf8"));
1829
+ buffer = buffer.subarray(length);
1830
+ }
1831
+ }
1832
+ async #capture() {
1833
+ this.#remember(await snapshot());
1834
+ }
1835
+ #remember(members) {
1836
+ const leader = members.find((member) => member.pid === this.native.pid);
1837
+ if (leader && !this.#exited && (!this.#owned.has(leader.pid) || this.#owned.get(leader.pid) === leader.birth)) {
1838
+ this.#session ??= leader.session;
1839
+ this.#owned.set(leader.pid, leader.birth);
1840
+ const included = /* @__PURE__ */ new Set([leader.pid]);
1841
+ for (let round = 0; round < members.length; round++) {
1842
+ let added = false;
1843
+ for (const member of members) if (!included.has(member.pid) && (included.has(member.ppid) || this.#session !== "0" && member.session === this.#session)) {
1844
+ included.add(member.pid);
1845
+ added = true;
1846
+ }
1847
+ if (!added) break;
1848
+ }
1849
+ for (const member of members) if (included.has(member.pid)) this.#owned.set(member.pid, member.birth);
1850
+ }
1851
+ }
1852
+ async #signal(signal) {
1853
+ await this.#capture();
1854
+ const members = await snapshot();
1855
+ this.#remember(members);
1856
+ const candidates = members.filter((member) => this.#owned.get(member.pid) === member.birth);
1857
+ const related = members.filter((member) => member.pid === this.native.pid || member.pgid === this.native.pid || this.#session && this.#session !== "0" && member.session === this.#session);
1858
+ if (!candidates.length) return related.length === 0;
1859
+ const groups = [...new Set(candidates.map((member) => member.pgid))].sort((a, b) => Number(a === this.native.pid) - Number(b === this.native.pid));
1860
+ for (const group of groups) {
1861
+ const latest = await snapshot();
1862
+ this.#remember(latest);
1863
+ const current = latest.filter((member) => member.pgid === group);
1864
+ if (!current.length) continue;
1865
+ if (!current.every((member) => this.#owned.get(member.pid) === member.birth)) return false;
1866
+ try {
1867
+ process.kill(-group, signal);
1868
+ } catch (error) {
1869
+ if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) return false;
1870
+ }
1871
+ }
1872
+ return true;
1873
+ }
1874
+ async #gone() {
1875
+ return !(await snapshot()).some((member) => this.#owned.get(member.pid) === member.birth || member.pid === this.native.pid || member.pgid === this.native.pid || this.#session && this.#session !== "0" && member.session === this.#session);
1876
+ }
1877
+ get exited() {
1878
+ return this.#exited;
1879
+ }
1880
+ get controlAvailable() {
1881
+ return this.#controlAvailable && !this.#exited && !this.#stop;
1882
+ }
1883
+ async #stopWindows() {
1884
+ const known = await processTreePids(this.native.pid).catch(() => [this.native.pid]);
1885
+ try {
1886
+ this.native.kill?.();
1887
+ } catch {}
1888
+ return await terminateProcessTree(this.native.pid) && !processAlive(this.native.pid) && known.every((pid) => !processAlive(pid));
1889
+ }
1890
+ stop() {
1891
+ this.#stop ??= (async () => {
1892
+ let stopped = false;
1893
+ try {
1894
+ await this.ready;
1895
+ if (process.platform === "win32") {
1896
+ stopped = await this.#stopWindows();
1897
+ return stopped;
1898
+ }
1899
+ if (!await this.#gone()) {
1900
+ if (!await this.#signal("SIGTERM")) return false;
1901
+ await delay(300);
1902
+ if (!await this.#gone() && !await this.#signal("SIGKILL")) return false;
1903
+ }
1904
+ const deadline = Date.now() + 2e3;
1905
+ do {
1906
+ if (this.#exited && await this.#gone()) {
1907
+ stopped = true;
1908
+ break;
1909
+ }
1910
+ await delay(20);
1911
+ } while (Date.now() < deadline);
1912
+ return stopped;
1913
+ } catch {
1914
+ return false;
1915
+ } finally {
1916
+ clearInterval(this.#timer);
1917
+ try {
1918
+ this.#emit(this.#redactor.push("", true));
1919
+ } catch {
1920
+ stopped = false;
1921
+ }
1922
+ this.#resolve({
1923
+ exitCode: this.#exitCode,
1924
+ stopped
1925
+ });
1926
+ }
1927
+ })();
1928
+ return this.#stop;
1929
+ }
1930
+ };
1931
+ const PAIRING_CODE_TTL_MS = 3e5;
1932
+ const PAIRING_REQUEST_TTL_MS = 6e5;
1933
+ const ENROLLMENT_TTL_MS = 3e5;
1934
+ function generatePairingCode() {
1935
+ const characters = [];
1936
+ const limit = 256;
1937
+ while (characters.length < 10) {
1938
+ const byte = randomInt(0, 256);
1939
+ if (byte < limit) characters.push("0123456789ABCDEFGHJKMNPQRSTVWXYZ"[byte % 32] ?? "0");
1940
+ }
1941
+ return characters.join("");
1942
+ }
1943
+ function formatPairingCode(code) {
1944
+ const normalized = normalizePairingCode(code);
1945
+ return `${normalized.slice(0, 5)}-${normalized.slice(5)}`;
1946
+ }
1947
+ function normalizePairingCode(input) {
1948
+ return input.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1");
1949
+ }
1950
+ function generateShortCode() {
1951
+ return randomInt(0, 1e6).toString().padStart(6, "0");
1952
+ }
1953
+ // src/dev-web/paths.ts
1954
+ const Manifest = z.object({
1955
+ dependencies: z.record(z.string(), z.string()).optional(),
1956
+ optionalDependencies: z.record(z.string(), z.string()).optional(),
1957
+ peerDependencies: z.record(z.string(), z.string()).optional()
1958
+ });
1959
+ const contains = (root, file) => file === root || file.startsWith(root + path.sep);
1960
+ function webRoots(webRoot) {
1961
+ const roots = /* @__PURE__ */ new Set();
1962
+ const visit = (directory) => {
1963
+ if (!existsSync(directory)) return;
1964
+ const root = realpathSync(directory);
1965
+ if (roots.has(root)) return;
1966
+ roots.add(root);
1967
+ const manifestPath = path.join(root, "package.json");
1968
+ if (!existsSync(manifestPath)) return;
1969
+ const pkg = Manifest.parse(JSON.parse(readFileSync(manifestPath, "utf8")));
1970
+ for (const name of Object.keys({
1971
+ ...pkg.dependencies,
1972
+ ...pkg.optionalDependencies,
1973
+ ...pkg.peerDependencies
1974
+ })) {
1975
+ let base = root;
1976
+ for (;;) {
1977
+ const candidate = path.join(base, "node_modules", name);
1978
+ if (existsSync(candidate)) {
1979
+ visit(candidate);
1980
+ break;
1981
+ }
1982
+ const parent = path.dirname(base);
1983
+ if (parent === base) break;
1984
+ base = parent;
1985
+ }
1986
+ }
1987
+ };
1988
+ visit(webRoot);
1989
+ visit(path.resolve(webRoot, "../../packages/ui"));
1990
+ visit(path.resolve(webRoot, "../../packages/shared"));
1991
+ visit(path.join(webRoot, "node_modules/vite"));
1992
+ return [...roots];
1993
+ }
1994
+ function isDevPath(pathname) {
1995
+ return /^\/(?:@vite(?:\/|$)|@react-refresh(?:\/|$)|@fs(?:\/|$)|@id(?:\/|$)|src(?:\/|$)|node_modules(?:\/|$)|__vite|__open-in-editor|_larness(?:\/|$))/.test(pathname);
1996
+ }
1997
+ function permittedPath(rawUrl, webRoot, roots) {
1998
+ try {
1999
+ const rawPath = rawUrl.split("?")[0] ?? "";
2000
+ const decoded = decodeURIComponent(rawPath);
2001
+ if (!decoded.startsWith("/") || decoded.startsWith("//") || decoded.includes("%") || decoded.includes("\\") || decoded.includes("\0")) return false;
2002
+ if (decoded.split("/").some((s) => s === ".." || s === "." || s.startsWith(".env") || s === ".git" || /^(?:config\.json|master\.key|larness\.(?:db|lock)|vite\.config\..*|.*\.log)$/.test(s))) return false;
2003
+ if (/^\/(?:api|ws|_larness)(?:\/|$)/.test(decoded) || decoded.startsWith("/__open-in-editor") || decoded.startsWith("/__vite")) return false;
2004
+ const file = decoded.startsWith("/@fs/") ? path.normalize(decoded.slice(process.platform === "win32" ? 5 : 4)) : path.join(webRoot, decoded);
2005
+ if (existsSync(file)) return roots.some((root) => contains(realpathSync(root), realpathSync(file)));
2006
+ let ancestor = file;
2007
+ while (!existsSync(ancestor)) {
2008
+ const parent = path.dirname(ancestor);
2009
+ if (parent === ancestor) return false;
2010
+ ancestor = parent;
2011
+ }
2012
+ return roots.some((root) => contains(realpathSync(root), realpathSync(ancestor)));
2013
+ } catch {
2014
+ return false;
2015
+ }
2016
+ }
2017
+ // src/dev-web/control.ts
2018
+ const HMR_PATH = "/_larness/dev/hmr";
2019
+ const NONCE_MARKER = "LARNESS_DEV_RESPONSE_NONCE";
2020
+ var DevWebUnavailable = class extends Error {
2021
+ code = "DEV_WEB_UNAVAILABLE";
2022
+ constructor() {
2023
+ super("开发运行环境已停止,请重新启动 TUI");
2024
+ }
2025
+ };
2026
+ var EntryConfigError = class extends Error {
2027
+ constructor(origin, port) {
2028
+ const canonical = new URL(OriginUrlSchema.parse(origin));
2029
+ const targetPort = Number(canonical.port || (canonical.protocol === "https:" ? 443 : 80));
2030
+ super(`浏览器地址是 ${canonical.origin},Server 监听端口是 ${port}。请关闭实例,一次性将 config.json 的 server.port 对齐为 ${targetPort},保留 publicUrl 和其他配置;若端口来自环境变量,请调整对应环境变量。`);
2031
+ }
2032
+ };
2033
+ const devWebCache = (generation) => path.join(tmpdir(), `larness-vite-cache-${z.uuid().parse(generation)}`);
2034
+ const DevWebTargetSchema = z.strictObject({
2035
+ generation: z.uuid(),
2036
+ host: z.literal("127.0.0.1"),
2037
+ port: z.int().min(1).max(65535)
2038
+ });
2039
+ const DevWebReadySchema = DevWebTargetSchema.extend({ type: z.literal("dev-web.ready") });
2040
+ const DevWebAttachSchema = DevWebTargetSchema.extend({ type: z.literal("dev-web.attach") });
2041
+ const DevWebAttachedSchema = z.strictObject({
2042
+ type: z.literal("dev-web.attached"),
2043
+ generation: z.uuid()
2044
+ });
2045
+ z.strictObject({
2046
+ type: z.literal("dev-web.start"),
2047
+ generation: z.uuid(),
2048
+ origin: OriginUrlSchema
2049
+ });
2050
+ var DevWebControl = class {
2051
+ child;
2052
+ generation;
2053
+ current = null;
2054
+ closed = false;
2055
+ constructor(child, generation) {
2056
+ this.child = child;
2057
+ this.generation = generation;
2058
+ }
2059
+ get target() {
2060
+ return this.current;
2061
+ }
2062
+ accept(child, message) {
2063
+ const parsed = DevWebReadySchema.safeParse(message);
2064
+ if (this.closed || child !== this.child || !parsed.success || parsed.data.generation !== this.generation) return false;
2065
+ const { type: _type, ...target } = parsed.data;
2066
+ if (this.current && this.current.port !== target.port) return false;
2067
+ this.current = target;
2068
+ return true;
2069
+ }
2070
+ close() {
2071
+ this.closed = true;
2072
+ this.current = null;
2073
+ }
2074
+ };
2075
+ // src/dev-web/managed.ts
2076
+ function managedWebFiles(serverRoot, target) {
2077
+ const webRoot = realpathSync(path.resolve(serverRoot, "../../apps/web"));
2078
+ return {
2079
+ webRoot,
2080
+ roots: [...webRoots(webRoot), realpathSync(devWebCache(target.generation))]
2081
+ };
2082
+ }
2083
+ function receiveDevWebTarget(timeoutMs = 25e3, signal) {
2084
+ if (!process.send) return Promise.reject(/* @__PURE__ */ new Error("开发转发需要受管控制通道"));
2085
+ return new Promise((resolve, reject) => {
2086
+ const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("开发控制通道超时")), timeoutMs);
2087
+ const disconnect = () => finish(/* @__PURE__ */ new Error("开发控制通道已关闭"));
2088
+ const abort = () => finish(/* @__PURE__ */ new Error("启动已取消"));
2089
+ const message = (value) => {
2090
+ const parsed = DevWebAttachSchema.safeParse(value);
2091
+ if (!parsed.success) {
2092
+ finish(/* @__PURE__ */ new Error("开发控制消息无效"));
2093
+ return;
2094
+ }
2095
+ const { type: _type, ...target } = parsed.data;
2096
+ finish(null, target);
2097
+ };
2098
+ const finish = (error, target) => {
2099
+ clearTimeout(timer);
2100
+ process.off("message", message);
2101
+ process.off("disconnect", disconnect);
2102
+ signal?.removeEventListener("abort", abort);
2103
+ if (error) reject(error);
2104
+ else if (target) resolve(target);
2105
+ };
2106
+ process.once("message", message);
2107
+ process.once("disconnect", disconnect);
2108
+ signal?.addEventListener("abort", abort, { once: true });
2109
+ if (signal?.aborted) abort();
2110
+ });
2111
+ }
2112
+ function waitChildMessage(child, parse, signal, phase = "Server") {
2113
+ return new Promise((resolve, reject) => {
2114
+ const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("开发子进程就绪超时")), 25e3);
2115
+ const fail = () => finish(/* @__PURE__ */ new Error(`${phase} 未就绪即退出 (code=${child.exitCode ?? "none"}, signal=${child.signalCode ?? "none"})`));
2116
+ const abort = () => finish(/* @__PURE__ */ new Error("启动已取消"));
2117
+ const message = (value) => {
2118
+ const parsed = parse(value);
2119
+ if (parsed === null) finish(/* @__PURE__ */ new Error("开发子进程控制消息无效"));
2120
+ else finish(null, parsed);
2121
+ };
2122
+ const finish = (error, value) => {
2123
+ clearTimeout(timer);
2124
+ child.off("message", message);
2125
+ child.off("exit", fail);
2126
+ child.off("error", fail);
2127
+ signal?.removeEventListener("abort", abort);
2128
+ if (error) reject(error);
2129
+ else if (value !== void 0) resolve(value);
2130
+ };
2131
+ child.on("message", message);
2132
+ child.once("exit", fail);
2133
+ child.once("error", fail);
2134
+ signal?.addEventListener("abort", abort, { once: true });
2135
+ if (signal?.aborted) abort();
2136
+ });
2137
+ }
2138
+ export { windowsLaunch as $, scanWatchPath as A, applyPatch$1 as B, parseBranches as C, snapshotOf as D, runGit as E, readEditableFile as F, searchCode as G, hashContent as H, resolveFilePath as I, isInsideRoot as J, PathGuardError as K, saveEditableFile as L, encodeEditableContent as M, listDirectory as N, validateGitPath as O, normalizeFilePath as P, resolveWindowsExecutable as Q, DEFAULT_IGNORED as R, GitError as S, parseStatus as T, listFiles as U, createTextFile as V, readTextFile as W, MAX_COMMAND_OUTPUT_BYTES as X, resolveInsideRoot as Y, runCommand as Z, formatPairingCode as _, DevWebControl as a, commandEnvironment as at, normalizePairingCode as b, EntryConfigError as c, devWebCache as d, processAlive as et, isDevPath as f, PAIRING_REQUEST_TTL_MS as g, PAIRING_CODE_TTL_MS as h, DevWebAttachedSchema as i, windowsTcpListeners as it, FileManagerError as j, createDirectoryWatcher as k, HMR_PATH as l, ENROLLMENT_TTL_MS as m, receiveDevWebTarget as n, processSnapshot as nt, DevWebTargetSchema as o, OutputRedactor as ot, permittedPath as p, canonicalDirectory as q, waitChildMessage as r, terminateProcessTree as rt, DevWebUnavailable as s, managedWebFiles as t, processCommandLine as tt, NONCE_MARKER as u, generatePairingCode as v, parseLog as w, ManagedPty as x, generateShortCode as y, FileError as z };