@clagentic/console 1.10.0-beta.1 → 1.10.0-beta.3

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 (94) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/activity-clock.js +23 -0
  4. package/lib/agent-dispatch-tool.js +20 -0
  5. package/lib/build-changes.js +79 -0
  6. package/lib/build-identity.js +192 -0
  7. package/lib/build-monitor.js +125 -0
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-offer.js +141 -0
  10. package/lib/build-update-restart.js +142 -0
  11. package/lib/build-update-standing.js +184 -0
  12. package/lib/cli/daemon-launch.js +8 -5
  13. package/lib/cli/ipc-subcommands.js +6 -0
  14. package/lib/cli/session-subcommands.js +122 -0
  15. package/lib/cli-sessions.js +8 -1
  16. package/lib/cli-transcript-title.js +131 -0
  17. package/lib/codex-defaults.js +8 -2
  18. package/lib/daemon-projects.js +19 -0
  19. package/lib/daemon.js +166 -127
  20. package/lib/debug-log.js +17 -0
  21. package/lib/exit-flush.js +44 -0
  22. package/lib/grant-keys.js +179 -0
  23. package/lib/log-field.js +34 -0
  24. package/lib/memory-shed.js +13 -32
  25. package/lib/project-connection.js +14 -0
  26. package/lib/project-external-trigger.js +91 -123
  27. package/lib/project-http.js +2 -0
  28. package/lib/project-loop.js +5 -4
  29. package/lib/project-notifications.js +4 -0
  30. package/lib/project-prompt-responses.js +7 -5
  31. package/lib/project-session-grants.js +73 -0
  32. package/lib/project-sessions.js +55 -68
  33. package/lib/project-user-message.js +13 -25
  34. package/lib/project.js +25 -5
  35. package/lib/prompt-kinds/permission.js +18 -0
  36. package/lib/prompt-label.js +60 -0
  37. package/lib/prompt-registry.js +123 -13
  38. package/lib/prompt-source.js +65 -0
  39. package/lib/public/css/diagnostics.css +30 -0
  40. package/lib/public/css/notifications-center.css +15 -0
  41. package/lib/public/css/overlays.css +18 -0
  42. package/lib/public/css/rewind.css +8 -0
  43. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  44. package/lib/public/modules/app-messages.js +10 -2
  45. package/lib/public/modules/app-notifications.js +9 -1
  46. package/lib/public/modules/app-panels.js +0 -1
  47. package/lib/public/modules/build-update-detail.js +54 -0
  48. package/lib/public/modules/diagnostics.js +126 -20
  49. package/lib/public/modules/prompt-banner.js +12 -0
  50. package/lib/public/modules/prompt-kinds/permission-choices.js +6 -1
  51. package/lib/public/modules/prompt-kinds/permission.js +15 -0
  52. package/lib/public/modules/prompt-label.js +44 -0
  53. package/lib/public/modules/prompts.js +9 -0
  54. package/lib/public/modules/session-grants.js +131 -0
  55. package/lib/public/modules/sidebar-sessions.js +11 -0
  56. package/lib/public/modules/tools.js +14 -2
  57. package/lib/public/modules/vendor-picker.js +2 -2
  58. package/lib/public/modules/vendor-registry.js +11 -2
  59. package/lib/runtime-env.js +1 -1
  60. package/lib/sdk-bridge.js +114 -115
  61. package/lib/sdk-message-processor.js +25 -87
  62. package/lib/sdk-skill-discovery.js +65 -60
  63. package/lib/server.js +15 -2
  64. package/lib/session-ai-title.js +80 -0
  65. package/lib/session-id.js +33 -0
  66. package/lib/session-input-ipc.js +32 -0
  67. package/lib/session-input.js +409 -0
  68. package/lib/session-reclaim.js +284 -0
  69. package/lib/session-resume.js +172 -0
  70. package/lib/sessions.js +31 -21
  71. package/lib/supervisor.js +39 -0
  72. package/lib/turn-initiator.js +108 -0
  73. package/lib/utils.js +9 -47
  74. package/lib/vendor-registry-message.js +1 -0
  75. package/lib/ws-schema.js +9 -4
  76. package/lib/yoke/adapters/claude-vendor.js +0 -1
  77. package/lib/yoke/adapters/claude-worker.js +6 -4
  78. package/lib/yoke/adapters/claude.js +29 -86
  79. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  80. package/lib/yoke/adapters/codex-vendor.js +15 -15
  81. package/lib/yoke/adapters/codex.js +125 -136
  82. package/lib/yoke/auth-checks.js +8 -21
  83. package/lib/yoke/codex-app-server.js +27 -71
  84. package/lib/yoke/codex-binary.js +254 -0
  85. package/lib/yoke/codex-command.js +122 -0
  86. package/lib/yoke/codex-protocol.js +96 -0
  87. package/lib/yoke/codex-version.js +135 -0
  88. package/lib/yoke/index.js +20 -4
  89. package/lib/yoke/install-probe.js +21 -6
  90. package/lib/yoke/interface.js +14 -12
  91. package/lib/yoke/registry.js +41 -4
  92. package/package.json +1 -2
  93. package/scripts/verify-installed-build.js +59 -17
  94. package/lib/lore-attestation.js +0 -73
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+
3
+ // What an "Allow for Session" answer grants, and how a later tool call is
4
+ // matched against it. One function builds the key for a call; the same key is
5
+ // what is stored when the operator grants it and what a later call is looked
6
+ // up by, so a grant covers exactly the calls that map to its key and no more.
7
+ //
8
+ // Key shapes (stored as keys of session.allowedTools, persisted in the session
9
+ // meta record, always with the value true):
10
+ // <Tool> whole tool. Older sessions hold these (the grant used
11
+ // to be the whole tool); they stay readable and in
12
+ // force until revoked. New grants never take this
13
+ // shape for a tool that has a narrower one.
14
+ // Bash=<command> exactly this command line and nothing wider. A line
15
+ // too long to keep has no key. Bash:<anything> (the
16
+ // retired prefix shape) is dropped on load.
17
+ // Skill:<name> one skill.
18
+ // <other tool> tool name (MCP tools already carry server and tool).
19
+ //
20
+ // File tools (Write, Edit, MultiEdit, NotebookEdit, the codex file change)
21
+ // have no key at all: every call is answered on its own, and only a legacy
22
+ // whole-tool grant persisted by an older session is honoured.
23
+ //
24
+ // A call with no usable key (a file-tool call, a command too long to persist)
25
+ // has key null: it can be allowed once, never for the session.
26
+
27
+ // The session meta record is read back from a 4 KiB chunk, so a grant map that
28
+ // grew without bound would make the whole session unloadable after a restart.
29
+ var MAX_KEY_LENGTH = 160;
30
+ var MAX_GRANTS = 16;
31
+ var MAX_GRANT_BYTES = 1600;
32
+
33
+ // Binding a file grant to the filesystem (lexical paths, then realpaths) left
34
+ // a new hole at every review, so file tools never produce a session grant: no
35
+ // key, no stored value, no filesystem read.
36
+ var FILE_TOOLS = Object.create(null);
37
+ FILE_TOOLS.Write = true;
38
+ FILE_TOOLS.Edit = true;
39
+ FILE_TOOLS.MultiEdit = true;
40
+ FILE_TOOLS.NotebookEdit = true;
41
+
42
+ function isFileTool(toolName) {
43
+ return FILE_TOOLS[toolName] === true;
44
+ }
45
+
46
+ // The one table of tools that have scoped keys, or (file tools) none. A
47
+ // bare-name key for any of them is the legacy whole-tool grant that older
48
+ // sessions persisted; isGranted honours it for every tool listed here, so
49
+ // changing a tool's keys cannot silently drop its persisted grants.
50
+ var SCOPED_TOOLS = Object.create(null);
51
+ SCOPED_TOOLS.Bash = true;
52
+ SCOPED_TOOLS.Skill = true;
53
+ Object.keys(FILE_TOOLS).forEach(function (t) { SCOPED_TOOLS[t] = true; });
54
+
55
+ function hasNarrowKey(toolName) {
56
+ return SCOPED_TOOLS[toolName] === true;
57
+ }
58
+
59
+ // Deriving a prefix from the command text (lexical rules over a shell grammar)
60
+ // missed shell semantics at two successive reviews, so a Bash grant is the
61
+ // exact line and nothing wider. The command is used byte for byte: any
62
+ // transform (trim, whitespace collapse, normalization) would let two different
63
+ // command strings, which bash runs differently, share one key.
64
+ function bashKey(input) {
65
+ var command = input && typeof input.command === "string" ? input.command : "";
66
+ if (command === "") return null;
67
+ return command.length + 5 <= MAX_KEY_LENGTH ? "Bash=" + command : null;
68
+ }
69
+
70
+ // Key shapes older sessions persisted that no call produces any more: a file
71
+ // tool key (Write:<path> in any form) and a Bash prefix key (Bash:<command>).
72
+ // They are dropped on load, never honoured.
73
+ function isRetiredKey(key) {
74
+ var m = /^([^:=]+)([:=])/.exec(key);
75
+ if (m === null) return false;
76
+ return isFileTool(m[1]) || (m[1] === "Bash" && m[2] === ":");
77
+ }
78
+
79
+ /**
80
+ * Whether a persisted value is one a grant under this key can hold: true, and
81
+ * never under a retired key.
82
+ */
83
+ function isGrantValue(key, value) {
84
+ return value === true && !isRetiredKey(key);
85
+ }
86
+
87
+ /**
88
+ * The key a call is granted and matched by, or null when it cannot be granted
89
+ * for the session.
90
+ * @param {string} toolName
91
+ * @param {?object} input
92
+ * @returns {?string}
93
+ */
94
+ function permissionGrantKey(toolName, input) {
95
+ if (toolName === "Bash") return bashKey(input);
96
+ if (isFileTool(toolName)) return null;
97
+ // The Skill tool is one name over many skills; a bare "Skill" key would
98
+ // authorize every one of them. Falls back to the bare name only when the
99
+ // call names no skill.
100
+ if (toolName === "Skill" && input && typeof input.skill === "string" && input.skill) {
101
+ return "Skill:" + input.skill;
102
+ }
103
+ return toolName;
104
+ }
105
+
106
+ /**
107
+ * Describe a stored key for the operator.
108
+ * @param {string} key
109
+ * @returns {{key: string, tool: string, wholeTool: boolean, text: string}}
110
+ */
111
+ function describeGrantKey(key) {
112
+ var m = /^([^:=]+)([:=])([\s\S]*)$/.exec(key);
113
+ if (!m) {
114
+ return {
115
+ key: key, tool: key, wholeTool: true,
116
+ text: "Every " + key + " call, whatever it does (whole-tool grant)",
117
+ };
118
+ }
119
+ var tool = m[1];
120
+ var value = m[3];
121
+ var text;
122
+ if (tool === "Bash") {
123
+ text = "Bash: exactly this command: " + value;
124
+ } else if (tool === "Skill") {
125
+ text = "Skill " + value;
126
+ } else {
127
+ text = key;
128
+ }
129
+ return { key: key, tool: tool, wholeTool: false, text: text };
130
+ }
131
+
132
+ /**
133
+ * The sentence the card and banner show before the click, or null when the
134
+ * call cannot be granted for the session.
135
+ * @returns {?string}
136
+ */
137
+ function grantScopeText(toolName, input) {
138
+ var key = permissionGrantKey(toolName, input);
139
+ if (key === null) return null;
140
+ var d = describeGrantKey(key);
141
+ if (d.wholeTool) return "Allow every " + toolName + " call in this session";
142
+ if (d.tool === "Bash") {
143
+ return "Allow only this exact command in this session";
144
+ }
145
+ if (d.tool === "Skill") return "Allow the " + key.slice(6) + " skill in this session";
146
+ return null;
147
+ }
148
+
149
+ /** Whether a call is covered by a grant in the session's map. */
150
+ function isGranted(allowedTools, toolName, input) {
151
+ if (!allowedTools) return false;
152
+ var own = function (k) { return Object.prototype.hasOwnProperty.call(allowedTools, k); };
153
+ var key = permissionGrantKey(toolName, input);
154
+ if (key !== null && own(key) && isGrantValue(key, allowedTools[key])) return true;
155
+ // A whole-tool grant from before grants were scoped.
156
+ return hasNarrowKey(toolName) && own(toolName) && allowedTools[toolName] === true;
157
+ }
158
+
159
+ /** Whether one more grant fits in the persisted record. */
160
+ function fitsBudget(allowedTools, key) {
161
+ var keys = Object.keys(allowedTools || {});
162
+ if (keys.indexOf(key) !== -1) return true;
163
+ if (keys.length >= MAX_GRANTS) return false;
164
+ var size = function (k) { return Buffer.byteLength(k) + 8; };
165
+ var bytes = keys.reduce(function (n, k) { return n + size(k); }, 0);
166
+ return bytes + size(key) <= MAX_GRANT_BYTES;
167
+ }
168
+
169
+ module.exports = {
170
+ permissionGrantKey: permissionGrantKey,
171
+ describeGrantKey: describeGrantKey,
172
+ grantScopeText: grantScopeText,
173
+ isGranted: isGranted,
174
+ isFileTool: isFileTool,
175
+ isGrantValue: isGrantValue,
176
+ fitsBudget: fitsBudget,
177
+ MAX_KEY_LENGTH: MAX_KEY_LENGTH,
178
+ MAX_GRANTS: MAX_GRANTS,
179
+ };
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ // One value for a key=value log line. Session titles, tool names, user ids and
4
+ // project slugs can come from outside the daemon, so nothing that could end a
5
+ // line or split a field survives: every character outside a small allowlist
6
+ // becomes "_", and the value is cut to maxLen. Never pass prompt text through
7
+ // here: the answer to "may this be logged?" is decided by the caller, this
8
+ // only keeps a permitted value on one line.
9
+
10
+ var DISALLOWED = /[^A-Za-z0-9._:@\/+-]/g;
11
+
12
+ // Control characters plus the Unicode line and paragraph separators. Built from
13
+ // char codes so the pattern never holds a raw line-terminator character.
14
+ var LINE_BREAKERS = new RegExp(
15
+ "[" + String.fromCharCode(0) + "-" + String.fromCharCode(0x1f) +
16
+ String.fromCharCode(0x7f) + String.fromCharCode(0x2028) + String.fromCharCode(0x2029) + "]+",
17
+ "g"
18
+ );
19
+
20
+ function logField(value, maxLen) {
21
+ if (value === undefined || value === null || value === "") return "-";
22
+ return String(value).replace(DISALLOWED, "_").slice(0, maxLen || 64);
23
+ }
24
+
25
+ // Free text that has to be readable (a refusal reason), for the END of a line:
26
+ // anything that could end the line or forge another becomes a space, and the
27
+ // text is cut to maxLen.
28
+ function logText(value, maxLen) {
29
+ return String(value === undefined || value === null ? "" : value)
30
+ .replace(LINE_BREAKERS, " ")
31
+ .slice(0, maxLen || 200);
32
+ }
33
+
34
+ module.exports = { logField: logField, logText: logText };
@@ -35,6 +35,8 @@
35
35
 
