@clagentic/console 1.9.0-beta.3 → 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
@@ -0,0 +1,179 @@
1
+ // mcp-tool-schema.js - turns an in-process MCP tool's input schema into the
2
+ // JSON schema handed to a worker process or to the Codex bridge, and reports
3
+ // the tools that cannot be converted instead of publishing them with no
4
+ // parameters. A tool the model sees with an empty schema is called with
5
+ // guessed arguments, and nothing says why; skipping it and naming the cause
6
+ // is the one outcome the operator can act on.
7
+
8
+ var MCP_DIAGNOSTIC_SOURCE = "mcp";
9
+
10
+ /**
11
+ * A converter that always fails with the reason the real one is unavailable, so
12
+ * every tool left out names the actual cause (a corrupt or incompatible zod
13
+ * install reads differently from a missing one).
14
+ */
15
+ function unavailableConverter(cause) {
16
+ return function () {
17
+ throw new Error("the zod schema converter is unavailable: " + cause);
18
+ };
19
+ }
20
+
21
+ /**
22
+ * Loads zod's JSON schema converter. When zod cannot be loaded, or has no
23
+ * converter, the function returned fails with that cause when used.
24
+ * @param {function(): object} [loadZod] how zod is loaded; tests inject it
25
+ * @returns {function} toJSONSchema
26
+ */
27
+ function loadToJSONSchema(loadZod) {
28
+ var zod;
29
+ try {
30
+ zod = (loadZod || function () { return require("zod"); })();
31
+ } catch (e) {
32
+ return unavailableConverter((e && e.message) || String(e));
33
+ }
34
+ if (typeof zod.toJSONSchema !== "function") {
35
+ return unavailableConverter("the installed zod has no toJSONSchema");
36
+ }
37
+ return zod.toJSONSchema;
38
+ }
39
+
40
+ /**
41
+ * Converts one registered tool's input schema.
42
+ * A tool declared without any input schema takes no parameters; that is a
43
+ * valid declaration, not a failure. A schema that exists but cannot be
44
+ * converted is a failure, including when the converter itself is missing.
45
+ *
46
+ * @param {?function} toJSONSchema converter from loadToJSONSchema (null: none)
47
+ * @param {object} toolDef the registered tool ({ inputSchema, ... })
48
+ * @returns {{ok: true, schema: object}|{ok: false, error: string}}
49
+ */
50
+ function convertToolInputSchema(toJSONSchema, toolDef) {
51
+ if (!toolDef || !toolDef.inputSchema) {
52
+ return { ok: true, schema: { type: "object", properties: {} } };
53
+ }
54
+ if (typeof toJSONSchema !== "function") {
55
+ return { ok: false, error: "the zod schema converter is not available" };
56
+ }
57
+ try {
58
+ return { ok: true, schema: toJSONSchema(toolDef.inputSchema) };
59
+ } catch (e) {
60
+ return { ok: false, error: (e && e.message) || String(e) };
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The diagnostic event that tells the operator a tool was left out.
66
+ * @param {string} serverName
67
+ * @param {string} toolName
68
+ * @param {string} error
69
+ * @returns {{type: string, severity: string, source: string, message: string}}
70
+ */
71
+ function skippedToolDiagnostic(serverName, toolName, error) {
72
+ return {
73
+ type: "diagnostic",
74
+ severity: "warning",
75
+ source: MCP_DIAGNOSTIC_SOURCE,
76
+ message: "The MCP tool " + (serverName ? serverName + "/" : "") + toolName
77
+ + " was left out because its input schema could not be converted: " + error,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Logs a skipped tool and tells the caller's reporter about it.
83
+ * @param {string} serverName
84
+ * @param {string} toolName
85
+ * @param {string} error
86
+ * @param {?function} onSkipped receives the diagnostic event
87
+ */
88
+ function reportSkippedTool(serverName, toolName, error, onSkipped) {
89
+ var diagnostic = skippedToolDiagnostic(serverName, toolName, error);
90
+ console.error("[mcp] " + diagnostic.message);
91
+ if (typeof onSkipped === "function") onSkipped(diagnostic);
92
+ return diagnostic;
93
+ }
94
+
95
+ /**
96
+ * The one place that reads the tool table of an SDK server object. The SDK
97
+ * offers no public way to enumerate the tools of an in-process server, so the
98
+ * table is read from its private field here and nowhere else in the listing
99
+ * path. When the field is absent or no longer a plain table the result says so,
100
+ * so a changed SDK surfaces as a diagnostic and not as tools that vanish.
101
+ *
102
+ * @param {?object} server SDK server object ({ instance: { _registeredTools } })
103
+ * @returns {{ok: true, tools: object}|{ok: false, error: string}}
104
+ */
105
+ function readRegisteredTools(server) {
106
+ // A server without an in-process instance (a plain config) has no tool table
107
+ // to read; that is not an SDK change.
108
+ if (!server || !server.instance) return { ok: true, tools: {} };
109
+ var table = server.instance._registeredTools;
110
+ if (table === undefined || table === null) {
111
+ return { ok: false, error: "the SDK server no longer exposes its registered tool table" };
112
+ }
113
+ if (typeof table !== "object" || Array.isArray(table) || table instanceof Map) {
114
+ return { ok: false, error: "the SDK server's registered tool table changed shape" };
115
+ }
116
+ return { ok: true, tools: table };
117
+ }
118
+
119
+ /**
120
+ * Tells the operator that a whole server's tools could not be read.
121
+ * @param {string} serverName
122
+ * @param {string} error
123
+ * @param {?function} onSkipped
124
+ */
125
+ function reportToolsUnreadable(serverName, error, onSkipped) {
126
+ var diagnostic = {
127
+ type: "diagnostic",
128
+ severity: "warning",
129
+ source: MCP_DIAGNOSTIC_SOURCE,
130
+ message: "The MCP server " + serverName + " was left out because its tools could not be listed: " + error,
131
+ };
132
+ console.error("[mcp] " + diagnostic.message);
133
+ if (typeof onSkipped === "function") onSkipped(diagnostic);
134
+ return diagnostic;
135
+ }
136
+
137
+ /**
138
+ * The tools of one in-process MCP server, each with its input schema as JSON
139
+ * schema. A tool whose schema cannot be converted is left out and reported.
140
+ *
141
+ * @param {string} serverName
142
+ * @param {object} server SDK server object ({ instance: { _registeredTools } })
143
+ * @param {?function} toJSONSchema converter from loadToJSONSchema
144
+ * @param {?function} onSkipped receives the diagnostic for a tool left out
145
+ * @returns {Array<{name: string, description: string, inputSchema: object}>}
146
+ */
147
+ function listServerTools(serverName, server, toJSONSchema, onSkipped) {
148
+ var found = readRegisteredTools(server);
149
+ if (!found.ok) {
150
+ reportToolsUnreadable(serverName, found.error, onSkipped);
151
+ return [];
152
+ }
153
+ var registered = found.tools;
154
+ var tools = [];
155
+ Object.keys(registered).forEach(function (toolName) {
156
+ var toolDef = registered[toolName];
157
+ var converted = convertToolInputSchema(toJSONSchema, toolDef);
158
+ if (!converted.ok) {
159
+ reportSkippedTool(serverName, toolName, converted.error, onSkipped);
160
+ return;
161
+ }
162
+ tools.push({
163
+ name: toolName,
164
+ description: toolDef.description || toolName,
165
+ inputSchema: converted.schema,
166
+ });
167
+ });
168
+ return tools;
169
+ }
170
+
171
+ module.exports = {
172
+ MCP_DIAGNOSTIC_SOURCE: MCP_DIAGNOSTIC_SOURCE,
173
+ loadToJSONSchema: loadToJSONSchema,
174
+ convertToolInputSchema: convertToolInputSchema,
175
+ readRegisteredTools: readRegisteredTools,
176
+ listServerTools: listServerTools,
177
+ skippedToolDiagnostic: skippedToolDiagnostic,
178
+ reportSkippedTool: reportSkippedTool,
179
+ };
@@ -500,16 +500,30 @@ function checkAppliedMemoryCeiling(opts) {
500
500
  * @param {function(object): void} [opts.onCrossing] — called with the same
501
501
  * detail object that is written to the log whenever a watermark crossing is
502
502
  * detected. Consumers (lr-6b30 drain) use this instead of parsing stderr.
503
+ * @param {function(object): void} [opts.onRecovery] — called once when usage
504
+ * is observed back below the threshold (minus hysteresis) after a crossing.
505
+ * @param {function(): (number|null)} [opts.readHighCounter] — test seam
506
+ * @param {function(): (number|null)} [opts.readCurrentBytes] — test seam
503
507
  * @returns {{ stop: function(): void }} handle to stop the watcher
504
508
  */
505
509
  function startMemoryHighWatcher(cfg, opts) {
506
510
  var pollMs = (opts && opts.pollIntervalMs) || POLL_INTERVAL_MS;
507
511
  var onCrossing = (opts && typeof opts.onCrossing === 'function') ? opts.onCrossing : null;
512
+ var onRecovery = (opts && typeof opts.onRecovery === 'function') ? opts.onRecovery : null;
513
+ // Readers are injectable so tests can drive the watcher without a cgroup.
514
+ var readHighCounter = (opts && typeof opts.readHighCounter === 'function')
515
+ ? opts.readHighCounter : readCgroupHighCounter;
516
+ var readCurrentBytes = (opts && typeof opts.readCurrentBytes === 'function')
517
+ ? opts.readCurrentBytes : readCgroupCurrentBytes;
508
518
 
509
519
  // State for de-duplication.
510
520
  var lastHighCounter = null; // last 'high' counter value seen (strategy A)
511
521
  var isAboveThreshold = false; // for strategy B hysteresis
522
+ var underPressure = false; // set on crossing, cleared on recovery
523
+ var quietPolls = 0; // polls since the last crossing (no-threshold fallback)
524
+ var warnedDetectionUnavailable = false;
512
525
  var HYSTERESIS_FRACTION = 0.05; // 5% drop required before re-alerting
526
+ var RECOVERY_QUIET_POLLS = 3;
513
527
 
514
528
  var handle = setInterval(function () {
515
529
  try {
@@ -533,15 +547,51 @@ function startMemoryHighWatcher(cfg, opts) {
533
547
  if (detail.thresholdBytes !== undefined) event.thresholdBytes = detail.thresholdBytes;
534
548
  // Emit as a prefixed JSON line on stderr (journald captures stderr to the journal).
535
549
  process.stderr.write('[memory-limits] WARN memory_high_watermark ' + JSON.stringify(event) + '\n');
550
+ underPressure = true;
551
+ quietPolls = 0;
536
552
  // Notify any registered crossing consumer (e.g. lr-6b30 drain controller).
537
553
  if (onCrossing) {
538
554
  try { onCrossing(event); } catch (_) {}
539
555
  }
540
556
  }
541
557
 
558
+ // A crossing leaves the watcher "under pressure" until usage is observed
559
+ // back below the threshold. Consumers that refuse work while pressured need
560
+ // this end edge; the kernel only reports the start edge.
561
+ function _checkRecovery(c) {
562
+ if (!underPressure) return;
563
+ var threshold = resolveMemoryHighBytes(c);
564
+ var now = threshold === null ? null : readCurrentBytes();
565
+ var recovered = false;
566
+ if (now === null) {
567
+ // No threshold, or cgroup usage unreadable: the daemon's own RSS says
568
+ // nothing about its child processes, so never substitute it. Treat a run
569
+ // of polls with no further kernel-reported crossing as recovery, so
570
+ // pressure can never stick.
571
+ quietPolls++;
572
+ recovered = quietPolls >= RECOVERY_QUIET_POLLS;
573
+ } else {
574
+ recovered = now < threshold - Math.floor(threshold * HYSTERESIS_FRACTION);
575
+ }
576
+ if (!recovered) return;
577
+ underPressure = false;
578
+ isAboveThreshold = false;
579
+ quietPolls = 0;
580
+ var event = { event: 'memory_high_recovered', timestamp: new Date().toISOString() };
581
+ process.stderr.write('[memory-limits] INFO memory_high_recovered ' + JSON.stringify(event) + '\n');
582
+ if (onRecovery) {
583
+ try { onRecovery(event); } catch (_) {}
584
+ }
585
+ }
586
+
542
587
  function _poll(c) {
588
+ _detect(c);
589
+ _checkRecovery(c);
590
+ }
591
+
592
+ function _detect(c) {
543
593
  // Strategy A: cgroup v2 memory.events high counter.
544
- var highCounter = readCgroupHighCounter();
594
+ var highCounter = readHighCounter();
545
595
  if (highCounter !== null) {
546
596
  if (lastHighCounter === null) {
547
597
  // First observation — record baseline, do not alert.
@@ -550,7 +600,7 @@ function startMemoryHighWatcher(cfg, opts) {
550
600
  }
551
601
  if (highCounter > lastHighCounter) {
552
602
  // Counter advanced — kernel confirmed a MemoryHigh crossing.
553
- var currentBytes = readCgroupCurrentBytes();
603
+ var currentBytes = readCurrentBytes();
554
604
  _emitWarning({
555
605
  source: 'cgroup.memory.events',
556
606
  highCounter: highCounter,
@@ -566,10 +616,16 @@ function startMemoryHighWatcher(cfg, opts) {
566
616
  var threshold = resolveMemoryHighBytes(c);
567
617
  if (threshold === null) return; // no threshold determinable
568
618
 
569
- var currentB = readCgroupCurrentBytes();
619
+ var currentB = readCurrentBytes();
570
620
  if (currentB === null) {
571
- // Fallback: use process.memoryUsage().rss when cgroup current is unavailable.
572
- currentB = process.memoryUsage().rss;
621
+ // Daemon RSS excludes the child processes that actually drive pressure,
622
+ // so it is not a valid stand-in for cgroup usage.
623
+ if (!warnedDetectionUnavailable) {
624
+ warnedDetectionUnavailable = true;
625
+ process.stderr.write('[memory-limits] WARN memory pressure detection unavailable: ' +
626
+ 'cgroup memory.events and memory.current are unreadable\n');
627
+ }
628
+ return;
573
629
  }
574
630
 
575
631
  var hysteresisBytes = Math.floor(threshold * HYSTERESIS_FRACTION);
@@ -0,0 +1,65 @@
1
+ // memory-setting-validate.js — shared range validation for the memory-guard
2
+ // config keys (lr-553d27).
3
+ //
4
+ // Extracted so the web/WS path (lib/daemon.js's onSetMemAvailableThreshold /
5
+ // onSetTokensPerMbHeadroom) and the raw IPC socket path (lib/daemon.js's
6
+ // set_mem_available_threshold / set_tokens_per_mb_headroom cases) validate
7
+ // against ONE contract instead of two independently-maintained copies. The
8
+ // divergence between those two copies is what let the raw IPC path silently
9
+ // clamp an out-of-range value to the default and report ok:true (the web
10
+ // path was fixed for this under lr-93e3c8; the raw IPC path was not) — see
11
+ // lr-553d27.
12
+ //
13
+ // Both functions return { ok: true, value } on success or
14
+ // { ok: false, error } on rejection; the error message always names the
15
+ // valid band so a caller (including the raw-socket escape-hatch documented
16
+ // to operators) can tell exactly what would be accepted.
17
+ //
18
+ // coerceCleanInteger (lr-553d27 fold-in, BOBBIE PR #417 coercion review):
19
+ // parseInt() alone accepts a PREFIX of its input -- parseInt("300abc", 10)
20
+ // is 300, not NaN -- so a caller sending {"value":"300abc"} over the raw IPC
21
+ // socket would have received ok:true with 300 silently persisted, a
22
+ // DIFFERENT value than the one it sent. That is the exact
23
+ // "control path reports success while silently substituting a different
24
+ // value" contract violation this task exists to close, one level down from
25
+ // the out-of-range case. A real number (already a clean integer/float, no
26
+ // parsing needed) or a numeric STRING that is a whole number with no trailing
27
+ // garbage is accepted; anything else (a non-numeric prefix, a decimal
28
+ // fraction, or a completely non-numeric value) is rejected. A caller passing
29
+ // a clean numeric string over a JSON socket (e.g. "1000") remains a
30
+ // legitimate, accepted case.
31
+ //
32
+ // Safe-integer guard: a digit-only string of 309+ digits makes parseInt return
33
+ // Infinity (which saveConfig serializes as null), and one past
34
+ // Number.MAX_SAFE_INTEGER loses precision -- both are a different value landing
35
+ // than the one sent, so only Number.isSafeInteger results are accepted.
36
+ function coerceCleanInteger(rawValue) {
37
+ var parsed = NaN;
38
+ if (typeof rawValue === "number") {
39
+ parsed = rawValue;
40
+ } else if (typeof rawValue === "string" && /^-?\d+$/.test(rawValue.trim())) {
41
+ parsed = parseInt(rawValue, 10);
42
+ }
43
+ return Number.isSafeInteger(parsed) ? parsed : NaN;
44
+ }
45
+
46
+ function validateMemAvailableThresholdMB(rawValue) {
47
+ var val = coerceCleanInteger(rawValue);
48
+ if (isNaN(val) || val < 0) {
49
+ return { ok: false, error: "Value must be a number >= 0" };
50
+ }
51
+ return { ok: true, value: val };
52
+ }
53
+
54
+ function validateTokensPerMbHeadroom(rawValue) {
55
+ var val = coerceCleanInteger(rawValue);
56
+ if (isNaN(val) || val < 10 || val > 500) {
57
+ return { ok: false, error: "Value must be 10-500" };
58
+ }
59
+ return { ok: true, value: val };
60
+ }
61
+
62
+ module.exports = {
63
+ validateMemAvailableThresholdMB: validateMemAvailableThresholdMB,
64
+ validateTokensPerMbHeadroom: validateTokensPerMbHeadroom,
65
+ };
@@ -0,0 +1,47 @@
1
+ // new-work-gate.js — process-wide switch for refusing new sessions and new
2
+ // agent work while the daemon is under memory pressure or draining.
3
+ //
4
+ // The drain controller is created late in daemon startup, after the modules
5
+ // that need to consult it are loaded, so it registers a predicate here rather
6
+ // than being threaded through every constructor. Existing sessions are never
7
+ // touched by this gate; callers only consult it at the point they would start
8
+ // something new.
9
+
10
+ 'use strict';
11
+
12
+ var REFUSAL_MESSAGE =
13
+ 'Clagentic: Console is under memory pressure and is not starting new sessions or agent work. ' +
14
+ 'Existing sessions keep running. Try again once active sessions finish and memory recovers.';
15
+
16
+ var _isRefusing = null;
17
+
18
+ /**
19
+ * Register the predicate that reports whether new work must be refused.
20
+ *
21
+ * @param {function(): boolean|null} fn — null clears the gate
22
+ */
23
+ function setNewWorkGate(fn) {
24
+ _isRefusing = typeof fn === 'function' ? fn : null;
25
+ }
26
+
27
+ /**
28
+ * @returns {string|null} user-facing refusal message, or null when new work is allowed.
29
+ */
30
+ function getNewWorkRefusal() {
31
+ if (!_isRefusing) return null;
32
+ var refusing;
33
+ try {
34
+ refusing = !!_isRefusing();
35
+ } catch (e) {
36
+ // Fail closed: an unknown pressure state must not let new work through.
37
+ console.error('[new-work-gate] predicate threw; refusing new work: ' + (e && e.message));
38
+ refusing = true;
39
+ }
40
+ return refusing ? REFUSAL_MESSAGE : null;
41
+ }
42
+
43
+ module.exports = {
44
+ setNewWorkGate: setNewWorkGate,
45
+ getNewWorkRefusal: getNewWorkRefusal,
46
+ REFUSAL_MESSAGE: REFUSAL_MESSAGE,
47
+ };
package/lib/os-users.js CHANGED
@@ -501,10 +501,12 @@ function deactivateLinuxUser(linuxUsername) {
501
501
  }
502
502
 
503
503
  /**
504
- * Ensure the shared projects directory exists.
504
+ * Ensure the shared projects directory exists. `dir` defaults to the
505
+ * os-users-mode directory from the shared resolver, which prefers an existing
506
+ * legacy directory and never moves it.
505
507
  */
506
- function ensureProjectsDir() {
507
- var dir = "/var/clagentic/projects";
508
+ function ensureProjectsDir(dir) {
509
+ dir = dir || require("./projects-dir").resolveProjectsDir({ config: { osUsers: true }, realHome: "" }).dir;
508
510
  if (!fs.existsSync(dir)) {
509
511
  fs.mkdirSync(dir, { recursive: true, mode: 0o711 });
510
512
  } else {
@@ -0,0 +1,139 @@
1
+ // The one place that answers "who is this, and may they touch that project?".
2
+ //
3
+ // Every caller (HTTP gate, WebSocket upgrade, per-message gate, project
4
+ // lists, palette, schedules, file and session handlers) goes through here so
5
+ // no site can forget the check, dereference a missing user, or treat a failed
6
+ // lookup as permission.
7
+ //
8
+ // AUTHENTICATION precedes and is separate from PRINCIPAL resolution. "No user"
9
+ // is the implicit owner only when the caller PROVED the request or connection
10
+ // was authenticated ({ authenticated: true }): isRequestAuthed(req) for HTTP,
11
+ // the WebSocket upgrade's auth check (carried on the connection by
12
+ // authOf(ws)), or the local MCP bridge. Without that proof no user is nobody,
13
+ // in every mode, so a route that forgets the login check refuses instead of
14
+ // serving the owner's data.
15
+ //
16
+ // Given the proof, whether "no user" means an owner or a stranger is decided
17
+ // by the MODE of the daemon, never by the absence alone:
18
+ // - single-user mode: the authenticated connection carries no user record,
19
+ // because the connection is the implicit owner. It is allowed everything,
20
+ // and every project.
21
+ // - multi-user mode: no user means unauthenticated, which is a refusal.
22
+ // A lookup that cannot be completed (no lookup wired, project unknown, lookup
23
+ // error, mode unknown) is a refusal, never an allow.
24
+ //
25
+ // deps:
26
+ // users module exposing canAccessProject(userId, access) and
27
+ // canAccessSession(userId, session, access)
28
+ // onGetProjectAccess function(slug) -> access object | { error } | falsy
29
+ // isMultiUser function() -> boolean; absent or throwing means
30
+ // multi-user, so a failure to learn the mode denies
31
+
32
+ // The proof a caller hands in alongside a possibly-missing user. Only the
33
+ // boolean true counts.
34
+ function isProven(opts) {
35
+ return !!opts && opts.authenticated === true;
36
+ }
37
+
38
+ // The proof carried by a WebSocket connection or an HTTP request object. The
39
+ // upgrade handler and the HTTP route set _clagenticAuthenticated only after
40
+ // their login check passed; anything else, including a bare object, is
41
+ // unproven.
42
+ function authOf(conn) {
43
+ return { authenticated: !!conn && conn._clagenticAuthenticated === true };
44
+ }
45
+
46
+ function createProjectAccess(deps) {
47
+ var users = deps.users;
48
+ var onGetProjectAccess = deps.onGetProjectAccess;
49
+ var isMultiUser = deps.isMultiUser;
50
+
51
+ function multiUserMode() {
52
+ if (typeof isMultiUser !== "function") return true;
53
+ try {
54
+ return isMultiUser() !== false;
55
+ } catch (e) {
56
+ return true;
57
+ }
58
+ }
59
+
60
+ // The principal behind a request or connection, or null when it must be
61
+ // refused. `user` is the authenticated user record, or null/undefined.
62
+ // { id, user, admin, implicit }
63
+ // id is null only for the implicit single-user owner, who needs
64
+ // opts.authenticated === true.
65
+ function principalFor(user, opts) {
66
+ if (user && typeof user === "object" && user.id) {
67
+ return { id: user.id, user: user, admin: user.role === "admin", implicit: false };
68
+ }
69
+ if (user) return null;
70
+ if (!isProven(opts)) return null;
71
+ if (multiUserMode()) return null;
72
+ return { id: null, user: null, admin: true, implicit: true };
73
+ }
74
+
75
+ function isAdmin(user, opts) {
76
+ var principal = principalFor(user, opts);
77
+ return !!principal && principal.admin;
78
+ }
79
+
80
+ // The access record for a slug, or null when it cannot be established.
81
+ function resolve(slug) {
82
+ if (typeof slug !== "string" || !slug) return null;
83
+ if (typeof onGetProjectAccess !== "function") return null;
84
+ var access;
85
+ try {
86
+ access = onGetProjectAccess(slug);
87
+ } catch (e) {
88
+ return null;
89
+ }
90
+ if (!access || access.error) return null;
91
+ return access;
92
+ }
93
+
94
+ // userId is the id of an authenticated user, or null/undefined for none.
95
+ function canAccess(userId, slug, opts) {
96
+ var principal = principalFor(userId ? { id: userId } : null, opts);
97
+ if (!principal) return false;
98
+ if (principal.implicit) return typeof slug === "string" && slug !== "";
99
+ var access = resolve(slug);
100
+ if (!access) return false;
101
+ return users.canAccessProject(principal.id, access) === true;
102
+ }
103
+
104
+ // Entries are project status objects (anything with a .slug).
105
+ function filterProjectList(userId, list, opts) {
106
+ if (!Array.isArray(list)) return [];
107
+ if (!principalFor(userId ? { id: userId } : null, opts)) return [];
108
+ return list.filter(function (p) {
109
+ return !!p && canAccess(userId, p.slug, opts);
110
+ });
111
+ }
112
+
113
+ // Whether `user` may see `session`. Access to the owning project is settled
114
+ // before a message reaches a handler (the per-message gate in project.js),
115
+ // so only the session's own owner/visibility rules are applied here. No
116
+ // principal or no session is a refusal; the implicit owner reads everything.
117
+ function canReadSession(user, session, opts) {
118
+ var principal = principalFor(user, opts);
119
+ if (!principal || !session) return false;
120
+ if (principal.implicit) return true;
121
+ return users.canAccessSession(principal.id, session, { visibility: "public" }) === true;
122
+ }
123
+
124
+ return {
125
+ principalFor: principalFor,
126
+ isMultiUser: multiUserMode,
127
+ authOf: authOf,
128
+ isAdmin: isAdmin,
129
+ resolve: resolve,
130
+ canAccess: canAccess,
131
+ filterProjectList: filterProjectList,
132
+ canReadSession: canReadSession,
133
+ };
134
+ }
135
+
136
+ module.exports = {
137
+ createProjectAccess: createProjectAccess,
138
+ authOf: authOf,
139
+ };
@@ -2,7 +2,10 @@ var fs = require("fs");
2
2
  var path = require("path");
3
3
  var usersModule = require("./users");
4
4
  var userPresence = require("./user-presence");
5
+ var { authOf } = require("./project-access");
5
6
  var { getCodexConfig } = require("./codex-defaults");
7
+ var { promptsFor } = require("./prompt-registry");
8
+ var { buildVendorRegistryMessage } = require("./vendor-registry-message");
6
9
  // detectLite is cached per-project in project.js and passed via ctx.liteStatus.
7
10
  // This import is retained only for backward compat if ctx.liteStatus is absent.
8
11
  var { detectLite } = require("./lite-detect");
@@ -17,7 +20,7 @@ var { detectLite } = require("./lite-detect");
17
20
  * hydrateImageRefs, broadcastClientCount, broadcastPresence,
18
21
  * getProjectList, getHubSchedules, loadContextSources,
19
22
  * handleMessage, handleDisconnection,
20
- * stopFileWatch, stopAllDirWatches,
23
+ * stopFileWatch(ws), stopAllDirWatches(ws),
21
24
  * getProjectOwnerId, setProjectOwnerId, getLatestVersion,
22
25
  * getTitle, getProject
23
26
  */
@@ -80,7 +83,13 @@ function attachConnection(ctx) {
80
83
  if (!active && allSessions.length > 0) {
81
84
  active = allSessions[0];
82
85
  for (var fi = 1; fi < allSessions.length; fi++) {
83
- if ((allSessions[fi].lastActivity || 0) > (active.lastActivity || 0)) {
86
+ // >= not >: lastActivity has millisecond resolution, and a session
87
+ // manager always creates a blank initial session at construction, so a
88
+ // session created right after it routinely shares its millisecond.
89
+ // allSessions is in creation order, so on a tie the later (newer)
90
+ // session must win; strict > made the blank one win, which restored
91
+ // clients into the wrong session on fast hosts.
92
+ if ((allSessions[fi].lastActivity || 0) >= (active.lastActivity || 0)) {
84
93
  active = allSessions[fi];
85
94
  }
86
95
  }
@@ -114,7 +123,7 @@ function attachConnection(ctx) {
114
123
 
115
124
  // Send cached state
116
125
  var _userId = ws._clagenticUser ? ws._clagenticUser.id : null;
117
- var _filteredProjects = getProjectList(_userId);
126
+ var _filteredProjects = getProjectList(_userId, authOf(ws));
118
127
  var title = getTitle();
119
128
  var project = getProject();
120
129
  var ownerLocked = !!(osUsers && osUsers.length > 0 && /^\/home\/[^/]+\//.test(cwd));
@@ -152,16 +161,19 @@ function attachConnection(ctx) {
152
161
  // it correctly to disk — only this display path never consulted it) —
153
162
  // the root cause of "picked opus 4.7, session ran on it, chip still says
154
163
  // sonnet after a reconnect." See effectiveSessionModel() in sessions.js.
164
+ // Install state is per OS identity; a connection is told its own.
165
+ var _osIdentity = osUsers && wsUser && wsUser.linuxUser ? wsUser.linuxUser : null;
155
166
  var _initialModel = sm.effectiveSessionModel(restoredActive);
156
167
  if (_initialModel) {
157
- sendTo(ws, { type: "model_info", model: _initialModel, models: initialModels, vendor: initialVendor, availableVendors: sm.availableVendors || [], installedVendors: sm.installedVendors || [] });
168
+ sendTo(ws, { type: "model_info", model: _initialModel, models: initialModels, vendor: initialVendor, availableVendors: sm.availableVendors || [] });
158
169
  }
170
+ sendTo(ws, buildVendorRegistryMessage(sm, _osIdentity));
159
171
  sendTo(ws, { type: "config_state", model: _initialModel, mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
160
172
  sendTo(ws, Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
161
173
  sendTo(ws, { type: "term_list", terminals: tm.list(ws) });
162
174
  // Context sources sent after session is resolved (per-session storage)
163
175
  sendTo(ws, { type: "notes_list", notes: nm.list() });
164
- sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules() });
176
+ sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules(_userId, authOf(ws)) });
165
177
  _loop.sendConnectionState(ws);
166
178
  if (_mcp) _mcp.sendConnectionState(ws);
167
179
  if (_notifications) _notifications.sendConnectionState(ws, sendTo);
@@ -254,19 +266,9 @@ function attachConnection(ctx) {
254
266
  // 'processing' latch blind to which session it belongs to.
255
267
  sendTo(ws, { type: "status", status: "processing", localId: active.localId });
256
268
  }
257
- var pendingIds = Object.keys(active.pendingPermissions);
258
- for (var pi = 0; pi < pendingIds.length; pi++) {
259
- var p = active.pendingPermissions[pendingIds[pi]];
260
- sendTo(ws, {
261
- type: "permission_request_pending",
262
- requestId: p.requestId,
263
- toolName: p.toolName,
264
- toolInput: p.toolInput,
265
- toolUseId: p.toolUseId,
266
- decisionReason: p.decisionReason,
267
- mateId: p.mateId || undefined,
268
- });
269
- }
269
+ promptsFor(sm).pendingMessages(active).forEach(function (pendingMsg) {
270
+ sendTo(ws, pendingMsg);
271
+ });
270
272
  }
271
273
 
272
274
  if (active) {
@@ -322,10 +324,9 @@ function attachConnection(ctx) {
322
324
  }
323
325
  tm.detachAll(ws);
324
326
  clients.delete(ws);
325
- if (clients.size === 0) {
326
- stopFileWatch();
327
- stopAllDirWatches();
328
- }
327
+ // Watches belong to the connection that opened them.
328
+ stopFileWatch(ws);
329
+ stopAllDirWatches(ws);
329
330
  broadcastClientCount();
330
331
  broadcastPresence();
331
332
  }