neural-loom 0.2.69 → 0.3.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 (161) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/build-manifest.json +3 -3
  3. package/.next/cache/.previewinfo +1 -1
  4. package/.next/cache/.rscinfo +1 -1
  5. package/.next/cache/.tsbuildinfo +1 -1
  6. package/.next/diagnostics/route-bundle-stats.json +11 -11
  7. package/.next/fallback-build-manifest.json +3 -3
  8. package/.next/next-server.js.nft.json +1 -1
  9. package/.next/prerender-manifest.json +3 -3
  10. package/.next/required-server-files.js +20 -20
  11. package/.next/required-server-files.json +20 -20
  12. package/.next/server/app/_global-error.html +1 -1
  13. package/.next/server/app/_global-error.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  17. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  18. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  19. package/.next/server/app/_not-found.html +1 -1
  20. package/.next/server/app/_not-found.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  22. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  25. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  26. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  27. package/.next/server/app/api/configs/route.js.nft.json +1 -1
  28. package/.next/server/app/api/context/aider/route.js.nft.json +1 -1
  29. package/.next/server/app/api/context/claude/route.js.nft.json +1 -1
  30. package/.next/server/app/api/context/route.js.nft.json +1 -1
  31. package/.next/server/app/api/context/ssh/route.js.nft.json +1 -1
  32. package/.next/server/app/api/files/route.js +1 -1
  33. package/.next/server/app/api/files/route.js.nft.json +1 -1
  34. package/.next/server/app/api/recents/route.js.nft.json +1 -1
  35. package/.next/server/app/api/sessions/inject/route.js.nft.json +1 -1
  36. package/.next/server/app/api/sessions/input/route.js.nft.json +1 -1
  37. package/.next/server/app/api/sessions/launch/route.js.nft.json +1 -1
  38. package/.next/server/app/api/sessions/route.js.nft.json +1 -1
  39. package/.next/server/app/api/sessions/scope/route.js.nft.json +1 -1
  40. package/.next/server/app/api/sessions/start/route.js.nft.json +1 -1
  41. package/.next/server/app/api/sessions/stats/route.js.nft.json +1 -1
  42. package/.next/server/app/api/sessions/stop/route.js.nft.json +1 -1
  43. package/.next/server/app/api/sessions/upload-image/route.js.nft.json +1 -1
  44. package/.next/server/app/api/sql/connections/route.js.nft.json +1 -1
  45. package/.next/server/app/api/sql/mcp/route.js +1 -1
  46. package/.next/server/app/api/sql/mcp/route.js.nft.json +1 -1
  47. package/.next/server/app/api/sql/query/route.js +1 -1
  48. package/.next/server/app/api/sql/query/route.js.nft.json +1 -1
  49. package/.next/server/app/api/sql/schema/route.js.nft.json +1 -1
  50. package/.next/server/app/api/telemetry/route.js +1 -1
  51. package/.next/server/app/api/telemetry/route.js.nft.json +1 -1
  52. package/.next/server/app/index.html +1 -1
  53. package/.next/server/app/index.rsc +2 -2
  54. package/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  55. package/.next/server/app/index.segments/_full.segment.rsc +2 -2
  56. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  57. package/.next/server/app/index.segments/_index.segment.rsc +1 -1
  58. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  59. package/.next/server/app/page/react-loadable-manifest.json +3 -3
  60. package/.next/server/app/page_client-reference-manifest.js +1 -1
  61. package/.next/server/chunks/[root-of-the-server]__0.hmw1f._.js +3 -0
  62. package/.next/server/chunks/[root-of-the-server]__0.hmw1f._.js.map +1 -0
  63. package/.next/server/chunks/[root-of-the-server]__00-sqou._.js +2 -2
  64. package/.next/server/chunks/[root-of-the-server]__00-sqou._.js.map +1 -1
  65. package/.next/server/chunks/[root-of-the-server]__00l5btc._.js +4 -4
  66. package/.next/server/chunks/[root-of-the-server]__00l5btc._.js.map +1 -1
  67. package/.next/server/chunks/[root-of-the-server]__06men8g._.js +4 -4
  68. package/.next/server/chunks/[root-of-the-server]__06men8g._.js.map +1 -1
  69. package/.next/server/chunks/[root-of-the-server]__097vtn1._.js +2 -2
  70. package/.next/server/chunks/[root-of-the-server]__097vtn1._.js.map +1 -1
  71. package/.next/server/chunks/[root-of-the-server]__0_v2.a8._.js +2 -2
  72. package/.next/server/chunks/[root-of-the-server]__0_v2.a8._.js.map +1 -1
  73. package/.next/server/chunks/{[root-of-the-server]__0.ptwor._.js → [root-of-the-server]__0ajln56._.js} +7 -7
  74. package/.next/server/chunks/[root-of-the-server]__0ajln56._.js.map +1 -0
  75. package/.next/server/chunks/{[root-of-the-server]__0co.g5k._.js → [root-of-the-server]__0auh-2z._.js} +5 -5
  76. package/.next/server/chunks/[root-of-the-server]__0auh-2z._.js.map +1 -0
  77. package/.next/server/chunks/[root-of-the-server]__0e03ite._.js +2 -2
  78. package/.next/server/chunks/[root-of-the-server]__0e03ite._.js.map +1 -1
  79. package/.next/server/chunks/[root-of-the-server]__0fxtx7z._.js +2 -2
  80. package/.next/server/chunks/[root-of-the-server]__0fxtx7z._.js.map +1 -1
  81. package/.next/server/chunks/[root-of-the-server]__0h.~hv6._.js +2 -2
  82. package/.next/server/chunks/[root-of-the-server]__0h.~hv6._.js.map +1 -1
  83. package/.next/server/chunks/[root-of-the-server]__0i83~95._.js +1 -1
  84. package/.next/server/chunks/[root-of-the-server]__0li1h1u._.js +19 -19
  85. package/.next/server/chunks/[root-of-the-server]__0li1h1u._.js.map +1 -1
  86. package/.next/server/chunks/[root-of-the-server]__0s1axek._.js +5 -5
  87. package/.next/server/chunks/[root-of-the-server]__0s1axek._.js.map +1 -1
  88. package/.next/server/chunks/[root-of-the-server]__0t713sv._.js +1 -1
  89. package/.next/server/chunks/[root-of-the-server]__0t713sv._.js.map +1 -1
  90. package/.next/server/chunks/[root-of-the-server]__0tq0maq._.js +5 -5
  91. package/.next/server/chunks/[root-of-the-server]__0tq0maq._.js.map +1 -1
  92. package/.next/server/chunks/[root-of-the-server]__0viil6b._.js +2 -2
  93. package/.next/server/chunks/[root-of-the-server]__0viil6b._.js.map +1 -1
  94. package/.next/server/chunks/[root-of-the-server]__0ykd4~u._.js +3 -0
  95. package/.next/server/chunks/[root-of-the-server]__0ykd4~u._.js.map +1 -0
  96. package/.next/server/chunks/[root-of-the-server]__11h_nxt._.js +1 -1
  97. package/.next/server/chunks/[root-of-the-server]__11h_nxt._.js.map +1 -1
  98. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_016qk~0.js +2 -2
  99. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_016qk~0.js.map +1 -1
  100. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0ev3h.z.js +1 -1
  101. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0ev3h.z.js.map +1 -1
  102. package/.next/server/edge/chunks/[root-of-the-server]__08ca2jv._.js +11 -0
  103. package/.next/server/edge/chunks/[root-of-the-server]__08ca2jv._.js.map +1 -0
  104. package/.next/server/edge/chunks/node_modules_next_dist_esm_build_templates_edge-wrapper_0kvehva.js +3 -0
  105. package/.next/server/edge/chunks/node_modules_next_dist_esm_build_templates_edge-wrapper_0kvehva.js.map +1 -0
  106. package/.next/server/edge/chunks/node_modules_next_dist_esm_build_templates_edge-wrapper_0lcpsxv.js.map +1 -0
  107. package/.next/server/edge/chunks/turbopack-node_modules_next_dist_esm_build_templates_edge-wrapper_0lcpsxv.js +3 -0
  108. package/.next/server/middleware/middleware-manifest.json +32 -0
  109. package/.next/server/middleware-build-manifest.js +3 -3
  110. package/.next/server/middleware-manifest.json +30 -2
  111. package/.next/server/pages/404.html +1 -1
  112. package/.next/server/pages/500.html +1 -1
  113. package/.next/server/server-reference-manifest.js +1 -1
  114. package/.next/server/server-reference-manifest.json +1 -1
  115. package/.next/static/04j4ht7eCOOXSLQ5Wixq0/_clientMiddlewareManifest.js +6 -0
  116. package/.next/static/chunks/{008bf~h8rh5_3.js → 0uyuco-451j.n.js} +2 -2
  117. package/.next/static/chunks/11c6f8pb_6s91.js +4 -0
  118. package/.next/static/chunks/{00pgauqedvo01.js → 14~-ojwsxf~oe.js} +4 -4
  119. package/.next/trace +1 -1
  120. package/.next/trace-build +1 -1
  121. package/README.md +18 -0
  122. package/bin/cli.js +12 -2
  123. package/package.json +9 -6
  124. package/src/app/api/files/route.ts +30 -0
  125. package/src/app/api/git/route.ts +46 -31
  126. package/src/app/api/sessions/stats/route.ts +40 -22
  127. package/src/app/api/sql/query/route.ts +2 -15
  128. package/src/app/api/telemetry/route.ts +2 -1
  129. package/src/app/components/MarkdownPreview.tsx +17 -10
  130. package/src/app/components/TerminalConsole.tsx +99 -21
  131. package/src/lib/agents/AgentRunner.ts +41 -5
  132. package/src/lib/agents/AiderRunner.ts +20 -36
  133. package/src/lib/agents/ClaudeRunner.ts +8 -62
  134. package/src/lib/agents/DockerRunner.ts +18 -54
  135. package/src/lib/agents/MockRunner.ts +3 -1
  136. package/src/lib/agents/SSHRunner.ts +8 -54
  137. package/src/lib/agents/SessionPersister.ts +11 -1
  138. package/src/lib/agents/ShellRunner.ts +10 -46
  139. package/src/lib/agents/WebSocketServer.ts +17 -2
  140. package/src/lib/agents/pricing.ts +45 -0
  141. package/src/lib/agents/runtime.ts +92 -0
  142. package/src/lib/gitSafe.ts +15 -0
  143. package/src/lib/security.ts +76 -0
  144. package/src/lib/sql/McpServer.ts +2 -11
  145. package/src/lib/sql/adapters/MssqlAdapter.ts +16 -1
  146. package/src/lib/sql/adapters/MysqlAdapter.ts +23 -1
  147. package/src/lib/sql/adapters/PostgresAdapter.ts +22 -1
  148. package/src/lib/sql/adapters/SqliteAdapter.ts +21 -10
  149. package/src/lib/sql/sqlGuard.ts +20 -0
  150. package/src/lib/workspaceParser.ts +23 -6
  151. package/src/middleware.ts +27 -0
  152. package/.next/server/chunks/[externals]__048y_op._.js +0 -3
  153. package/.next/server/chunks/[externals]__048y_op._.js.map +0 -1
  154. package/.next/server/chunks/[root-of-the-server]__0.ptwor._.js.map +0 -1
  155. package/.next/server/chunks/[root-of-the-server]__08r0s-s._.js +0 -3
  156. package/.next/server/chunks/[root-of-the-server]__08r0s-s._.js.map +0 -1
  157. package/.next/server/chunks/[root-of-the-server]__0co.g5k._.js.map +0 -1
  158. package/.next/static/EglcK14vXeSWIjxjJCP9A/_clientMiddlewareManifest.js +0 -1
  159. package/.next/static/chunks/0ii_nb0g40rmj.js +0 -4
  160. /package/.next/static/{EglcK14vXeSWIjxjJCP9A → 04j4ht7eCOOXSLQ5Wixq0}/_buildManifest.js +0 -0
  161. /package/.next/static/{EglcK14vXeSWIjxjJCP9A → 04j4ht7eCOOXSLQ5Wixq0}/_ssgManifest.js +0 -0
