@clagentic/console 1.9.0 → 1.10.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) 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 +9 -3
  5. package/bin/cli.js +40 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/agent-dispatch-tool.js +20 -0
  8. package/lib/audit.js +3 -2
  9. package/lib/build-changes.js +79 -0
  10. package/lib/build-identity.js +192 -0
  11. package/lib/build-monitor.js +125 -0
  12. package/lib/build-sha.json +2 -2
  13. package/lib/build-update-check.js +138 -0
  14. package/lib/build-update-offer.js +141 -0
  15. package/lib/build-update-restart.js +142 -0
  16. package/lib/build-update-standing.js +184 -0
  17. package/lib/cli/daemon-launch.js +25 -22
  18. package/lib/cli/ipc-subcommands.js +6 -0
  19. package/lib/cli/session-subcommands.js +122 -0
  20. package/lib/cli-sessions.js +8 -1
  21. package/lib/codex-defaults.js +8 -2
  22. package/lib/config.js +32 -20
  23. package/lib/daemon-env-settings.js +84 -0
  24. package/lib/daemon-projects.js +57 -0
  25. package/lib/daemon.js +288 -205
  26. package/lib/drain.js +74 -17
  27. package/lib/env-compat.js +61 -0
  28. package/lib/extension-commands.js +45 -0
  29. package/lib/history-visibility.js +4 -0
  30. package/lib/idle-adapter-reaper.js +71 -0
  31. package/lib/link-trap.js +78 -0
  32. package/lib/mcp-local.js +8 -6
  33. package/lib/mcp-tool-input.js +116 -0
  34. package/lib/mcp-tool-schema.js +179 -0
  35. package/lib/memory-limits.js +61 -5
  36. package/lib/memory-setting-validate.js +65 -0
  37. package/lib/memory-shed.js +13 -32
  38. package/lib/new-work-gate.js +47 -0
  39. package/lib/os-users.js +5 -3
  40. package/lib/project-access.js +139 -0
  41. package/lib/project-connection.js +37 -22
  42. package/lib/project-external-trigger.js +166 -105
  43. package/lib/project-file-scope.js +172 -0
  44. package/lib/project-file-watch.js +86 -61
  45. package/lib/project-filesystem.js +144 -128
  46. package/lib/project-git.js +119 -0
  47. package/lib/project-http.js +44 -28
  48. package/lib/project-loop.js +17 -9
  49. package/lib/project-mcp.js +53 -72
  50. package/lib/project-message-gate.js +70 -0
  51. package/lib/project-notifications.js +31 -4
  52. package/lib/project-prompt-responses.js +217 -0
  53. package/lib/project-sessions.js +192 -355
  54. package/lib/project-user-message.js +27 -15
  55. package/lib/project.js +212 -147
  56. package/lib/projects-dir.js +90 -0
  57. package/lib/prompt-access.js +22 -0
  58. package/lib/prompt-kinds/answer-limits.js +15 -0
  59. package/lib/prompt-kinds/ask-user.js +58 -0
  60. package/lib/prompt-kinds/codecs.js +97 -0
  61. package/lib/prompt-kinds/elicitation.js +77 -0
  62. package/lib/prompt-kinds/extension.js +39 -0
  63. package/lib/prompt-kinds/index.js +68 -0
  64. package/lib/prompt-kinds/permission.js +114 -0
  65. package/lib/prompt-kinds/plan.js +79 -0
  66. package/lib/prompt-kinds/tool-call.js +38 -0
  67. package/lib/prompt-registry.js +680 -0
  68. package/lib/public/app.js +1 -1
  69. package/lib/public/css/diagnostics.css +80 -0
  70. package/lib/public/css/input.css +17 -3
  71. package/lib/public/css/menus.css +10 -0
  72. package/lib/public/css/messages.css +5 -0
  73. package/lib/public/css/rewind.css +22 -0
  74. package/lib/public/index.html +4 -12
  75. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  76. package/lib/public/modules/app-connection.js +7 -0
  77. package/lib/public/modules/app-cursors.js +7 -5
  78. package/lib/public/modules/app-messages.js +52 -47
  79. package/lib/public/modules/app-notifications.js +47 -71
  80. package/lib/public/modules/app-panels.js +61 -59
  81. package/lib/public/modules/app-projects.js +2 -1
  82. package/lib/public/modules/app-rendering.js +4 -10
  83. package/lib/public/modules/build-update-detail.js +54 -0
  84. package/lib/public/modules/diagnostics.js +170 -20
  85. package/lib/public/modules/filebrowser.js +18 -16
  86. package/lib/public/modules/history-visibility.js +4 -0
  87. package/lib/public/modules/mention.js +3 -2
  88. package/lib/public/modules/mode-options.js +38 -0
  89. package/lib/public/modules/project-settings.js +19 -8
  90. package/lib/public/modules/prompt-banner.js +78 -0
  91. package/lib/public/modules/prompt-card.js +201 -0
  92. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  93. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  94. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  95. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  96. package/lib/public/modules/prompt-kinds/index.js +18 -0
  97. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  98. package/lib/public/modules/prompt-kinds/package.json +3 -0
  99. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  100. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  101. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  102. package/lib/public/modules/prompt-state.js +142 -0
  103. package/lib/public/modules/prompts.js +134 -0
  104. package/lib/public/modules/rewind.js +4 -1
  105. package/lib/public/modules/server-settings.js +2 -4
  106. package/lib/public/modules/sidebar-mobile.js +19 -9
  107. package/lib/public/modules/sidebar-sessions.js +21 -14
  108. package/lib/public/modules/sticky-notes.js +3 -2
  109. package/lib/public/modules/team-panel.js +5 -4
  110. package/lib/public/modules/tools.js +81 -906
  111. package/lib/public/modules/vendor-picker.js +53 -0
  112. package/lib/public/modules/vendor-registry.js +142 -0
  113. package/lib/public/sw.js +3 -1
  114. package/lib/rc-migrate.js +44 -0
  115. package/lib/runtime-env-keys.js +109 -0
  116. package/lib/runtime-env.js +236 -0
  117. package/lib/sdk-bridge.js +348 -284
  118. package/lib/sdk-message-processor.js +117 -146
  119. package/lib/sdk-skill-discovery.js +65 -60
  120. package/lib/server-hub-sessions.js +13 -10
  121. package/lib/server-palette.js +28 -19
  122. package/lib/server.js +156 -115
  123. package/lib/service-install.js +96 -0
  124. package/lib/session-capabilities.js +76 -0
  125. package/lib/session-id.js +33 -0
  126. package/lib/session-input-ipc.js +32 -0
  127. package/lib/session-input.js +379 -0
  128. package/lib/session-reclaim.js +284 -0
  129. package/lib/session-resume.js +172 -0
  130. package/lib/sessions.js +61 -30
  131. package/lib/supervisor.js +39 -0
  132. package/lib/turn-initiator.js +108 -0
  133. package/lib/users-permissions.js +9 -6
  134. package/lib/users.js +9 -0
  135. package/lib/utils.js +4 -2
  136. package/lib/vendor-auth.js +22 -0
  137. package/lib/vendor-registry-message.js +66 -0
  138. package/lib/ws-origin.js +99 -0
  139. package/lib/ws-schema.js +36 -23
  140. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  141. package/lib/yoke/adapters/claude-vendor.js +34 -0
  142. package/lib/yoke/adapters/claude-worker.js +57 -87
  143. package/lib/yoke/adapters/claude.js +182 -88
  144. package/lib/yoke/adapters/codex-capabilities.js +40 -0
  145. package/lib/yoke/adapters/codex-vendor.js +46 -0
  146. package/lib/yoke/adapters/codex.js +462 -211
  147. package/lib/yoke/adapters/effort-control.js +34 -0
  148. package/lib/yoke/adapters/permission-relay.js +58 -0
  149. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  150. package/lib/yoke/auth-checks.js +91 -0
  151. package/lib/yoke/capabilities.js +49 -0
  152. package/lib/yoke/codex-app-server.js +30 -56
  153. package/lib/yoke/codex-binary.js +254 -0
  154. package/lib/yoke/codex-command.js +122 -0
  155. package/lib/yoke/codex-protocol.js +96 -0
  156. package/lib/yoke/codex-version.js +135 -0
  157. package/lib/yoke/env-ownership.js +40 -0
  158. package/lib/yoke/index.js +84 -174
  159. package/lib/yoke/install-probe.js +136 -0
  160. package/lib/yoke/instructions.js +7 -11
  161. package/lib/yoke/interface.js +206 -4
  162. package/lib/yoke/package.json +1 -1
  163. package/lib/yoke/provider-credentials.js +96 -0
  164. package/lib/yoke/registry.js +377 -0
  165. package/package.json +12 -9
  166. package/scripts/check-sdk-lock-drift.js +160 -0
  167. package/scripts/check-test-count.js +76 -1
  168. package/scripts/postinstall.js +218 -136
  169. package/scripts/prompt-harness-history.js +202 -0
  170. package/scripts/verify-installed-build.js +59 -17
  171. package/scripts/verify-installed.js +67 -0
  172. package/lib/sdk-permission-ownership.js +0 -136
