@clagentic/console 1.10.0 → 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 (97) hide show
  1. package/README.md +14 -1
  2. package/bin/cli.js +38 -16
  3. package/lib/agents.js +1 -55
  4. package/lib/bash-auto-approve.js +133 -0
  5. package/lib/build-identity.js +23 -5
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-check.js +0 -62
  8. package/lib/build-update-offer.js +23 -13
  9. package/lib/build-update-restart.js +59 -43
  10. package/lib/cli/arg-validation.js +50 -0
  11. package/lib/cli/daemon-launch.js +5 -4
  12. package/lib/cli/menus.js +2 -2
  13. package/lib/cli/schedule-input-subcommands.js +327 -0
  14. package/lib/cli/session-subcommands.js +101 -17
  15. package/lib/client-build-id.js +56 -0
  16. package/lib/daemon.js +38 -6
  17. package/lib/identity/index.js +9 -4
  18. package/lib/injected-sender.js +225 -0
  19. package/lib/message-sender-record.js +133 -0
  20. package/lib/pending-prompts.js +55 -0
  21. package/lib/permission-mode-policy.js +63 -0
  22. package/lib/permission-settings.js +96 -0
  23. package/lib/permission-summary.js +67 -0
  24. package/lib/project-connection.js +10 -11
  25. package/lib/project-external-trigger.js +9 -1
  26. package/lib/project-loop.js +50 -23
  27. package/lib/project-permission-settings.js +59 -0
  28. package/lib/project-prompt-responses.js +25 -15
  29. package/lib/project-sessions.js +164 -60
  30. package/lib/project-user-message.js +18 -47
  31. package/lib/project.js +46 -74
  32. package/lib/public/app.js +4 -7
  33. package/lib/public/css/channel-layout.css +20 -0
  34. package/lib/public/css/diagnostics.css +7 -0
  35. package/lib/public/css/input.css +78 -0
  36. package/lib/public/css/menus.css +17 -0
  37. package/lib/public/css/overlays.css +0 -3
  38. package/lib/public/css/scheduler-modal.css +5 -0
  39. package/lib/public/index.html +44 -8
  40. package/lib/public/modules/app-connection.js +18 -1
  41. package/lib/public/modules/app-loop-ui.js +11 -1
  42. package/lib/public/modules/app-messages.js +23 -30
  43. package/lib/public/modules/app-panels.js +10 -3
  44. package/lib/public/modules/app-rate-limit.js +64 -88
  45. package/lib/public/modules/app-rendering.js +37 -6
  46. package/lib/public/modules/approve-tools-toggle.js +33 -0
  47. package/lib/public/modules/at-agents.js +8 -0
  48. package/lib/public/modules/build-guard.js +61 -0
  49. package/lib/public/modules/build-update-detail.js +1 -4
  50. package/lib/public/modules/diagnostics.js +98 -9
  51. package/lib/public/modules/injected-identity.js +78 -0
  52. package/lib/public/modules/injected-label.js +62 -0
  53. package/lib/public/modules/input.js +64 -114
  54. package/lib/public/modules/loop-hooks-warning.js +20 -0
  55. package/lib/public/modules/mode-options.js +35 -16
  56. package/lib/public/modules/permission-settings.js +56 -0
  57. package/lib/public/modules/project-settings.js +3 -0
  58. package/lib/public/modules/rate-limit-state.js +47 -22
  59. package/lib/public/modules/schedule-panel.js +234 -0
  60. package/lib/public/modules/schedule-time.js +193 -0
  61. package/lib/public/modules/scheduled-input-actions.js +19 -0
  62. package/lib/public/modules/scheduler-config.js +12 -0
  63. package/lib/public/modules/scheduler.js +8 -0
  64. package/lib/public/modules/server-settings.js +5 -9
  65. package/lib/public/modules/settings-defaults.js +18 -4
  66. package/lib/runtime-env.js +4 -0
  67. package/lib/scheduled-input/ipc.js +92 -0
  68. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  69. package/lib/scheduled-input/records.js +350 -0
  70. package/lib/scheduled-input/service.js +743 -0
  71. package/lib/scheduled-input/store.js +132 -0
  72. package/lib/scheduled-input/ws.js +194 -0
  73. package/lib/scheduler.js +4 -0
  74. package/lib/sdk-bridge.js +194 -175
  75. package/lib/sdk-message-processor.js +13 -5
  76. package/lib/sdk-skill-discovery.js +17 -0
  77. package/lib/sender-ref.js +109 -0
  78. package/lib/server.js +37 -11
  79. package/lib/session-directory.js +224 -0
  80. package/lib/session-file-scan.js +55 -0
  81. package/lib/session-input-ipc.js +21 -0
  82. package/lib/session-input.js +396 -23
  83. package/lib/session-name-holder.js +82 -0
  84. package/lib/session-resume.js +3 -0
  85. package/lib/sessions.js +111 -2
  86. package/lib/turn-initiator.js +6 -2
  87. package/lib/updater.js +8 -2
  88. package/lib/ws-schema.js +20 -9
  89. package/lib/yoke/adapters/claude-worker.js +3 -1
  90. package/lib/yoke/adapters/claude.js +13 -17
  91. package/lib/yoke/adapters/codex.js +18 -5
  92. package/lib/yoke/adapters/permission-relay.js +9 -0
  93. package/lib/yoke/interface.js +7 -1
  94. package/package.json +1 -1
  95. package/scripts/check-test-count.js +1 -1
  96. package/scripts/install-local-test.js +45 -1
  97. package/scripts/postinstall.js +1 -0