@@ -1,5 +1,11 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
+ import { getConfigDir } from "../config";
4
+ import { SessionPersister } from "./SessionPersister";
5
+ import { estimateCost } from "./pricing";
6
+
7
+ /** Maximum number of log chunks retained per session (older chunks are dropped). */
8
+ export const MAX_LOG_LINES = 5000;
3
9
 
4
10
  export interface RunnerStatus {
5
11
  id: string;
@@ -40,6 +46,8 @@ export abstract class AgentRunner {
40
46
  lastSyncedWorkspaceFolders?: string[];
41
47
  tokenUsage: { input: number; output: number; cost: number } = { input: 0, output: 0, cost: 0 };
42
48
  agentState: 'idle' | 'thinking' | 'complete' | 'needs-input' = 'idle';
49
+ /** Model name, when known, used for fallback cost estimation. */
50
+ protected model?: string;
43
51
  protected hasAnalyzedInitialState = false;
44
52
  private stateTimer: NodeJS.Timeout | null = null;
45
53
  private idleTimer: NodeJS.Timeout | null = null;
@@ -64,10 +72,9 @@ export abstract class AgentRunner {
64
72
 
65
73
  if (diffInput > 0 || diffOutput > 0 || diffCost > 0) {
66
74
  try {
67
- const configDir = path.join(process.cwd(), ".ai", "neural-loom");
68
- if (!fs.existsSync(configDir)) {
69
- fs.mkdirSync(configDir, { recursive: true });
70
- }
75
+ // Use the canonical config dir (honours ORIGINAL_CWD and the read-only
76
+ // fallback) rather than process.cwd(), which is the package root under npx.
77
+ const configDir = getConfigDir();
71
78
  const historyFile = path.join(configDir, "token-history.json");
72
79
  let history: TokenTransaction[] = [];
73
80
  if (fs.existsSync(historyFile)) {
@@ -139,7 +146,7 @@ export abstract class AgentRunner {
139
146
 
140
147
  // Fallback cost estimation if input/output is updated but cost is 0/unmatched
141
148
  if (this.tokenUsage.cost === 0 && (this.tokenUsage.input > 0 || this.tokenUsage.output > 0)) {
142
- this.tokenUsage.cost = (this.tokenUsage.input * 0.000003) + (this.tokenUsage.output * 0.000015);
149
+ this.tokenUsage.cost = estimateCost(this.tokenUsage.input, this.tokenUsage.output, this.model);
143
150
  }
144
151
  this.logTokenUsageUpdate();
145
152
  }
@@ -171,6 +178,11 @@ export abstract class AgentRunner {
171
178
  // No-op by default, overridden by PTY runners
172
179
  }
173
180
 
181
+ /** OS process id of the underlying PTY, when one exists. Overridden by PTY runners. */
182
+ getPid(): number | undefined {
183
+ return undefined;
184
+ }
185
+
174
186
  protected listeners: ((data: string) => void)[] = [];
175
187
 
176
188
  public onOutput(callback: (data: string) => void): void {
@@ -186,6 +198,30 @@ export abstract class AgentRunner {
186
198
  this.listeners.forEach(cb => cb(data));
187
199
  }
188
200
 
201
+ /** Whether appendLog parses token usage / persists the session. Subclasses
202
+ * (e.g. the ephemeral workspace shell) may disable these. */
203
+ protected parseTokensOnLog = true;
204
+ protected persistOnLog = true;
205
+
206
+ /**
207
+ * Append a chunk to the session log, enforce the retention cap, emit it to
208
+ * subscribers and (per the flags above) parse token usage / persist the
209
+ * session. Shared by all PTY-backed runners.
210
+ */
211
+ protected appendLog(line: string): void {
212
+ this.logs.push(line);
213
+ if (this.logs.length > MAX_LOG_LINES) {
214
+ this.logs.shift();
215
+ }
216
+ if (this.parseTokensOnLog) {
217
+ this.parseTokenUsage(line);
218
+ }
219
+ this.emitOutput(line);
220
+ if (this.persistOnLog) {
221
+ SessionPersister.saveSession(this);
222
+ }
223
+ }
224
+
189
225
  /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
190
226
  protected async writeToPty(ptyProcess: any, text: string): Promise<void> {
191
227
  if (!ptyProcess) return;
@@ -1,32 +1,13 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
- import { exec } from "child_process";
3
+ import { exec, execFile } from "child_process";
4
+ import { promisify } from "util";
4
5
  import { getConfigDir } from "../config";
5
6
  import type { IPty } from "node-pty";
6
7
  import { AgentRunner } from "./AgentRunner";
7
- import { SessionPersister } from "./SessionPersister";
8
+ import { isWindows, findGitBash, loadNodePty } from "./runtime";
8
9
 
9
- function isWindows(): boolean {
10
- return typeof process !== "undefined" && process.platform === "win32";
11
- }
12
-
13
- function findGitBash(): string | null {
14
- if (!isWindows()) {
15
- return "bash";
16
- }
17
- const pf = process.env.PROGRAMFILES || "C:\\Program Files";
18
- const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
19
- const local = process.env.LOCALAPPDATA || "";
20
-
21
- const candidates: string[] = [
22
- process.env.WINGMAN_BASH_PATH,
23
- path.join(pf, "Git", "bin", "bash.exe"),
24
- path.join(pf86, "Git", "bin", "bash.exe"),
25
- local ? path.join(local, "Programs", "Git", "bin", "bash.exe") : "",
26
- ].filter((p): p is string => typeof p === "string" && p !== "");
27
-
28
- return candidates.find(p => fs.existsSync(p)) || null;
29
- }
10
+ const execFilePromise = promisify(execFile);
30
11
 
31
12
  function getFilesForAider(dir: string): string {
32
13
  const maxFiles = 150;
@@ -87,16 +68,6 @@ export class AiderRunner extends AgentRunner {
87
68
  this.createdAt = new Date().toISOString();
88
69
  }
89
70
 
90
- private appendLog(line: string) {
91
- this.logs.push(line);
92
- if (this.logs.length > 5000) {
93
- this.logs.shift();
94
- }
95
- this.parseTokenUsage(line);
96
- this.emitOutput(line);
97
- SessionPersister.saveSession(this);
98
- }
99
-
100
71
  async start(resume?: boolean): Promise<void> {
101
72
  if (this.status === 'running') return;
102
73
 
@@ -115,9 +86,7 @@ export class AiderRunner extends AgentRunner {
115
86
  const shellArgs = useCmd ? ["/c"] : ["-c"];
116
87
 
117
88
  try {
118
- if (!this.ptyModule) {
119
- this.ptyModule = eval("require")("node-pty");
120
- }
89
+ this.ptyModule = loadNodePty();
121
90
 
122
91
  // Load Aider configuration
123
92
  let aiderConfig = {
@@ -137,6 +106,8 @@ export class AiderRunner extends AgentRunner {
137
106
  console.error("Failed to parse Aider configuration:", err);
138
107
  }
139
108
  }
109
+ // Record the model so fallback cost estimates use the right rate.
110
+ this.model = aiderConfig.model;
140
111
 
141
112
  // Setup process environment with injected keys
142
113
  const customEnv = {
@@ -282,6 +253,15 @@ export class AiderRunner extends AgentRunner {
282
253
  }
283
254
  this.ptyProcess = null;
284
255
  }
256
+ // For containerised Aider, ensure the container is torn down (the PTY hangup
257
+ // alone may not trigger the run's --rm cleanup).
258
+ if (this.type === "aider-docker") {
259
+ try {
260
+ await execFilePromise("docker", ["stop", `neural-loom-session-${this.id}`]);
261
+ } catch {
262
+ // Container already gone or docker unavailable.
263
+ }
264
+ }
285
265
  this.appendLog("\r\n\x1b[1;31m[System] Aider session terminated.\x1b[0m\r\n");
286
266
  }
287
267
 
@@ -304,5 +284,9 @@ export class AiderRunner extends AgentRunner {
304
284
  }
305
285
  }
306
286
  }
287
+
288
+ override getPid(): number | undefined {
289
+ return this.ptyProcess?.pid;
290
+ }
307
291
  }
308
292
 
@@ -1,33 +1,8 @@
1
1
  import fs from "fs";
2
- import path from "path";
3
- import os from "os";
4
2
  import { execSync } from "child_process";
5
- import { getConfigDir } from "../config";
6
3
  import type { IPty } from "node-pty";
7
4
  import { AgentRunner } from "./AgentRunner";
8
- import { SessionPersister } from "./SessionPersister";
9
-
10
- function isWindows(): boolean {
11
- return typeof process !== "undefined" && process.platform === "win32";
12
- }
13
-
14
- function findGitBash(): string | null {
15
- if (!isWindows()) {
16
- return "bash";
17
- }
18
- const pf = process.env.PROGRAMFILES || "C:\\Program Files";
19
- const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
20
- const local = process.env.LOCALAPPDATA || "";
21
-
22
- const candidates: string[] = [
23
- process.env.WINGMAN_BASH_PATH,
24
- path.join(pf, "Git", "bin", "bash.exe"),
25
- path.join(pf86, "Git", "bin", "bash.exe"),
26
- local ? path.join(local, "Programs", "Git", "bin", "bash.exe") : "",
27
- ].filter((p): p is string => typeof p === "string" && p !== "");
28
-
29
- return candidates.find(p => fs.existsSync(p)) || null;
30
- }
5
+ import { isWindows, findGitBash, loadNodePty, loadClaudeExtraFlags, windowsPathOverride } from "./runtime";
31
6
 
32
7
  export class ClaudeRunner extends AgentRunner {
33
8
  id: string;
@@ -47,16 +22,6 @@ export class ClaudeRunner extends AgentRunner {
47
22
  this.createdAt = new Date().toISOString();
48
23
  }
49
24
 
50
- private appendLog(line: string) {
51
- this.logs.push(line);
52
- if (this.logs.length > 5000) {
53
- this.logs.shift();
54
- }
55
- this.parseTokenUsage(line);
56
- this.emitOutput(line);
57
- SessionPersister.saveSession(this);
58
- }
59
-
60
25
  async start(resume?: boolean): Promise<void> {
61
26
  if (this.status === 'running') return;
62
27
 
@@ -71,10 +36,7 @@ export class ClaudeRunner extends AgentRunner {
71
36
  const shellArgs = useCmd ? ["/c"] : ["-c"];
72
37
 
73
38
  try {
74
- // Dynamic import to prevent bundler SSR/Turbopack errors on server start
75
- if (!this.ptyModule) {
76
- this.ptyModule = eval("require")("node-pty");
77
- }
39
+ this.ptyModule = loadNodePty();
78
40
 
79
41
  this.status = 'running';
80
42
  this.appendLog("\x1b[1;35m==================================================\x1b[0m\r\n");
@@ -85,23 +47,7 @@ export class ClaudeRunner extends AgentRunner {
85
47
  ? this.workspaceRoot
86
48
  : process.env.ORIGINAL_CWD || process.cwd();
87
49
 
88
- // Load Claude configuration to check for extraFlags (like --resume)
89
- let extraFlags = "";
90
- if (resume) {
91
- extraFlags = "--resume";
92
- } else {
93
- const claudeConfigPath = path.join(getConfigDir(), "claude.json");
94
- if (fs.existsSync(claudeConfigPath)) {
95
- try {
96
- const config = JSON.parse(fs.readFileSync(claudeConfigPath, "utf8"));
97
- if (config.extraFlags) {
98
- extraFlags = config.extraFlags;
99
- }
100
- } catch (err) {
101
- console.error("Failed to parse Claude configuration:", err);
102
- }
103
- }
104
- }
50
+ const extraFlags = loadClaudeExtraFlags(resume);
105
51
 
106
52
  // Setup process environment with injected keys
107
53
  const customEnv = {
@@ -111,11 +57,7 @@ export class ClaudeRunner extends AgentRunner {
111
57
  } as NodeJS.ProcessEnv;
112
58
 
113
59
  if (isWindows()) {
114
- const vsNode = "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\MSBuild\\Microsoft\\VisualStudio\\NodeJs";
115
- const localNpm = path.join(os.homedir(), "AppData", "Local", "npm");
116
- const existingPath = process.env.Path || process.env.PATH || "";
117
- const winPath = [vsNode, localNpm, existingPath].filter(Boolean).join(";");
118
-
60
+ const winPath = windowsPathOverride();
119
61
  for (const key of Object.keys(customEnv)) {
120
62
  if (key.toLowerCase() === "path") {
121
63
  delete customEnv[key];
@@ -198,5 +140,9 @@ export class ClaudeRunner extends AgentRunner {
198
140
  }
199
141
  }
200
142
  }
143
+
144
+ override getPid(): number | undefined {
145
+ return this.ptyProcess?.pid;
146
+ }
201
147
  }
202
148
 
@@ -1,31 +1,12 @@
1
1
  import fs from "fs";
2
2
  import path from "path";
3
- import { getConfigDir } from "../config";
3
+ import { promisify } from "util";
4
+ import { execFile } from "child_process";
4
5
  import type { IPty } from "node-pty";
5
6
  import { AgentRunner } from "./AgentRunner";
6
- import { SessionPersister } from "./SessionPersister";
7
+ import { findGitBash, loadNodePty, loadClaudeExtraFlags } from "./runtime";
7
8
 
8
- function isWindows(): boolean {
9
- return typeof process !== "undefined" && process.platform === "win32";
10
- }
11
-
12
- function findGitBash(): string | null {
13
- if (!isWindows()) {
14
- return "bash";
15
- }
16
- const pf = process.env.PROGRAMFILES || "C:\\Program Files";
17
- const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
18
- const local = process.env.LOCALAPPDATA || "";
19
-
20
- const candidates: string[] = [
21
- process.env.WINGMAN_BASH_PATH,
22
- path.join(pf, "Git", "bin", "bash.exe"),
23
- path.join(pf86, "Git", "bin", "bash.exe"),
24
- local ? path.join(local, "Programs", "Git", "bin", "bash.exe") : "",
25
- ].filter((p): p is string => typeof p === "string" && p !== "");
26
-
27
- return candidates.find(p => fs.existsSync(p)) || null;
28
- }
9
+ const execFilePromise = promisify(execFile);
29
10
 
30
11
  export class DockerRunner extends AgentRunner {
31
12
  id: string;
@@ -45,16 +26,6 @@ export class DockerRunner extends AgentRunner {
45
26
  this.createdAt = new Date().toISOString();
46
27
  }
47
28
 
48
- private appendLog(line: string) {
49
- this.logs.push(line);
50
- if (this.logs.length > 5000) {
51
- this.logs.shift();
52
- }
53
- this.parseTokenUsage(line);
54
- this.emitOutput(line);
55
- SessionPersister.saveSession(this);
56
- }
57
-
58
29
  async start(resume?: boolean): Promise<void> {
59
30
  if (this.status === 'running') return;
60
31
 
@@ -72,11 +43,9 @@ export class DockerRunner extends AgentRunner {
72
43
  }
73
44
 
74
45
  try {
75
- if (!this.ptyModule) {
76
- this.ptyModule = eval("require")("node-pty");
77
- }
46
+ this.ptyModule = loadNodePty();
78
47
 
79
- const targetCwd = (this.workspaceRoot && fs.existsSync(this.workspaceRoot))
48
+ const targetCwd = (this.workspaceRoot && fs.existsSync(this.workspaceRoot))
80
49
  ? this.workspaceRoot
81
50
  : process.env.ORIGINAL_CWD || process.cwd();
82
51
 
@@ -121,23 +90,7 @@ export class DockerRunner extends AgentRunner {
121
90
  }
122
91
  const mountsStr = mounts.join(" ");
123
92
 
124
- // Load Claude configuration to check for extraFlags (like --resume)
125
- let extraFlags = "";
126
- if (resume) {
127
- extraFlags = "--resume";
128
- } else {
129
- const claudeConfigPath = path.join(getConfigDir(), "claude.json");
130
- if (fs.existsSync(claudeConfigPath)) {
131
- try {
132
- const config = JSON.parse(fs.readFileSync(claudeConfigPath, "utf8"));
133
- if (config.extraFlags) {
134
- extraFlags = config.extraFlags;
135
- }
136
- } catch (err) {
137
- console.error("Failed to parse Claude configuration:", err);
138
- }
139
- }
140
- }
93
+ const extraFlags = loadClaudeExtraFlags(resume);
141
94
 
142
95
  const dockerCmd = `docker run -it --name neural-loom-session-${this.id} --rm ${mountsStr} -w /workspace node:20-alpine npx -y @anthropic-ai/claude-code ${extraFlags}`.trim();
143
96
 
@@ -180,6 +133,13 @@ export class DockerRunner extends AgentRunner {
180
133
  }
181
134
  this.ptyProcess = null;
182
135
  }
136
+ // Killing the PTY doesn't guarantee the `docker run` child receives a clean
137
+ // hangup, so explicitly stop the container (this also triggers its --rm cleanup).
138
+ try {
139
+ await execFilePromise("docker", ["stop", `neural-loom-session-${this.id}`]);
140
+ } catch {
141
+ // Container already gone or docker unavailable — nothing to clean up.
142
+ }
183
143
  this.appendLog("\r\n\x1b[1;31m[System] Docker container stopped and unmounted.\x1b[0m\r\n");
184
144
  }
185
145
 
@@ -202,5 +162,9 @@ export class DockerRunner extends AgentRunner {
202
162
  }
203
163
  }
204
164
  }
165
+
166
+ override getPid(): number | undefined {
167
+ return this.ptyProcess?.pid;
168
+ }
205
169
  }
206
170
 
@@ -28,7 +28,9 @@ export class MockRunner extends AgentRunner {
28
28
  this.createdAt = new Date().toISOString();
29
29
  }
30
30
 
31
- private appendLog(line: string) {
31
+ // Mock output is line-oriented, so it appends its own CRLF and overrides the
32
+ // base PTY-stream appendLog.
33
+ protected override appendLog(line: string) {
32
34
  this.logs.push(line);
33
35
  this.parseTokenUsage(line);
34
36
  this.emitOutput(line + "\r\n");
@@ -3,29 +3,7 @@ import path from "path";
3
3
  import { getConfigDir } from "../config";
4
4
  import type { IPty } from "node-pty";
5
5
  import { AgentRunner } from "./AgentRunner";
6
- import { SessionPersister } from "./SessionPersister";
7
-
8
- function isWindows(): boolean {
9
- return typeof process !== "undefined" && process.platform === "win32";
10
- }
11
-
12
- function findGitBash(): string | null {
13
- if (!isWindows()) {
14
- return "bash";
15
- }
16
- const pf = process.env.PROGRAMFILES || "C:\\Program Files";
17
- const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
18
- const local = process.env.LOCALAPPDATA || "";
19
-
20
- const candidates: string[] = [
21
- process.env.WINGMAN_BASH_PATH,
22
- path.join(pf, "Git", "bin", "bash.exe"),
23
- path.join(pf86, "Git", "bin", "bash.exe"),
24
- local ? path.join(local, "Programs", "Git", "bin", "bash.exe") : "",
25
- ].filter((p): p is string => typeof p === "string" && p !== "");
26
-
27
- return candidates.find(p => fs.existsSync(p)) || null;
28
- }
6
+ import { findGitBash, loadNodePty, loadClaudeExtraFlags } from "./runtime";
29
7
 
30
8
  interface SSHConfig {
31
9
  host: string;
@@ -52,16 +30,6 @@ export class SSHRunner extends AgentRunner {
52
30
  this.createdAt = new Date().toISOString();
53
31
  }
54
32
 
55
- private appendLog(line: string) {
56
- this.logs.push(line);
57
- if (this.logs.length > 5000) {
58
- this.logs.shift();
59
- }
60
- this.parseTokenUsage(line);
61
- this.emitOutput(line);
62
- SessionPersister.saveSession(this);
63
- }
64
-
65
33
  async start(resume?: boolean): Promise<void> {
66
34
  if (this.status === 'running') return;
67
35
 
@@ -110,32 +78,14 @@ export class SSHRunner extends AgentRunner {
110
78
  return;
111
79
  }
112
80
 
113
- if (!this.ptyModule) {
114
- this.ptyModule = eval("require")("node-pty");
115
- }
81
+ this.ptyModule = loadNodePty();
116
82
 
117
83
  this.appendLog(`[System] Connecting to ${config.username}@${config.host}...\r\n`);
118
84
 
119
85
  const portOpt = config.port ? `-p ${config.port}` : "";
120
86
  const keyOpt = config.privateKeyPath ? `-i "${config.privateKeyPath}"` : "";
121
-
122
- // Load Claude configuration to check for extraFlags (like --resume)
123
- let extraFlags = "";
124
- if (resume) {
125
- extraFlags = "--resume";
126
- } else {
127
- const claudeConfigPath = path.join(getConfigDir(), "claude.json");
128
- if (fs.existsSync(claudeConfigPath)) {
129
- try {
130
- const config = JSON.parse(fs.readFileSync(claudeConfigPath, "utf8"));
131
- if (config.extraFlags) {
132
- extraFlags = config.extraFlags;
133
- }
134
- } catch (err) {
135
- console.error("Failed to parse Claude configuration:", err);
136
- }
137
- }
138
- }
87
+
88
+ const extraFlags = loadClaudeExtraFlags(resume);
139
89
 
140
90
  const sshCmd = `ssh -t ${keyOpt} ${portOpt} ${config.username}@${config.host} "claude ${extraFlags}"`;
141
91
 
@@ -200,5 +150,9 @@ export class SSHRunner extends AgentRunner {
200
150
  }
201
151
  }
202
152
  }
153
+
154
+ override getPid(): number | undefined {
155
+ return this.ptyProcess?.pid;
156
+ }
203
157
  }
204
158
 
@@ -75,10 +75,20 @@ export class SessionPersister {
75
75
  try {
76
76
  const dir = this.getSessionsDir();
77
77
  const filePath = path.join(dir, `${id}.json`);
78
- fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf8", (err) => {
78
+ // Write to a temp file then rename, so a crash mid-write can't leave a
79
+ // truncated/corrupt session file (rename is atomic on the same filesystem).
80
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
81
+ fs.writeFile(tmpPath, JSON.stringify(data, null, 2), "utf8", (err) => {
79
82
  if (err) {
80
83
  console.error(`[SessionPersister] Failed to save session ${id} asynchronously:`, err);
84
+ return;
81
85
  }
86
+ fs.rename(tmpPath, filePath, (renameErr) => {
87
+ if (renameErr) {
88
+ console.error(`[SessionPersister] Failed to finalize session ${id}:`, renameErr);
89
+ fs.unlink(tmpPath, () => {});
90
+ }
91
+ });
82
92
  });
83
93
  } catch (err) {
84
94
  console.error(`[SessionPersister] Failed to save session ${id}:`, err);
@@ -1,40 +1,7 @@
1
1
  import fs from "fs";
2
- import path from "path";
3
2
  import type { IPty } from "node-pty";
4
3
  import { AgentRunner } from "./AgentRunner";
5
-
6
- function isWindows(): boolean {
7
- return typeof process !== "undefined" && process.platform === "win32";
8
- }
9
-
10
- function findGitBash(): string | null {
11
- if (!isWindows()) {
12
- return "bash";
13
- }
14
- const pf = process.env.PROGRAMFILES || "C:\\Program Files";
15
- const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
16
- const local = process.env.LOCALAPPDATA || "";
17
-
18
- const candidates: string[] = [
19
- process.env.WINGMAN_BASH_PATH,
20
- path.join(pf, "Git", "bin", "bash.exe"),
21
- path.join(pf86, "Git", "bin", "bash.exe"),
22
- local ? path.join(local, "Programs", "Git", "bin", "bash.exe") : "",
23
- ].filter((p): p is string => typeof p === "string" && p !== "");
24
-
25
- const found = candidates.find(p => fs.existsSync(p));
26
- if (found) return found;
27
-
28
- // Fallback to PowerShell or Cmd on Windows
29
- const windir = process.env.windir || "C:\\Windows";
30
- const powershell = path.join(windir, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
31
- if (fs.existsSync(powershell)) return powershell;
32
-
33
- const cmd = path.join(windir, "System32", "cmd.exe");
34
- if (fs.existsSync(cmd)) return cmd;
35
-
36
- return null;
37
- }
4
+ import { isWindows, findInteractiveShell, loadNodePty } from "./runtime";
38
5
 
39
6
  export class ShellRunner extends AgentRunner {
40
7
  id: string;
@@ -53,20 +20,15 @@ export class ShellRunner extends AgentRunner {
53
20
  this.name = name || "Workspace Shell";
54
21
  this.workspaceRoot = workspaceRoot;
55
22
  this.createdAt = new Date().toISOString();
56
- }
57
-
58
- private appendLog(line: string) {
59
- this.logs.push(line);
60
- if (this.logs.length > 5000) {
61
- this.logs.shift();
62
- }
63
- this.emitOutput(line);
23
+ // The workspace shell is ephemeral: don't parse tokens or persist its logs.
24
+ this.parseTokensOnLog = false;
25
+ this.persistOnLog = false;
64
26
  }
65
27
 
66
28
  async start(resume?: boolean): Promise<void> {
67
29
  if (this.status === 'running') return;
68
30
 
69
- const shellPath = findGitBash();
31
+ const shellPath = findInteractiveShell();
70
32
  if (!shellPath) {
71
33
  this.status = 'stopped';
72
34
  this.appendLog("[System Error] Shell executable (Git Bash/PowerShell) not found.\r\n");
@@ -74,9 +36,7 @@ export class ShellRunner extends AgentRunner {
74
36
  }
75
37
 
76
38
  try {
77
- if (!this.ptyModule) {
78
- this.ptyModule = eval("require")("node-pty");
79
- }
39
+ this.ptyModule = loadNodePty();
80
40
 
81
41
  this.status = 'running';
82
42
  this.appendLog("\x1b[1;36m[System] Launching workspace terminal interactive shell...\x1b[0m\r\n");
@@ -149,5 +109,9 @@ export class ShellRunner extends AgentRunner {
149
109
  }
150
110
  }
151
111
  }
112
+
113
+ override getPid(): number | undefined {
114
+ return this.ptyProcess?.pid;
115
+ }
152
116
  }
153
117
 
@@ -1,5 +1,6 @@
1
1
  import { WebSocketServer, WebSocket } from "ws";
2
2
  import { AgentRunner } from "./AgentRunner";
3
+ import { getBindHost, isRequestAllowed } from "../security";
3
4
 
4
5
  declare global {
5
6
  var wss: WebSocketServer | undefined;
@@ -20,12 +21,26 @@ export function initWebSocketServer(port = 9601, getSession?: (id: string) => Ag
20
21
 
21
22
  let currentPort = port;
22
23
  const maxPort = port + 10;
24
+ const bindHost = getBindHost();
23
25
 
24
26
  function tryBind() {
25
- console.log(`[WebSocketServer] Launching NeuralLoom WebSocket Gateway on port ${currentPort}...`);
27
+ console.log(`[WebSocketServer] Launching NeuralLoom WebSocket Gateway on ${bindHost}:${currentPort}...`);
26
28
 
27
29
  try {
28
- const wss = new WebSocketServer({ port: currentPort });
30
+ const wss = new WebSocketServer({
31
+ port: currentPort,
32
+ host: bindHost,
33
+ // Reject cross-origin / non-loopback handshakes (mirrors the HTTP middleware).
34
+ verifyClient: (info: { origin?: string; req: { headers: Record<string, string | string[] | undefined> } }) => {
35
+ const hostHeader = (info.req.headers.host as string) || null;
36
+ const originHeader = info.origin || (info.req.headers.origin as string) || null;
37
+ const allowed = isRequestAllowed(hostHeader, originHeader);
38
+ if (!allowed) {
39
+ console.warn(`[WebSocketServer] Rejected gateway connection (origin=${originHeader ?? "none"}, host=${hostHeader ?? "none"}).`);
40
+ }
41
+ return allowed;
42
+ },
43
+ });
29
44
 
30
45
  wss.on("error", (err: unknown) => {
31
46
  const socketErr = err as { code?: string };