36
36
  'use strict';
37
37
 
38
+ var sessionReclaim = require('./session-reclaim');
39
+
38
40
  // Minimum interval between shedding passes (ms). A crossing that arrives
39
41
  // inside this window returns immediately with skipped=true rather than
40
42
  // running a second pass.
@@ -241,38 +243,17 @@ function shedMemory(opts) {
241
243
  // replays correctly on reconnect like any other history entry.
242
244
  for (var li = 0; li < liveChildReclaims.length; li++) {
243
245
  var reclaim = liveChildReclaims[li];
244
- var rSession = reclaim.session;
245
- if (!rSession) continue;
246
- try {
247
- rSession.pendingAutoResume = true;
248
- rSession.pendingAutoResumeReason = 'memory_pressure_reclaim';
249
- if (reclaim.sm && typeof reclaim.sm.saveSessionFile === 'function') {
250
- reclaim.sm.saveSessionFile(rSession);
251
- }
252
- } catch (e) {
253
- // Marker persistence failing must not block the notification below —
254
- // the operator still needs to see the reclaim happened.
255
- }
256
-
257
- var reclaimMessage = 'Memory pressure reclaimed this session while a background task was still running. '
258
- + 'It will auto-resume; if it does not, resume it manually.';
259
-
260
- if (reclaim.send) {
261
- try {
262
- reclaim.send({
263
- type: 'diagnostic',
264
- severity: 'warning',
265
- source: 'memory-reclaim',
266
- message: (reclaim.slug ? '[' + reclaim.slug + '] ' : '') + reclaimMessage,
267
- });
268
- } catch (e) { /* one client's send failure must not block others */ }
269
- }
270
-
271
- if (reclaim.sm && typeof reclaim.sm.sendAndRecord === 'function') {
272
- try {
273
- reclaim.sm.sendAndRecord(rSession, { type: 'error', text: reclaimMessage });
274
- } catch (e) { /* inline marker failing must not block the rest of the pass */ }
275
- }
246
+ // The idle reaper announces through the same helper, so both paths name
247
+ // the interrupted agents and mark the session the same way.
248
+ sessionReclaim.announceLiveAgentReclaim({
249
+ session: reclaim.session,
250
+ sm: reclaim.sm,
251
+ send: reclaim.send,
252
+ slug: reclaim.slug,
253
+ reason: 'memory_pressure_reclaim',
254
+ source: 'memory-reclaim',
255
+ cause: 'Memory pressure reclaimed this session while a background task was still running.',
256
+ });
276
257
  }
277
258
 
278
259
  return summary;
@@ -5,6 +5,7 @@ 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 sessionReclaim = require("./session-reclaim");
8
9
  var { buildVendorRegistryMessage } = require("./vendor-registry-message");
9
10
  // detectLite is cached per-project in project.js and passed via ctx.liteStatus.
10
11
  // This import is retained only for backward compat if ctx.liteStatus is absent.
@@ -147,6 +148,11 @@ function attachConnection(ctx) {
147
148
  infoMsg.dangerouslySkipPermissionsBlocked = true;
148
149
  }
149
150
  sendTo(ws, infoMsg);
151
+ // Background agents the last shutdown interrupted: nobody was connected
152
+ // to be told then.
153
+ sessionReclaim.restartDiagnostics(sm, slug, wsUser ? function (s) {
154
+ return usersModule.canAccessSession(wsUser.id, s, { visibility: "public" });
155
+ } : function () { return true; }).forEach(function (d) { sendTo(ws, d); });
150
156
  // Update notifications are pushed on a scheduled interval (see
151
157
  // scheduleUpdateBroadcast). We no longer push on connect to avoid
152
158
  // re-triggering the banner on every page refresh.
@@ -177,6 +183,13 @@ function attachConnection(ctx) {
177
183
  _loop.sendConnectionState(ws);
178
184
  if (_mcp) _mcp.sendConnectionState(ws);
179
185
  if (_notifications) _notifications.sendConnectionState(ws, sendTo);
186
+ // A client that connects is told the current offer state: the held offer, or
187
+ // an explicit retraction when none stands, so a missed retraction cannot
188
+ // leave a dead restart action on screen.
189
+ if (typeof opts.onGetBuildUpdateDiagnostic === "function") {
190
+ var _buildUpdateDiag = opts.onGetBuildUpdateDiagnostic();
191
+ if (_buildUpdateDiag) sendTo(ws, _buildUpdateDiag);
192
+ }
180
193
 
181
194
  // Session list (filtered for access control)
182
195
  // Use the canonical mapper from sessions.js
@@ -228,6 +241,7 @@ function attachConnection(ctx) {
228
241
  // subsequent reconnect to the same session.
229
242
  if (active.pendingAutoResume) {
230
243
  active.pendingAutoResume = false;
244
+ active.restartNoticeAgents = null;
231
245
  sm.saveSessionFile(active);
232
246
  }
233
247
  // lr-2ea2a7: hasHistory uses the ABSOLUTE count (_historyBaseIndex +
@@ -1,12 +1,13 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
+ var { createSessionInput, settle, RESULT } = require("./session-input");
3
4
 
4
5
  // How long (ms) to keep processed trigger files before pruning on startup.
5
6
  var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days (processed/ and expired/)
6
7
  // Default grace period before an unprocessed trigger is moved to expired/.
7
8
  var DEFAULT_UNPROCESSED_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
8
9
  var CLOCK_SKEW_TOLERANCE_MS = 5 * 60 * 1000; // future createdAt beyond this is ignored
9
- var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
10
+ var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
10
11
  var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
11
12
 
12
13
  /**
@@ -19,23 +20,44 @@ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
19
20
  * processed/ on success.
20
21
  *
21
22
  * Schema v1 (all fields except * are required):
22
- * { version: 1, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt* }
23
- * -> always spawns a new session (backward-compatible, v1 files remain valid)
23
+ * { version: 1, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt*,
24
+ * vendor*, agentName*, sessionVisibility*, initiator* }
25
+ * -> always opens a new session (backward-compatible, v1 files remain valid)
24
26
  *
25
27
  * Schema v2 (all fields except * are required):
26
- * { version: 2, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt*, sessionId* }
27
- * -> if sessionId present: pushMessage to the named session (mid-session inject)
28
- * -> if sessionId absent: spawnSession (same as v1)
29
- * On push_message path, if sessionId is not found the trigger is NOT archived
30
- * so daemon-down recovery can retry when the session reconnects.
28
+ * { version: 2, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt*,
29
+ * sessionId*, vendor*, agentName*, sessionVisibility*, initiator* }
30
+ * -> if sessionId present: send initialPrompt as that session's next turn,
31
+ * resuming the session first when its runtime has ended (vendor, agentName
32
+ * and sessionVisibility are ignored: the session keeps its own)
33
+ * -> if sessionId absent: open a new session (same as v1)
31
34
  *
32
- * contextNote on the push_message path: sdk.pushMessage(session, text, images)
33
- * takes IMAGES as its third argument, so contextNote is never passed there
34
- * (it stays null). The prompt text delivered to the agent is unchanged; instead
35
- * a user_message entry carrying { source: "external-trigger", triggerId,
36
- * contextNote } is recorded in the session history and session file so the
37
- * agent-origin is distinguishable from operator-typed input. The entry is
38
- * recorded only after the push succeeds, so retries never duplicate it.
35
+ * vendor, agentName and sessionVisibility choose the kind of session an open
36
+ * creates; absent means the default vendor, no named agent, shared. initiator
37
+ * names who started the turn: trigger (default), scheduled, scheduled-now or
38
+ * loop. human and anything unknown are refused: a file is never a human turn.
39
+ *
40
+ * Every file is acted on by lib/session-input.js, the same code the daemon IPC
41
+ * verbs run. A file whose outcome is final (delivered, resumed-and-delivered,
42
+ * opened, not-found, refused) moves to processed/ with the outcome written into
43
+ * it under "result". A session id that exists nowhere is not-found, never
44
+ * retried. Only a delivery failure ("error") or memory pressure keeps the file
45
+ * in place, until it expires. A query that fails to start is such a failure:
46
+ * "error" is reported only then, never "delivered".
47
+ *
48
+ * Archiving is one rename into processed/ after the request is handled, then
49
+ * the result is written into the processed record. Delivery is therefore
50
+ * at-least-once across a daemon crash: a crash between delivery and the rename
51
+ * leaves the trigger pending, and it is dispatched again on restart. A crash (or
52
+ * a write failure) between the rename and the result write leaves a processed
53
+ * record without a "result": the request was handled, its outcome was not kept,
54
+ * and nothing retries it.
55
+ *
56
+ * contextNote on the send path: the prompt text delivered to the agent is
57
+ * unchanged; a user_message entry carrying { source: "external-trigger",
58
+ * triggerId, initiator, contextNote } is recorded in the session history and
59
+ * session file so the agent-origin is distinguishable from operator-typed
60
+ * input. The entry is recorded only after the delivery succeeds.
39
61
  *
40
62
  * Trigger lifecycle directories under triggersDir:
41
63
  * (triggersDir) — pending / retrying
@@ -52,6 +74,7 @@ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
52
74
  * triggersDir — absolute path to ~/.clagentic/external-triggers/
53
75
  * getProject — function(slug) -> project context | null
54
76
  * unprocessedTtlMs — optional grace period before expiry (default 7 days)
77
+ * sessionInput — optional createSessionInput() instance shared with the IPC verbs
55
78
  *
56
79
  * Security: triggers dir is under the user's home. Any process running as
57
80
  * the same OS user can write files. Acceptable for single-user self-hosted
@@ -72,6 +95,7 @@ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
72
95
  function attachExternalTrigger(ctx) {
73
96
  var triggersDir = ctx.triggersDir;
74
97
  var getProject = ctx.getProject;
98
+ var sessionInput = ctx.sessionInput || createSessionInput({ getProject: getProject });
75
99
 
76
100
  var triggersRoot = path.dirname(path.join(triggersDir, "x"));
77
101
  var processedDir = path.join(triggersDir, "processed");
@@ -109,110 +133,43 @@ function attachExternalTrigger(ctx) {
109
133
  if (obj.sessionId !== undefined && (typeof obj.sessionId !== "string" || !obj.sessionId)) {
110
134
  return "sessionId must be a non-empty string when present";
111
135
  }
136
+ // vendor, agentName, sessionVisibility and initiator are not checked here:
137
+ // session-input.js refuses a bad one by name, and that refusal is recorded
138
+ // in processed/ where the writer can read it.
112
139
  return null; // valid
113
140
  }
114
141
 
115
- // --- Session spawn ---
116
-
117
- function spawnSession(project, trigger) {
118
- var sm = project.sm;
119
- var sdk = project.sdk;
120
- var send = project.send;
121
- var onProcessingChanged = project.onProcessingChanged;
122
- var getLinuxUserForSession = project.getLinuxUserForSession;
123
-
124
- if (!sm || !sdk || !send || !onProcessingChanged || !getLinuxUserForSession) {
125
- console.error("[external-trigger] Project context missing required fields for slug:", trigger.projectSlug);
126
- return false;
127
- }
128
-
129
- var sess = sm.createSession({});
130
- sess.title = (trigger.contextNote || "External trigger") + " — " + trigger.id.substring(0, 12);
131
- if (trigger.cwd) sess.cwd = trigger.cwd;
132
- sm.saveSessionFile(sess);
133
- sm.broadcastSessionList();
134
-
135
- var userMsg = { type: "user_message", text: trigger.initialPrompt };
136
- // lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
137
- sm.recordHistoryEntry(sess, userMsg, true);
138
- sm.appendToSessionFile(sess, userMsg);
139
-
140
- sess.isProcessing = true;
141
- onProcessingChanged();
142
- sess.sentToolResults = {};
143
- // singleTurn=false (default): session stays open for human follow-up.
144
- // The trigger JSON can set singleTurn:true for fire-and-forget agentic
145
- // dispatches (not part of v1 schema, reserved for future use).
146
- sess.acceptEditsAfterStart = true;
142
+ // --- Dispatch ---
147
143
 
148
- try {
149
- sdk.startQuery(sess, trigger.initialPrompt, undefined, getLinuxUserForSession(sess));
150
- } catch (e) {
151
- console.error("[external-trigger] startQuery failed for trigger " + trigger.id + ":", e.message || e);
152
- return false;
153
- }
154
-
155
- console.log("[external-trigger] Session spawned: project=" + trigger.projectSlug + " session=" + sess.localId + " trigger=" + trigger.id);
156
- return true;
157
- }
158
-
159
- // --- Mid-session inject ---
160
-
161
- // Marks the pushed message as agent-origin in history/session file. Failure
162
- // here must not turn a delivered message into a retry (double delivery).
163
- function recordPushedMessage(sm, sess, trigger) {
164
- var entry = {
165
- type: "user_message",
166
- text: trigger.initialPrompt,
167
- source: "external-trigger",
144
+ // Hands a validated trigger to session-input.js: send to the named session
145
+ // (v2 with sessionId) or open a new one. Returns a result or a Promise of one.
146
+ function dispatchTrigger(trigger) {
147
+ var request = {
148
+ projectSlug: trigger.projectSlug,
149
+ prompt: trigger.initialPrompt,
150
+ contextNote: trigger.contextNote,
168
151
  triggerId: trigger.id,
152
+ initiator: trigger.initiator,
169
153
  };
170
- if (trigger.contextNote) entry.contextNote = trigger.contextNote;
171
- try {
172
- sm.recordHistoryEntry(sess, entry, true);
173
- sm.appendToSessionFile(sess, entry);
174
- } catch (e) {
175
- console.error("[external-trigger] Failed to record pushed message for trigger " + trigger.id + ":", e.message || e);
176
- }
177
- }
178
-
179
- function pushMessageToSession(project, trigger) {
180
- var sm = project.sm;
181
- var sdk = project.sdk;
182
-
183
- if (!sm || !sdk) {
184
- console.error("[external-trigger] Project context missing sm/sdk for push_message, slug:", trigger.projectSlug);
185
- return "error";
186
- }
187
-
188
- var found = null;
189
- sm.sessions.forEach(function (s) {
190
- if (!found && s.cliSessionId === trigger.sessionId) {
191
- found = s;
192
- }
193
- });
194
-
195
- if (!found) {
196
- console.warn("[external-trigger] push_message: session not found: " + trigger.sessionId + " (trigger " + trigger.id + " not archived — will retry)");
197
- return "not_found";
198
- }
199
-
200
- try {
201
- // Third argument is images, not metadata: contextNote travels via the
202
- // recorded history entry below.
203
- sdk.pushMessage(found, trigger.initialPrompt, null);
204
- console.log("[external-trigger] push_message delivered to session " + trigger.sessionId + " (trigger " + trigger.id + ")");
205
- recordPushedMessage(sm, found, trigger);
206
- return "ok";
207
- } catch (e) {
208
- console.error("[external-trigger] push_message failed for trigger " + trigger.id + ":", e.message || e);
209
- return "error";
154
+ if (trigger.sessionId) {
155
+ request.sessionId = trigger.sessionId;
156
+ return sessionInput.sendInput(request);
210
157
  }
158
+ request.cwd = trigger.cwd;
159
+ request.vendor = trigger.vendor;
160
+ request.agentName = trigger.agentName;
161
+ request.sessionVisibility = trigger.sessionVisibility;
162
+ return sessionInput.openSession(request);
211
163
  }
212
164
 
213
165
  // --- Archive ---
214
166
 
215
- function archiveTrigger(triggerPath, id) {
167
+ // Moves the trigger to processed/ in one rename once the request is handled,
168
+ // then writes the outcome into the processed record so the writer can read
169
+ // what happened to its request. Delivery is at-least-once across a daemon
170
+ // crash: a crash after the input is delivered and before the rename leaves
171
+ // the trigger pending, and it is dispatched again on restart.
172
+ function archiveTrigger(triggerPath, id, obj, result) {
216
173
  var dest = path.join(processedDir, id + ".json");
217
174
  try {
218
175
  fs.renameSync(triggerPath, dest);
@@ -223,10 +180,18 @@ function attachExternalTrigger(ctx) {
223
180
  fs.unlinkSync(triggerPath);
224
181
  } catch (e2) {
225
182
  console.error("[external-trigger] Failed to archive trigger " + id + ":", e2.message || e2);
183
+ return;
226
184
  }
227
185
  }
186
+ var record = Object.assign({}, obj, { result: result, processedAt: new Date().toISOString() });
187
+ try {
188
+ fs.writeFileSync(dest, JSON.stringify(record, null, 2) + "\n");
189
+ } catch (e) {
190
+ console.error("[external-trigger] Failed to record the result of trigger " + id + ":", e.message || e);
191
+ }
228
192
  }
229
193
 
194
+
230
195
  // --- Expiry ---
231
196
 
232
197
  function triggerAgeMs(filePath, obj) {
@@ -302,23 +267,26 @@ function attachExternalTrigger(ctx) {
302
267
  return;
303
268
  }
304
269
 
305
- if (obj.sessionId) {
306
- // v2 mid-session inject path
307
- var result = pushMessageToSession(project, obj);
308
- if (result === "ok") {
309
- archiveTrigger(filePath, id);
310
- } else if (result === "not_found") {
311
- // Do not archive — allow daemon-down / timing retry.
312
- // Clear dispatched so the watcher can re-process if the file is still present.
313
- delete dispatched[id];
270
+ settle(dispatchTrigger(obj), function (result) {
271
+ if (result.result === RESULT.ERROR && result.retryable !== false) {
272
+ // Delivery was attempted and failed in a way trying again can help, and
273
+ // the failure is reported as one (never archived as done): leave the
274
+ // file and keep dispatched[id] set to avoid a rapid retry loop. A
275
+ // restart tries it again; it expires by TTL otherwise. An error marked
276
+ // not retryable (a failed open, which removed its session) is archived
277
+ // below with that result.
278
+ console.error("[external-trigger] Trigger " + id + " failed: " + result.reason);
279
+ return;
314
280
  }
315
- // "error" case: leave dispatched[id] set to avoid a rapid retry loop.
316
- } else {
317
- var ok = spawnSession(project, obj);
318
- if (ok) {
319
- archiveTrigger(filePath, id);
281
+ if (result.retryable) {
282
+ // The daemon is shedding work: keep the file and let the next scan retry.
283
+ delete dispatched[id];
284
+ console.warn("[external-trigger] Trigger " + id + " deferred: " + result.reason);
285
+ return;
320
286
  }
321
- }
287
+ console.log("[external-trigger] Trigger " + id + " " + result.result + (result.reason ? ": " + result.reason : ""));
288
+ archiveTrigger(filePath, id, obj, result);
289
+ });
322
290
  }
323
291
 
324
292
  // --- Watcher ---
@@ -7,6 +7,7 @@ var { fsAsUser } = require("./os-users");
7
7
  var usersModule = require("./users");
8
8
  var { promptsFor } = require("./prompt-registry");
9
9
  var { mayAnswerPrompt } = require("./prompt-access");
10
+ var promptSource = require("./prompt-source");
10
11
  var fileScope = require("./project-file-scope");
11
12
 
12
13
  var IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico"]);
@@ -244,6 +245,7 @@ function attachHTTP(ctx) {
244
245
  : prompts.respond(requestId, { decision: decision }, {
245
246
  kinds: ["permission", "plan"],
246
247
  denyMessage: "Denied via push notification",
248
+ source: promptSource.fromPush(req, decision),
247
249
  });
248
250
  if (outcome.status === "resolved") {
249
251
  res.writeHead(200, { "Content-Type": "application/json" });
@@ -7,6 +7,7 @@ var store = require("./store");
7
7
  var usersModule = require("./users");
8
8
  var { writeHandoff, buildHandoffPreamble } = require("./loop-handoff");
9
9
  var { authOf } = require("./project-access");
10
+ var { INITIATORS } = require("./turn-initiator");
10
11
 
11
12
  var LOOP_ID_RE = /^loop_[A-Za-z0-9_-]+$/;
12
13
 
@@ -613,7 +614,7 @@ function attachLoop(ctx) {
613
614
  session.acceptEditsAfterStart = true;
614
615
  session.singleTurn = true;
615
616
  if (loopState.settings) session.loopSettings = loopState.settings;
616
- sdk.startQuery(session, _iterationPrompt, undefined, getLinuxUserForSession(session));
617
+ sdk.startQuery(session, _iterationPrompt, undefined, getLinuxUserForSession(session), INITIATORS.LOOP);
617
618
  }
618
619
 
619
620
  function runJudge() {
@@ -736,7 +737,7 @@ function attachLoop(ctx) {
736
737
  judgeSession.acceptEditsAfterStart = true;
737
738
  judgeSession.singleTurn = true;
738
739
  if (loopState.settings) judgeSession.loopSettings = loopState.settings;
739
- sdk.startQuery(judgeSession, judgePrompt, undefined, getLinuxUserForSession(judgeSession));
740
+ sdk.startQuery(judgeSession, judgePrompt, undefined, getLinuxUserForSession(judgeSession), INITIATORS.LOOP);
740
741
  }
741
742
 
742
743
  // lr-2ea2a7: forward-accumulates delta/text across the FULL heap array —
@@ -1162,7 +1163,7 @@ function attachLoop(ctx) {
1162
1163
  onProcessingChanged();
1163
1164
  judgeCraftSession.sentToolResults = {};
1164
1165
  sendToSession(judgeCraftSession.localId, { type: "status", status: "processing" });
1165
- sdk.startQuery(judgeCraftSession, judgeCraftPrompt, undefined, getLinuxUserForSession(judgeCraftSession));
1166
+ sdk.startQuery(judgeCraftSession, judgeCraftPrompt, undefined, getLinuxUserForSession(judgeCraftSession), INITIATORS.LOOP);
1166
1167
 
1167
1168
  send({ type: "ralph_crafting_started", sessionId: judgeCraftSession.localId, taskId: newLoopId, source: recordSource });
1168
1169
  send({ type: "ralph_phase", phase: "crafting", wizardData: loopState.wizardData, craftingSessionId: judgeCraftSession.localId });
@@ -1239,7 +1240,7 @@ function attachLoop(ctx) {
1239
1240
  onProcessingChanged();
1240
1241
  craftingSession.sentToolResults = {};
1241
1242
  sendToSession(craftingSession.localId, { type: "status", status: "processing" });
1242
- sdk.startQuery(craftingSession, craftingPrompt, undefined, getLinuxUserForSession(craftingSession));
1243
+ sdk.startQuery(craftingSession, craftingPrompt, undefined, getLinuxUserForSession(craftingSession), INITIATORS.LOOP);
1243
1244
 
1244
1245
  send({ type: "ralph_crafting_started", sessionId: craftingSession.localId, taskId: newLoopId, source: recordSource });
1245
1246
  send({ type: "ralph_phase", phase: "crafting", wizardData: loopState.wizardData, craftingSessionId: craftingSession.localId });