@@ -1,69 +1,126 @@
1
1
  // lib/cli/session-subcommands.js
2
2
  //
3
- // `clagentic-console open-session` and `clagentic-console send-input`: open a
4
- // session in a project, or send input to one, through the running daemon's IPC
5
- // socket. Both print the daemon's result as JSON on stdout and exit 0 when the
6
- // request was acted on (opened, delivered, resumed-and-delivered), 1 otherwise
7
- // (not-found, refused, error), so a script can branch on either.
3
+ // `clagentic-console open-session`, `send-input` and `list-sessions`: open a
4
+ // session in a project, send input to one, or list the sessions, through the
5
+ // running daemon's IPC socket. Each prints the daemon's result as JSON on stdout.
6
+ //
7
+ // Exit codes (documented in docs/guides/AGENT-GUIDE.md):
8
+ // 0 the request was acted on (opened, delivered, resumed-and-delivered, listed)
9
+ // 1 refused, error, or not-found for a request that named a session id
10
+ // 3 ambiguous: an address named several sessions; the candidates are in the JSON
11
+ // 4 not-found for a request that gave an address (--to) or --reply
8
12
 
9
13
  var fs = require("fs");
10
14
 
11
15
  var { loadConfig, socketPath, isDaemonAliveAsync } = require("../config");
12
16
  var { sendIPCCommand } = require("../ipc");
17
+ var senderRef = require("../sender-ref");
13
18
 
14
19
  // A resumed session starts a runtime before the call answers: longer than the
15
20
  // IPC default.
16
21
  var IPC_TIMEOUT_MS = 30000;
17
22
 
23
+ var EXIT = Object.freeze({ OK: 0, FAILED: 1, AMBIGUOUS: 3, NOT_FOUND_BY_ADDRESS: 4 });
24
+
18
25
  var FLAGS = {
19
26
  "--project": "projectSlug",
20
27
  "--session": "sessionId",
28
+ "--to": "to",
21
29
  "--prompt": "prompt",
22
30
  "--vendor": "vendor",
23
31
  "--agent": "agentName",
32
+ "--name": "sessionName",
33
+ "--state": "state",
24
34
  "--visibility": "sessionVisibility",
35
+ "--permission-mode": "permissionMode",
25
36
  "--initiator": "initiator",
26
37
  "--context-note": "contextNote",
38
+ "--from": "from",
39
+ "--from-session": "fromSession",
40
+ };
41
+
42
+ // Kept apart from FLAGS because the parser reads a value after every FLAGS
43
+ // entry; a flag listed there would swallow the next argument.
44
+ var SWITCHES = {
45
+ "--reply": "reply",
27
46
  };
28
47
 
29
48
  var USAGE = {
30
- "open-session": "Usage: clagentic-console open-session --project <slug> --prompt <text|-> [--vendor <id>] [--agent <name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>]",
31
- "send-input": "Usage: clagentic-console send-input --project <slug> --session <id> --prompt <text|-> [--initiator <kind>] [--context-note <text>]",
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>]",
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>]",
51
+ "list-sessions": "Usage: clagentic-console list-sessions [--project <slug>] [--agent <name>] [--vendor <id>] [--state live|idle|reaped|any]",
32
52
  };