@@ -4,13 +4,32 @@ function attachPalette(ctx) {
4
4
  var users = ctx.users;
5
5
  var projects = ctx.projects;
6
6
  var getMultiUserFromReq = ctx.getMultiUserFromReq;
7
- var onGetProjectAccess = ctx.onGetProjectAccess;
7
+ var isRequestAuthed = ctx.isRequestAuthed;
8
+ var projectAccess = ctx.projectAccess;
9
+
10
+ // What the single-user owner is shown: every project, as a public one.
11
+ var OWNER_PROJECT_ACCESS = { visibility: "public" };
12
+
13
+ // The project's access record when the principal may use that project, else
14
+ // null. A failed lookup is a refusal, never an allow.
15
+ function accessibleProject(principal, slug) {
16
+ if (principal.implicit) return OWNER_PROJECT_ACCESS;
17
+ var access = projectAccess.resolve(slug);
18
+ return access && users.canAccessProject(principal.id, access) ? access : null;
19
+ }
20
+
21
+ function canSeeSession(principal, session, access) {
22
+ return principal.implicit || users.canAccessSession(principal.id, session, access);
23
+ }
8
24
 
9
25
  function handleRequest(req, res, fullUrl) {
10
26
  if (req.method !== "GET" || fullUrl !== "/api/palette/search") return false;
11
27
 
12
- var paletteUser = getMultiUserFromReq(req);
13
- if (!paletteUser) {
28
+ // Authentication first: appHandler has no login check ahead of this
29
+ // route, and "no user" is the implicit owner only for a request that
30
+ // proved it logged in. Without that proof there is no principal in any mode.
31
+ var principal = projectAccess.principalFor(getMultiUserFromReq(req), { authenticated: isRequestAuthed(req) === true });
32
+ if (!principal) {
14
33
  res.writeHead(401, { "Content-Type": "application/json" });
15
34
  res.end('{"error":"unauthorized"}');
16
35
  return true;
@@ -24,16 +43,11 @@ function attachPalette(ctx) {
24
43
  projects.forEach(function (pCtx, pSlug) {
25
44
  var status = pCtx.getStatus();
26
45
  if (status.isWorktree) return;
27
- if (paletteUser && onGetProjectAccess) {
28
- var pAccess = onGetProjectAccess(pSlug);
29
- if (pAccess && !pAccess.error && !users.canAccessProject(paletteUser.id, pAccess)) return;
30
- }
46
+ var pAccess = accessibleProject(principal, pSlug);
47
+ if (!pAccess) return;
31
48
  pCtx.sm.sessions.forEach(function (session) {
32
49
  if (session.hidden) return;
33
- if (paletteUser) {
34
- var sAccess = onGetProjectAccess ? onGetProjectAccess(pSlug) : null;
35
- if (!users.canAccessSession(paletteUser.id, session, sAccess)) return;
36
- }
50
+ if (!canSeeSession(principal, session, pAccess)) return;
37
51
  var pItem = {
38
52
  projectSlug: pSlug,
39
53
  projectTitle: status.title || status.project,
@@ -64,17 +78,12 @@ function attachPalette(ctx) {
64
78
  projects.forEach(function (pCtx, pSlug) {
65
79
  var status = pCtx.getStatus();
66
80
  if (status.isWorktree) return;
67
- if (paletteUser && onGetProjectAccess) {
68
- var pAccess = onGetProjectAccess(pSlug);
69
- if (pAccess && !pAccess.error && !users.canAccessProject(paletteUser.id, pAccess)) return;
70
- }
81
+ var pAccess = accessibleProject(principal, pSlug);
82
+ if (!pAccess) return;
71
83
  var accessibleSessions = [];
72
84
  pCtx.sm.sessions.forEach(function (session) {
73
85
  if (session.hidden) return;
74
- if (paletteUser) {
75
- var sAccess = onGetProjectAccess ? onGetProjectAccess(pSlug) : null;
76
- if (!users.canAccessSession(paletteUser.id, session, sAccess)) return;
77
- }
86
+ if (!canSeeSession(principal, session, pAccess)) return;
78
87
  smBySession.set(session, pCtx.sm);
79
88
  accessibleSessions.push(session);
80
89
  });
package/lib/server.js CHANGED
@@ -20,6 +20,9 @@ var { detectLite } = require("./lite-detect");
20
20
  var { readCappedBody } = require("./utils");
21
21
  var { computeAllProjectSessions } = require("./server-hub-sessions");
22
22
  var { resolveEffectiveProtocol } = require("./effective-protocol");
23
+ var { createProjectAccess } = require("./project-access");
24
+ var { checkWsOrigin } = require("./ws-origin");
25
+ var sessionReclaim = require("./session-reclaim");
23
26
 
24
27
  var https = require("https");
25
28
  var pkg = require("../package.json");
@@ -75,8 +78,8 @@ function serveStatic(urlPath, res) {
75
78
  var appVersion = pkg.version;
76
79
  // Replace the static cache name with a version-stamped one
77
80
  swContent = swContent.replace(
78
- /var CACHE_NAME = "clagentic-offline-[^"]*"/,
79
- 'var CACHE_NAME = "clagentic-offline-v' + appVersion + '"'
81
+ /var CACHE_NAME = "clagentic-console-offline-[^"]*"/,
82
+ 'var CACHE_NAME = "clagentic-console-offline-v' + appVersion + '"'
80
83
  );
81
84
  res.writeHead(200, {
82
85
  "Content-Type": "application/javascript; charset=utf-8",
@@ -129,6 +132,10 @@ function extractSlug(urlPath) {
129
132
  // Sec-WebSocket-Protocol list; this extracts the raw ticket back out.
130
133
  var WS_TICKET_SUBPROTOCOL_PREFIX = "clagentic.auth.";
131
134
 
135
+ // Stands for the single-user owner while a WebSocket upgrade is decided: the
136
+ // login gate admitted the request and there is no user record to attach.
137
+ var IMPLICIT_OWNER = Object.freeze({});
138
+
132
139
  /**
133
140
  * Extract a ws-ticket (lr-de5fcb) from a raw Sec-WebSocket-Protocol header
134
141
  * value. Returns null if the header is absent or carries no ticket-shaped
@@ -231,6 +238,9 @@ function createServer(opts) {
231
238
  // lr-20e71c: operator-declared trust boundary for reading X-Forwarded-Proto
232
239
  // from a reverse proxy. See lib/effective-protocol.js.
233
240
  var trustedProxy = !!opts.trustedProxy;
241
+ // Operator-configured origins (daemon.json allowedOrigins) that may open a
242
+ // WebSocket in addition to the daemon's own host; see lib/ws-origin.js.
243
+ var allowedOrigins = Array.isArray(opts.allowedOrigins) ? opts.allowedOrigins : [];
234
244
  // lr-2ea2a7: daemon.json knob overriding the in-heap session-history tail cap.
235
245
  var historyInMemMax = opts.historyInMemMax;
236
246
  var onAddProject = opts.onAddProject || null;
@@ -266,13 +276,21 @@ function createServer(opts) {
266
276
  var onGetProjectMcpServers = opts.onGetProjectMcpServers || null;
267
277
  var onSetProjectMcpServers = opts.onSetProjectMcpServers || null;
268
278
  var onGetDaemonConfig = opts.onGetDaemonConfig || null;
279
+ var onGetProjectEnv = opts.onGetProjectEnv || null;
280
+ var onSetProjectEnv = opts.onSetProjectEnv || null;
281
+ var onGetSharedEnv = opts.onGetSharedEnv || null;
282
+ var onSetSharedEnv = opts.onSetSharedEnv || null;
269
283
  var onSetPin = opts.onSetPin || null;
270
284
  var onSetKeepAwake = opts.onSetKeepAwake || null;
271
285
  var onSetImageRetention = opts.onSetImageRetention || null;
272
286
  var onSetMemAvailableThreshold = opts.onSetMemAvailableThreshold || null;
287
+ var onSetTokensPerMbHeadroom = opts.onSetTokensPerMbHeadroom || null;
288
+ var onSetAutoContinue = opts.onSetAutoContinue || null;
273
289
  var onSetLiteAutoEnroll = opts.onSetLiteAutoEnroll || null;
274
290
  var onShutdown = opts.onShutdown || null;
275
291
  var onRestart = opts.onRestart || null;
292
+ var onRestartForBuildUpdate = opts.onRestartForBuildUpdate || null;
293
+ var onGetBuildUpdateDiagnostic = opts.onGetBuildUpdateDiagnostic || null;
276
294
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
277
295
  var onSetProjectVisibility = opts.onSetProjectVisibility || null;
278
296
  var onSetProjectAllowedUsers = opts.onSetProjectAllowedUsers || null;
@@ -282,6 +300,16 @@ function createServer(opts) {
282
300
  var onUserDeleted = opts.onUserDeleted || null;
283
301
  var getRemovedProjects = opts.getRemovedProjects || function () { return []; };
284
302
 
303
+ // The one answer to "who is this and may they use that project": every
304
+ // check below goes through it. "No user" is decided by the daemon's mode
305
+ // (the single-user owner is implicit, a missing user in multi-user mode is
306
+ // a stranger), and a lookup that cannot be completed is a refusal.
307
+ var projectAccess = createProjectAccess({
308
+ users: users,
309
+ onGetProjectAccess: onGetProjectAccess,
310
+ isMultiUser: typeof opts.isMultiUser === "function" ? opts.isMultiUser : users.isMultiUser,
311
+ });
312
+
285
313
  // --- Auth module ---
286
314
  var auth = serverAuth.attachAuth({
287
315
  users: users,
@@ -342,7 +370,8 @@ function createServer(opts) {
342
370
  users: users,
343
371
  projects: projects,
344
372
  getMultiUserFromReq: getMultiUserFromReq,
345
- onGetProjectAccess: onGetProjectAccess,
373
+ isRequestAuthed: isRequestAuthed,
374
+ projectAccess: projectAccess,
346
375
  });
347
376
 
348
377
  // --- Push module (global) ---
@@ -368,9 +397,15 @@ function createServer(opts) {
368
397
  // emitted — the trigger carries its own notification channel (e.g. ntfy).
369
398
  var { attachExternalTrigger } = require("./project-external-trigger");
370
399
  var { EXTERNAL_TRIGGERS_DIR } = require("./config");
400
+ // One implementation for the file drop and the daemon IPC verbs (open-session,
401
+ // send-input).
402
+ var _sessionInput = require("./session-input").createSessionInput({
403
+ getProject: function (slug) { return projects.get(slug) || null; },
404
+ });
371
405
  var _externalTrigger = attachExternalTrigger({
372
406
  triggersDir: EXTERNAL_TRIGGERS_DIR,
373
407
  getProject: function (slug) { return projects.get(slug) || null; },
408
+ sessionInput: _sessionInput,
374
409
  });
375
410
  _externalTrigger.startWatcher();
376
411
 
@@ -645,28 +680,17 @@ function createServer(opts) {
645
680
  var reqUser = getMultiUserFromReq(req);
646
681
  // Check for last-visited project cookie
647
682
  var lastProject = parseCookies(req)["clagentic_last_project"] || parseCookies(req)["clay_last_project"];
648
- if (lastProject && projects.has(lastProject)) {
649
- if (reqUser && onGetProjectAccess) {
650
- var lpAccess = onGetProjectAccess(lastProject);
651
- if (lpAccess && !lpAccess.error && users.canAccessProject(reqUser.id, lpAccess)) {
652
- targetSlug = lastProject;
653
- }
654
- } else {
655
- targetSlug = lastProject;
656
- }
683
+ var reqUserId = reqUser ? reqUser.id : null;
684
+ // isRequestAuthed(req) passed above: that is the proof an implicit owner needs.
685
+ var rootProof = { authenticated: true };
686
+ if (lastProject && projects.has(lastProject) && projectAccess.canAccess(reqUserId, lastProject, rootProof)) {
687
+ targetSlug = lastProject;
657
688
  }
658
689
  // Fall back to first accessible project
659
690
  if (!targetSlug) {
660
691
  projects.forEach(function (ctx, s) {
661
692
  if (targetSlug) return;
662
- if (reqUser && onGetProjectAccess) {
663
- var access = onGetProjectAccess(s);
664
- if (access && !access.error && users.canAccessProject(reqUser.id, access)) {
665
- targetSlug = s;
666
- }
667
- } else {
668
- targetSlug = s;
669
- }
693
+ if (projectAccess.canAccess(reqUserId, s, rootProof)) targetSlug = s;
670
694
  });
671
695
  }
672
696
  if (targetSlug) {
@@ -798,16 +822,16 @@ function createServer(opts) {
798
822
  }).protocol;
799
823
  res.setHeader("Set-Cookie", "clagentic_last_project=" + slug + "; Path=/; SameSite=Strict; Max-Age=31536000" + (cookieEffectiveProtocol === "https" ? "; Secure" : ""));
800
824
 
801
- // Check project access for HTTP requests
802
- if (onGetProjectAccess) {
825
+ // Check project access for HTTP requests. The local MCP bridge carries no
826
+ // login (it is a child process of the daemon's own host); every other
827
+ // request must belong to a user who may use this project.
828
+ if (!isMcpBridgeLocal) {
803
829
  var httpUser = getMultiUserFromReq(req);
804
- if (httpUser) {
805
- var httpAccess = onGetProjectAccess(slug);
806
- if (httpAccess && !httpAccess.error && !users.canAccessProject(httpUser.id, httpAccess)) {
807
- res.writeHead(302, { "Location": "/" });
808
- res.end();
809
- return;
810
- }
830
+ // Not the bridge, so the isRequestAuthed gate above admitted this request.
831
+ if (!projectAccess.canAccess(httpUser ? httpUser.id : null, slug, { authenticated: true })) {
832
+ res.writeHead(302, { "Location": "/" });
833
+ res.end();
834
+ return;
811
835
  }
812
836
  }
813
837
 
@@ -819,6 +843,9 @@ function createServer(opts) {
819
843
 
820
844
  // Attach user info for project HTTP handler
821
845
  req._clagenticUser = getMultiUserFromReq(req);
846
+ // Reaching here means the login gate admitted the request or it is the
847
+ // local MCP bridge: the two proofs an implicit owner may rest on.
848
+ req._clagenticAuthenticated = true;
822
849
 
823
850
  // Try project HTTP handler first (APIs)
824
851
  var origUrl = req.url;
@@ -919,34 +946,33 @@ function createServer(opts) {
919
946
  },
920
947
  });
921
948
 
949
+ // Every outcome of an upgrade answers or destroys the socket: nothing thrown
950
+ // while deciding can leave the client hanging or reach the process.
922
951
  server.on("upgrade", function (req, socket, head) {
923
- // Origin validation (CSRF prevention)
924
- var origin = req.headers.origin;
925
- if (origin) {
926
- try {
927
- var originUrl = new URL(origin);
928
- var originPort = String(originUrl.port || (originUrl.protocol === "https:" ? "443" : "80"));
929
- // Extract port from Host header for reverse proxy support.
930
- // Use URL parser to correctly handle IPv6 addresses (e.g. [::1])
931
- // and infer default port from origin protocol (not backend tlsOptions)
932
- // so TLS-terminating proxies on :443 with HTTP backends work.
933
- var hostPort;
934
- try {
935
- var hostUrl = new URL(originUrl.protocol + "//" + (req.headers.host || ""));
936
- hostPort = String(hostUrl.port || (originUrl.protocol === "https:" ? "443" : "80"));
937
- } catch (e2) {
938
- hostPort = String(portNum);
939
- }
940
- if (originPort !== String(portNum) && originPort !== hostPort) {
941
- socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
942
- socket.destroy();
943
- return;
944
- }
945
- } catch (e) {
946
- socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
947
- socket.destroy();
948
- return;
949
- }
952
+ try {
953
+ handleUpgrade(req, socket, head);
954
+ } catch (err) {
955
+ console.error("[server] WS upgrade failed:", err && err.message ? err.message : err);
956
+ if (socket.writable) socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n");
957
+ socket.destroy();
958
+ }
959
+ });
960
+
961
+ function handleUpgrade(req, socket, head) {
962
+ // Origin validation (CSRF prevention): the full origin, not just its port,
963
+ // must belong to this daemon or be allow-listed. See lib/ws-origin.js for
964
+ // the rules, including the no-Origin case for non-browser clients.
965
+ var originCheck = checkWsOrigin({
966
+ headers: req.headers,
967
+ tls: !!tlsOptions,
968
+ trustedProxy: trustedProxy,
969
+ allowedOrigins: allowedOrigins,
970
+ });
971
+ if (!originCheck.ok) {
972
+ if (debug) console.log("[server] WS rejected: " + originCheck.reason);
973
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
974
+ socket.destroy();
975
+ return;
950
976
  }
951
977
 
952
978
  // Auth (lr-de5fcb): primary path is the relay_auth_user session cookie
@@ -974,6 +1000,13 @@ function createServer(opts) {
974
1000
  wsTicketUser = auth.consumeWsTicket(offeredTicket);
975
1001
  }
976
1002
  var wsAuthedUser = wsCookieUser || wsTicketUser;
1003
+ // The same login gate as the HTTP routes decides who is authenticated. A
1004
+ // request it admits that carries no user record is the implicit owner in
1005
+ // single-user mode (IMPLICIT_OWNER stands in until the connection is bound
1006
+ // below) and nobody in multi-user mode (lib/project-access.js).
1007
+ if (!wsAuthedUser && isRequestAuthed(req) && projectAccess.principalFor(null, { authenticated: true })) {
1008
+ wsAuthedUser = IMPLICIT_OWNER;
1009
+ }
977
1010
 
978
1011
  if (!wsAuthedUser) {
979
1012
  // Observability (DRUMMER-flagged, lr-de5fcb): debug-gated only, never
@@ -1038,21 +1071,16 @@ function createServer(opts) {
1038
1071
  // Attach user info to the WS connection. Reuse wsAuthedUser (resolved
1039
1072
  // above from the cookie or, on mobile, the ticket fallback) rather than
1040
1073
  // re-deriving from the cookie — a ticket-authed request has no cookie.
1041
- var wsUser = wsAuthedUser;
1042
- // Check project access
1043
- if (wsUser && onGetProjectAccess) {
1044
- // For worktree projects, inherit access from parent
1045
- var accessSlug = (wsSlug.indexOf("--") !== -1) ? wsSlug.split("--")[0] : wsSlug;
1046
- var projectAccess = onGetProjectAccess(accessSlug);
1047
- if (debug) console.log("[server] WS access check:", wsSlug, "user:", wsUser.id, "role:", wsUser.role, "visibility:", projectAccess && projectAccess.visibility, "ownerId:", projectAccess && projectAccess.ownerId, "allowed:", projectAccess && projectAccess.allowedUsers);
1048
- if (projectAccess && !projectAccess.error) {
1049
- if (!users.canAccessProject(wsUser.id, projectAccess)) {
1050
- if (debug) console.log("[server] WS rejected: access denied for", wsUser.id, "on", wsSlug);
1051
- socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
1052
- socket.destroy();
1053
- return;
1054
- }
1055
- }
1074
+ var wsUser = wsAuthedUser === IMPLICIT_OWNER ? null : wsAuthedUser;
1075
+ // Check project access. A worktree slug resolves to its parent's access
1076
+ // inside onGetProjectAccess (daemon.js), so no slug is special-cased here.
1077
+ // Past the 401 above this upgrade is authenticated (cookie, ticket or the
1078
+ // login gate), which is the proof an implicit owner needs.
1079
+ if (!projectAccess.canAccess(wsUser ? wsUser.id : null, wsSlug, { authenticated: true })) {
1080
+ if (debug) console.log("[server] WS rejected: access denied for", wsUser ? wsUser.id : "(no user)", "on", wsSlug);
1081
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
1082
+ socket.destroy();
1083
+ return;
1056
1084
  }
1057
1085
 
1058
1086
  wss.handleUpgrade(req, socket, head, function (ws) {
@@ -1090,6 +1118,9 @@ function createServer(opts) {
1090
1118
  return origEmit.apply(ws, arguments);
1091
1119
  };
1092
1120
  ws._clagenticUser = wsUser; // attach user context
1121
+ // The only place a connection is marked authenticated: handleUpgrade
1122
+ // answered 401 above for anything that failed the login check.
1123
+ ws._clagenticAuthenticated = true;
1093
1124
  var remoteAddr = req.socket.remoteAddress || "";
1094
1125
  ws._clagenticLocal = (remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1");
1095
1126
  // lr-20e71c: resolve the real external protocol for THIS connection at
@@ -1111,7 +1142,7 @@ function createServer(opts) {
1111
1142
  }
1112
1143
  ctx.handleConnection(ws, wsUser);
1113
1144
  });
1114
- });
1145
+ }
1115
1146
 
1116
1147
  // --- Cross-project unread tracking ---
1117
1148
  // WeakMap<ws, { "slug::localId": count }> tracks how many done events
@@ -1238,17 +1269,7 @@ function createServer(opts) {
1238
1269
  // Always send per-client to include cross-project unread counts
1239
1270
  projects.forEach(function (ctx, projSlug) {
1240
1271
  ctx.forEachClient(function (ws) {
1241
- var filtered = allProjectsList;
1242
- if (onGetProjectAccess) {
1243
- var wsUser = ws._clagenticUser;
1244
- if (wsUser) {
1245
- filtered = allProjectsList.filter(function (p) {
1246
- var access = onGetProjectAccess(p.slug);
1247
- if (!access || access.error) return true;
1248
- return users.canAccessProject(wsUser.id, access);
1249
- });
1250
- }
1251
- }
1272
+ var filtered = projectAccess.filterProjectList(ws._clagenticUser ? ws._clagenticUser.id : null, allProjectsList, projectAccess.authOf(ws));
1252
1273
  // Attach per-project unread counts for this client. lr-0aa7b6:
1253
1274
  // crossProjectUnread is now keyed per-session ("slug::localId"),
1254
1275
  // not per-project — the Projects-list badge total is a rollup
@@ -1303,18 +1324,15 @@ function createServer(opts) {
1303
1324
  tls: !!tlsOptions,
1304
1325
  historyInMemMax: historyInMemMax,
1305
1326
  getProjectCount: function () { return projects.size; },
1306
- getProjectList: function (userId) {
1307
- var list = [];
1308
- projects.forEach(function (ctx, s) {
1309
- var status = ctx.getStatus();
1310
- if (userId && onGetProjectAccess) {
1311
- var access = onGetProjectAccess(s);
1312
- if (access && !access.error && !users.canAccessProject(userId, access)) return;
1313
- }
1314
- list.push(status);
1315
- });
1316
- return list;
1327
+ // The projects `userId` may see. No user means every project for the
1328
+ // implicit single-user owner and none in multi-user mode.
1329
+ getProjectList: function (userId, proof) {
1330
+ return projectAccess.filterProjectList(userId, getProjects(), proof);
1317
1331
  },
1332
+ canAccessProject: function (userId, projSlug, proof) {
1333
+ return projectAccess.canAccess(userId, projSlug, proof);
1334
+ },
1335
+ projectAccess: projectAccess,
1318
1336
  // includeSelf: when true, the calling project's own sessions are included
1319
1337
  // in the uniform pass (so callers need not special-case self). The Hub
1320
1338
  // recent-sessions list uses this to gather every project identically —
@@ -1329,13 +1347,9 @@ function createServer(opts) {
1329
1347
  // enforce per-project access or private-session visibility, leaking
1330
1348
  // cross-project and private sessions into the Home Hub recent-sessions
1331
1349
  // list. Fails CLOSED: no userId (or no onGetProjectAccess wiring) means
1332
- // no sessions are returned. There is no legitimate no-auth caller of
1333
- // this function -- the WS upgrade handler above rejects any connection
1334
- // without an authenticated user (wsAuthedUser) with 401 before
1335
- // ws._clagenticUser can ever be set, including in single-user/PIN mode
1336
- // (still a real authenticated user, just one account) -- so failing
1337
- // closed here never breaks a real deployment mode.
1338
- getAllProjectSessions: function (includeSelf, userId) {
1350
+ // no sessions are returned, except for the implicit single-user owner
1351
+ // (no user record, mode decided in lib/project-access.js).
1352
+ getAllProjectSessions: function (includeSelf, userId, proof) {
1339
1353
  return computeAllProjectSessions({
1340
1354
  projects: projects,
1341
1355
  users: users,
@@ -1343,11 +1357,15 @@ function createServer(opts) {
1343
1357
  callerSlug: slug,
1344
1358
  includeSelf: includeSelf,
1345
1359
  userId: userId,
1360
+ implicitOwner: !userId && !!projectAccess.principalFor(null, proof),
1346
1361
  });
1347
1362
  },
1348
- getHubSchedules: function () {
1363
+ // Schedules of the projects `userId` may see; no user and no proof of
1364
+ // login, no schedules.
1365
+ getHubSchedules: function (userId, proof) {
1349
1366
  var allSchedules = [];
1350
1367
  projects.forEach(function (ctx, s) {
1368
+ if (!projectAccess.canAccess(userId, s, proof)) return;
1351
1369
  var status = ctx.getStatus();
1352
1370
  var recs = ctx.getSchedules();
1353
1371
  for (var i = 0; i < recs.length; i++) {
@@ -1457,15 +1475,23 @@ function createServer(opts) {
1457
1475
  onGetProjectMcpServers: onGetProjectMcpServers,
1458
1476
  onSetProjectMcpServers: onSetProjectMcpServers,
1459
1477
  onGetDaemonConfig: onGetDaemonConfig,
1478
+ onGetProjectEnv: onGetProjectEnv,
1479
+ onSetProjectEnv: onSetProjectEnv,
1480
+ onGetSharedEnv: onGetSharedEnv,
1481
+ onSetSharedEnv: onSetSharedEnv,
1460
1482
  onSetPin: onSetPin,
1461
1483
  onSetKeepAwake: onSetKeepAwake,
1462
1484
  onSetImageRetention: onSetImageRetention,
1463
1485
  onSetMemAvailableThreshold: onSetMemAvailableThreshold,
1486
+ onSetTokensPerMbHeadroom: onSetTokensPerMbHeadroom,
1487
+ onSetAutoContinue: onSetAutoContinue,
1464
1488
  onSetLiteAutoEnroll: onSetLiteAutoEnroll,
1465
1489
  onSetUpdateChannel: onSetUpdateChannel,
1466
1490
  updateChannel: onGetDaemonConfig ? (onGetDaemonConfig().updateChannel || "stable") : "stable",
1467
1491
  onShutdown: onShutdown,
1468
1492
  onRestart: onRestart,
1493
+ onRestartForBuildUpdate: onRestartForBuildUpdate,
1494
+ onGetBuildUpdateDiagnostic: onGetBuildUpdateDiagnostic,
1469
1495
  onDmMessage: handleDmMessage,
1470
1496
  broadcastAll: broadcastAll,
1471
1497
  notificationsModule: _globalNotifications,
@@ -1501,7 +1527,8 @@ function createServer(opts) {
1501
1527
  function removeProject(slug) {
1502
1528
  var ctx = projects.get(slug);
1503
1529
  if (!ctx) return false;
1504
- var shutdownResult = ctx.destroy();
1530
+ // A deliberate removal: its sessions are not recorded as resumable.
1531
+ var shutdownResult = ctx.destroy({ reason: "project_removed" });
1505
1532
  projects.delete(slug);
1506
1533
  if (shutdownResult && typeof shutdownResult.catch === "function") {
1507
1534
  shutdownResult.catch(function(err) {
@@ -1624,21 +1651,14 @@ function createServer(opts) {
1624
1651
  projects.forEach(function (ctx) {
1625
1652
  ctx.forEachClient(function (ws) {
1626
1653
  var userId = ws._clagenticUser ? ws._clagenticUser.id : null;
1627
- var key = userId || "__anon__";
1654
+ var wsProof = projectAccess.authOf(ws);
1655
+ var key = userId || (wsProof.authenticated ? "__anon__" : "__unproven__");
1628
1656
  if (sentUsers[key]) {
1629
1657
  // Already computed for this user, just send the cached msg
1630
1658
  ws.send(sentUsers[key]);
1631
1659
  return;
1632
1660
  }
1633
- var filteredProjects = [];
1634
- projects.forEach(function (pCtx, s) {
1635
- var status = pCtx.getStatus();
1636
- if (userId && onGetProjectAccess) {
1637
- var access = onGetProjectAccess(s);
1638
- if (access && !access.error && !users.canAccessProject(userId, access)) return;
1639
- }
1640
- filteredProjects.push(status);
1641
- });
1661
+ var filteredProjects = projectAccess.filterProjectList(userId, getProjects(), wsProof);
1642
1662
  // Per-user DM data
1643
1663
  var userDmFavorites = userId ? users.getDmFavorites(userId) : [];
1644
1664
  var userDmHidden = userId ? users.getDmHidden(userId) : [];
@@ -1669,7 +1689,23 @@ function createServer(opts) {
1669
1689
  }, 300);
1670
1690
  }
1671
1691
 
1692
+ // A project list is never sent as one shared message: every client gets
1693
+ // the entries its user may see, whichever call site asked for the broadcast.
1694
+ function broadcastProjectsUpdated(msg) {
1695
+ projects.forEach(function (ctx) {
1696
+ ctx.forEachClient(function (ws) {
1697
+ if (ws.readyState !== 1) return;
1698
+ var visible = projectAccess.filterProjectList(ws._clagenticUser ? ws._clagenticUser.id : null, msg.projects, projectAccess.authOf(ws));
1699
+ ws.send(JSON.stringify(Object.assign({}, msg, { projects: visible, projectCount: visible.length })));
1700
+ });
1701
+ });
1702
+ }
1703
+
1672
1704
  function broadcastAll(msg) {
1705
+ if (msg && msg.type === "projects_updated" && Array.isArray(msg.projects)) {
1706
+ broadcastProjectsUpdated(msg);
1707
+ return;
1708
+ }
1673
1709
  projects.forEach(function (ctx) {
1674
1710
  ctx.send(msg);
1675
1711
  });
@@ -1716,9 +1752,10 @@ function createServer(opts) {
1716
1752
  function destroyAll() {
1717
1753
  _externalTrigger.stopWatcher();
1718
1754
  var shutdowns = [];
1755
+ var tally = sessionReclaim.createShutdownTally();
1719
1756
  projects.forEach(function (ctx, slug) {
1720
1757
  console.log("[server] Destroying project:", slug);
1721
- var result = ctx.destroy();
1758
+ var result = ctx.destroy({ reason: sessionReclaim.RESTART_REASON, tally: tally });
1722
1759
  if (result && typeof result.then === "function") {
1723
1760
  shutdowns.push(result.catch(function(err) {
1724
1761
  console.error("[server] Project destroy failed for " + slug + ":", err && err.message ? err.message : err);
@@ -1727,6 +1764,7 @@ function createServer(opts) {
1727
1764
  }
1728
1765
  });
1729
1766
  projects.clear();
1767
+ sessionReclaim.logShutdownSummary(tally);
1730
1768
  return Promise.all(shutdowns);
1731
1769
  }
1732
1770
 
@@ -1775,7 +1813,9 @@ function createServer(opts) {
1775
1813
  }
1776
1814
  }
1777
1815
  cleanupOldImages();
1778
- setInterval(cleanupOldImages, 24 * 60 * 60 * 1000);
1816
+ // unref: the HTTP server keeps the daemon alive; this timer must not keep a
1817
+ // process alive that has closed its server (tests, shutdown).
1818
+ setInterval(cleanupOldImages, 24 * 60 * 60 * 1000).unref();
1779
1819
 
1780
1820
  return {
1781
1821
  server: server,
@@ -1794,6 +1834,7 @@ function createServer(opts) {
1794
1834
  clearRecovery: auth.clearRecovery,
1795
1835
  broadcastAll: broadcastAll,
1796
1836
  forEachProject: forEachProject,
1837
+ sessionInput: _sessionInput,
1797
1838
  destroyProject: removeProject,
1798
1839
  destroyAll: destroyAll,
1799
1840
  // Drain controller injection (lr-6b30).