@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,53 @@
1
+ // vendor-picker.js - draws the agent picker into its container from picker
2
+ // rows. An agent that is not installed (or could not be checked) is shown
3
+ // disabled with why, and a Re-check button asks the server to look again.
4
+ // Kept free of app state: the caller passes the rows and the two actions.
5
+
6
+ /**
7
+ * @param {Element} container emptied and refilled
8
+ * @param {Array} rows from pickerRows (vendor-registry.js)
9
+ * @param {{onSelect: function(string), onRecheck: function()}} actions
10
+ */
11
+ export function renderVendorPicker(container, rows, actions) {
12
+ container.innerHTML = "";
13
+ var anyUnavailable = false;
14
+ rows.forEach(function (row) {
15
+ var btn = document.createElement("button");
16
+ btn.type = "button";
17
+ btn.className = "vendor-toggle-btn" + (row.active ? " active" : "") + (row.installed ? "" : " disabled");
18
+ btn.dataset.vendor = row.id;
19
+ btn.title = row.title;
20
+ if (!row.installed) {
21
+ btn.setAttribute("aria-disabled", "true");
22
+ anyUnavailable = true;
23
+ }
24
+ if (row.icon) {
25
+ var icon = document.createElement("img");
26
+ icon.className = "vendor-toggle-icon";
27
+ icon.src = row.icon;
28
+ icon.alt = row.displayName;
29
+ btn.appendChild(icon);
30
+ }
31
+ var label = document.createElement("span");
32
+ label.className = "vendor-toggle-label";
33
+ label.textContent = row.displayName;
34
+ btn.appendChild(label);
35
+ if (row.checkFailed) {
36
+ var note = document.createElement("span");
37
+ note.className = "vendor-toggle-note";
38
+ note.textContent = "Could not check";
39
+ btn.appendChild(note);
40
+ }
41
+ btn.addEventListener("click", function () { actions.onSelect(row.id); });
42
+ container.appendChild(btn);
43
+ });
44
+ if (anyUnavailable) {
45
+ var recheck = document.createElement("button");
46
+ recheck.type = "button";
47
+ recheck.className = "vendor-recheck-btn";
48
+ recheck.textContent = "Re-check";
49
+ recheck.title = "Look again for installed agents";
50
+ recheck.addEventListener("click", function () { actions.onRecheck(); });
51
+ container.appendChild(recheck);
52
+ }
53
+ }
@@ -0,0 +1,133 @@
1
+ // vendor-registry.js - the agent registry as the server sent it, and the
2
+ // helpers every capability-gated control reads it through. Controls ask what
3
+ // the current agent can do (capabilityGate); nothing here or in a caller
4
+ // compares a vendor name. A control the agent cannot support is shown
5
+ // disabled with the one-line reason from the registry, never silently absent.
6
+
7
+ import { store } from './store.js';
8
+
9
+ // Names and avatars by vendor id, filled from the registry message. The two
10
+ // shipped agents are seeded only to cover the moment before that message
11
+ // arrives; the registry overrides them and adds every other agent.
12
+ export var VENDOR_NAMES = {
13
+ claude: "Claude Code",
14
+ codex: "Codex",
15
+ };
16
+ export var VENDOR_AVATARS = {
17
+ claude: "/claude-code-avatar.png",
18
+ codex: "/codex-avatar.png",
19
+ };
20
+
21
+ function idsWhere(vendors, field) {
22
+ return vendors.filter(function (v) { return v[field]; }).map(function (v) { return v.id; });
23
+ }
24
+
25
+ /**
26
+ * Applies a vendor_registry message: names, avatars and the lists the picker
27
+ * and the gated controls read.
28
+ */
29
+ export function applyVendorRegistry(msg) {
30
+ var vendors = Array.isArray(msg && msg.vendors) ? msg.vendors : [];
31
+ vendors.forEach(function (v) {
32
+ VENDOR_NAMES[v.id] = v.displayName;
33
+ if (v.icon) VENDOR_AVATARS[v.id] = v.icon;
34
+ });
35
+ store.set({
36
+ vendorRegistry: vendors,
37
+ capabilityReasons: (msg && msg.reasons) || {},
38
+ installedVendors: idsWhere(vendors, "installed"),
39
+ availableVendors: idsWhere(vendors, "available"),
40
+ });
41
+ }
42
+
43
+ /** The registry entry for an agent id, or null. */
44
+ export function vendorEntry(vendorId) {
45
+ var vendors = store.get('vendorRegistry') || [];
46
+ for (var i = 0; i < vendors.length; i++) {
47
+ if (vendors[i].id === vendorId) return vendors[i];
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /** The most preferred registered agent (the server sends them in order). */
53
+ export function defaultVendorId() {
54
+ var vendors = store.get('vendorRegistry') || [];
55
+ return vendors.length ? vendors[0].id : "";
56
+ }
57
+
58
+ /**
59
+ * What an agent can do. The registry carries every agent's capabilities, so a
60
+ * session on an agent other than the project default is gated on its own
61
+ * agent. The capabilities the active session reported are the fallback for
62
+ * the moment before the registry arrives.
63
+ */
64
+ export function capabilitiesFor(vendorId) {
65
+ var entry = vendorEntry(vendorId);
66
+ if (entry) return entry.capabilities;
67
+ return store.get('vendorCapabilities') || {};
68
+ }
69
+
70
+ /** What the agent the user is on (chosen or bound) can do. */
71
+ export function currentCapabilities() {
72
+ return capabilitiesFor(store.get('currentVendor') || defaultVendorId());
73
+ }
74
+
75
+ /**
76
+ * Whether a control gated on one capability is usable, and when it is not, the
77
+ * one line that says why.
78
+ * @param {string} key a capability of the YOKE ledger
79
+ * @returns {{enabled: boolean, reason: string}}
80
+ */
81
+ export function capabilityGate(key) {
82
+ var caps = currentCapabilities();
83
+ var value = caps[key];
84
+ var enabled = Array.isArray(value) ? value.length > 0 : value === true;
85
+ var reasons = store.get('capabilityReasons') || {};
86
+ return { enabled: enabled, reason: enabled ? "" : (reasons[key] || "This agent does not support this.") };
87
+ }
88
+
89
+ function escapeAttr(text) {
90
+ return String(text).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
91
+ }
92
+
93
+ /**
94
+ * Attribute text for a button whose use depends on a capability: a plain title
95
+ * when usable, otherwise disabled with the reason in the title.
96
+ * @param {string} key capability
97
+ * @param {string} label what the control does
98
+ */
99
+ export function gatedButtonAttrs(key, label) {
100
+ var gate = capabilityGate(key);
101
+ if (gate.enabled) return 'title="' + escapeAttr(label) + '"';
102
+ return 'title="' + escapeAttr(label + " (unavailable): " + gate.reason) + '" disabled aria-disabled="true"';
103
+ }
104
+
105
+ /** The command that signs in to an agent, from the registry ("" if unknown). */
106
+ export function loginCommandFor(vendorId) {
107
+ var entry = vendorEntry(vendorId);
108
+ return entry ? entry.loginCommand : "";
109
+ }
110
+
111
+ /**
112
+ * The picker's rows, one per registered agent.
113
+ * An agent whose install lookup failed is not reported as missing: its row says
114
+ * the check could not be made, with the failure class.
115
+ * @returns {Array<{id: string, displayName: string, icon: string, installed: boolean, checkFailed: boolean, active: boolean, title: string}>}
116
+ */
117
+ export function pickerRows(vendors, current) {
118
+ return (vendors || []).map(function (v) {
119
+ var checkFailed = !v.installed && !!v.probeFailure;
120
+ var title = v.displayName;
121
+ if (checkFailed) title = v.displayName + ". Could not check: " + v.probeFailure + ". Use Re-check to try again.";
122
+ else if (!v.installed) title = v.displayName + " is not installed. " + v.installHint;
123
+ return {
124
+ id: v.id,
125
+ displayName: v.displayName,
126
+ icon: v.icon || "",
127
+ installed: !!v.installed,
128
+ checkFailed: checkFailed,
129
+ active: v.id === current,
130
+ title: title,
131
+ };
132
+ });
133
+ }
package/lib/public/sw.js CHANGED
@@ -1,4 +1,4 @@
1
- var CACHE_NAME = "clagentic-offline-v__VERSION__";
1
+ var CACHE_NAME = "clagentic-console-offline-v__VERSION__";
2
2
 
3
3
  // Minimal app-shell paths pre-cached on install so the new cache generation
4
4
  // is never empty at activate time. Without this, an offline mobile client
@@ -26,6 +26,8 @@ self.addEventListener("activate", function (event) {
26
26
  // Clean up old cache versions only after the new cache has the app shell
27
27
  // (guaranteed by install above), so there is no window where a client can
28
28
  // hit an empty cache and fall through to the minimal offline placeholder.
29
+ // Every cache not named CACHE_NAME goes, which includes the caches of the
30
+ // earlier "clagentic-offline-v*" naming.
29
31
  event.waitUntil(
30
32
  caches.keys().then(function (names) {
31
33
  return Promise.all(
@@ -0,0 +1,44 @@
1
+ // rc-migrate.js — one-time COPY of the recent-projects file into the console
2
+ // data dir.
3
+ //
4
+ // The file used to live in the user's home as a bare-brand dotfile. It now
5
+ // lives at <console data dir>/recent-projects.json. The old file is never
6
+ // modified or deleted: a rollback to an older release must still find it.
7
+
8
+ var fs = require("fs");
9
+ var path = require("path");
10
+
11
+ var RC_FILENAME = "recent-projects.json";
12
+
13
+ /**
14
+ * @param {object} opts
15
+ * @param {string} opts.rcPath Destination file.
16
+ * @param {string[]} opts.legacyPaths Candidates, newest first.
17
+ * @param {object} [opts.fs] fs-like, for tests.
18
+ * @param {function} [opts.log]
19
+ * @returns {{copied: boolean, from: (string|null)}}
20
+ */
21
+ function migrateRc(opts) {
22
+ var fsImpl = opts.fs || fs;
23
+ var log = opts.log || console.log;
24
+ if (fsImpl.existsSync(opts.rcPath)) return { copied: false, from: null };
25
+
26
+ for (var i = 0; i < opts.legacyPaths.length; i++) {
27
+ var src = opts.legacyPaths[i];
28
+ if (!fsImpl.existsSync(src)) continue;
29
+ try {
30
+ fsImpl.mkdirSync(path.dirname(opts.rcPath), { recursive: true, mode: 0o700 });
31
+ // COPYFILE_EXCL: never overwrite a file that appeared since the check.
32
+ fsImpl.copyFileSync(src, opts.rcPath, fs.constants.COPYFILE_EXCL);
33
+ log("[config] Copied " + src + " -> " + opts.rcPath + " (the original is left in place)");
34
+ return { copied: true, from: src };
35
+ } catch (e) {
36
+ if (e.code === "EEXIST") return { copied: false, from: null };
37
+ console.error("[config] Could not copy " + src + " to " + opts.rcPath + ":", e.message);
38
+ return { copied: false, from: null };
39
+ }
40
+ }
41
+ return { copied: false, from: null };
42
+ }
43
+
44
+ module.exports = { migrateRc: migrateRc, RC_FILENAME: RC_FILENAME };
@@ -0,0 +1,109 @@
1
+ // runtime-env-keys.js - the environment variables Settings may not set.
2
+ //
3
+ // Shared and per-project environment variables reach the agent runtimes the
4
+ // console starts. A variable that makes a shell, interpreter, loader or tool
5
+ // run code, or that replaces the system's own search path, is refused whoever
6
+ // sets it. This is defense in depth for the integrity of the host: it is NOT
7
+ // what keeps one user's variables from another user's session, which a list of
8
+ // names cannot do (the next variable would be missing from it). That is
9
+ // lib/runtime-env.js projectEnvApplies. This module is the one list of what is
10
+ // refused: at save time (lib/runtime-env.js validateEnvText) and dropped at
11
+ // build time (lib/runtime-env.js buildRuntimeEnvOverlay / composeRuntimeEnv).
12
+ //
13
+ // Names are compared case-insensitively: on platforms where the environment is
14
+ // case-insensitive "path" is PATH, and refusing both everywhere costs nothing.
15
+
16
+ var CLASSES = [
17
+ {
18
+ name: "identity",
19
+ description: "the runtime's own identity and search path",
20
+ exact: ["HOME", "PATH", "USER", "LOGNAME", "SHELL", "TMPDIR"],
21
+ },
22
+ {
23
+ name: "loader",
24
+ description: "the dynamic loader, which runs code inside every process",
25
+ prefixes: ["LD_", "DYLD_"],
26
+ },
27
+ {
28
+ name: "node",
29
+ description: "Node.js startup options and module search path",
30
+ exact: ["NODE_OPTIONS", "NODE_PATH"],
31
+ },
32
+ {
33
+ name: "console",
34
+ description: "Clagentic: Console's own configuration",
35
+ prefixes: ["CLAGENTIC_", "CLAY_"],
36
+ },
37
+ {
38
+ name: "shell-startup",
39
+ description: "files and commands a shell runs on its own at startup or on every prompt",
40
+ exact: ["BASH_ENV", "ENV", "PROMPT_COMMAND", "PS4", "SHELLOPTS", "BASHOPTS"],
41
+ },
42
+ {
43
+ name: "interpreter",
44
+ description: "startup hooks and library search paths of Python, Perl and Ruby",
45
+ exact: [
46
+ "PYTHONSTARTUP", "PYTHONPATH", "PYTHONHOME",
47
+ "PERL5OPT", "PERL5LIB", "PERLLIB",
48
+ "RUBYOPT", "RUBYLIB",
49
+ ],
50
+ },
51
+ {
52
+ name: "git",
53
+ description: "Git settings that name programs for Git to run",
54
+ exact: [
55
+ "GIT_SSH", "GIT_SSH_COMMAND", "GIT_EXTERNAL_DIFF", "GIT_PAGER",
56
+ "GIT_EDITOR", "GIT_ASKPASS", "GIT_EXEC_PATH",
57
+ ],
58
+ prefixes: ["GIT_CONFIG_"],
59
+ },
60
+ {
61
+ name: "tool-launcher",
62
+ description: "programs other tools start on the user's behalf",
63
+ exact: ["PAGER", "EDITOR", "VISUAL", "SSH_ASKPASS", "SUDO_ASKPASS"],
64
+ },
65
+ {
66
+ name: "process-wrapper",
67
+ description: "the launcher or wrapper a runtime is started through",
68
+ exact: ["CLAUDE_CODE_PROCESS_WRAPPER", "CLAUDE_CODE_PATH"],
69
+ },
70
+ {
71
+ name: "reserved",
72
+ description: "a name JavaScript reserves on every object",
73
+ exact: ["__PROTO__"],
74
+ },
75
+ ];
76
+
77
+ function normalize(name) {
78
+ return typeof name === "string" ? name.toUpperCase() : "";
79
+ }
80
+
81
+ /**
82
+ * The protected class a variable name belongs to, or null when settings may
83
+ * set it.
84
+ * @param {string} name
85
+ * @returns {{name: string, description: string}|null}
86
+ */
87
+ function protectedClassOf(name) {
88
+ var upper = normalize(name);
89
+ if (!upper) return null;
90
+ for (var i = 0; i < CLASSES.length; i++) {
91
+ var cls = CLASSES[i];
92
+ if (cls.exact && cls.exact.indexOf(upper) !== -1) return { name: cls.name, description: cls.description };
93
+ var prefixes = cls.prefixes || [];
94
+ for (var p = 0; p < prefixes.length; p++) {
95
+ if (upper.indexOf(prefixes[p]) === 0) return { name: cls.name, description: cls.description };
96
+ }
97
+ }
98
+ return null;
99
+ }
100
+
101
+ function isProtectedKey(name) {
102
+ return protectedClassOf(name) !== null;
103
+ }
104
+
105
+ module.exports = {
106
+ CLASSES: CLASSES,
107
+ protectedClassOf: protectedClassOf,
108
+ isProtectedKey: isProtectedKey,
109
+ };
@@ -0,0 +1,236 @@
1
+ // runtime-env.js - the one place the environment of an agent runtime is built.
2
+ //
3
+ // Settings hold two environment texts: shared (every project, administrators
4
+ // only) and per project. Every agent-runtime start (a Claude query in process
5
+ // or in a worker, a Codex app-server, title generation, a model-list warmup)
6
+ // takes its environment from here: the runtime's own environment first, then
7
+ // the shared text, then the project text.
8
+ //
9
+ // Two rules the callers rely on:
10
+ // - The Claude Agent SDK's options.env REPLACES the subprocess environment, so
11
+ // composeRuntimeEnv always returns the COMPLETE environment, never only
12
+ // the additions.
13
+ // - Values are secrets. Nothing here logs, returns in an error, or stores a
14
+ // value; warnings name the variable and the settings layer only.
15
+ //
16
+ // Protected names (lib/runtime-env-keys.js) are refused when saved and dropped
17
+ // when built, so a text saved before a name was protected cannot reach a
18
+ // runtime either. That list is defense in depth. What keeps one user's text
19
+ // from another user's runtime is projectEnvApplies: in multi-user mode a
20
+ // project's text reaches only sessions of the project's owner.
21
+
22
+ var crypto = require("crypto");
23
+ var protectedKeys = require("./runtime-env-keys");
24
+
25
+ var KEY_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
26
+ var SHELL_META_RE = /[`$\\;|&><(){}\n]/;
27
+ var QUOTED_RE = /^["'].*["']$/;
28
+ // Characters an environment string cannot carry; refused when saved and dropped
29
+ // when built, in names and values alike.
30
+ var UNREPRESENTABLE_RE = /[\0\r]/;
31
+ var EXPORT_PREFIX_RE = /^export\s+/;
32
+
33
+ var _warned = new Set();
34
+
35
+ function unquote(value) {
36
+ if (value.length >= 2) {
37
+ var first = value.charAt(0);
38
+ if ((first === '"' || first === "'") && value.charAt(value.length - 1) === first) {
39
+ return value.substring(1, value.length - 1);
40
+ }
41
+ }
42
+ return value;
43
+ }
44
+
45
+ // Reads a KEY=VALUE text, one assignment per line. Blank lines and lines
46
+ // starting with # are skipped. Returns the assignments that are well formed
47
+ // and, in line order, every problem found (a malformed line, or a protected
48
+ // name).
49
+ function scanEnvText(text) {
50
+ var entries = [];
51
+ var issues = [];
52
+ if (typeof text !== "string" || !text.trim()) return { entries: entries, issues: issues };
53
+ var lines = text.split("\n");
54
+ for (var i = 0; i < lines.length; i++) {
55
+ var line = lines[i].trim();
56
+ if (!line || line.charAt(0) === "#") continue;
57
+ // NUL ends an environment string early in the process that receives it and
58
+ // CR is not part of any name or value a user means; either one anywhere on
59
+ // the line is refused whatever the quoting.
60
+ if (UNREPRESENTABLE_RE.test(lines[i])) {
61
+ issues.push({ line: i + 1, kind: "format", message: "Invalid character at line " + (i + 1) + ": NUL and carriage return are not allowed" });
62
+ continue;
63
+ }
64
+ // The Settings pages write every row as "export KEY=VALUE" and read it
65
+ // back with the prefix stripped, so that is the form that arrives here.
66
+ line = line.replace(EXPORT_PREFIX_RE, "");
67
+ var eqIdx = line.indexOf("=");
68
+ if (eqIdx < 1) {
69
+ issues.push({ line: i + 1, kind: "format", message: "Invalid format at line " + (i + 1) + ": expected KEY=VALUE" });
70
+ continue;
71
+ }
72
+ var key = line.substring(0, eqIdx);
73
+ if (!KEY_RE.test(key)) {
74
+ issues.push({ line: i + 1, kind: "format", message: "Invalid variable name at line " + (i + 1) + ": " + key });
75
+ continue;
76
+ }
77
+ var value = line.substring(eqIdx + 1);
78
+ if (SHELL_META_RE.test(value) && !QUOTED_RE.test(value)) {
79
+ issues.push({ line: i + 1, kind: "format", message: "Potentially unsafe value at line " + (i + 1) + ": shell metacharacters detected" });
80
+ continue;
81
+ }
82
+ var cls = protectedKeys.protectedClassOf(key);
83
+ if (cls) {
84
+ issues.push({
85
+ line: i + 1,
86
+ kind: "protected",
87
+ key: key,
88
+ protectedClass: cls.name,
89
+ message: "Line " + (i + 1) + ": " + key + " cannot be set here. It is protected because it controls " +
90
+ cls.description + ". Remove the line to save.",
91
+ });
92
+ continue;
93
+ }
94
+ entries.push({ line: i + 1, key: key, value: unquote(value) });
95
+ }
96
+ return { entries: entries, issues: issues };
97
+ }
98
+
99
+ /**
100
+ * Save-time check of one environment text. Returns null when it may be saved,
101
+ * or the message to show the user. Refuses malformed lines and protected names.
102
+ * @param {string} text
103
+ * @returns {string|null}
104
+ */
105
+ function validateEnvText(text) {
106
+ var scanned = scanEnvText(text);
107
+ return scanned.issues.length ? scanned.issues[0].message : null;
108
+ }
109
+
110
+ function warnOnce(warned, warn, dedupeKey, message) {
111
+ if (warned.has(dedupeKey)) return;
112
+ warned.add(dedupeKey);
113
+ warn(message);
114
+ }
115
+
116
+ /**
117
+ * The variables the settings add to a runtime's environment.
118
+ *
119
+ * @param {Array<{label: string, text: string}>} layers Lowest precedence
120
+ * first (shared, then project); a later layer overrides an earlier one.
121
+ * @param {object} [opts]
122
+ * @param {function} [opts.warn=console.warn]
123
+ * @param {Set} [opts.warned] Dedup set, so a protected name is reported once.
124
+ * @returns {object} variable name -> value, protected names removed
125
+ */
126
+ function buildRuntimeEnvOverlay(layers, opts) {
127
+ opts = opts || {};
128
+ var warn = opts.warn || console.warn;
129
+ var warned = opts.warned || _warned;
130
+ var overlay = {};
131
+ (layers || []).forEach(function (layer) {
132
+ var label = (layer && layer.label) || "settings";
133
+ var scanned = scanEnvText(layer && layer.text);
134
+ scanned.issues.forEach(function (issue) {
135
+ if (issue.kind === "protected") {
136
+ warnOnce(warned, warn, label + "\0" + issue.key,
137
+ "[runtime-env] ignoring " + issue.key + " in " + label + " environment settings: protected (" +
138
+ issue.protectedClass + "); remove it in Settings");
139
+ } else {
140
+ warnOnce(warned, warn, label + "\0line" + issue.line + "\0" + issue.kind,
141
+ "[runtime-env] ignoring a malformed line (" + issue.line + ") in " + label + " environment settings");
142
+ }
143
+ });
144
+ scanned.entries.forEach(function (entry) {
145
+ overlay[entry.key] = entry.value;
146
+ });
147
+ });
148
+ return overlay;
149
+ }
150
+
151
+ /**
152
+ * The complete environment for a runtime: base, then overlay. Protected names
153
+ * in the overlay are dropped here as well, so a caller that hands in an
154
+ * overlay it did not build through buildRuntimeEnvOverlay cannot override them.
155
+ *
156
+ * @param {object} base the runtime's own environment (process.env, or the
157
+ * OS user's worker environment)
158
+ * @param {object} overlay variables to add
159
+ * @param {object} [opts] same as buildRuntimeEnvOverlay
160
+ * @returns {object} a new object; base is not modified
161
+ */
162
+ function composeRuntimeEnv(base, overlay, opts) {
163
+ opts = opts || {};
164
+ var warn = opts.warn || console.warn;
165
+ var warned = opts.warned || _warned;
166
+ var env = {};
167
+ var baseNames = Object.keys(base || {});
168
+ for (var i = 0; i < baseNames.length; i++) {
169
+ if (typeof base[baseNames[i]] === "string") env[baseNames[i]] = base[baseNames[i]];
170
+ }
171
+ var names = Object.keys(overlay || {});
172
+ for (var j = 0; j < names.length; j++) {
173
+ var name = names[j];
174
+ if (typeof overlay[name] !== "string") continue;
175
+ if (UNREPRESENTABLE_RE.test(name) || UNREPRESENTABLE_RE.test(overlay[name])) {
176
+ warnOnce(warned, warn, "runtime\0unrepresentable\0" + name.replace(UNREPRESENTABLE_RE, "?"),
177
+ "[runtime-env] ignoring a variable handed to a runtime: NUL or carriage return in its name or value");
178
+ continue;
179
+ }
180
+ var cls = protectedKeys.protectedClassOf(name);
181
+ if (cls) {
182
+ warnOnce(warned, warn, "runtime\0" + name,
183
+ "[runtime-env] ignoring " + name + " handed to a runtime: protected (" + cls.name + ")");
184
+ continue;
185
+ }
186
+ env[name] = overlay[name];
187
+ }
188
+ return env;
189
+ }
190
+
191
+ /**
192
+ * Whether a project's environment text applies to a session.
193
+ *
194
+ * Single-user: always. Multi-user: only to a session owned by the project's
195
+ * owner, because the owner writes the text and a variable such as a base URL
196
+ * or a tool-options variable would otherwise redirect or run code in another
197
+ * user's session. A list of refused names cannot close that, so the text is
198
+ * simply never handed to anyone else. Shared settings are administrator-only
199
+ * and are not subject to this. Anything but an explicit multiUser === false is
200
+ * treated as multi-user, and a missing owner on either side applies to no one.
201
+ *
202
+ * @param {{multiUser: boolean, projectOwnerId: string|null, sessionOwnerId: string|null}} scope
203
+ * @returns {boolean}
204
+ */
205
+ function projectEnvApplies(scope) {
206
+ if (scope && scope.multiUser === false) return true;
207
+ if (!scope || !scope.projectOwnerId || !scope.sessionOwnerId) return false;
208
+ return scope.projectOwnerId === scope.sessionOwnerId;
209
+ }
210
+
211
+ function hasOverlay(overlay) {
212
+ return !!overlay && Object.keys(overlay).length > 0;
213
+ }
214
+
215
+ /**
216
+ * A digest of an overlay, so a runtime started with one can be told from a
217
+ * later settings change without keeping the values. Empty overlay -> "".
218
+ */
219
+ function envSignature(overlay) {
220
+ var names = Object.keys(overlay || {}).sort();
221
+ if (names.length === 0) return "";
222
+ var hash = crypto.createHash("sha256");
223
+ for (var i = 0; i < names.length; i++) {
224
+ hash.update(names[i] + "\0" + overlay[names[i]] + "\0");
225
+ }
226
+ return hash.digest("hex");
227
+ }
228
+
229
+ module.exports = {
230
+ validateEnvText: validateEnvText,
231
+ buildRuntimeEnvOverlay: buildRuntimeEnvOverlay,
232
+ composeRuntimeEnv: composeRuntimeEnv,
233
+ projectEnvApplies: projectEnvApplies,
234
+ hasOverlay: hasOverlay,
235
+ envSignature: envSignature,
236
+ };