33
53
 
34
54
  var ALLOWED = {
35
- "open-session": ["projectSlug", "prompt", "vendor", "agentName", "sessionVisibility", "initiator", "contextNote"],
36
- "send-input": ["projectSlug", "sessionId", "prompt", "initiator", "contextNote"],
55
+ "open-session": ["projectSlug", "to", "prompt", "vendor", "agentName", "sessionName", "sessionVisibility", "permissionMode", "initiator", "contextNote", "from", "fromSession"],
56
+ "send-input": ["projectSlug", "sessionId", "to", "reply", "prompt", "initiator", "contextNote", "from", "fromSession"],
57
+ "list-sessions": ["projectSlug", "agentName", "vendor", "state"],
37
58
  };
38
59
 
39
60
  var REQUIRED = {
40
- "open-session": ["projectSlug", "prompt"],
41
- "send-input": ["projectSlug", "sessionId", "prompt"],
61
+ "open-session": ["prompt"],
62
+ "send-input": ["prompt"],
63
+ "list-sessions": [],
64
+ };
65
+
66
+ var TARGET_HINT = {
67
+ "open-session": "--project, or --to",
68
+ "send-input": "--session (with --project), or --to, or --reply",
42
69
  };
43
70
 
44
71
  var IPC_COMMAND = {
45
72
  "open-session": "open_session",
46
73
  "send-input": "send_session_input",
74
+ "list-sessions": "list_sessions",
47
75
  };
48
76
 
77
+ function flagOf(key) {
78
+ var all = Object.keys(FLAGS).concat(Object.keys(SWITCHES));
79
+ return all.filter(function (f) { return FLAGS[f] === key || SWITCHES[f] === key; })[0];
80
+ }
81
+
82
+ function has(obj, key) {
83
+ return Object.prototype.hasOwnProperty.call(obj, key);
84
+ }
85
+
86
+ // Checks how the target is named: a project (and for send-input a session id),
87
+ // or an address (--to, which may be given beside the project it names), or for
88
+ // send-input --reply. One way only. Returns an error string or null.
89
+ function checkTarget(verb, request) {
90
+ if (!TARGET_HINT[verb]) return null;
91
+ var conflict = "Give the target one way only: " + TARGET_HINT[verb];
92
+ var given = function (k) { return request[k] !== undefined; };
93
+ if (given("to")) return given("sessionId") || given("reply") ? conflict : null;
94
+ if (given("reply")) return given("projectSlug") || given("sessionId") ? conflict : null;
95
+ if (!given("projectSlug") && !given("sessionId")) return "Missing the target: " + TARGET_HINT[verb];
96
+ if (!given("projectSlug")) return "Missing required option --project";
97
+ if (verb === "send-input" && !given("sessionId")) return "Missing required option --session";
98
+ return null;
99
+ }
100
+
49
101
  // Parses the arguments after the verb. Returns { request } or { error }.
50
102
  // Pure: reading a "-" prompt from stdin is the handler's job.
51
103
  function parseSessionArgs(verb, args) {
52
104
  var allowed = ALLOWED[verb];
53
105
  var request = {};
54
106
  for (var i = 0; i < args.length; i++) {
55
- var key = Object.prototype.hasOwnProperty.call(FLAGS, args[i]) ? FLAGS[args[i]] : null;
107
+ if (has(SWITCHES, args[i])) {
108
+ var switchKey = SWITCHES[args[i]];
109
+ if (allowed.indexOf(switchKey) === -1) return { error: "Unknown option for " + verb + ": " + args[i] };
110
+ request[switchKey] = true;
111
+ continue;
112
+ }
113
+ var key = has(FLAGS, args[i]) ? FLAGS[args[i]] : null;
56
114
  if (!key || allowed.indexOf(key) === -1) return { error: "Unknown option for " + verb + ": " + args[i] };
57
115
  if (i + 1 >= args.length) return { error: "Missing value for " + args[i] };
58
116
  request[key] = args[++i];
59
117
  }
60
118
  var required = REQUIRED[verb];
61
119
  for (var r = 0; r < required.length; r++) {
62
- if (!request[required[r]]) {
63
- var flag = Object.keys(FLAGS).filter(function (f) { return FLAGS[f] === required[r]; })[0];
64
- return { error: "Missing required option " + flag };
65
- }
120
+ if (!request[required[r]]) return { error: "Missing required option " + flagOf(required[r]) };
66
121
  }
122
+ var targetError = checkTarget(verb, request);
123
+ if (targetError) return { error: targetError };
67
124
  return { request: request };
68
125
  }
