@clagentic/console 1.9.0 → 1.10.0-beta.1

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 (146) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. package/lib/sdk-permission-ownership.js +0 -136
@@ -2,8 +2,11 @@ var fs = require("fs");
2
2
  var path = require("path");
3
3
 
4
4
  // How long (ms) to keep processed trigger files before pruning on startup.
5
- var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
6
- var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
5
+ var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days (processed/ and expired/)
6
+ // Default grace period before an unprocessed trigger is moved to expired/.
7
+ var DEFAULT_UNPROCESSED_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
8
+ var CLOCK_SKEW_TOLERANCE_MS = 5 * 60 * 1000; // future createdAt beyond this is ignored
9
+ var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
7
10
  var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
8
11
 
9
12
  /**
@@ -26,9 +29,29 @@ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
26
29
  * On push_message path, if sessionId is not found the trigger is NOT archived
27
30
  * so daemon-down recovery can retry when the session reconnects.
28
31
  *
32
+ * contextNote on the push_message path: sdk.pushMessage(session, text, images)
33
+ * takes IMAGES as its third argument, so contextNote is never passed there
34
+ * (it stays null). The prompt text delivered to the agent is unchanged; instead
35
+ * a user_message entry carrying { source: "external-trigger", triggerId,
36
+ * contextNote } is recorded in the session history and session file so the
37
+ * agent-origin is distinguishable from operator-typed input. The entry is
38
+ * recorded only after the push succeeds, so retries never duplicate it.
39
+ *
40
+ * Trigger lifecycle directories under triggersDir:
41
+ * (triggersDir) — pending / retrying
42
+ * processed/ — delivered
43
+ * expired/ — never delivered within the grace period
44
+ * A file still in the triggers dir once its age exceeds unprocessedTtlMs is
45
+ * MOVED (never deleted) to expired/. This covers push_message triggers whose
46
+ * session is never found, malformed JSON, schema-invalid files, and unknown
47
+ * projectSlug. Age is the parsed trigger.createdAt when it is a valid date
48
+ * not more than 5 minutes in the future, else the file mtime. The check runs on every scan (startup + 30 s poll).
49
+ * processed/ and expired/ files older than 30 days are pruned.
50
+ *
29
51
  * ctx fields:
30
52
  * triggersDir — absolute path to ~/.clagentic/external-triggers/
31
53
  * getProject — function(slug) -> project context | null
54
+ * unprocessedTtlMs — optional grace period before expiry (default 7 days)
32
55
  *
33
56
  * Security: triggers dir is under the user's home. Any process running as
34
57
  * the same OS user can write files. Acceptable for single-user self-hosted
@@ -50,7 +73,11 @@ function attachExternalTrigger(ctx) {
50
73
  var triggersDir = ctx.triggersDir;
51
74
  var getProject = ctx.getProject;
52
75
 
76
+ var triggersRoot = path.dirname(path.join(triggersDir, "x"));
53
77
  var processedDir = path.join(triggersDir, "processed");
78
+ var expiredDir = path.join(triggersDir, "expired");
79
+ var unprocessedTtlMs = (typeof ctx.unprocessedTtlMs === "number" && ctx.unprocessedTtlMs >= 0)
80
+ ? ctx.unprocessedTtlMs : DEFAULT_UNPROCESSED_TTL_MS;
54
81
  var watcher = null;
55
82
  var debounce = null;
56
83
  // Track IDs already dispatched this session to guard against double-fire
@@ -67,6 +94,7 @@ function attachExternalTrigger(ctx) {
67
94
  function ensureDirs() {
68
95
  try { fs.mkdirSync(triggersDir, { recursive: true }); } catch (e) {}
69
96
  try { fs.mkdirSync(processedDir, { recursive: true }); } catch (e) {}
97
+ try { fs.mkdirSync(expiredDir, { recursive: true }); } catch (e) {}
70
98
  }
71
99
 
72
100
  // --- Trigger file validation ---
@@ -130,6 +158,24 @@ function attachExternalTrigger(ctx) {
130
158
 
131
159
  // --- Mid-session inject ---
132
160
 
161
+ // Marks the pushed message as agent-origin in history/session file. Failure
162
+ // here must not turn a delivered message into a retry (double delivery).
163
+ function recordPushedMessage(sm, sess, trigger) {
164
+ var entry = {
165
+ type: "user_message",
166
+ text: trigger.initialPrompt,
167
+ source: "external-trigger",
168
+ triggerId: trigger.id,
169
+ };
170
+ if (trigger.contextNote) entry.contextNote = trigger.contextNote;
171
+ try {
172
+ sm.recordHistoryEntry(sess, entry, true);
173
+ sm.appendToSessionFile(sess, entry);
174
+ } catch (e) {
175
+ console.error("[external-trigger] Failed to record pushed message for trigger " + trigger.id + ":", e.message || e);
176
+ }
177
+ }
178
+
133
179
  function pushMessageToSession(project, trigger) {
134
180
  var sm = project.sm;
135
181
  var sdk = project.sdk;
@@ -152,8 +198,11 @@ function attachExternalTrigger(ctx) {
152
198
  }
153
199
 
154
200
  try {
201
+ // Third argument is images, not metadata: contextNote travels via the
202
+ // recorded history entry below.
155
203
  sdk.pushMessage(found, trigger.initialPrompt, null);
156
204
  console.log("[external-trigger] push_message delivered to session " + trigger.sessionId + " (trigger " + trigger.id + ")");
205
+ recordPushedMessage(sm, found, trigger);
157
206
  return "ok";
158
207
  } catch (e) {
159
208
  console.error("[external-trigger] push_message failed for trigger " + trigger.id + ":", e.message || e);
@@ -178,29 +227,71 @@ function attachExternalTrigger(ctx) {
178
227
  }
179
228
  }
180
229
 
230
+ // --- Expiry ---
231
+
232
+ function triggerAgeMs(filePath, obj) {
233
+ if (obj && typeof obj.createdAt === "string") {
234
+ var t = Date.parse(obj.createdAt);
235
+ // A createdAt beyond the skew tolerance is untrustworthy (bad producer
236
+ // clock) and would otherwise dodge the TTL forever; use mtime instead.
237
+ if (!isNaN(t) && t <= Date.now() + CLOCK_SKEW_TOLERANCE_MS) return Date.now() - t;
238
+ }
239
+ try { return Date.now() - fs.statSync(filePath).mtimeMs; } catch (e) { return 0; }
240
+ }
241
+
242
+ // Moves filePath to expired/ when past the grace period. Returns true if moved.
243
+ function expireIfStale(filePath, obj) {
244
+ if (triggerAgeMs(filePath, obj) <= unprocessedTtlMs) return false;
245
+ var base = path.basename(filePath);
246
+ try { fs.mkdirSync(expiredDir, { recursive: true }); } catch (e) {}
247
+ var dest = path.join(expiredDir, base);
248
+ try {
249
+ fs.renameSync(filePath, dest);
250
+ } catch (e) {
251
+ try {
252
+ fs.copyFileSync(filePath, dest);
253
+ fs.unlinkSync(filePath);
254
+ } catch (e2) {
255
+ console.error("[external-trigger] Failed to expire trigger " + base + ":", e2.message || e2);
256
+ return false;
257
+ }
258
+ }
259
+ if (obj && obj.id) delete dispatched[obj.id];
260
+ console.warn("[external-trigger] Trigger " + base + " undelivered past TTL — moved to expired/");
261
+ return true;
262
+ }
263
+
181
264
  // --- File handler ---
182
265
 
183
266
  function handleFile(filePath) {
184
267
  var base = path.basename(filePath);
185
268
  if (!base.endsWith(".json")) return;
186
- // Skip processed/ subdir entries that might bubble up
187
- if (filePath.indexOf(processedDir) === 0) return;
269
+ // Only direct children of the triggers dir are triggers; entries in
270
+ // processed/ or expired/ are excluded by exact directory match, so a
271
+ // top-level processed-<id>.json is still a normal trigger.
272
+ if (path.dirname(filePath) !== triggersRoot) return;
188
273
 
189
274
  var raw;
190
275
  try { raw = fs.readFileSync(filePath, "utf8"); } catch (e) { return; }
191
276
 
192
277
  var obj;
193
278
  try { obj = JSON.parse(raw); } catch (e) {
279
+ if (expireIfStale(filePath, null)) return;
194
280
  console.warn("[external-trigger] Malformed JSON in " + base + ":", e.message);
195
281
  return;
196
282
  }
197
283
 
198
284
  var err = validateTrigger(obj);
199
285
  if (err) {
286
+ if (expireIfStale(filePath, obj)) return;
200
287
  console.warn("[external-trigger] Invalid trigger " + base + ": " + err);
201
288
  return;
202
289
  }
203
290
 
291
+ // Before the dispatched guard: files held back by it (unknown project,
292
+ // push error) must still expire.
293
+ if (expireIfStale(filePath, obj)) return;
294
+
204
295
  var id = obj.id;
205
296
  if (dispatched[id]) return; // already handled this session
206
297
  dispatched[id] = true;
@@ -239,10 +330,7 @@ function attachExternalTrigger(ctx) {
239
330
  try { files = fs.readdirSync(triggersDir); } catch (e) { return; }
240
331
  for (var i = 0; i < files.length; i++) {
241
332
  if (!files[i].endsWith(".json")) continue;
242
- var fp = path.join(triggersDir, files[i]);
243
- // Skip entries inside processed/ subdir
244
- if (fp.indexOf(processedDir) === 0) continue;
245
- handleFile(fp);
333
+ handleFile(path.join(triggersDir, files[i]));
246
334
  }
247
335
  }, 200);
248
336
  }
@@ -321,11 +409,16 @@ function attachExternalTrigger(ctx) {
321
409
  // --- Processed file pruning ---
322
410
 
323
411
  function pruneOldProcessed() {
412
+ pruneDir(processedDir);
413
+ pruneDir(expiredDir);
414
+ }
415
+
416
+ function pruneDir(dir) {
324
417
  var now = Date.now();
325
418
  var files;
326
- try { files = fs.readdirSync(processedDir); } catch (e) { return; }
419
+ try { files = fs.readdirSync(dir); } catch (e) { return; }
327
420
  for (var i = 0; i < files.length; i++) {
328
- var fp = path.join(processedDir, files[i]);
421
+ var fp = path.join(dir, files[i]);
329
422
  try {
330
423
  var stat = fs.statSync(fp);
331
424
  if (now - stat.mtimeMs > PROCESSED_MAX_AGE_MS) {
@@ -0,0 +1,172 @@
1
+ // File-scope policy shared by the WebSocket fs_* handlers, the HTTP file
2
+ // routes and the file/directory watchers: who may touch files, how a client
3
+ // supplied path is resolved, and how a file is read.
4
+ //
5
+ // Two rules hold everywhere this module is used:
6
+ // - the fileBrowser permission is checked before any file is touched;
7
+ // - in os-users mode a caller without a resolved OS identity is refused,
8
+ // never served by a privileged read as the daemon user.
9
+
10
+ var fs = require("fs");
11
+ var path = require("path");
12
+ var { authOf } = require("./project-access");
13
+
14
+ function isUsablePath(requested) {
15
+ return typeof requested === "string" && requested.indexOf("\0") === -1;
16
+ }
17
+
18
+ // Resolve `requested` inside `base`, following symlinks. Null for anything
19
+ // that is not a string, holds a null byte, or lands outside `base`.
20
+ function safePath(base, requested) {
21
+ if (!isUsablePath(requested)) return null;
22
+ var resolved = path.resolve(base, requested);
23
+ if (resolved !== base && !resolved.startsWith(base + path.sep)) return null;
24
+ try {
25
+ var real = fs.realpathSync(resolved);
26
+ if (real !== base && !real.startsWith(base + path.sep)) return null;
27
+ return real;
28
+ } catch (e) {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ // Resolve an absolute path without requiring it to be within a project root.
34
+ // Only used in os-users mode, where the kernel's ACLs decide access.
35
+ function safeAbsPath(requested) {
36
+ if (!requested || !isUsablePath(requested)) return null;
37
+ var resolved = path.resolve(requested);
38
+ try {
39
+ return fs.realpathSync(resolved);
40
+ } catch (e) {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ // Resolve a path inside the Claude data directory (~/.claude/), read-only
46
+ // fallback so plan files that live outside the project can be previewed.
47
+ function safeClaudePath(requested) {
48
+ if (!requested || !isUsablePath(requested)) return null;
49
+ var claudeDir = path.join(require("./config").REAL_HOME, ".claude");
50
+ var resolved = path.resolve(requested);
51
+ if (resolved !== claudeDir && !resolved.startsWith(claudeDir + path.sep)) return null;
52
+ try {
53
+ var real = fs.realpathSync(resolved);
54
+ if (real !== claudeDir && !real.startsWith(claudeDir + path.sep)) return null;
55
+ return real;
56
+ } catch (e) {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ // Returns an error string when the caller may not use file features, else null.
62
+ // user the authenticated user, if any
63
+ // osUsers whether os-users mode is on
64
+ // osUserInfo the caller's resolved OS identity, or null
65
+ // usersModule module exposing getEffectivePermissions(user, osUsers)
66
+ function checkFileAccess(o) {
67
+ if (o.user) {
68
+ var perms = o.usersModule.getEffectivePermissions(o.user, o.osUsers);
69
+ if (!perms.fileBrowser) return "File browser access is not permitted";
70
+ }
71
+ if (o.osUsers && !o.osUserInfo) return "File access requires an OS user identity";
72
+ return null;
73
+ }
74
+
75
+ // Path a caller may read or write: inside the project, or (os-users) wherever
76
+ // the OS grants that identity access. Used by writes and by the HTTP file route.
77
+ function resolveProjectPath(cwd, requested, osUserInfo) {
78
+ var resolved = safePath(cwd, requested);
79
+ if (!resolved && osUserInfo) resolved = safeAbsPath(requested);
80
+ return resolved;
81
+ }
82
+
83
+ // Path a caller may read over the WebSocket: as above, plus read-only access
84
+ // inside ~/.claude (plan files).
85
+ function resolveReadPath(cwd, requested, osUserInfo) {
86
+ return resolveProjectPath(cwd, requested, osUserInfo) || safeClaudePath(requested);
87
+ }
88
+
89
+ // A project-relative path for git, or null when the request is not a path
90
+ // that stays inside the project. The file need not exist (history can name
91
+ // deleted files), so this is lexical rather than a realpath check.
92
+ function resolveGitPath(cwd, requested) {
93
+ if (!requested || !isUsablePath(requested)) return null;
94
+ var abs = path.resolve(cwd, requested);
95
+ if (abs === cwd || !abs.startsWith(cwd + path.sep)) return null;
96
+ return path.relative(cwd, abs).split(path.sep).join("/");
97
+ }
98
+
99
+ // Read a file as the caller. Result kind: "text", "binary" or "too_large".
100
+ // file, osUsers, osUserInfo, fsAsUser, maxSize, binaryExts
101
+ function readFileForUser(file, o) {
102
+ if (o.osUsers && !o.osUserInfo) throw new Error("File access requires an OS user identity");
103
+ var ext = path.extname(file).toLowerCase();
104
+ var size = o.osUserInfo
105
+ ? o.fsAsUser("stat", { file: file }, o.osUserInfo).size
106
+ : fs.statSync(file).size;
107
+ if (size > o.maxSize) return { kind: "too_large", size: size, ext: ext };
108
+ if (o.binaryExts.has(ext)) return { kind: "binary", size: size, ext: ext };
109
+ var content = o.osUserInfo
110
+ ? o.fsAsUser("read", { file: file, readContent: true }, o.osUserInfo).content
111
+ : fs.readFileSync(file, "utf8");
112
+ return { kind: "text", size: size, content: content, ext: ext };
113
+ }
114
+
115
+ // List a directory as the caller: [{ name, isDir }].
116
+ function listDirForUser(dir, o) {
117
+ if (o.osUsers && !o.osUserInfo) throw new Error("File access requires an OS user identity");
118
+ if (o.osUserInfo) {
119
+ return o.fsAsUser("list", { dir: dir }, o.osUserInfo).map(function (e) {
120
+ return { name: e.name, isDir: !!e.isDir };
121
+ });
122
+ }
123
+ return fs.readdirSync(dir, { withFileTypes: true }).map(function (d) {
124
+ return { name: d.name, isDir: d.isDirectory() };
125
+ });
126
+ }
127
+
128
+ // Binds the policy above to one project's settings so the WebSocket handlers
129
+ // and the watchers ask the same questions of the same code.
130
+ // osUsers, usersModule, fsAsUser, binaryExts, maxSize
131
+ // projectAccess the lib/project-access.js resolver: a connection with no
132
+ // principal (no user in multi-user mode) is refused here
133
+ // as well, however it got this far
134
+ // getOsUserInfoForWs(ws) -> the connection's OS identity, or null
135
+ function createFileAccess(deps) {
136
+ function readOptions(ws) {
137
+ return {
138
+ osUsers: deps.osUsers,
139
+ osUserInfo: deps.getOsUserInfoForWs(ws),
140
+ fsAsUser: deps.fsAsUser,
141
+ maxSize: deps.maxSize,
142
+ binaryExts: deps.binaryExts,
143
+ };
144
+ }
145
+ return {
146
+ // Error string when this connection may not use file features, else null.
147
+ authorize: function (ws) {
148
+ if (deps.projectAccess && !deps.projectAccess.principalFor(ws._clagenticUser, authOf(ws))) return "Authentication required";
149
+ return checkFileAccess({
150
+ user: ws._clagenticUser,
151
+ osUsers: deps.osUsers,
152
+ osUserInfo: deps.getOsUserInfoForWs(ws),
153
+ usersModule: deps.usersModule,
154
+ });
155
+ },
156
+ readFile: function (ws, file) { return readFileForUser(file, readOptions(ws)); },
157
+ listDir: function (ws, dir) { return listDirForUser(dir, readOptions(ws)); },
158
+ };
159
+ }
160
+
161
+ module.exports = {
162
+ createFileAccess: createFileAccess,
163
+ safePath: safePath,
164
+ safeAbsPath: safeAbsPath,
165
+ safeClaudePath: safeClaudePath,
166
+ checkFileAccess: checkFileAccess,
167
+ resolveReadPath: resolveReadPath,
168
+ resolveProjectPath: resolveProjectPath,
169
+ resolveGitPath: resolveGitPath,
170
+ readFileForUser: readFileForUser,
171
+ listDirForUser: listDirForUser,
172
+ };
@@ -1,111 +1,135 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
3
 
4
+ // Most directory watches one connection may hold; each is an inotify handle.
5
+ var MAX_DIR_WATCHES_PER_CONNECTION = 64;
6
+
4
7
  /**
5
- * Attach file/directory watcher engine to a project context.
8
+ * Attach the file/directory watcher engine to a project context.
9
+ *
10
+ * Watches belong to the connection that asked for them. Every change is read
11
+ * as that connection's user (an OS user in os-users mode) and is sent to that
12
+ * connection only, so a watch can neither read a file the user may not read
13
+ * nor show its contents to anyone else on the project.
6
14
  *
7
15
  * ctx fields:
8
- * cwd, send, safePath, BINARY_EXTS, FS_MAX_SIZE, IGNORED_DIRS
16
+ * cwd, sendTo(ws, msg), safePath(base, requested)
17
+ * authorize(ws) -> error string | null (file-browser policy)
18
+ * readFile(ws, absFile) -> { kind: "text"|"binary"|"too_large", content, size }
19
+ * listDir(ws, absDir) -> [{ name, isDir }]
20
+ * IGNORED_DIRS
9
21
  */
