@clagentic/console 1.11.0-beta.1 → 1.11.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +0 -1
  2. package/bin/cli.js +24 -14
  3. package/lib/bash-auto-approve.js +1 -1
  4. package/lib/build-sha.json +2 -2
  5. package/lib/cli/arg-validation.js +50 -0
  6. package/lib/cli/daemon-launch.js +5 -4
  7. package/lib/cli/menus.js +2 -2
  8. package/lib/cli/session-subcommands.js +3 -2
  9. package/lib/daemon.js +18 -1
  10. package/lib/identity/index.js +9 -4
  11. package/lib/permission-mode-policy.js +2 -2
  12. package/lib/permission-settings.js +96 -0
  13. package/lib/project-connection.js +9 -11
  14. package/lib/project-loop.js +24 -3
  15. package/lib/project-permission-settings.js +59 -0
  16. package/lib/project-prompt-responses.js +7 -3
  17. package/lib/project-sessions.js +93 -41
  18. package/lib/project.js +11 -13
  19. package/lib/public/app.js +1 -2
  20. package/lib/public/css/overlays.css +0 -3
  21. package/lib/public/css/scheduler-modal.css +5 -0
  22. package/lib/public/index.html +44 -8
  23. package/lib/public/modules/app-loop-ui.js +11 -1
  24. package/lib/public/modules/app-messages.js +4 -13
  25. package/lib/public/modules/app-panels.js +1 -1
  26. package/lib/public/modules/app-rate-limit.js +1 -1
  27. package/lib/public/modules/approve-tools-toggle.js +33 -0
  28. package/lib/public/modules/loop-hooks-warning.js +20 -0
  29. package/lib/public/modules/mode-options.js +16 -0
  30. package/lib/public/modules/permission-settings.js +56 -0
  31. package/lib/public/modules/project-settings.js +3 -0
  32. package/lib/public/modules/scheduler-config.js +12 -0
  33. package/lib/public/modules/scheduler.js +8 -0
  34. package/lib/public/modules/server-settings.js +5 -9
  35. package/lib/public/modules/settings-defaults.js +18 -4
  36. package/lib/scheduler.js +4 -0
  37. package/lib/sdk-bridge.js +74 -40
  38. package/lib/server.js +9 -3
  39. package/lib/session-input-ipc.js +1 -0
  40. package/lib/session-input.js +41 -4
  41. package/lib/session-resume.js +2 -0
  42. package/lib/sessions.js +67 -2
  43. package/lib/updater.js +8 -2
  44. package/lib/ws-schema.js +5 -2
  45. package/lib/yoke/adapters/claude.js +0 -10
  46. package/package.json +1 -1
package/README.md CHANGED
@@ -107,7 +107,6 @@ npx @clagentic/console --add . # Add current directory to running daemon
107
107
  npx @clagentic/console --remove . # Remove project
108
108
  npx @clagentic/console --list # List registered projects
109
109
  npx @clagentic/console --shutdown # Stop daemon