69
126
 
@@ -75,6 +132,29 @@ function normalizeResponse(res) {
75
132
  return { ok: false, result: "error", reason: reason };
76
133
  }
77
134
 
135
+ // Called from inside a console session, the caller's environment holds the
136
+ // console's reference to that session (lib/sender-ref.js). It is passed to the
137
+ // daemon automatically, no flag; outside a console session there is none.
138
+ function withSenderRef(request, env) {
139
+ var ref = senderRef.fromEnv(env);
140
+ if (ref) {
141
+ request.senderProject = ref.project;
142
+ request.senderSessionId = ref.sessionId;
143
+ }
144
+ return request;
145
+ }
146
+
147
+ // The process exit code for a result. request says how the target was named: an
148
+ // address or a reply is told apart from an id so a script can branch on it.
149
+ function exitCodeFor(res, request) {
150
+ if (res && res.ok) return EXIT.OK;
151
+ if (res && res.result === "ambiguous") return EXIT.AMBIGUOUS;
152
+ if (res && res.result === "not-found" && request && (request.to !== undefined || request.reply)) {
153
+ return EXIT.NOT_FOUND_BY_ADDRESS;
154
+ }
155
+ return EXIT.FAILED;
156
+ }
157
+
78
158
  function fail(message) {
79
159
  console.error(message);
80
160
  process.exit(1);
@@ -92,11 +172,12 @@ function runSessionVerb(verb, args) {
92
172
  request.prompt = fs.readFileSync(0, "utf8").replace(/\n$/, "");
93
173
  }
94
174
  request.cmd = IPC_COMMAND[verb];
175
+ if (verb !== "list-sessions") withSenderRef(request, process.env);
95
176
 
96
177
  requestDaemon(request).then(function (res) {
97
178
  console.log(JSON.stringify(res, null, 2));
98
179
  // Not process.exit: on a pipe it can cut the JSON off before stdout drains.
99
- process.exitCode = res && res.ok ? 0 : 1;
180
+ process.exitCode = exitCodeFor(res, request);
100
181
  });
101
182
  }
102
183
 
@@ -117,6 +198,9 @@ function requestDaemon(request, deps) {
117
198
  module.exports = {
118
199
  requestDaemon: requestDaemon,
119
200
  parseSessionArgs: parseSessionArgs,
201
+ withSenderRef: withSenderRef,
202
+ exitCodeFor: exitCodeFor,
120
203
  runSessionVerb: runSessionVerb,
204
+ EXIT: EXIT,
121
205
  SESSION_VERBS: Object.keys(IPC_COMMAND),
122
206
  };
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ // client-build-id.js — the one identity a browser compares to decide whether the
4
+ // client code it is running still matches the daemon that serves it.
5
+ //
6
+ // It is keyed on the BUILD, not on package.json's version: two builds can share
7
+ // a version (consecutive betas do), and a client keyed on the version then never
8
+ // notices the restart onto the newer one. The build SHA the daemon loaded at
9
+ // startup is used when the install carries one; a checkout without
10
+ // lib/build-sha.json gets a per-start nonce, so a restart still changes the id.
11
+
12
+ var crypto = require("crypto");
13
+
14
+ var SERVICE_WORKER_CACHE_PATTERN = /var CACHE_NAME = "clagentic-console-offline-[^"]*"/;
15
+
16
+ var current = null;
17
+
18
+ function newNonce() {
19
+ return "start-" + crypto.randomBytes(6).toString("hex");
20
+ }
21
+
22
+ /**
23
+ * Fixes the id for this process. Called once, with the SHA the daemon captured
24
+ * at startup (null when the install has none). Later calls are ignored: an id
25
+ * that moved mid-process would tell clients to reload for no deploy.
26
+ */
27
+ function init(buildSha) {
28
+ if (current) return current;
29
+ current = typeof buildSha === "string" && buildSha ? buildSha : newNonce();
30
+ return current;
31
+ }
32
+
33
+ /** The id for this process; a nonce when init was never given a SHA. */
34
+ function get() {
35
+ return current || init(null);
36
+ }
37
+
38
+ // Cache names are restricted to a conservative alphabet: the id is embedded in
39
+ // served JavaScript, and a hand-edited build-sha.json must not break out of it.
40
+ function cacheSafe(id) {
41
+ return String(id).replace(/[^A-Za-z0-9._-]/g, "_");
42
+ }
43
+
44
+ /**
45
+ * The service worker source with its cache name stamped for `buildId`. A
46
+ * different id yields different bytes, which is what makes the browser install
47
+ * the new worker after a restart onto a new build.
48
+ */
49
+ function stampServiceWorker(source, buildId) {
50
+ return source.replace(
51
+ SERVICE_WORKER_CACHE_PATTERN,
52
+ 'var CACHE_NAME = "clagentic-console-offline-v' + cacheSafe(buildId) + '"'
53
+ );
54
+ }
55
+
56
+ module.exports = { init: init, get: get, stampServiceWorker: stampServiceWorker };
package/lib/daemon.js CHANGED
@@ -40,14 +40,14 @@ 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");
46
47
  var { dropSkillsCache } = require("./server-skills");