10
22
  function attachFileWatch(ctx) {
11
23
  var cwd = ctx.cwd;
12
- var send = ctx.send;
24
+ var sendTo = ctx.sendTo;
13
25
  var safePath = ctx.safePath;
14
- var BINARY_EXTS = ctx.BINARY_EXTS;
15
- var FS_MAX_SIZE = ctx.FS_MAX_SIZE;
26
+ var authorize = ctx.authorize;
27
+ var readFile = ctx.readFile;
28
+ var listDir = ctx.listDir;
16
29
  var IGNORED_DIRS = ctx.IGNORED_DIRS;
17
30
 
18
- // --- File watcher ---
19
- var fileWatcher = null;
20
- var watchedPath = null;
21
- var watchDebounce = null;
31
+ // --- Single-file watch: at most one per connection ---
32
+ var fileWatches = new Map(); // ws -> { relPath, watcher, debounce }
22
33
 
23
- function startFileWatch(relPath) {
34
+ function startFileWatch(ws, relPath) {
35
+ if (authorize(ws)) return;
24
36
  var absPath = safePath(cwd, relPath);
25
37
  if (!absPath) return;
26
- if (watchedPath === relPath) return;
27
- stopFileWatch();
28
- watchedPath = relPath;
38
+ var existing = fileWatches.get(ws);
39
+ if (existing && existing.relPath === relPath) return;
40
+ stopFileWatch(ws);
41
+ var entry = { relPath: relPath, watcher: null, debounce: null };
29
42
  try {
30
- fileWatcher = fs.watch(absPath, function () {
31
- clearTimeout(watchDebounce);
32
- watchDebounce = setTimeout(function () {
43
+ entry.watcher = fs.watch(absPath, function () {
44
+ clearTimeout(entry.debounce);
45
+ entry.debounce = setTimeout(function () {
33
46
  try {
34
- var stat = fs.statSync(absPath);
35
- var ext = path.extname(absPath).toLowerCase();
36
- if (stat.size > FS_MAX_SIZE || BINARY_EXTS.has(ext)) return;
37
- var content = fs.readFileSync(absPath, "utf8");
38
- send({ type: "fs_file_changed", path: relPath, content: content, size: stat.size });
47
+ if (authorize(ws)) { stopFileWatch(ws); return; }
48
+ var result = readFile(ws, absPath);
49
+ if (result.kind !== "text") return;
50
+ sendTo(ws, { type: "fs_file_changed", path: relPath, content: result.content, size: result.size });
39
51
  } catch (e) {
40
- stopFileWatch();
52
+ stopFileWatch(ws);
41
53
  }
42
54
  }, 200);
43
55
  });
44
- fileWatcher.on("error", function () { stopFileWatch(); });
56
+ entry.watcher.on("error", function () { stopFileWatch(ws); });
57
+ fileWatches.set(ws, entry);
45
58
  } catch (e) {
46
- watchedPath = null;
59
+ // The file vanished or cannot be watched; the client simply gets no events.
47
60
  }
48
61
  }
49
62
 
50
- function stopFileWatch() {
51
- if (fileWatcher) {
52
- try { fileWatcher.close(); } catch (e) {}
53
- fileWatcher = null;
54
- }
55
- clearTimeout(watchDebounce);
56
- watchDebounce = null;
57
- watchedPath = null;
63
+ function stopFileWatch(ws) {
64
+ var entry = fileWatches.get(ws);
65
+ if (!entry) return;
66
+ clearTimeout(entry.debounce);
67
+ try { entry.watcher.close(); } catch (e) {}
68
+ fileWatches.delete(ws);
58
69
  }
59
70
 
60
- // --- Directory watcher ---
61
- var dirWatchers = {}; // relPath -> { watcher, debounce }
71
+ // --- Directory watches: any number per connection, up to the cap ---
72
+ var dirWatches = new Map(); // ws -> Map(relPath -> { watcher, debounce })
62
73
 
63
- function startDirWatch(relPath) {
64
- if (dirWatchers[relPath]) return;
74
+ function startDirWatch(ws, relPath) {
75
+ if (authorize(ws)) return;
76
+ var mine = dirWatches.get(ws);
77
+ if (mine && mine.has(relPath)) return;
78
+ if (mine && mine.size >= MAX_DIR_WATCHES_PER_CONNECTION) return;
65
79
  var absPath = safePath(cwd, relPath);
66
80
  if (!absPath) return;
81
+ var entry = { watcher: null, debounce: null };
67
82
  try {
68
- var debounce = null;
69
- var watcher = fs.watch(absPath, function () {
70
- clearTimeout(debounce);
71
- debounce = setTimeout(function () {
72
- // Re-read directory and broadcast to all clients
83
+ entry.watcher = fs.watch(absPath, function () {
84
+ clearTimeout(entry.debounce);
85
+ entry.debounce = setTimeout(function () {
73
86
  try {
74
- var items = fs.readdirSync(absPath, { withFileTypes: true });
87
+ if (authorize(ws)) { stopDirWatch(ws, relPath); return; }
75
88
  var entries = [];
89
+ var items = listDir(ws, absPath);
76
90
  for (var i = 0; i < items.length; i++) {
77
- if (items[i].isDirectory() && IGNORED_DIRS.has(items[i].name)) continue;
91
+ if (items[i].isDir && IGNORED_DIRS.has(items[i].name)) continue;
78
92
  entries.push({
79
93
  name: items[i].name,
80
- type: items[i].isDirectory() ? "dir" : "file",
94
+ type: items[i].isDir ? "dir" : "file",
81
95
  path: path.relative(cwd, path.join(absPath, items[i].name)).split(path.sep).join("/"),
82
96
  });
83
97
  }
84
- send({ type: "fs_dir_changed", path: relPath, entries: entries });
98
+ sendTo(ws, { type: "fs_dir_changed", path: relPath, entries: entries });
85
99
  } catch (e) {
86
- stopDirWatch(relPath);
100
+ stopDirWatch(ws, relPath);
87
101
  }
88
102
  }, 300);
89
103
  });
90
- watcher.on("error", function () { stopDirWatch(relPath); });
91
- dirWatchers[relPath] = { watcher: watcher, debounce: debounce };
92
- } catch (e) {}
104
+ entry.watcher.on("error", function () { stopDirWatch(ws, relPath); });
105
+ if (!mine) { mine = new Map(); dirWatches.set(ws, mine); }
106
+ mine.set(relPath, entry);
107
+ } catch (e) {
108
+ // Not watchable; listing still works, it just will not refresh itself.
109
+ }
93
110
  }
94
111
 
95
- function stopDirWatch(relPath) {
96
- var entry = dirWatchers[relPath];
97
- if (entry) {
98
- clearTimeout(entry.debounce);
99
- try { entry.watcher.close(); } catch (e) {}
100
- delete dirWatchers[relPath];
101
- }
112
+ function stopDirWatch(ws, relPath) {
113
+ var mine = dirWatches.get(ws);
114
+ var entry = mine && mine.get(relPath);
115
+ if (!entry) return;
116
+ clearTimeout(entry.debounce);
117
+ try { entry.watcher.close(); } catch (e) {}
118
+ mine.delete(relPath);
119
+ if (mine.size === 0) dirWatches.delete(ws);
102
120
  }
103
121
 
104
- function stopAllDirWatches() {
105
- var paths = Object.keys(dirWatchers);
106
- for (var i = 0; i < paths.length; i++) {
107
- stopDirWatch(paths[i]);
108
- }
122
+ // Every directory watch one connection holds; with stopFileWatch(ws) this
123
+ // releases everything the connection owns when it disconnects.
124
+ function stopAllDirWatches(ws) {
125
+ var mine = dirWatches.get(ws);
126
+ if (!mine) return;
127
+ Array.from(mine.keys()).forEach(function (relPath) { stopDirWatch(ws, relPath); });
128
+ }
129
+
130
+ function stopAll() {
131
+ Array.from(fileWatches.keys()).forEach(stopFileWatch);
132
+ Array.from(dirWatches.keys()).forEach(stopAllDirWatches);
109
133
  }
110
134
 
111
135
  return {
@@ -114,6 +138,7 @@ function attachFileWatch(ctx) {
114
138
  startDirWatch: startDirWatch,
115
139
  stopDirWatch: stopDirWatch,
116
140
  stopAllDirWatches: stopAllDirWatches,
141
+ stopAll: stopAll,
117
142
  };
118
143
  }
119
144