110
- npx @clagentic/console --dangerously-skip-permissions
111
110
  ```
112
111
 
113
112
  Also available as `clagentic-console` if installed globally.
package/bin/cli.js CHANGED
@@ -43,6 +43,12 @@ var args = process.argv.slice(2);
43
43
  // start exits 78 (EX_CONFIG), which the unit lists in RestartPreventExitStatus
44
44
  // so a mis-installed package is not restart-looped.
45
45
  if (args[0] === "daemon") {
46
+ // The documented form takes no further tokens. 78, not 1: the unit lists 78 in
47
+ // RestartPreventExitStatus, so a mis-edited ExecStart is refused once, not looped.
48
+ if (args.length > 1) {
49
+ console.error(require("../lib/cli/arg-validation").unrecognisedArgMessage(args[1]));
50
+ process.exit(78);
51
+ }
46
52
  var { findLinkTrap, linkTrapMessage, LinkTrapProbeError } = require("../lib/link-trap");
47
53
  var linkTrap = null;
48
54
  try {
@@ -65,7 +71,10 @@ if (args[0] === "daemon") {
65
71
  // Positional subcommand, handled before flag parsing: `clagentic-console release list-betas`.
66
72
  if (args[0] === "release") {
67
73
  var releaseSub = args[1];
68
- if (releaseSub === "list-betas") {
74
+ if (releaseSub === "list-betas" && args.length > 2) {
75
+ console.error(require("../lib/cli/arg-validation").unrecognisedArgMessage(args[2]));
76
+ process.exit(1);
77
+ } else if (releaseSub === "list-betas") {
69
78
  var releaseList = require("../lib/release-list");
70
79
  var betasResult = releaseList.readBetasFile(process.cwd());
71
80
  var betasLines = releaseList.formatBetasOutput(betasResult);
@@ -108,13 +117,20 @@ var removePath = null;
108
117
  var listMode = false;
109
118
  var activityDiagnosticsMode = false;
110
119
  var processBuildStatusMode = false;
111
- var dangerouslySkipPermissions = false;
112
120
  var headlessMode = false;
113
121
  var watchMode = false;
114
122
  var host = null;
115
123
  var multiUserMode = false;
116
124
  var osUsersMode = false;
117
125
 
126
+ // Reject unknown words/flags before any action runs (no IPC, no daemon fork).
127
+ var { findUnrecognisedArg, unrecognisedArgMessage } = require("../lib/cli/arg-validation");
128
+ var _badArg = findUnrecognisedArg(args);
129
+ if (_badArg !== null) {
130
+ console.error(unrecognisedArgMessage(_badArg));
131
+ process.exit(1);
132
+ }
133
+
118
134
  for (var i = 0; i < args.length; i++) {
119
135
  if (args[i] === "-p" || args[i] === "--port") {
120
136
  port = parseInt(args[i + 1], 10);
@@ -165,7 +181,8 @@ for (var i = 0; i < args.length; i++) {
165
181
  headlessMode = true;
166
182
  autoYes = true;
167
183
  } else if (args[i] === "--dangerously-skip-permissions") {
168
- dangerouslySkipPermissions = true;
184
+ console.error("clagentic-console: --dangerously-skip-permissions has been removed. Tool approval follows each agent's own permission settings; Clagentic: Console does not bypass it.");
185
+ process.exit(1);
169
186
  } else if (args[i] === "--multi-user") {
170
187
  multiUserMode = true;
171
188
  } else if (args[i] === "--os-users") {
@@ -177,7 +194,7 @@ for (var i = 0; i < args.length; i++) {
177
194
  console.log(" clagentic-console --list List registered projects");
178
195
  console.log(" clagentic-console --activity-diagnostics Print activity-divergence probe totals as JSON (agent-readable)");
179
196
  console.log(" clagentic-console --process-build-status Print the running process's loaded build SHA as JSON (agent-readable)");
180
- console.log(" clagentic-console open-session (--project <slug> | --to <address>) --prompt <text|-> [--vendor <id>] [--agent <name>] [--name <session-name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>] Open a session and run a first prompt (prints JSON)");
197
+ console.log(" clagentic-console open-session (--project <slug> | --to <address>) --prompt <text|-> [--vendor <id>] [--agent <name>] [--name <session-name>] [--visibility shared|private] [--permission-mode <mode>] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>] Open a session and run a first prompt (prints JSON)");
181
198
  console.log(" clagentic-console send-input (--project <slug> --session <id> | --to <address> | --reply) --prompt <text|-> [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>] Send input to a session, resuming it if needed (prints JSON; exit 3 ambiguous, 4 not found by address)");
182
199
  console.log(" clagentic-console list-sessions [--project <slug>] [--agent <name>] [--vendor <id>] [--state live|idle|reaped|any] List the console's sessions (prints JSON)");
183
200
  console.log(" clagentic-console schedule-input create --session <id> [--project <slug>] (--in <dur> | --at <time> | --every <dur> (--until <time> | --count <n>)) (--prompt <text|-> | --prompt-file <path>) Send text into a session later, once or on a repeat with an end (prints JSON)");
@@ -209,8 +226,6 @@ for (var i = 0; i < args.length; i++) {
209
226
  console.log(" --headless Start daemon and exit immediately (implies --yes)");
210
227
  console.log(" --multi-user Start in multi-user mode (use with --yes for headless)");
211
228
  console.log(" --os-users Enable OS-level user isolation (Linux, requires root + --multi-user)");
212
- console.log(" --dangerously-skip-permissions");
213
- console.log(" Bypass all permission prompts");
214
229
  process.exit(0);
215
230
  }
216
231
  }
@@ -280,7 +295,6 @@ function currentCliOpts() {
280
295
  forceMkcert: forceMkcert,
281
296
  debugMode: debugMode,
282
297
  headlessMode: headlessMode,
283
- dangerouslySkipPermissions: dangerouslySkipPermissions,
284
298
  osUsersMode: osUsersMode,
285
299
  cliPin: cliPin,
286
300
  watchMode: watchMode,
@@ -330,7 +344,7 @@ var currentVersion = require("../package.json").version;
330
344
  setup(function (mode, keepAwake, wantOsUsers, chosenPort) {
331
345
  port = chosenPort;
332
346
  devMode(mode, keepAwake, null, wantOsUsers, currentCliOpts());
333
- }, port, { host: host, dangerouslySkipPermissions: dangerouslySkipPermissions });
347
+ }, port, { host: host });
334
348
  } else {
335
349
  // Reuse existing config (repeat run)
336
350
  await devMode(devConfig.mode || "single", devConfig.keepAwake || false, devConfig.pinHash || null, devConfig.osUsers || false, currentCliOpts());
@@ -460,8 +474,7 @@ var currentVersion = require("../package.json").version;
460
474
 
461
475
  if (savedConfig && savedConfig.port) port = savedConfig.port;
462
476
  if (savedConfig && savedConfig.host) host = savedConfig.host;
463
- if (savedConfig && savedConfig.dangerouslySkipPermissions) dangerouslySkipPermissions = true;
464
- // Re-sync: port/host/dangerouslySkipPermissions above may have just
477
+ // Re-sync: port/host above may have just
465
478
  // changed after the initial setDaemonWatcherOpts() call at module
466
479
  // load — keep the crash-watcher/getCliOpts() snapshot current so a
467
480
  // later crash-restart or "re-run setup" re-fork doesn't use stale values.
@@ -470,9 +483,6 @@ var currentVersion = require("../package.json").version;
470
483
  if (autoYes) {
471
484
  console.log(" " + sym.done + " Auto-accepted disclaimer");
472
485
  console.log(" " + sym.done + " Mode: " + savedMode);
473
- if (dangerouslySkipPermissions) {
474
- console.log(" " + sym.warn + " " + a.yellow + "Skip permissions mode enabled" + a.reset);
475
- }
476
486
  }
477
487
 
478
488
  var autoRc = loadClayrc();
@@ -511,7 +521,7 @@ var currentVersion = require("../package.json").version;
511
521
  log("");
512
522
  forkDaemon(mode, keepAwake, undefined, true, wantOsUsers, currentCliOpts());
513
523
  }
514
- }, port, { host: host, dangerouslySkipPermissions: dangerouslySkipPermissions });
524
+ }, port, { host: host });
515
525
  }
516
526
  }
517
527
  })();
@@ -63,7 +63,7 @@ var COMMANDS = {
63
63
  od: { opts: opts("-c -x") }, hexdump: { opts: opts("-C") },
64
64
  // Misc read-only
65
65
  test: { opts: opts("-e -f -d -r -w -x -s -z -n") }, "true": {}, "false": {}, seq: {},
66
- sleep: {}, help: {}, apropos: {},
66
+ help: {}, apropos: {},
67
67
  cal: { opts: opts("-y") }, bc: { opts: opts("-l") }, expr: {}, factor: {},
68
68
  lsof: { opts: opts("-i -n -P") },
69
69
  ps: { opts: opts("-e -f -ef -A") },
@@ -1,4 +1,4 @@
1
1
  {
2
- "sha": "a4cb5e209eda16dbb89bf60fa906daf6c9ad402a",
3
- "writtenAt": "2026-10-23T12:30:14.423Z"
2
+ "sha": "5933d0c3d1e21fbe7af541057983cc4c0c879276",
3
+ "writtenAt": "2026-10-23T20:53:39.484Z"
4
4
  }
@@ -0,0 +1,50 @@
1
+ // lib/cli/arg-validation.js
2
+ //
3
+ // Rejects CLI arguments that bin/cli.js's flag loop does not recognise, so an
4
+ // unknown leading word or flag fails with a usage error instead of falling
5
+ // through to daemon control (--shutdown, --restart, ...) or a daemon start.
6
+ // Kept as a pure function so it is testable without spawning the CLI.
7
+
8
+ // Flags that take no value.
9
+ var BOOLEAN_FLAGS = [
10
+ "--no-https", "--local-cert", "--no-update", "--skip-update", "--dev",
11
+ "--watch", "-w", "--debug", "-y", "--yes", "--shutdown", "--restart",
12
+ "--no-restart", "--list", "--activity-diagnostics", "--process-build-status",
13
+ "--headless", "--multi-user", "--os-users",
14
+ // Removed flag: the flag loop prints its own dedicated message and exits 1.
15
+ "--dangerously-skip-permissions",
16
+ ];
17
+
18
+ // Flags that consume the next argument as their value, whatever it looks like.
19
+ var VALUE_FLAGS = ["-p", "--port", "--host", "--bind", "--pin", "--add", "--remove"];
20
+
21
+ var HELP_FLAGS = ["-h", "--help"];
22
+
23
+ /**
24
+ * Returns the first argument that is neither a known flag nor a flag's
25
+ * consumed value, or null when every argument is recognised. Scanning stops at
26
+ * -h/--help, which prints usage and exits before any later token is acted on.
27
+ */
28
+ function findUnrecognisedArg(args) {
29
+ for (var i = 0; i < args.length; i++) {
30
+ var arg = args[i];
31
+ if (HELP_FLAGS.indexOf(arg) !== -1) return null;
32
+ if (VALUE_FLAGS.indexOf(arg) !== -1) {
33
+ i++;
34
+ continue;
35
+ }
36
+ if (BOOLEAN_FLAGS.indexOf(arg) !== -1) continue;
37
+ return arg;
38
+ }
39
+ return null;
40
+ }
41
+
42
+ function unrecognisedArgMessage(arg) {
43
+ return "clagentic-console: unrecognised argument '" + arg + "'\n" +
44
+ "Run 'clagentic-console --help' for usage.";
45
+ }
46
+
47
+ module.exports = {
48
+ findUnrecognisedArg: findUnrecognisedArg,
49
+ unrecognisedArgMessage: unrecognisedArgMessage,
50
+ };
@@ -243,7 +243,7 @@ async function restartDaemonFromConfig(opts) {
243
243
  // ==============================
244
244
  /**
245
245
  * `cliOpts`: { port, useHttps, forceMkcert, debugMode, headlessMode,
246
- * dangerouslySkipPermissions, osUsersMode, cliPin, cwd } — the subset of
246
+ * osUsersMode, cliPin, cwd } — the subset of
247
247
  * parsed CLI flags that shape daemon startup. Passed explicitly since this
248
248
  * module no longer owns arg parsing (that stays in bin/cli.js).
249
249
  */
@@ -359,12 +359,13 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers, c
359
359
  debug: cliOpts.debugMode,
360
360
  headless: cliOpts.headlessMode,
361
361
  keepAwake: keepAwake,
362
- dangerouslySkipPermissions: cliOpts.dangerouslySkipPermissions,
363
362
  osUsers: wantOsUsers || cliOpts.osUsersMode,
364
363
  mode: mode || "multi",
365
364
  setupCompleted: true,
366
365
  projects: allProjects,
367
366
  });
367
+ // A key left by an older release is dead; drop it when the file is rewritten.
368
+ delete config.dangerouslySkipPermissions;
368
369
 
369
370
  ensureConfigDir();
370
371
  saveConfig(config);
@@ -446,7 +447,7 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers, c
446
447
  // Dev mode — foreground daemon with file watching
447
448
  // ==============================
448
449
  /**
449
- * `cliOpts`: { port, useHttps, dangerouslySkipPermissions, watchMode,
450
+ * `cliOpts`: { port, useHttps, watchMode,
450
451
  * noRestart, cwd }.
451
452
  */
452
453
  async function devMode(mode, keepAwake, existingPinHash, wantOsUsers, cliOpts) {
@@ -544,12 +545,12 @@ async function devMode(mode, keepAwake, existingPinHash, wantOsUsers, cliOpts) {
544
545
  mkcertDetected: mkcertDetected,
545
546
  debug: true,
546
547
  keepAwake: keepAwake || false,
547
- dangerouslySkipPermissions: cliOpts.dangerouslySkipPermissions,
548
548
  mode: mode || "multi",
549
549
  setupCompleted: true,
550
550
  projects: allProjects,
551
551
  osUsers: wantOsUsers || (prevDevConfig ? (prevDevConfig.osUsers || false) : false),
552
552
  });
553
+ delete config.dangerouslySkipPermissions;
553
554
 
554
555
  ensureConfigDir();
555
556
  saveConfig(config);
package/lib/cli/menus.js CHANGED
@@ -78,7 +78,7 @@ function promptRestoreProjects(projects, callback) {
78
78
  // ==============================
79
79
  /**
80
80
  * `defaultPort` seeds the port prompt (mirrors the CLI's --port / default
81
- * value). `cliOpts`: { host, dangerouslySkipPermissions } — preserved onto
81
+ * value). `cliOpts`: { host } — preserved onto
82
82
  * the config when OS-user isolation is requested without root, mirroring
83
83
  * the original bin/cli.js behavior of reading those from parsed CLI flags.
84
84
  */
@@ -197,7 +197,7 @@ function setup(callback, defaultPort, cliOpts) {
197
197
  existingCfg.mode = "multi";
198
198
  existingCfg.osUsers = true;
199
199
  existingCfg.setupCompleted = true;
200
- if (cliOpts.dangerouslySkipPermissions) existingCfg.dangerouslySkipPermissions = true;
200
+ delete existingCfg.dangerouslySkipPermissions;
201
201
  saveConfig(existingCfg);
202
202
  log(sym.bar);
203
203
  log(sym.warn + " " + a.yellow + "OS user isolation requires root." + a.reset);
@@ -32,6 +32,7 @@ var FLAGS = {
32
32
  "--name": "sessionName",
33
33
  "--state": "state",
34
34
  "--visibility": "sessionVisibility",
35
+ "--permission-mode": "permissionMode",
35
36
  "--initiator": "initiator",
36
37
  "--context-note": "contextNote",
37
38
  "--from": "from",
@@ -45,13 +46,13 @@ var SWITCHES = {
45
46
  };
46
47
 
47
48
  var USAGE = {
48
- "open-session": "Usage: clagentic-console open-session (--project <slug> | --to <address>) --prompt <text|-> [--vendor <id>] [--agent <name>] [--name <session-name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>]",
49
+ "open-session": "Usage: clagentic-console open-session (--project <slug> | --to <address>) --prompt <text|-> [--vendor <id>] [--agent <name>] [--name <session-name>] [--visibility shared|private] [--permission-mode <mode>] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>]",
49
50
  "send-input": "Usage: clagentic-console send-input (--project <slug> --session <id> | --to <address> | --reply) --prompt <text|-> [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>]",
50
51
  "list-sessions": "Usage: clagentic-console list-sessions [--project <slug>] [--agent <name>] [--vendor <id>] [--state live|idle|reaped|any]",
51
52
  };
52
53
 
53
54
  var ALLOWED = {
54
- "open-session": ["projectSlug", "to", "prompt", "vendor", "agentName", "sessionName", "sessionVisibility", "initiator", "contextNote", "from", "fromSession"],
55
+ "open-session": ["projectSlug", "to", "prompt", "vendor", "agentName", "sessionName", "sessionVisibility", "permissionMode", "initiator", "contextNote", "from", "fromSession"],
55
56
  "send-input": ["projectSlug", "sessionId", "to", "reply", "prompt", "initiator", "contextNote", "from", "fromSession"],
56
57
  "list-sessions": ["projectSlug", "agentName", "vendor", "state"],
57
58
  };
package/lib/daemon.js CHANGED
@@ -40,6 +40,7 @@ var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
40
40
  var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, buildActivityDiagnosticsResponse } = require("./sdk-bridge");
41
41
  var { validateMemAvailableThresholdMB, validateTokensPerMbHeadroom } = require("./memory-setting-validate");
42
42
  var { startMemoryHighWatcher, checkAppliedMemoryCeiling } = require("./memory-limits");
43
+ var { readPermissionSettings, DEFAULT_OPENED_SESSION_MODE } = require("./permission-settings");
43
44
  var { createDrain } = require("./drain");
44
45
  var { setNewWorkGate } = require("./new-work-gate");
45
46
  var { shedMemory } = require("./memory-shed");
@@ -303,7 +304,6 @@ var relay = createServer({
303
304
  allowedOrigins: Array.isArray(config.allowedOrigins) ? config.allowedOrigins : [],
304
305
  port: config.port,
305
306
  debug: config.debug || false,
306
- dangerouslySkipPermissions: config.dangerouslySkipPermissions || false,
307
307
  osUsers: config.osUsers || false,
308
308
  lanHost: lanIp ? lanIp + ":" + config.port : null,
309
309
  // lr-2ea2a7: optional daemon.json override for the in-heap session-history
@@ -1030,6 +1030,23 @@ var relay = createServer({
1030
1030
  saveConfig(config);
1031
1031
  return { ok: true };
1032
1032
  },
1033
+ onGetPermissionSettings: function () {
1034
+ return readPermissionSettings(config);
1035
+ },
1036
+ onSetPermissionSettings: function (values) {
1037
+ // Stored as given; a value equal to its default is removed so daemon.json
1038
+ // keeps showing only what an administrator changed.
1039
+ if (values.autoApproveReadOnly !== undefined) {
1040
+ if (values.autoApproveReadOnly === false) config.autoApproveReadOnly = false;
1041
+ else delete config.autoApproveReadOnly;
1042
+ }
1043
+ if (values.openedSessionMode !== undefined) {
1044
+ if (values.openedSessionMode === DEFAULT_OPENED_SESSION_MODE) delete config.openedSessionMode;
1045
+ else config.openedSessionMode = values.openedSessionMode;
1046
+ }
1047
+ saveConfig(config);
1048
+ return { ok: true, settings: readPermissionSettings(config) };
1049
+ },
1033
1050
  onGetProjectDefaultMode: function (slug) {
1034
1051
  for (var i = 0; i < config.projects.length; i++) {
1035
1052
  if (config.projects[i].slug === slug) {
@@ -39,19 +39,19 @@ var PROVIDER_TIMEOUT_MS = 15000;
39
39
  // { timedOut } it did not answer within `ms`
40
40
  // When the limit wins, onTimeout(pending) runs so the caller can cancel the
41
41
  // provider and claim whatever it yields later.
42
- function askProvider(call, ms, onTimeout) {
42
+ function askProvider(call, ms, onTimeout, timers) {
43
43
  var pending = new Promise(function (resolve) { resolve(call()); });
44
44
  return new Promise(function (resolve) {
45
45
  var settled = false;
46
46
  function settle(outcome) {
47
47
  if (settled) return;
48
48
  settled = true;
49
- clearTimeout(timer);
49
+ timers.clearTimeout(timer);
50
50
  resolve(outcome);
51
51
  }
52
52
  // The limit is decided before onTimeout runs: cancelling the provider can
53
53
  // settle its own promise synchronously, and that must not outrank the timeout.
54
- var timer = setTimeout(function () {
54
+ var timer = timers.setTimeout(function () {
55
55
  settle({ timedOut: true });
56
56
  onTimeout(pending);
57
57
  }, ms);
@@ -90,8 +90,12 @@ function declaredLease(origin, result) {
90
90
  // test can make a provider settle late, and nothing in the console sets it.
91
91
  // options.releaseTimeoutMs bounds how long a provider's release is waited on for a
92
92
  // warning; it exists for the same reason.
93
+ // options.timers ({ setTimeout, clearTimeout }) replaces the clock that decides the
94
+ // provider limit, so a test can fire the limit at a chosen moment instead of racing
95
+ // a provider against wall-clock time; nothing in the console sets it.
93
96
  function createIdentity(options) {
94
97
  var warn = options.warn || console.warn;
98
+ var timers = options.timers || { setTimeout: setTimeout, clearTimeout: clearTimeout };
95
99
  var providerTimeoutMs = options.providerTimeoutMs > 0 ? options.providerTimeoutMs : PROVIDER_TIMEOUT_MS;
96
100
  var current = { key: null, cfg: null, provider: null };
97
101
 
@@ -175,7 +179,8 @@ function createIdentity(options) {
175
179
  holder.end(null);
176
180
  warn("[identity] the provider failed after the console stopped waiting: " + (err && err.message));
177
181
  });
178
- }
182
+ },
183
+ timers
179
184
  );
180
185
  var result;
181
186
  if (answer.timedOut) {
@@ -4,8 +4,8 @@
4
4
  // place a mode enters the server: the per-session, project-default and
5
5
  // server-default setters, a loop's mode at query start, and a saved default
6
6
  // read at load. A mode is accepted only when the vendor can run it AND the
7
- // server allows it; bypassPermissions is accepted only while the server's
8
- // skip-permissions setting is on.
7
+ // server allows it; bypassPermissions is accepted only when a caller passes
8
+ // skipPermissionsAllowed: true, and no caller in the server does.
9
9
 
10
10
  var { ownValue } = require("./prompt-kinds/codecs");
11
11
 
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ // The server-wide permission settings an administrator may change. Each default
4
+ // equals the behaviour before the setting existed, so nothing changes until a
5
+ // person changes it. Stored in daemon.json beside the other server settings;
6
+ // read at decision time, so a change needs no restart.
7
+
8
+ var { ownValue } = require("./prompt-kinds/codecs");
9
+
10
+ var DEFAULT_OPENED_SESSION_MODE = "acceptEdits";
11
+
12
+ // The setting names a client may send, each with its type check. Anything else
13
+ // in a request is refused rather than stored.
14
+ var SETTING_TYPES = {
15
+ autoApproveReadOnly: function (v) { return typeof v === "boolean"; },
16
+ openedSessionMode: function (v) { return typeof v === "string" && v.length > 0; },
17
+ };
18
+
19
+ /**
20
+ * @param {?object} config - the daemon configuration (daemon.json contents).
21
+ * @returns {{autoApproveReadOnly: boolean, openedSessionMode: string}}
22
+ */
23
+ function readPermissionSettings(config) {
24
+ var cfg = config || {};
25
+ return {
26
+ // Only an explicit false turns it off: an absent field is today's behaviour.
27
+ autoApproveReadOnly: cfg.autoApproveReadOnly !== false,
28
+ openedSessionMode: typeof cfg.openedSessionMode === "string" && cfg.openedSessionMode
29
+ ? cfg.openedSessionMode
30
+ : DEFAULT_OPENED_SESSION_MODE,
31
+ };
32
+ }
33
+
34
+ /**
35
+ * The fields of a change request that name a known setting with a value of the
36
+ * right type; nothing else passes. `rejected` lists the names that did not.
37
+ * @returns {{values: object, rejected: string[]}}
38
+ */
39
+ function pickSettingChanges(request) {
40
+ var values = {};
41
+ var rejected = [];
42
+ Object.keys(request || {}).forEach(function (name) {
43
+ if (name === "type") return;
44
+ var check = ownValue(SETTING_TYPES, name);
45
+ if (typeof check === "function" && check(request[name])) values[name] = request[name];
46
+ else rejected.push(name);
47
+ });
48
+ return { values: values, rejected: rejected };
49
+ }
50
+
51
+ /**
52
+ * The mode a session opened by the CLI or a trigger starts in. Precedence: the
53
+ * open request's own mode, then the server setting, then accept edits.
54
+ *
55
+ * A mode the request names that fails the check refuses the open (the caller
56
+ * asked for it by name). A stored setting that fails it falls back to accept
57
+ * edits: it was valid when saved and may have stopped being so (a vendor
58
+ * change).
59
+ *
60
+ * @param {object} args
61
+ * @param {*} args.requested - the open request's mode, or undefined/null.
62
+ * @param {string} args.setting - the server setting's value.
63
+ * @param {function(string): {ok: boolean, error: ?string}} args.check - the shared mode check
64
+ * for the vendor the session will run on.
65
+ * @param {function(string): void} [args.onFallback] - told why the stored setting was not used.
66
+ * @returns {{mode: string}|{error: string}}
67
+ */
68
+ function resolveOpenedSessionMode(args) {
69
+ if (args.requested !== undefined && args.requested !== null) {
70
+ var asked = args.check(args.requested);
71
+ return asked.ok ? { mode: args.requested } : { error: asked.error };
72
+ }
73
+ if (args.setting && args.setting !== DEFAULT_OPENED_SESSION_MODE) {
74
+ var stored = args.check(args.setting);
75
+ if (stored.ok) return { mode: args.setting };
76
+ if (args.onFallback) args.onFallback(stored.error);
77
+ }
78
+ return { mode: DEFAULT_OPENED_SESSION_MODE };
79
+ }
80
+
81
+ /** The wire message that tells a client the current settings. */
82
+ function settingsMessage(settings) {
83
+ return {
84
+ type: "permission_settings",
85
+ autoApproveReadOnly: settings.autoApproveReadOnly,
86
+ openedSessionMode: settings.openedSessionMode,
87
+ };
88
+ }
89
+
90
+ module.exports = {
91
+ DEFAULT_OPENED_SESSION_MODE: DEFAULT_OPENED_SESSION_MODE,
92
+ readPermissionSettings: readPermissionSettings,
93
+ pickSettingChanges: pickSettingChanges,
94
+ resolveOpenedSessionMode: resolveOpenedSessionMode,
95
+ settingsMessage: settingsMessage,
96
+ };
@@ -5,6 +5,8 @@ var userPresence = require("./user-presence");
5
5
  var { authOf } = require("./project-access");
6
6
  var { getCodexConfig } = require("./codex-defaults");
7
7
  var { promptsFor } = require("./prompt-registry");
8
+ var { settingsMessage } = require("./permission-settings");
9
+ var { effectiveSessionMode } = require("./sessions");
8
10
  var sessionReclaim = require("./session-reclaim");
9
11
  var clientBuildId = require("./client-build-id");
10
12
  var { buildVendorRegistryMessage } = require("./vendor-registry-message");
@@ -16,7 +18,7 @@ var { detectLite } = require("./lite-detect");
16
18
  * Attach connection/disconnection handlers to a project context.
17
19
  *
18
20
  * ctx fields:
19
- * cwd, slug, isMate, osUsers, debug, dangerouslySkipPermissions,
21
+ * cwd, slug, isMate, osUsers, debug,
20
22
  * currentVersion, lanHost, sm, tm, nm, clients, send, sendTo,
21
23
  * opts, loopState, loopRegistry, _loop, pushModule,
22
24
  * hydrateImageRefs, broadcastClientCount, broadcastPresence,
@@ -31,8 +33,6 @@ function attachConnection(ctx) {
31
33
  var slug = ctx.slug;
32
34
  var osUsers = ctx.osUsers;
33
35
  var debug = ctx.debug;
34
- var dangerouslySkipPermissions = ctx.dangerouslySkipPermissions;
35
- var dangerouslySkipPermissionsConfigured = ctx.dangerouslySkipPermissionsConfigured || false;
36
36
  var currentVersion = ctx.currentVersion;
37
37
  var lanHost = ctx.lanHost;
38
38
  var sm = ctx.sm;
@@ -142,12 +142,7 @@ function attachConnection(ctx) {
142
142
  // Use the liteStatus cached at project-context creation time (project.js) to
143
143
  // avoid a synchronous execFileSync("which",...) on every WS connect.
144
144
  var _liteStatus = ctx.liteStatus || detectLite();
145
- var infoMsg = { type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, buildId: clientBuildId.get(), debug: !!debug, dangerouslySkipPermissions: dangerouslySkipPermissions, osUsers: osUsers, lanHost: lanHost, projectCount: _filteredProjects.length, projects: _filteredProjects, projectOwnerId: projectOwnerId, ownerLocked: ownerLocked, liteInstalled: _liteStatus.installed, liteHome: _liteStatus.liteHome };
146
- // When dangerouslySkipPermissions is set in config but suppressed because
147
- // multi-user mode is active, tell the client so it can surface a warning.
148
- if (dangerouslySkipPermissionsConfigured && !dangerouslySkipPermissions) {
149
- infoMsg.dangerouslySkipPermissionsBlocked = true;
150
- }
145
+ var infoMsg = { type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, buildId: clientBuildId.get(), debug: !!debug, osUsers: osUsers, lanHost: lanHost, projectCount: _filteredProjects.length, projects: _filteredProjects, projectOwnerId: projectOwnerId, ownerLocked: ownerLocked, liteInstalled: _liteStatus.installed, liteHome: _liteStatus.liteHome };
151
146
  sendTo(ws, infoMsg);
152
147
  // Background agents the last shutdown interrupted: nobody was connected
153
148
  // to be told then.
@@ -175,8 +170,11 @@ function attachConnection(ctx) {
175
170
  sendTo(ws, { type: "model_info", model: _initialModel, models: initialModels, vendor: initialVendor, availableVendors: sm.availableVendors || [] });
176
171
  }
177
172
  sendTo(ws, buildVendorRegistryMessage(sm, _osIdentity));
178
- 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 });
173
+ sendTo(ws, { type: "config_state", model: _initialModel, mode: effectiveSessionMode(restoredActive, sm), effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
179
174
  sendTo(ws, Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
175
+ if (typeof opts.onGetPermissionSettings === "function") {
176
+ sendTo(ws, settingsMessage(opts.onGetPermissionSettings()));
177
+ }
180
178
  sendTo(ws, { type: "term_list", terminals: tm.list(ws) });
181
179
  // Context sources sent after session is resolved (per-session storage)
182
180
  sendTo(ws, { type: "notes_list", notes: nm.list() });
@@ -266,7 +264,7 @@ function attachConnection(ctx) {
266
264
  // server truth across a reconnect. Carrying it directly on
267
265
  // session_switched matches switchSession() and gives the client a
268
266
  // single authoritative snapshot value to reconcile the footer against.
269
- sendTo(ws, { type: "session_switched", id: active.localId, cliSessionId: active.cliSessionId || null, loop: active.loop || null, vendor: active.vendor || null, model: sm.effectiveSessionModel(active), hasHistory: _hasHistory, capabilities: _vendorCaps, isProcessing: !!active.isProcessing, agentName: active.agentName || null });
267
+ sendTo(ws, { type: "session_switched", id: active.localId, cliSessionId: active.cliSessionId || null, loop: active.loop || null, vendor: active.vendor || null, model: sm.effectiveSessionModel(active), mode: effectiveSessionMode(active, sm), hasHistory: _hasHistory, capabilities: _vendorCaps, isProcessing: !!active.isProcessing, agentName: active.agentName || null });
270
268
  // Send per-session context sources
271
269
  var sessionSources = loadContextSources(slug, active.localId);
272
270
  sendTo(ws, { type: "context_sources_state", active: sessionSources });
@@ -467,6 +467,15 @@ function attachLoop(ctx) {
467
467
  runNextIteration();
468
468
  }
469
469
 
470
+ // The loop's "Approve tools automatically during this loop" setting, read
471
+ // from its registry record when each run's sessions are made. A loop with no
472
+ // record, or a record from before the field existed, approves, as every loop
473
+ // did.
474
+ function loopApprovesTools() {
475
+ var rec = loopRegistry.getById(loopState.loopId);
476
+ return !(rec && rec.approveToolsAutomatically === false);
477
+ }
478
+
470
479
  function runNextIteration() {
471
480
  console.log("[ralph-loop] runNextIteration called, iteration: " + loopState.iteration + ", active: " + loopState.active + ", stopping: " + loopState.stopping);
472
481
  if (!loopState.active || loopState.stopping) {
@@ -485,7 +494,7 @@ function attachLoop(ctx) {
485
494
  var loopName = (loopState.wizardData && loopState.wizardData.name) || (loopSource && loopSource.name) || "";
486
495
  var loopSourceTag = (loopSource && loopSource.source) || null;
487
496
  var isRalphLoop = loopSourceTag === "ralph";
488
- session.loop = { active: true, iteration: loopState.iteration, role: "coder", loopId: loopState.loopId, name: loopName, source: loopSourceTag, startedAt: loopState.startedAt };
497
+ session.loop = { active: true, iteration: loopState.iteration, role: "coder", loopId: loopState.loopId, name: loopName, source: loopSourceTag, startedAt: loopState.startedAt, approveTools: loopApprovesTools() };
489
498
  session.title = (isRalphLoop ? "Ralph" : "Task") + (loopName ? " " + loopName : "") + " #" + loopState.iteration;
490
499
  sm.saveSessionFile(session);
491
500
  sm.broadcastSessionList();
@@ -666,7 +675,7 @@ function attachLoop(ctx) {
666
675
  var judgeName = (loopState.wizardData && loopState.wizardData.name) || (judgeSource && judgeSource.name) || "";
667
676
  var judgeSourceTag = (judgeSource && judgeSource.source) || null;
668
677
  var isRalphJudge = judgeSourceTag === "ralph";
669
- judgeSession.loop = { active: true, iteration: loopState.iteration, role: "judge", loopId: loopState.loopId, name: judgeName, source: judgeSourceTag, startedAt: loopState.startedAt };
678
+ judgeSession.loop = { active: true, iteration: loopState.iteration, role: "judge", loopId: loopState.loopId, name: judgeName, source: judgeSourceTag, startedAt: loopState.startedAt, approveTools: loopApprovesTools() };
670
679
  judgeSession.title = (isRalphJudge ? "Ralph" : "Task") + (judgeName ? " " + judgeName : "") + " Judge #" + loopState.iteration;
671
680
  sm.saveSessionFile(judgeSession);
672
681
  sm.broadcastSessionList();
@@ -957,6 +966,11 @@ function attachLoop(ctx) {
957
966
  // --- Message handler for loop-related messages ---
958
967
  function handleLoopMessage(ws, msg) {
959
968
  if (msg.type === "loop_start") {
969
+ // The preview's "Approve tools automatically" choice is the record's, so it
970
+ // holds for a scheduled loop too, which returns below without running.
971
+ if (typeof msg.approveToolsAutomatically === "boolean" && loopState.loopId) {
972
+ loopRegistry.updateRecord(loopState.loopId, { approveToolsAutomatically: msg.approveToolsAutomatically });
973
+ }
960
974
  // If this loop has a cron schedule, don't run immediately
961
975
  if (loopState.wizardData && loopState.wizardData.cron) {
962
976
  loopState.active = false;
@@ -1397,6 +1411,7 @@ function attachLoop(ctx) {
1397
1411
  recurrenceEnd: sData.recurrenceEnd || null,
1398
1412
  skipIfRunning: sData.skipIfRunning !== undefined ? sData.skipIfRunning : true,
1399
1413
  intervalEnd: sData.intervalEnd || null,
1414
+ approveToolsAutomatically: sData.approveToolsAutomatically,
1400
1415
  });
1401
1416
  return true;
1402
1417
  }
@@ -1464,7 +1479,13 @@ function attachLoop(ctx) {
1464
1479
  }
1465
1480
 
1466
1481
  if (msg.type === "loop_registry_update") {
1467
- var updatedRec = loopRegistry.update(msg.id, msg.data || {});
1482
+ var updateData = msg.data || {};
1483
+ // The tool-approval choice alone is not a reschedule: update() would
1484
+ // recompute the next run, which can re-arm a one-off that already ran.
1485
+ var approvalOnly = Object.keys(updateData).length === 1 && typeof updateData.approveToolsAutomatically === "boolean";
1486
+ var updatedRec = approvalOnly
1487
+ ? loopRegistry.updateRecord(msg.id, updateData)
1488
+ : loopRegistry.update(msg.id, updateData);
1468
1489
  if (!updatedRec) {
1469
1490
  sendTo(ws, { type: "loop_registry_error", text: "Record not found" });
1470
1491
  }