47
- var { waitForIdleThenAct } = require("./build-update-check");
48
48
  var { createBuildMonitor } = require("./build-monitor");
49
49
  var { createBuildUpdateRestart } = require("./build-update-restart");
50
- var { composeNotice, noticeCooldownFrom } = require("./build-update-offer");
50
+ var { composeNotice, noticeCooldownFrom, composeRestartingNotice } = require("./build-update-offer");
51
51
  var { createStandingOffer } = require("./build-update-standing");
52
52
  var { listBuildChanges, resolveHistoryRepo } = require("./build-changes");
53
53
  var { RESTART_EXIT_CODE, isSupervised, unsupervisedEnv } = require("./supervisor");
@@ -134,6 +134,9 @@ function checkStaleInodes() {
134
134
  // the file and it is gitignored): "no build-identity signal", not an error.
135
135
  var loadedBuildSha = null;
136
136
  loadedBuildSha = buildIdentity.loaded.sha;
137
+ // Browsers compare this id to know the client they run is the one this daemon
138
+ // serves; fixed here, from the SHA captured above, before any request is served.
139
+ require("./client-build-id").init(loadedBuildSha);
137
140
  console.log("[daemon] Build: sha=" + (loadedBuildSha || "(none)") +
138
141
  " files=" + (buildIdentity.loaded.contentHash ? buildIdentity.loaded.contentHash.slice(0, 12) : "(unreadable)"));
139
142
 
@@ -301,7 +304,6 @@ var relay = createServer({
301
304
  allowedOrigins: Array.isArray(config.allowedOrigins) ? config.allowedOrigins : [],
302
305
  port: config.port,
303
306
  debug: config.debug || false,
304
- dangerouslySkipPermissions: config.dangerouslySkipPermissions || false,
305
307
  osUsers: config.osUsers || false,
306
308
  lanHost: lanIp ? lanIp + ":" + config.port : null,
307
309
  // lr-2ea2a7: optional daemon.json override for the in-heap session-history
@@ -1028,6 +1030,23 @@ var relay = createServer({
1028
1030
  saveConfig(config);
1029
1031
  return { ok: true };
1030
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
+ },
1031
1050
  onGetProjectDefaultMode: function (slug) {
1032
1051
  for (var i = 0; i < config.projects.length; i++) {
1033
1052
  if (config.projects[i].slug === slug) {
@@ -1424,9 +1443,9 @@ var buildUpdateRestart = createBuildUpdateRestart({
1424
1443
  console.log("[daemon] Restarting to adopt the installed build, as the operator confirmed");
1425
1444
  spawnAndRestart();
1426
1445
  },
1427
- waitForIdleThenAct: waitForIdleThenAct,
1428
- announce: function (message) {
1429
- relay.broadcastAll({ type: "diagnostic", severity: "warning", source: "build-update", message: message });
1446
+ onScheduled: function () {
1447
+ relay.broadcastAll({ type: "diagnostic_retract", source: "build-update" });
1448
+ relay.broadcastAll(composeRestartingNotice());
1430
1449
  },
1431
1450
  log: function (line) { console.log("[daemon] " + line); },
1432
1451
  });
@@ -1678,8 +1697,21 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1678
1697
  // counts as a human turn (session-input.js refuses that initiator).
1679
1698
  case "open_session":
1680
1699
  case "send_session_input":
1700
+ case "list_sessions":
1681
1701
  return require("./session-input-ipc").handleSessionCommand(relay.sessionInput, msg);
1682
1702
 
1703
+ // Scheduled input: text sent into a session later, once or on a repeat with
1704
+ // an end. The same service the clock button in the browser uses, so a record
1705
+ // made here shows there and the reverse. Same OS-level socket gate as the
1706
+ // commands above.
1707
+ case "schedule_input_create":
1708
+ case "schedule_input_list":
1709
+ case "schedule_input_delete":
1710
+ return require("./scheduled-input/ipc").handleScheduledInputCommand({
1711
+ service: relay.scheduledInput,
1712
+ getProject: relay.getProject,
1713
+ }, msg);
1714
+
1683
1715
  case "set_pin": {
1684
1716
  config.pinHash = msg.pinHash || null;
1685
1717
  relay.setAuthToken(config.pinHash);
@@ -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) {
@@ -0,0 +1,225 @@
1
+ // injected-sender.js - who sent an injected user_message, as the chat shows it.
2
+ //
3
+ // Input that reaches a session through session-input.js is not typed by the
4
+ // person at the browser, so its history entry names a sender instead of
5
+ // borrowing the operator's identity. The sender is recorded at injection time
6
+ // (senderFields) and completed on the way to a client (forClient) so an injected
7
+ // entry never renders as the local user.
8
+ //
9
+ // senderKind:
10
+ // "extracted" derived from the console's own records for a process the console
11
+ // started (lib/sender-ref.js); not proof against a same-user process
12
+ // copying the reference
13
+ // "declared" the caller named itself with --from (self-reported, unverified)
14
+ // "undeclared" the caller named nobody
15
+ // "automation" a turn the console composed itself (a scheduled message, a run-now,
16
+ // a loop iteration, a rate-limit resume); the console is the sender
17
+ // "unrecorded" a new entry (marked, see below) that names no initiator, or an
18
+ // injected entry that names no usable sender
19
+ // ("attested" is reserved for a caller identity the console itself verified;
20
+ // nothing produces it yet.) Precedence: attested > extracted > declared >
21
+ // undeclared.
22
+ //
23
+ // Record-format marker. Every user_message recorded from this format on carries
24
+ // `entryFormat: 1` (stampRecord, called by each writer) and ALWAYS an initiator,
25
+ // the human one included. The marker is what tells a new entry that lost its
26
+ // initiator (a defect: fail closed, never the operator) from a legacy entry that
27
+ // predates initiators (the console cannot tell a legacy typed turn from a legacy
28
+ // automated one, so it renders exactly as it always did). Additive field: older
29
+ // readers ignore it.
30
+ //
31
+ // marked + initiator human operator
32
+ // marked + other initiator the automation or sender it names
33
+ // marked + no initiator not the operator; "sender not recorded"
34
+ // unmarked (legacy) as before: operator, unless it is injected
35
+ // (source external-trigger or a non-human
36
+ // initiator), in which case the sender path
37
+
38
+ var crypto = require("crypto");
39
+ var { INITIATORS } = require("./turn-initiator");
40
+
41
+ var SENDER_KIND = Object.freeze({
42
+ EXTRACTED: "extracted",
43
+ DECLARED: "declared",
44
+ UNDECLARED: "undeclared",
45
+ AUTOMATION: "automation",
46
+ UNRECORDED: "unrecorded",
47
+ });
48
+
49
+ // Sender names of the console's own automations. Run-now shares the scheduled
50
+ // name, so the same schedule keeps one avatar whichever way it fired.
51
+ var AUTOMATION_NAMES = Object.freeze({
52
+ [INITIATORS.SCHEDULED]: "Scheduled message",
53
+ [INITIATORS.SCHEDULED_NOW]: "Scheduled message",
54
+ [INITIATORS.LOOP]: "Loop",
55
+ });
56
+
57
+ var RECORD_FORMAT_FIELD = "entryFormat";
58
+ var RECORD_FORMAT = 1;
59
+
60
+ var MAX_FROM_LENGTH = 64;
61
+ // Vendor session ids are uuids or short opaque ids; this bounds a declared one.
62
+ var MAX_FROM_SESSION_LENGTH = 128;
63
+ // C0 controls, DEL and C1 controls: nothing a sender name needs, and they can
64
+ // disguise or break the one-line label.
65
+ var CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
66
+
67
+ // Prefix keeps a sender id from ever equalling a real user id.
68
+ var SENDER_ID_PREFIX = "injected:";
69
+
70
+ var MESSAGE_ID_FIELD = "messageId";
71
+
72
+ // The id one message carries from the console to the vendor and into the
73
+ // published per-message sender record (lib/message-sender-record.js).
74
+ function newMessageId() {
75
+ return crypto.randomUUID();
76
+ }
77
+
78
+ // Marks a new user_message as recorded in the current format and gives it its
79
+ // message id (kept when the writer already minted one, because the same id must
80
+ // reach the vendor with the turn). Returns the entry.
81
+ function stampRecord(entry) {
82
+ entry[RECORD_FORMAT_FIELD] = RECORD_FORMAT;
83
+ if (!entry[MESSAGE_ID_FIELD]) entry[MESSAGE_ID_FIELD] = newMessageId();
84
+ return entry;
85
+ }
86
+
87
+ function isMarked(entry) {
88
+ return typeof entry[RECORD_FORMAT_FIELD] === "number" && entry[RECORD_FORMAT_FIELD] >= RECORD_FORMAT;
89
+ }
90
+
91
+ // Returns { from } (absent when the caller named nobody) or { error }.
92
+ function validateFrom(raw) {
93
+ if (raw === undefined || raw === null) return {};
94
+ if (typeof raw !== "string") return { error: "from must be a string" };
95
+ var name = raw.trim();
96
+ if (!name) return {};
97
+ if (name.length > MAX_FROM_LENGTH) return { error: "from is longer than " + MAX_FROM_LENGTH + " characters" };
98
+ if (CONTROL_CHARS.test(name)) return { error: "from contains control characters" };
99
+ return { from: name };
100
+ }
101
+
102
+ // Returns { fromSession } (absent when the caller named none) or { error }. The
103
+ // id is the sending session's own id at its vendor (the vendor's field is
104
+ // fromSession), written by the sender: a navigation target, never authority.
105
+ function validateFromSession(raw) {
106
+ if (raw === undefined || raw === null) return {};
107
+ if (typeof raw !== "string") return { error: "fromSession must be a string" };
108
+ var id = raw.trim();
109
+ if (!id) return {};
110
+ if (id.length > MAX_FROM_SESSION_LENGTH) return { error: "fromSession is longer than " + MAX_FROM_SESSION_LENGTH + " characters" };
111
+ if (CONTROL_CHARS.test(id)) return { error: "fromSession contains control characters" };
112
+ return { fromSession: id };
113
+ }
114
+
115
+ function senderId(initiator) {
116
+ return SENDER_ID_PREFIX + (initiator || "unknown");
117
+ }
118
+
119
+ // Fields to store on a new injected entry. declaredName is validateFrom().from;
120
+ // extracted is lib/sender-ref.js resolve() or null; declaredSession is
121
+ // validateFromSession().fromSession. An extracted sender wins the display; a
122
+ // --from that names someone else is kept beside it as declaredName. fromSession
123
+ // is the sending session's vendor session id: the console's own record of an
124
+ // extracted sender when it has one, else what the caller declared.
125
+ function senderFields(initiator, declaredName, extracted, declaredSession) {
126
+ var fields = { from: senderId(initiator) };
127
+ if (extracted && extracted.cliSessionId && extracted.vendor) fields.fromSession = extracted.cliSessionId;
128
+ else if (declaredSession) fields.fromSession = declaredSession;
129
+ if (extracted) {
130
+ fields.senderKind = SENDER_KIND.EXTRACTED;
131
+ fields.fromName = extracted.name;
132
+ fields.senderProject = extracted.project;
133
+ fields.senderSessionId = extracted.sessionId;
134
+ if (extracted.agent) fields.senderAgent = extracted.agent;
135
+ if (extracted.agentSlug) fields.senderAgentSlug = extracted.agentSlug;
136
+ if (extracted.vendor) fields.senderVendor = extracted.vendor;
137
+ // Optional history field, and recorded only together with the vendor: a
138
+ // vendor session id means nothing without the vendor that issued it, and
139
+ // --reply routes by the pair. Absent when the sender had no vendor session id
140
+ // yet, and on entries recorded before it existed.
141
+ if (extracted.cliSessionId && extracted.vendor) fields.senderCliSessionId = extracted.cliSessionId;
142
+ var lower = String(declaredName || "").toLowerCase();
143
+ if (declaredName && lower !== extracted.name.toLowerCase()
144
+ && lower !== String(extracted.agent || extracted.vendor || "").toLowerCase()) {
145
+ fields.declaredName = declaredName;
146
+ }
147
+ } else if (declaredName) {
148
+ fields.fromName = declaredName;
149
+ fields.senderKind = SENDER_KIND.DECLARED;
150
+ } else {
151
+ fields.senderKind = SENDER_KIND.UNDECLARED;
152
+ }
153
+ return fields;
154
+ }
155
+
156
+ // The history entry for a turn the console composed itself. `initiator` is the
157
+ // same value the caller passes to startQuery, so the entry and the vendor's
158
+ // origin stamp (turn-initiator.js) cannot name different sources. `note` is the
159
+ // automation's own detail (the schedule or loop name, the iteration).
160
+ function consoleTurnEntry(initiator, text, note) {
161
+ var name = Object.prototype.hasOwnProperty.call(AUTOMATION_NAMES, initiator) ? AUTOMATION_NAMES[initiator] : null;
162
+ if (!name) throw new Error("not a console automation initiator: " + String(initiator));
163
+ var entry = stampRecord({
164
+ type: "user_message",
165
+ text: text,
166
+ _ts: Date.now(),
167
+ initiator: initiator,
168
+ from: senderId(initiator),
169
+ fromName: name,
170
+ senderKind: SENDER_KIND.AUTOMATION,
171
+ });
172
+ if (note) entry.contextNote = note;
173
+ return entry;
174
+ }
175
+
176
+ function isInjected(entry) {
177
+ if (!entry || entry.type !== "user_message") return false;
178
+ return entry.source === "external-trigger" || (!!entry.initiator && entry.initiator !== INITIATORS.HUMAN);
179
+ }
180
+
181
+ // Whether the entry is the operator's own, by the table at the top of the file.
182
+ function isOperatorEntry(entry) {
183
+ if (!entry || entry.type !== "user_message") return false;
184
+ if (entry.source === "external-trigger") return false;
185
+ if (isMarked(entry)) return entry.initiator === INITIATORS.HUMAN;
186
+ return !isInjected(entry);
187
+ }
188
+
189
+ // The entry as a client should receive it. Every user message that is not the
190
+ // operator's leaves with a sender id that is not a user's and a senderKind,
191
+ // whatever was stored, so the client cannot fall back to drawing it as the local
192
+ // user. Operator entries and other entry types are returned untouched.
193
+ function forClient(entry) {
194
+ if (!entry || entry.type !== "user_message" || isOperatorEntry(entry)) return entry;
195
+ var out = {};
196
+ for (var k in entry) out[k] = entry[k];
197
+ out.from = senderId(entry.initiator);
198
+ var known = out.senderKind === SENDER_KIND.DECLARED || out.senderKind === SENDER_KIND.UNDECLARED
199
+ || (out.senderKind === SENDER_KIND.AUTOMATION && Object.prototype.hasOwnProperty.call(AUTOMATION_NAMES, out.initiator)
200
+ && typeof out.fromName === "string" && !!out.fromName)
201
+ || (out.senderKind === SENDER_KIND.EXTRACTED && typeof out.fromName === "string" && !!out.fromName);
202
+ if (!known) {
203
+ out.senderKind = SENDER_KIND.UNRECORDED;
204
+ delete out.fromName;
205
+ }
206
+ return out;
207
+ }
208
+
209
+ module.exports = {
210
+ SENDER_KIND: SENDER_KIND,
211
+ MAX_FROM_LENGTH: MAX_FROM_LENGTH,
212
+ validateFrom: validateFrom,
213
+ validateFromSession: validateFromSession,
214
+ MAX_FROM_SESSION_LENGTH: MAX_FROM_SESSION_LENGTH,
215
+ newMessageId: newMessageId,
216
+ MESSAGE_ID_FIELD: MESSAGE_ID_FIELD,
217
+ senderFields: senderFields,
218
+ stampRecord: stampRecord,
219
+ RECORD_FORMAT_FIELD: RECORD_FORMAT_FIELD,
220
+ consoleTurnEntry: consoleTurnEntry,
221
+ AUTOMATION_NAMES: AUTOMATION_NAMES,
222
+ isInjected: isInjected,
223
+ isOperatorEntry: isOperatorEntry,
224
+ forClient: forClient,
225
+ };