@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
package/lib/server.js CHANGED
@@ -20,6 +20,8 @@ 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");
23
25
 
24
26
  var https = require("https");
25
27
  var pkg = require("../package.json");
@@ -75,8 +77,8 @@ function serveStatic(urlPath, res) {
75
77
  var appVersion = pkg.version;
76
78
  // Replace the static cache name with a version-stamped one
77
79
  swContent = swContent.replace(
78
- /var CACHE_NAME = "clagentic-offline-[^"]*"/,
79
- 'var CACHE_NAME = "clagentic-offline-v' + appVersion + '"'
80
+ /var CACHE_NAME = "clagentic-console-offline-[^"]*"/,
81
+ 'var CACHE_NAME = "clagentic-console-offline-v' + appVersion + '"'
80
82
  );
81
83
  res.writeHead(200, {
82
84
  "Content-Type": "application/javascript; charset=utf-8",
@@ -129,6 +131,10 @@ function extractSlug(urlPath) {
129
131
  // Sec-WebSocket-Protocol list; this extracts the raw ticket back out.
130
132
  var WS_TICKET_SUBPROTOCOL_PREFIX = "clagentic.auth.";
131
133
 
134
+ // Stands for the single-user owner while a WebSocket upgrade is decided: the
135
+ // login gate admitted the request and there is no user record to attach.
136
+ var IMPLICIT_OWNER = Object.freeze({});
137
+
132
138
  /**
133
139
  * Extract a ws-ticket (lr-de5fcb) from a raw Sec-WebSocket-Protocol header
134
140
  * value. Returns null if the header is absent or carries no ticket-shaped
@@ -231,6 +237,9 @@ function createServer(opts) {
231
237
  // lr-20e71c: operator-declared trust boundary for reading X-Forwarded-Proto
232
238
  // from a reverse proxy. See lib/effective-protocol.js.
233
239
  var trustedProxy = !!opts.trustedProxy;
240
+ // Operator-configured origins (daemon.json allowedOrigins) that may open a
241
+ // WebSocket in addition to the daemon's own host; see lib/ws-origin.js.
242
+ var allowedOrigins = Array.isArray(opts.allowedOrigins) ? opts.allowedOrigins : [];
234
243
  // lr-2ea2a7: daemon.json knob overriding the in-heap session-history tail cap.
235
244
  var historyInMemMax = opts.historyInMemMax;
236
245
  var onAddProject = opts.onAddProject || null;
@@ -266,13 +275,20 @@ function createServer(opts) {
266
275
  var onGetProjectMcpServers = opts.onGetProjectMcpServers || null;
267
276
  var onSetProjectMcpServers = opts.onSetProjectMcpServers || null;
268
277
  var onGetDaemonConfig = opts.onGetDaemonConfig || null;
278
+ var onGetProjectEnv = opts.onGetProjectEnv || null;
279
+ var onSetProjectEnv = opts.onSetProjectEnv || null;
280
+ var onGetSharedEnv = opts.onGetSharedEnv || null;
281
+ var onSetSharedEnv = opts.onSetSharedEnv || null;
269
282
  var onSetPin = opts.onSetPin || null;
270
283
  var onSetKeepAwake = opts.onSetKeepAwake || null;
271
284
  var onSetImageRetention = opts.onSetImageRetention || null;
272
285
  var onSetMemAvailableThreshold = opts.onSetMemAvailableThreshold || null;
286
+ var onSetTokensPerMbHeadroom = opts.onSetTokensPerMbHeadroom || null;
287
+ var onSetAutoContinue = opts.onSetAutoContinue || null;
273
288
  var onSetLiteAutoEnroll = opts.onSetLiteAutoEnroll || null;
274
289
  var onShutdown = opts.onShutdown || null;
275
290
  var onRestart = opts.onRestart || null;
291
+ var onRestartForBuildUpdate = opts.onRestartForBuildUpdate || null;
276
292
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
277
293
  var onSetProjectVisibility = opts.onSetProjectVisibility || null;
278
294
  var onSetProjectAllowedUsers = opts.onSetProjectAllowedUsers || null;
@@ -282,6 +298,16 @@ function createServer(opts) {
282
298
  var onUserDeleted = opts.onUserDeleted || null;
283
299
  var getRemovedProjects = opts.getRemovedProjects || function () { return []; };
284
300
 
301
+ // The one answer to "who is this and may they use that project": every
302
+ // check below goes through it. "No user" is decided by the daemon's mode
303
+ // (the single-user owner is implicit, a missing user in multi-user mode is
304
+ // a stranger), and a lookup that cannot be completed is a refusal.
305
+ var projectAccess = createProjectAccess({
306
+ users: users,
307
+ onGetProjectAccess: onGetProjectAccess,
308
+ isMultiUser: typeof opts.isMultiUser === "function" ? opts.isMultiUser : users.isMultiUser,
309
+ });
310
+
285
311
  // --- Auth module ---
286
312
  var auth = serverAuth.attachAuth({
287
313
  users: users,
@@ -342,7 +368,8 @@ function createServer(opts) {
342
368
  users: users,
343
369
  projects: projects,
344
370
  getMultiUserFromReq: getMultiUserFromReq,
345
- onGetProjectAccess: onGetProjectAccess,
371
+ isRequestAuthed: isRequestAuthed,
372
+ projectAccess: projectAccess,
346
373
  });
347
374
 
348
375
  // --- Push module (global) ---
@@ -645,28 +672,17 @@ function createServer(opts) {
645
672
  var reqUser = getMultiUserFromReq(req);
646
673
  // Check for last-visited project cookie
647
674
  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
- }
675
+ var reqUserId = reqUser ? reqUser.id : null;
676
+ // isRequestAuthed(req) passed above: that is the proof an implicit owner needs.
677
+ var rootProof = { authenticated: true };
678
+ if (lastProject && projects.has(lastProject) && projectAccess.canAccess(reqUserId, lastProject, rootProof)) {
679
+ targetSlug = lastProject;
657
680
  }
658
681
  // Fall back to first accessible project
659
682
  if (!targetSlug) {
660
683
  projects.forEach(function (ctx, s) {
661
684
  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
- }
685
+ if (projectAccess.canAccess(reqUserId, s, rootProof)) targetSlug = s;
670
686
  });
671
687
  }
672
688
  if (targetSlug) {
@@ -798,16 +814,16 @@ function createServer(opts) {
798
814
  }).protocol;
799
815
  res.setHeader("Set-Cookie", "clagentic_last_project=" + slug + "; Path=/; SameSite=Strict; Max-Age=31536000" + (cookieEffectiveProtocol === "https" ? "; Secure" : ""));
800
816
 
801
- // Check project access for HTTP requests
802
- if (onGetProjectAccess) {
817
+ // Check project access for HTTP requests. The local MCP bridge carries no
818
+ // login (it is a child process of the daemon's own host); every other
819
+ // request must belong to a user who may use this project.
820
+ if (!isMcpBridgeLocal) {
803
821
  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
- }
822
+ // Not the bridge, so the isRequestAuthed gate above admitted this request.
823
+ if (!projectAccess.canAccess(httpUser ? httpUser.id : null, slug, { authenticated: true })) {
824
+ res.writeHead(302, { "Location": "/" });
825
+ res.end();
826
+ return;
811
827
  }
812
828
  }
813
829
 
@@ -819,6 +835,9 @@ function createServer(opts) {
819
835
 
820
836
  // Attach user info for project HTTP handler
821
837
  req._clagenticUser = getMultiUserFromReq(req);
838
+ // Reaching here means the login gate admitted the request or it is the
839
+ // local MCP bridge: the two proofs an implicit owner may rest on.
840
+ req._clagenticAuthenticated = true;
822
841
 
823
842
  // Try project HTTP handler first (APIs)
824
843
  var origUrl = req.url;
@@ -919,34 +938,33 @@ function createServer(opts) {
919
938
  },
920
939
  });
921
940
 
941
+ // Every outcome of an upgrade answers or destroys the socket: nothing thrown
942
+ // while deciding can leave the client hanging or reach the process.
922
943
  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
- }
944
+ try {
945
+ handleUpgrade(req, socket, head);
946
+ } catch (err) {
947
+ console.error("[server] WS upgrade failed:", err && err.message ? err.message : err);
948
+ if (socket.writable) socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n");
949
+ socket.destroy();
950
+ }
951
+ });
952
+
953
+ function handleUpgrade(req, socket, head) {
954
+ // Origin validation (CSRF prevention): the full origin, not just its port,
955
+ // must belong to this daemon or be allow-listed. See lib/ws-origin.js for
956
+ // the rules, including the no-Origin case for non-browser clients.
957
+ var originCheck = checkWsOrigin({
958
+ headers: req.headers,
959
+ tls: !!tlsOptions,
960
+ trustedProxy: trustedProxy,
961
+ allowedOrigins: allowedOrigins,
962
+ });
963
+ if (!originCheck.ok) {
964
+ if (debug) console.log("[server] WS rejected: " + originCheck.reason);
965
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
966
+ socket.destroy();
967
+ return;
950
968
  }
951
969
 
952
970
  // Auth (lr-de5fcb): primary path is the relay_auth_user session cookie
@@ -974,6 +992,13 @@ function createServer(opts) {
974
992
  wsTicketUser = auth.consumeWsTicket(offeredTicket);
975
993
  }
976
994
  var wsAuthedUser = wsCookieUser || wsTicketUser;
995
+ // The same login gate as the HTTP routes decides who is authenticated. A
996
+ // request it admits that carries no user record is the implicit owner in
997
+ // single-user mode (IMPLICIT_OWNER stands in until the connection is bound
998
+ // below) and nobody in multi-user mode (lib/project-access.js).
999
+ if (!wsAuthedUser && isRequestAuthed(req) && projectAccess.principalFor(null, { authenticated: true })) {
1000
+ wsAuthedUser = IMPLICIT_OWNER;
1001
+ }
977
1002
 
978
1003
  if (!wsAuthedUser) {
979
1004
  // Observability (DRUMMER-flagged, lr-de5fcb): debug-gated only, never
@@ -1038,21 +1063,16 @@ function createServer(opts) {
1038
1063
  // Attach user info to the WS connection. Reuse wsAuthedUser (resolved
1039
1064
  // above from the cookie or, on mobile, the ticket fallback) rather than
1040
1065
  // 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
- }
1066
+ var wsUser = wsAuthedUser === IMPLICIT_OWNER ? null : wsAuthedUser;
1067
+ // Check project access. A worktree slug resolves to its parent's access
1068
+ // inside onGetProjectAccess (daemon.js), so no slug is special-cased here.
1069
+ // Past the 401 above this upgrade is authenticated (cookie, ticket or the
1070
+ // login gate), which is the proof an implicit owner needs.
1071
+ if (!projectAccess.canAccess(wsUser ? wsUser.id : null, wsSlug, { authenticated: true })) {
1072
+ if (debug) console.log("[server] WS rejected: access denied for", wsUser ? wsUser.id : "(no user)", "on", wsSlug);
1073
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
1074
+ socket.destroy();
1075
+ return;
1056
1076
  }
1057
1077
 
1058
1078
  wss.handleUpgrade(req, socket, head, function (ws) {
@@ -1090,6 +1110,9 @@ function createServer(opts) {
1090
1110
  return origEmit.apply(ws, arguments);
1091
1111
  };
1092
1112
  ws._clagenticUser = wsUser; // attach user context
1113
+ // The only place a connection is marked authenticated: handleUpgrade
1114
+ // answered 401 above for anything that failed the login check.
1115
+ ws._clagenticAuthenticated = true;
1093
1116
  var remoteAddr = req.socket.remoteAddress || "";
1094
1117
  ws._clagenticLocal = (remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1");
1095
1118
  // lr-20e71c: resolve the real external protocol for THIS connection at
@@ -1111,7 +1134,7 @@ function createServer(opts) {
1111
1134
  }
1112
1135
  ctx.handleConnection(ws, wsUser);
1113
1136
  });
1114
- });
1137
+ }
1115
1138
 
1116
1139
  // --- Cross-project unread tracking ---
1117
1140
  // WeakMap<ws, { "slug::localId": count }> tracks how many done events
@@ -1238,17 +1261,7 @@ function createServer(opts) {
1238
1261
  // Always send per-client to include cross-project unread counts
1239
1262
  projects.forEach(function (ctx, projSlug) {
1240
1263
  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
- }
1264
+ var filtered = projectAccess.filterProjectList(ws._clagenticUser ? ws._clagenticUser.id : null, allProjectsList, projectAccess.authOf(ws));
1252
1265
  // Attach per-project unread counts for this client. lr-0aa7b6:
1253
1266
  // crossProjectUnread is now keyed per-session ("slug::localId"),
1254
1267
  // not per-project — the Projects-list badge total is a rollup
@@ -1303,18 +1316,15 @@ function createServer(opts) {
1303
1316
  tls: !!tlsOptions,
1304
1317
  historyInMemMax: historyInMemMax,
1305
1318
  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;
1319
+ // The projects `userId` may see. No user means every project for the
1320
+ // implicit single-user owner and none in multi-user mode.
1321
+ getProjectList: function (userId, proof) {
1322
+ return projectAccess.filterProjectList(userId, getProjects(), proof);
1323
+ },
1324
+ canAccessProject: function (userId, projSlug, proof) {
1325
+ return projectAccess.canAccess(userId, projSlug, proof);
1317
1326
  },
1327
+ projectAccess: projectAccess,
1318
1328
  // includeSelf: when true, the calling project's own sessions are included
1319
1329
  // in the uniform pass (so callers need not special-case self). The Hub
1320
1330
  // recent-sessions list uses this to gather every project identically —
@@ -1329,13 +1339,9 @@ function createServer(opts) {
1329
1339
  // enforce per-project access or private-session visibility, leaking
1330
1340
  // cross-project and private sessions into the Home Hub recent-sessions
1331
1341
  // 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) {
1342
+ // no sessions are returned, except for the implicit single-user owner
1343
+ // (no user record, mode decided in lib/project-access.js).
1344
+ getAllProjectSessions: function (includeSelf, userId, proof) {
1339
1345
  return computeAllProjectSessions({
1340
1346
  projects: projects,
1341
1347
  users: users,
@@ -1343,11 +1349,15 @@ function createServer(opts) {
1343
1349
  callerSlug: slug,
1344
1350
  includeSelf: includeSelf,
1345
1351
  userId: userId,
1352
+ implicitOwner: !userId && !!projectAccess.principalFor(null, proof),
1346
1353
  });
1347
1354
  },
1348
- getHubSchedules: function () {
1355
+ // Schedules of the projects `userId` may see; no user and no proof of
1356
+ // login, no schedules.
1357
+ getHubSchedules: function (userId, proof) {
1349
1358
  var allSchedules = [];
1350
1359
  projects.forEach(function (ctx, s) {
1360
+ if (!projectAccess.canAccess(userId, s, proof)) return;
1351
1361
  var status = ctx.getStatus();
1352
1362
  var recs = ctx.getSchedules();
1353
1363
  for (var i = 0; i < recs.length; i++) {
@@ -1457,15 +1467,22 @@ function createServer(opts) {
1457
1467
  onGetProjectMcpServers: onGetProjectMcpServers,
1458
1468
  onSetProjectMcpServers: onSetProjectMcpServers,
1459
1469
  onGetDaemonConfig: onGetDaemonConfig,
1470
+ onGetProjectEnv: onGetProjectEnv,
1471
+ onSetProjectEnv: onSetProjectEnv,
1472
+ onGetSharedEnv: onGetSharedEnv,
1473
+ onSetSharedEnv: onSetSharedEnv,
1460
1474
  onSetPin: onSetPin,
1461
1475
  onSetKeepAwake: onSetKeepAwake,
1462
1476
  onSetImageRetention: onSetImageRetention,
1463
1477
  onSetMemAvailableThreshold: onSetMemAvailableThreshold,
1478
+ onSetTokensPerMbHeadroom: onSetTokensPerMbHeadroom,
1479
+ onSetAutoContinue: onSetAutoContinue,
1464
1480
  onSetLiteAutoEnroll: onSetLiteAutoEnroll,
1465
1481
  onSetUpdateChannel: onSetUpdateChannel,
1466
1482
  updateChannel: onGetDaemonConfig ? (onGetDaemonConfig().updateChannel || "stable") : "stable",
1467
1483
  onShutdown: onShutdown,
1468
1484
  onRestart: onRestart,
1485
+ onRestartForBuildUpdate: onRestartForBuildUpdate,
1469
1486
  onDmMessage: handleDmMessage,
1470
1487
  broadcastAll: broadcastAll,
1471
1488
  notificationsModule: _globalNotifications,
@@ -1624,21 +1641,14 @@ function createServer(opts) {
1624
1641
  projects.forEach(function (ctx) {
1625
1642
  ctx.forEachClient(function (ws) {
1626
1643
  var userId = ws._clagenticUser ? ws._clagenticUser.id : null;
1627
- var key = userId || "__anon__";
1644
+ var wsProof = projectAccess.authOf(ws);
1645
+ var key = userId || (wsProof.authenticated ? "__anon__" : "__unproven__");
1628
1646
  if (sentUsers[key]) {
1629
1647
  // Already computed for this user, just send the cached msg
1630
1648
  ws.send(sentUsers[key]);
1631
1649
  return;
1632
1650
  }
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
- });
1651
+ var filteredProjects = projectAccess.filterProjectList(userId, getProjects(), wsProof);
1642
1652
  // Per-user DM data
1643
1653
  var userDmFavorites = userId ? users.getDmFavorites(userId) : [];
1644
1654
  var userDmHidden = userId ? users.getDmHidden(userId) : [];
@@ -1669,7 +1679,23 @@ function createServer(opts) {
1669
1679
  }, 300);
1670
1680
  }
1671
1681
 
1682
+ // A project list is never sent as one shared message: every client gets
1683
+ // the entries its user may see, whichever call site asked for the broadcast.
1684
+ function broadcastProjectsUpdated(msg) {
1685
+ projects.forEach(function (ctx) {
1686
+ ctx.forEachClient(function (ws) {
1687
+ if (ws.readyState !== 1) return;
1688
+ var visible = projectAccess.filterProjectList(ws._clagenticUser ? ws._clagenticUser.id : null, msg.projects, projectAccess.authOf(ws));
1689
+ ws.send(JSON.stringify(Object.assign({}, msg, { projects: visible, projectCount: visible.length })));
1690
+ });
1691
+ });
1692
+ }
1693
+
1672
1694
  function broadcastAll(msg) {
1695
+ if (msg && msg.type === "projects_updated" && Array.isArray(msg.projects)) {
1696
+ broadcastProjectsUpdated(msg);
1697
+ return;
1698
+ }
1673
1699
  projects.forEach(function (ctx) {
1674
1700
  ctx.send(msg);
1675
1701
  });
@@ -1775,7 +1801,9 @@ function createServer(opts) {
1775
1801
  }
1776
1802
  }
1777
1803
  cleanupOldImages();
1778
- setInterval(cleanupOldImages, 24 * 60 * 60 * 1000);
1804
+ // unref: the HTTP server keeps the daemon alive; this timer must not keep a
1805
+ // process alive that has closed its server (tests, shutdown).
1806
+ setInterval(cleanupOldImages, 24 * 60 * 60 * 1000).unref();
1779
1807
 
1780
1808
  return {
1781
1809
  server: server,
@@ -0,0 +1,96 @@
1
+ // service-install.js — pure helpers for scripts/postinstall.js (systemd unit
2
+ // install). Kept free of side effects so each decision can be tested without
3
+ // touching /etc/systemd or /usr/local/bin.
4
+
5
+ var path = require("path");
6
+
7
+ var BIN_NAME = "clagentic-console";
8
+ var LEGACY_WRAPPER_PATH = "/usr/local/bin/clagentic-daemon.sh";
9
+
10
+ // Exact text of the hand-placed wrapper that earlier releases told operators to
11
+ // create. It is removed only when the file matches this byte for byte (modulo
12
+ // line endings and trailing whitespace); an operator-modified copy is theirs.
13
+ var LEGACY_WRAPPER_CONTENT = [
14
+ "#!/bin/bash",
15
+ "# Run Clagentic Console daemon directly so systemd can track the process",
16
+ "# Prefer global npm install, fall back to npx cache",
17
+ "",
18
+ "# Safety: refuse to start if a workspace symlink exists at the unscoped package name.",
19
+ "# npm link / npm install -g <workspace-path> creates exactly this trap — workspace edits",
20
+ "# become live in the daemon without going through pack/install. If this fires, remove the",
21
+ "# symlink with: rm /usr/lib/node_modules/clagentic-console",
22
+ "SYMLINK_TRAP=\"/usr/lib/node_modules/clagentic-console\"",
23
+ "if [ -L \"$SYMLINK_TRAP\" ]; then",
24
+ " echo \"ERROR: $SYMLINK_TRAP is a symlink (npm link trap). Remove it before starting:\" >&2",
25
+ " echo \" rm $SYMLINK_TRAP\" >&2",
26
+ " echo \"Then reinstall via: npm pack --pack-destination /tmp/ && npm install -g /tmp/clagentic-console-*.tgz\" >&2",
27
+ " exit 1",
28
+ "fi",
29
+ "",
30
+ "DAEMON_LIB=\"/usr/lib/node_modules/@clagentic/console/lib/daemon.js\"",
31
+ "if [ ! -f \"$DAEMON_LIB\" ]; then",
32
+ " DAEMON_LIB=$(node -e \"console.log(require.resolve('@clagentic/console/lib/daemon'))\" 2>/dev/null || \\",
33
+ " ls /root/.npm/_npx/*/node_modules/@clagentic/console/lib/daemon.js 2>/dev/null | tail -1)",
34
+ "fi",
35
+ "exec /usr/bin/node \"$DAEMON_LIB\"",
36
+ ].join("\n");
37
+
38
+ function normalize(text) {
39
+ return String(text).replace(/\r\n/g, "\n").split("\n").map(function (l) { return l.replace(/[ \t]+$/, ""); }).join("\n").replace(/\n+$/, "");
40
+ }
41
+
42
+ function isLegacyWrapperContent(content) {
43
+ return normalize(content) === normalize(LEGACY_WRAPPER_CONTENT);
44
+ }
45
+
46
+ /**
47
+ * npm exposes its config to lifecycle scripts as npm_config_* variables.
48
+ * `npm install -g` sets npm_config_global=true (and npm_config_location=global
49
+ * on npm 8+); a local `npm ci` / `npm install` sets neither.
50
+ */
51
+ function isGlobalInstall(env) {
52
+ return env.npm_config_global === "true" || env.npm_config_location === "global";
53
+ }
54
+
55
+ /**
56
+ * Absolute path of the globally installed bin symlink, or null when it cannot
57
+ * be determined. Prefers npm's own prefix; otherwise derives it from the
58
+ * package location <prefix>/lib/node_modules/@clagentic/console.
59
+ */
60
+ function resolveCliBin(opts) {
61
+ var prefix = opts.env.npm_config_prefix;
62
+ if (!prefix || !path.isAbsolute(prefix)) {
63
+ var scopeDir = path.dirname(opts.pkgDir);
64
+ if (path.basename(scopeDir) !== "@clagentic") return null;
65
+ var modulesDir = path.dirname(scopeDir);
66
+ if (path.basename(modulesDir) !== "node_modules") return null;
67
+ prefix = path.dirname(path.dirname(modulesDir));
68
+ }
69
+ return path.join(prefix, "bin", BIN_NAME);
70
+ }
71
+
72
+ var BIN_PLACEHOLDER = "@CLAGENTIC_CONSOLE_BIN@";
73
+ var BIN_DIR_PLACEHOLDER = "@CLAGENTIC_CONSOLE_BIN_DIR@";
74
+
75
+ /**
76
+ * Fill the shipped unit template. Throws if a placeholder is left behind, so a
77
+ * half-rendered unit is never written to /etc/systemd.
78
+ */
79
+ function renderUnit(template, cliBin) {
80
+ var out = template
81
+ .split(BIN_PLACEHOLDER).join(cliBin)
82
+ .split(BIN_DIR_PLACEHOLDER).join(path.dirname(cliBin));
83
+ var left = out.match(/@CLAGENTIC_CONSOLE_[A-Z_]+@/);
84
+ if (left) throw new Error("unit template has unfilled placeholder " + left[0]);
85
+ return out;
86
+ }
87
+
88
+ module.exports = {
89
+ BIN_NAME: BIN_NAME,
90
+ LEGACY_WRAPPER_PATH: LEGACY_WRAPPER_PATH,
91
+ LEGACY_WRAPPER_CONTENT: LEGACY_WRAPPER_CONTENT,
92
+ isLegacyWrapperContent: isLegacyWrapperContent,
93
+ isGlobalInstall: isGlobalInstall,
94
+ resolveCliBin: resolveCliBin,
95
+ renderUnit: renderUnit,
96
+ };
@@ -0,0 +1,76 @@
1
+ // session-capabilities.js - what each agent can do in this project right now,
2
+ // kept on the session manager as sm.capabilitiesByVendor.
3
+ //
4
+ // The value is always a RESOLVED set (yoke/capabilities.js): the agent's
5
+ // declaration, overlaid by a connection, narrowed by what its live session
6
+ // advertised. Every session-facing runtime decision reads it through
7
+ // capabilitiesFor and nothing else, so no site can act on a declaration the live
8
+ // agent has already withdrawn. Declarations enter only here, through
9
+ // resolveCapabilities, never read directly.
10
+
11
+ var yoke = require("./yoke");
12
+
13
+ /**
14
+ * The vendor a session's decisions are made for: the session's own, else the
15
+ * adapter that serves it, else the project default.
16
+ * @param {object} sm
17
+ * @param {?{vendor: ?string}} session
18
+ * @param {?string} [adapterVendor]
19
+ * @returns {?string}
20
+ */
21
+ function effectiveVendorId(sm, session, adapterVendor) {
22
+ return (session && session.vendor) || adapterVendor || (sm && sm.defaultVendor) || null;
23
+ }
24
+
25
+ /**
26
+ * The resolved capabilities recorded for a vendor, as a copy. A vendor with
27
+ * nothing recorded (or not registered) has none: every flag off, every list
28
+ * empty, so a control gated on it stays disabled and a guard fails closed.
29
+ * @param {object} sm
30
+ * @param {?string} vendorId
31
+ * @returns {object} every ledger key
32
+ */
33
+ function capabilitiesFor(sm, vendorId) {
34
+ var recorded = sm && sm.capabilitiesByVendor;
35
+ var has = typeof vendorId === "string" && recorded
36
+ && Object.prototype.hasOwnProperty.call(recorded, vendorId);
37
+ return yoke.completeCapabilities(has ? recorded[vendorId] : {});
38
+ }
39
+
40
+ /**
41
+ * Records the resolved capabilities of one vendor from what its live session
42
+ * advertised (the capabilities member of init()'s result; none when the
43
+ * adapter reported none).
44
+ * @param {object} sm
45
+ * @param {string} vendorId
46
+ * @param {?object} advertised
47
+ * @returns {object} what was recorded
48
+ */
49
+ function recordCapabilities(sm, vendorId, advertised) {
50
+ sm.capabilitiesByVendor = sm.capabilitiesByVendor || {};
51
+ var resolved = yoke.registry.isKnown(vendorId)
52
+ ? yoke.resolveCapabilities(yoke.registry.get(vendorId), null, advertised || null)
53
+ : (advertised || {});
54
+ sm.capabilitiesByVendor[vendorId] = resolved;
55
+ return resolved;
56
+ }
57
+
58
+ /**
59
+ * Gives every registered vendor an entry before any session has reported, so a
60
+ * session on a vendor other than the project default is gated on what its own
61
+ * agent can do. An entry already recorded from a live session is kept.
62
+ * @param {object} sm
63
+ */
64
+ function seedCapabilities(sm) {
65
+ sm.capabilitiesByVendor = sm.capabilitiesByVendor || {};
66
+ yoke.registry.list().forEach(function (vendor) {
67
+ if (!sm.capabilitiesByVendor[vendor.id]) recordCapabilities(sm, vendor.id, null);
68
+ });
69
+ }
70
+
71
+ module.exports = {
72
+ effectiveVendorId: effectiveVendorId,
73
+ capabilitiesFor: capabilitiesFor,
74
+ recordCapabilities: recordCapabilities,
75
+ seedCapabilities: seedCapabilities,
76
+ };