@clagentic/console 1.9.0 → 1.10.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.
- package/LICENSE +117 -12
- package/LICENSES/MIT-legacy.txt +22 -0
- package/LICENSES/README.md +15 -0
- package/README.md +9 -3
- package/bin/cli.js +40 -5
- package/deploy/clagentic-console.service +10 -6
- package/lib/agent-dispatch-tool.js +20 -0
- package/lib/audit.js +3 -2
- package/lib/build-changes.js +79 -0
- package/lib/build-identity.js +192 -0
- package/lib/build-monitor.js +125 -0
- package/lib/build-sha.json +2 -2
- package/lib/build-update-check.js +138 -0
- package/lib/build-update-offer.js +141 -0
- package/lib/build-update-restart.js +142 -0
- package/lib/build-update-standing.js +184 -0
- package/lib/cli/daemon-launch.js +25 -22
- package/lib/cli/ipc-subcommands.js +6 -0
- package/lib/cli/session-subcommands.js +122 -0
- package/lib/cli-sessions.js +8 -1
- package/lib/codex-defaults.js +8 -2
- package/lib/config.js +32 -20
- package/lib/daemon-env-settings.js +84 -0
- package/lib/daemon-projects.js +57 -0
- package/lib/daemon.js +288 -205
- package/lib/drain.js +74 -17
- package/lib/env-compat.js +61 -0
- package/lib/extension-commands.js +45 -0
- package/lib/history-visibility.js +4 -0
- package/lib/idle-adapter-reaper.js +71 -0
- package/lib/link-trap.js +78 -0
- package/lib/mcp-local.js +8 -6
- package/lib/mcp-tool-input.js +116 -0
- package/lib/mcp-tool-schema.js +179 -0
- package/lib/memory-limits.js +61 -5
- package/lib/memory-setting-validate.js +65 -0
- package/lib/memory-shed.js +13 -32
- package/lib/new-work-gate.js +47 -0
- package/lib/os-users.js +5 -3
- package/lib/project-access.js +139 -0
- package/lib/project-connection.js +37 -22
- package/lib/project-external-trigger.js +166 -105
- package/lib/project-file-scope.js +172 -0
- package/lib/project-file-watch.js +86 -61
- package/lib/project-filesystem.js +144 -128
- package/lib/project-git.js +119 -0
- package/lib/project-http.js +44 -28
- package/lib/project-loop.js +17 -9
- package/lib/project-mcp.js +53 -72
- package/lib/project-message-gate.js +70 -0
- package/lib/project-notifications.js +31 -4
- package/lib/project-prompt-responses.js +217 -0
- package/lib/project-sessions.js +192 -355
- package/lib/project-user-message.js +27 -15
- package/lib/project.js +212 -147
- package/lib/projects-dir.js +90 -0
- package/lib/prompt-access.js +22 -0
- package/lib/prompt-kinds/answer-limits.js +15 -0
- package/lib/prompt-kinds/ask-user.js +58 -0
- package/lib/prompt-kinds/codecs.js +97 -0
- package/lib/prompt-kinds/elicitation.js +77 -0
- package/lib/prompt-kinds/extension.js +39 -0
- package/lib/prompt-kinds/index.js +68 -0
- package/lib/prompt-kinds/permission.js +114 -0
- package/lib/prompt-kinds/plan.js +79 -0
- package/lib/prompt-kinds/tool-call.js +38 -0
- package/lib/prompt-registry.js +680 -0
- package/lib/public/app.js +1 -1
- package/lib/public/css/diagnostics.css +80 -0
- package/lib/public/css/input.css +17 -3
- package/lib/public/css/menus.css +10 -0
- package/lib/public/css/messages.css +5 -0
- package/lib/public/css/rewind.css +22 -0
- package/lib/public/index.html +4 -12
- package/lib/public/modules/agent-dispatch-tool.js +9 -0
- package/lib/public/modules/app-connection.js +7 -0
- package/lib/public/modules/app-cursors.js +7 -5
- package/lib/public/modules/app-messages.js +52 -47
- package/lib/public/modules/app-notifications.js +47 -71
- package/lib/public/modules/app-panels.js +61 -59
- package/lib/public/modules/app-projects.js +2 -1
- package/lib/public/modules/app-rendering.js +4 -10
- package/lib/public/modules/build-update-detail.js +54 -0
- package/lib/public/modules/diagnostics.js +170 -20
- package/lib/public/modules/filebrowser.js +18 -16
- package/lib/public/modules/history-visibility.js +4 -0
- package/lib/public/modules/mention.js +3 -2
- package/lib/public/modules/mode-options.js +38 -0
- package/lib/public/modules/project-settings.js +19 -8
- package/lib/public/modules/prompt-banner.js +78 -0
- package/lib/public/modules/prompt-card.js +201 -0
- package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
- package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
- package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
- package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
- package/lib/public/modules/prompt-kinds/index.js +18 -0
- package/lib/public/modules/prompt-kinds/own-key.js +29 -0
- package/lib/public/modules/prompt-kinds/package.json +3 -0
- package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
- package/lib/public/modules/prompt-kinds/permission.js +209 -0
- package/lib/public/modules/prompt-kinds/plan.js +102 -0
- package/lib/public/modules/prompt-state.js +142 -0
- package/lib/public/modules/prompts.js +134 -0
- package/lib/public/modules/rewind.js +4 -1
- package/lib/public/modules/server-settings.js +2 -4
- package/lib/public/modules/sidebar-mobile.js +19 -9
- package/lib/public/modules/sidebar-sessions.js +21 -14
- package/lib/public/modules/sticky-notes.js +3 -2
- package/lib/public/modules/team-panel.js +5 -4
- package/lib/public/modules/tools.js +81 -906
- package/lib/public/modules/vendor-picker.js +53 -0
- package/lib/public/modules/vendor-registry.js +142 -0
- package/lib/public/sw.js +3 -1
- package/lib/rc-migrate.js +44 -0
- package/lib/runtime-env-keys.js +109 -0
- package/lib/runtime-env.js +236 -0
- package/lib/sdk-bridge.js +348 -284
- package/lib/sdk-message-processor.js +117 -146
- package/lib/sdk-skill-discovery.js +65 -60
- package/lib/server-hub-sessions.js +13 -10
- package/lib/server-palette.js +28 -19
- package/lib/server.js +156 -115
- package/lib/service-install.js +96 -0
- package/lib/session-capabilities.js +76 -0
- package/lib/session-id.js +33 -0
- package/lib/session-input-ipc.js +32 -0
- package/lib/session-input.js +379 -0
- package/lib/session-reclaim.js +284 -0
- package/lib/session-resume.js +172 -0
- package/lib/sessions.js +61 -30
- package/lib/supervisor.js +39 -0
- package/lib/turn-initiator.js +108 -0
- package/lib/users-permissions.js +9 -6
- package/lib/users.js +9 -0
- package/lib/utils.js +4 -2
- package/lib/vendor-auth.js +22 -0
- package/lib/vendor-registry-message.js +66 -0
- package/lib/ws-origin.js +99 -0
- package/lib/ws-schema.js +36 -23
- package/lib/yoke/adapters/claude-capabilities.js +38 -0
- package/lib/yoke/adapters/claude-vendor.js +34 -0
- package/lib/yoke/adapters/claude-worker.js +57 -87
- package/lib/yoke/adapters/claude.js +182 -88
- package/lib/yoke/adapters/codex-capabilities.js +40 -0
- package/lib/yoke/adapters/codex-vendor.js +46 -0
- package/lib/yoke/adapters/codex.js +462 -211
- package/lib/yoke/adapters/effort-control.js +34 -0
- package/lib/yoke/adapters/permission-relay.js +58 -0
- package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
- package/lib/yoke/auth-checks.js +91 -0
- package/lib/yoke/capabilities.js +49 -0
- package/lib/yoke/codex-app-server.js +30 -56
- package/lib/yoke/codex-binary.js +254 -0
- package/lib/yoke/codex-command.js +122 -0
- package/lib/yoke/codex-protocol.js +96 -0
- package/lib/yoke/codex-version.js +135 -0
- package/lib/yoke/env-ownership.js +40 -0
- package/lib/yoke/index.js +84 -174
- package/lib/yoke/install-probe.js +136 -0
- package/lib/yoke/instructions.js +7 -11
- package/lib/yoke/interface.js +206 -4
- package/lib/yoke/package.json +1 -1
- package/lib/yoke/provider-credentials.js +96 -0
- package/lib/yoke/registry.js +377 -0
- package/package.json +12 -9
- package/scripts/check-sdk-lock-drift.js +160 -0
- package/scripts/check-test-count.js +76 -1
- package/scripts/postinstall.js +218 -136
- package/scripts/prompt-harness-history.js +202 -0
- package/scripts/verify-installed-build.js +59 -17
- package/scripts/verify-installed.js +67 -0
- package/lib/sdk-permission-ownership.js +0 -136
|
@@ -2,7 +2,11 @@ var fs = require("fs");
|
|
|
2
2
|
var path = require("path");
|
|
3
3
|
var usersModule = require("./users");
|
|
4
4
|
var userPresence = require("./user-presence");
|
|
5
|
+
var { authOf } = require("./project-access");
|
|
5
6
|
var { getCodexConfig } = require("./codex-defaults");
|
|
7
|
+
var { promptsFor } = require("./prompt-registry");
|
|
8
|
+
var sessionReclaim = require("./session-reclaim");
|
|
9
|
+
var { buildVendorRegistryMessage } = require("./vendor-registry-message");
|
|
6
10
|
// detectLite is cached per-project in project.js and passed via ctx.liteStatus.
|
|
7
11
|
// This import is retained only for backward compat if ctx.liteStatus is absent.
|
|
8
12
|
var { detectLite } = require("./lite-detect");
|
|
@@ -17,7 +21,7 @@ var { detectLite } = require("./lite-detect");
|
|
|
17
21
|
* hydrateImageRefs, broadcastClientCount, broadcastPresence,
|
|
18
22
|
* getProjectList, getHubSchedules, loadContextSources,
|
|
19
23
|
* handleMessage, handleDisconnection,
|
|
20
|
-
* stopFileWatch, stopAllDirWatches,
|
|
24
|
+
* stopFileWatch(ws), stopAllDirWatches(ws),
|
|
21
25
|
* getProjectOwnerId, setProjectOwnerId, getLatestVersion,
|
|
22
26
|
* getTitle, getProject
|
|
23
27
|
*/
|
|
@@ -80,7 +84,13 @@ function attachConnection(ctx) {
|
|
|
80
84
|
if (!active && allSessions.length > 0) {
|
|
81
85
|
active = allSessions[0];
|
|
82
86
|
for (var fi = 1; fi < allSessions.length; fi++) {
|
|
83
|
-
|
|
87
|
+
// >= not >: lastActivity has millisecond resolution, and a session
|
|
88
|
+
// manager always creates a blank initial session at construction, so a
|
|
89
|
+
// session created right after it routinely shares its millisecond.
|
|
90
|
+
// allSessions is in creation order, so on a tie the later (newer)
|
|
91
|
+
// session must win; strict > made the blank one win, which restored
|
|
92
|
+
// clients into the wrong session on fast hosts.
|
|
93
|
+
if ((allSessions[fi].lastActivity || 0) >= (active.lastActivity || 0)) {
|
|
84
94
|
active = allSessions[fi];
|
|
85
95
|
}
|
|
86
96
|
}
|
|
@@ -114,7 +124,7 @@ function attachConnection(ctx) {
|
|
|
114
124
|
|
|
115
125
|
// Send cached state
|
|
116
126
|
var _userId = ws._clagenticUser ? ws._clagenticUser.id : null;
|
|
117
|
-
var _filteredProjects = getProjectList(_userId);
|
|
127
|
+
var _filteredProjects = getProjectList(_userId, authOf(ws));
|
|
118
128
|
var title = getTitle();
|
|
119
129
|
var project = getProject();
|
|
120
130
|
var ownerLocked = !!(osUsers && osUsers.length > 0 && /^\/home\/[^/]+\//.test(cwd));
|
|
@@ -138,6 +148,11 @@ function attachConnection(ctx) {
|
|
|
138
148
|
infoMsg.dangerouslySkipPermissionsBlocked = true;
|
|
139
149
|
}
|
|
140
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); });
|
|
141
156
|
// Update notifications are pushed on a scheduled interval (see
|
|
142
157
|
// scheduleUpdateBroadcast). We no longer push on connect to avoid
|
|
143
158
|
// re-triggering the banner on every page refresh.
|
|
@@ -152,19 +167,29 @@ function attachConnection(ctx) {
|
|
|
152
167
|
// it correctly to disk — only this display path never consulted it) —
|
|
153
168
|
// the root cause of "picked opus 4.7, session ran on it, chip still says
|
|
154
169
|
// sonnet after a reconnect." See effectiveSessionModel() in sessions.js.
|
|
170
|
+
// Install state is per OS identity; a connection is told its own.
|
|
171
|
+
var _osIdentity = osUsers && wsUser && wsUser.linuxUser ? wsUser.linuxUser : null;
|
|
155
172
|
var _initialModel = sm.effectiveSessionModel(restoredActive);
|
|
156
173
|
if (_initialModel) {
|
|
157
|
-
sendTo(ws, { type: "model_info", model: _initialModel, models: initialModels, vendor: initialVendor, availableVendors: sm.availableVendors || []
|
|
174
|
+
sendTo(ws, { type: "model_info", model: _initialModel, models: initialModels, vendor: initialVendor, availableVendors: sm.availableVendors || [] });
|
|
158
175
|
}
|
|
176
|
+
sendTo(ws, buildVendorRegistryMessage(sm, _osIdentity));
|
|
159
177
|
sendTo(ws, { type: "config_state", model: _initialModel, mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
|
|
160
178
|
sendTo(ws, Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
|
|
161
179
|
sendTo(ws, { type: "term_list", terminals: tm.list(ws) });
|
|
162
180
|
// Context sources sent after session is resolved (per-session storage)
|
|
163
181
|
sendTo(ws, { type: "notes_list", notes: nm.list() });
|
|
164
|
-
sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules() });
|
|
182
|
+
sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules(_userId, authOf(ws)) });
|
|
165
183
|
_loop.sendConnectionState(ws);
|
|
166
184
|
if (_mcp) _mcp.sendConnectionState(ws);
|
|
167
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
|
+
}
|
|
168
193
|
|
|
169
194
|
// Session list (filtered for access control)
|
|
170
195
|
// Use the canonical mapper from sessions.js
|
|
@@ -216,6 +241,7 @@ function attachConnection(ctx) {
|
|
|
216
241
|
// subsequent reconnect to the same session.
|
|
217
242
|
if (active.pendingAutoResume) {
|
|
218
243
|
active.pendingAutoResume = false;
|
|
244
|
+
active.restartNoticeAgents = null;
|
|
219
245
|
sm.saveSessionFile(active);
|
|
220
246
|
}
|
|
221
247
|
// lr-2ea2a7: hasHistory uses the ABSOLUTE count (_historyBaseIndex +
|
|
@@ -254,19 +280,9 @@ function attachConnection(ctx) {
|
|
|
254
280
|
// 'processing' latch blind to which session it belongs to.
|
|
255
281
|
sendTo(ws, { type: "status", status: "processing", localId: active.localId });
|
|
256
282
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
sendTo(ws, {
|
|
261
|
-
type: "permission_request_pending",
|
|
262
|
-
requestId: p.requestId,
|
|
263
|
-
toolName: p.toolName,
|
|
264
|
-
toolInput: p.toolInput,
|
|
265
|
-
toolUseId: p.toolUseId,
|
|
266
|
-
decisionReason: p.decisionReason,
|
|
267
|
-
mateId: p.mateId || undefined,
|
|
268
|
-
});
|
|
269
|
-
}
|
|
283
|
+
promptsFor(sm).pendingMessages(active).forEach(function (pendingMsg) {
|
|
284
|
+
sendTo(ws, pendingMsg);
|
|
285
|
+
});
|
|
270
286
|
}
|
|
271
287
|
|
|
272
288
|
if (active) {
|
|
@@ -322,10 +338,9 @@ function attachConnection(ctx) {
|
|
|
322
338
|
}
|
|
323
339
|
tm.detachAll(ws);
|
|
324
340
|
clients.delete(ws);
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
}
|
|
341
|
+
// Watches belong to the connection that opened them.
|
|
342
|
+
stopFileWatch(ws);
|
|
343
|
+
stopAllDirWatches(ws);
|
|
329
344
|
broadcastClientCount();
|
|
330
345
|
broadcastPresence();
|
|
331
346
|
}
|
|
@@ -1,9 +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
|
-
var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
|
|
6
|
-
|
|
6
|
+
var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days (processed/ and expired/)
|
|
7
|
+
// Default grace period before an unprocessed trigger is moved to expired/.
|
|
8
|
+
var DEFAULT_UNPROCESSED_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
9
|
+
var CLOCK_SKEW_TOLERANCE_MS = 5 * 60 * 1000; // future createdAt beyond this is ignored
|
|
10
|
+
var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
|
|
7
11
|
var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
|
|
8
12
|
|
|
9
13
|
/**
|
|
@@ -16,19 +20,61 @@ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
|
|
|
16
20
|
* processed/ on success.
|
|
17
21
|
*
|
|
18
22
|
* Schema v1 (all fields except * are required):
|
|
19
|
-
* { version: 1, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt
|
|
20
|
-
*
|
|
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)
|
|
21
26
|
*
|
|
22
27
|
* Schema v2 (all fields except * are required):
|
|
23
|
-
* { version: 2, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt*,
|
|
24
|
-
*
|
|
25
|
-
* -> if sessionId
|
|
26
|
-
*
|
|
27
|
-
*
|
|
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)
|
|
34
|
+
*
|
|
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.
|
|
61
|
+
*
|
|
62
|
+
* Trigger lifecycle directories under triggersDir:
|
|
63
|
+
* (triggersDir) — pending / retrying
|
|
64
|
+
* processed/ — delivered
|
|
65
|
+
* expired/ — never delivered within the grace period
|
|
66
|
+
* A file still in the triggers dir once its age exceeds unprocessedTtlMs is
|
|
67
|
+
* MOVED (never deleted) to expired/. This covers push_message triggers whose
|
|
68
|
+
* session is never found, malformed JSON, schema-invalid files, and unknown
|
|
69
|
+
* projectSlug. Age is the parsed trigger.createdAt when it is a valid date
|
|
70
|
+
* not more than 5 minutes in the future, else the file mtime. The check runs on every scan (startup + 30 s poll).
|
|
71
|
+
* processed/ and expired/ files older than 30 days are pruned.
|
|
28
72
|
*
|
|
29
73
|
* ctx fields:
|
|
30
74
|
* triggersDir — absolute path to ~/.clagentic/external-triggers/
|
|
31
75
|
* getProject — function(slug) -> project context | null
|
|
76
|
+
* unprocessedTtlMs — optional grace period before expiry (default 7 days)
|
|
77
|
+
* sessionInput — optional createSessionInput() instance shared with the IPC verbs
|
|
32
78
|
*
|
|
33
79
|
* Security: triggers dir is under the user's home. Any process running as
|
|
34
80
|
* the same OS user can write files. Acceptable for single-user self-hosted
|
|
@@ -49,8 +95,13 @@ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
|
|
|
49
95
|
function attachExternalTrigger(ctx) {
|
|
50
96
|
var triggersDir = ctx.triggersDir;
|
|
51
97
|
var getProject = ctx.getProject;
|
|
98
|
+
var sessionInput = ctx.sessionInput || createSessionInput({ getProject: getProject });
|
|
52
99
|
|
|
100
|
+
var triggersRoot = path.dirname(path.join(triggersDir, "x"));
|
|
53
101
|
var processedDir = path.join(triggersDir, "processed");
|
|
102
|
+
var expiredDir = path.join(triggersDir, "expired");
|
|
103
|
+
var unprocessedTtlMs = (typeof ctx.unprocessedTtlMs === "number" && ctx.unprocessedTtlMs >= 0)
|
|
104
|
+
? ctx.unprocessedTtlMs : DEFAULT_UNPROCESSED_TTL_MS;
|
|
54
105
|
var watcher = null;
|
|
55
106
|
var debounce = null;
|
|
56
107
|
// Track IDs already dispatched this session to guard against double-fire
|
|
@@ -67,6 +118,7 @@ function attachExternalTrigger(ctx) {
|
|
|
67
118
|
function ensureDirs() {
|
|
68
119
|
try { fs.mkdirSync(triggersDir, { recursive: true }); } catch (e) {}
|
|
69
120
|
try { fs.mkdirSync(processedDir, { recursive: true }); } catch (e) {}
|
|
121
|
+
try { fs.mkdirSync(expiredDir, { recursive: true }); } catch (e) {}
|
|
70
122
|
}
|
|
71
123
|
|
|
72
124
|
// --- Trigger file validation ---
|
|
@@ -81,101 +133,97 @@ function attachExternalTrigger(ctx) {
|
|
|
81
133
|
if (obj.sessionId !== undefined && (typeof obj.sessionId !== "string" || !obj.sessionId)) {
|
|
82
134
|
return "sessionId must be a non-empty string when present";
|
|
83
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.
|
|
84
139
|
return null; // valid
|
|
85
140
|
}
|
|
86
141
|
|
|
87
|
-
// ---
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
var
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
142
|
+
// --- Dispatch ---
|
|
143
|
+
|
|
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,
|
|
151
|
+
triggerId: trigger.id,
|
|
152
|
+
initiator: trigger.initiator,
|
|
153
|
+
};
|
|
154
|
+
if (trigger.sessionId) {
|
|
155
|
+
request.sessionId = trigger.sessionId;
|
|
156
|
+
return sessionInput.sendInput(request);
|
|
99
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);
|
|
163
|
+
}
|
|
100
164
|
|
|
101
|
-
|
|
102
|
-
sess.title = (trigger.contextNote || "External trigger") + " — " + trigger.id.substring(0, 12);
|
|
103
|
-
if (trigger.cwd) sess.cwd = trigger.cwd;
|
|
104
|
-
sm.saveSessionFile(sess);
|
|
105
|
-
sm.broadcastSessionList();
|
|
106
|
-
|
|
107
|
-
var userMsg = { type: "user_message", text: trigger.initialPrompt };
|
|
108
|
-
// lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
|
|
109
|
-
sm.recordHistoryEntry(sess, userMsg, true);
|
|
110
|
-
sm.appendToSessionFile(sess, userMsg);
|
|
111
|
-
|
|
112
|
-
sess.isProcessing = true;
|
|
113
|
-
onProcessingChanged();
|
|
114
|
-
sess.sentToolResults = {};
|
|
115
|
-
// singleTurn=false (default): session stays open for human follow-up.
|
|
116
|
-
// The trigger JSON can set singleTurn:true for fire-and-forget agentic
|
|
117
|
-
// dispatches (not part of v1 schema, reserved for future use).
|
|
118
|
-
sess.acceptEditsAfterStart = true;
|
|
165
|
+
// --- Archive ---
|
|
119
166
|
|
|
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) {
|
|
173
|
+
var dest = path.join(processedDir, id + ".json");
|
|
120
174
|
try {
|
|
121
|
-
|
|
175
|
+
fs.renameSync(triggerPath, dest);
|
|
122
176
|
} catch (e) {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
// --- Mid-session inject ---
|
|
132
|
-
|
|
133
|
-
function pushMessageToSession(project, trigger) {
|
|
134
|
-
var sm = project.sm;
|
|
135
|
-
var sdk = project.sdk;
|
|
136
|
-
|
|
137
|
-
if (!sm || !sdk) {
|
|
138
|
-
console.error("[external-trigger] Project context missing sm/sdk for push_message, slug:", trigger.projectSlug);
|
|
139
|
-
return "error";
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
var found = null;
|
|
143
|
-
sm.sessions.forEach(function (s) {
|
|
144
|
-
if (!found && s.cliSessionId === trigger.sessionId) {
|
|
145
|
-
found = s;
|
|
177
|
+
// Cross-device or race — try copy+delete
|
|
178
|
+
try {
|
|
179
|
+
fs.copyFileSync(triggerPath, dest);
|
|
180
|
+
fs.unlinkSync(triggerPath);
|
|
181
|
+
} catch (e2) {
|
|
182
|
+
console.error("[external-trigger] Failed to archive trigger " + id + ":", e2.message || e2);
|
|
183
|
+
return;
|
|
146
184
|
}
|
|
147
|
-
});
|
|
148
|
-
|
|
149
|
-
if (!found) {
|
|
150
|
-
console.warn("[external-trigger] push_message: session not found: " + trigger.sessionId + " (trigger " + trigger.id + " not archived — will retry)");
|
|
151
|
-
return "not_found";
|
|
152
185
|
}
|
|
153
|
-
|
|
186
|
+
var record = Object.assign({}, obj, { result: result, processedAt: new Date().toISOString() });
|
|
154
187
|
try {
|
|
155
|
-
|
|
156
|
-
console.log("[external-trigger] push_message delivered to session " + trigger.sessionId + " (trigger " + trigger.id + ")");
|
|
157
|
-
return "ok";
|
|
188
|
+
fs.writeFileSync(dest, JSON.stringify(record, null, 2) + "\n");
|
|
158
189
|
} catch (e) {
|
|
159
|
-
console.error("[external-trigger]
|
|
160
|
-
return "error";
|
|
190
|
+
console.error("[external-trigger] Failed to record the result of trigger " + id + ":", e.message || e);
|
|
161
191
|
}
|
|
162
192
|
}
|
|
163
193
|
|
|
164
|
-
// --- Archive ---
|
|
165
194
|
|
|
166
|
-
|
|
167
|
-
|
|
195
|
+
// --- Expiry ---
|
|
196
|
+
|
|
197
|
+
function triggerAgeMs(filePath, obj) {
|
|
198
|
+
if (obj && typeof obj.createdAt === "string") {
|
|
199
|
+
var t = Date.parse(obj.createdAt);
|
|
200
|
+
// A createdAt beyond the skew tolerance is untrustworthy (bad producer
|
|
201
|
+
// clock) and would otherwise dodge the TTL forever; use mtime instead.
|
|
202
|
+
if (!isNaN(t) && t <= Date.now() + CLOCK_SKEW_TOLERANCE_MS) return Date.now() - t;
|
|
203
|
+
}
|
|
204
|
+
try { return Date.now() - fs.statSync(filePath).mtimeMs; } catch (e) { return 0; }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Moves filePath to expired/ when past the grace period. Returns true if moved.
|
|
208
|
+
function expireIfStale(filePath, obj) {
|
|
209
|
+
if (triggerAgeMs(filePath, obj) <= unprocessedTtlMs) return false;
|
|
210
|
+
var base = path.basename(filePath);
|
|
211
|
+
try { fs.mkdirSync(expiredDir, { recursive: true }); } catch (e) {}
|
|
212
|
+
var dest = path.join(expiredDir, base);
|
|
168
213
|
try {
|
|
169
|
-
fs.renameSync(
|
|
214
|
+
fs.renameSync(filePath, dest);
|
|
170
215
|
} catch (e) {
|
|
171
|
-
// Cross-device or race — try copy+delete
|
|
172
216
|
try {
|
|
173
|
-
fs.copyFileSync(
|
|
174
|
-
fs.unlinkSync(
|
|
217
|
+
fs.copyFileSync(filePath, dest);
|
|
218
|
+
fs.unlinkSync(filePath);
|
|
175
219
|
} catch (e2) {
|
|
176
|
-
console.error("[external-trigger] Failed to
|
|
220
|
+
console.error("[external-trigger] Failed to expire trigger " + base + ":", e2.message || e2);
|
|
221
|
+
return false;
|
|
177
222
|
}
|
|
178
223
|
}
|
|
224
|
+
if (obj && obj.id) delete dispatched[obj.id];
|
|
225
|
+
console.warn("[external-trigger] Trigger " + base + " undelivered past TTL — moved to expired/");
|
|
226
|
+
return true;
|
|
179
227
|
}
|
|
180
228
|
|
|
181
229
|
// --- File handler ---
|
|
@@ -183,24 +231,32 @@ function attachExternalTrigger(ctx) {
|
|
|
183
231
|
function handleFile(filePath) {
|
|
184
232
|
var base = path.basename(filePath);
|
|
185
233
|
if (!base.endsWith(".json")) return;
|
|
186
|
-
//
|
|
187
|
-
|
|
234
|
+
// Only direct children of the triggers dir are triggers; entries in
|
|
235
|
+
// processed/ or expired/ are excluded by exact directory match, so a
|
|
236
|
+
// top-level processed-<id>.json is still a normal trigger.
|
|
237
|
+
if (path.dirname(filePath) !== triggersRoot) return;
|
|
188
238
|
|
|
189
239
|
var raw;
|
|
190
240
|
try { raw = fs.readFileSync(filePath, "utf8"); } catch (e) { return; }
|
|
191
241
|
|
|
192
242
|
var obj;
|
|
193
243
|
try { obj = JSON.parse(raw); } catch (e) {
|
|
244
|
+
if (expireIfStale(filePath, null)) return;
|
|
194
245
|
console.warn("[external-trigger] Malformed JSON in " + base + ":", e.message);
|
|
195
246
|
return;
|
|
196
247
|
}
|
|
197
248
|
|
|
198
249
|
var err = validateTrigger(obj);
|
|
199
250
|
if (err) {
|
|
251
|
+
if (expireIfStale(filePath, obj)) return;
|
|
200
252
|
console.warn("[external-trigger] Invalid trigger " + base + ": " + err);
|
|
201
253
|
return;
|
|
202
254
|
}
|
|
203
255
|
|
|
256
|
+
// Before the dispatched guard: files held back by it (unknown project,
|
|
257
|
+
// push error) must still expire.
|
|
258
|
+
if (expireIfStale(filePath, obj)) return;
|
|
259
|
+
|
|
204
260
|
var id = obj.id;
|
|
205
261
|
if (dispatched[id]) return; // already handled this session
|
|
206
262
|
dispatched[id] = true;
|
|
@@ -211,23 +267,26 @@ function attachExternalTrigger(ctx) {
|
|
|
211
267
|
return;
|
|
212
268
|
}
|
|
213
269
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
//
|
|
221
|
-
//
|
|
222
|
-
|
|
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;
|
|
223
280
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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;
|
|
229
286
|
}
|
|
230
|
-
|
|
287
|
+
console.log("[external-trigger] Trigger " + id + " " + result.result + (result.reason ? ": " + result.reason : ""));
|
|
288
|
+
archiveTrigger(filePath, id, obj, result);
|
|
289
|
+
});
|
|
231
290
|
}
|
|
232
291
|
|
|
233
292
|
// --- Watcher ---
|
|
@@ -239,10 +298,7 @@ function attachExternalTrigger(ctx) {
|
|
|
239
298
|
try { files = fs.readdirSync(triggersDir); } catch (e) { return; }
|
|
240
299
|
for (var i = 0; i < files.length; i++) {
|
|
241
300
|
if (!files[i].endsWith(".json")) continue;
|
|
242
|
-
|
|
243
|
-
// Skip entries inside processed/ subdir
|
|
244
|
-
if (fp.indexOf(processedDir) === 0) continue;
|
|
245
|
-
handleFile(fp);
|
|
301
|
+
handleFile(path.join(triggersDir, files[i]));
|
|
246
302
|
}
|
|
247
303
|
}, 200);
|
|
248
304
|
}
|
|
@@ -321,11 +377,16 @@ function attachExternalTrigger(ctx) {
|
|
|
321
377
|
// --- Processed file pruning ---
|
|
322
378
|
|
|
323
379
|
function pruneOldProcessed() {
|
|
380
|
+
pruneDir(processedDir);
|
|
381
|
+
pruneDir(expiredDir);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function pruneDir(dir) {
|
|
324
385
|
var now = Date.now();
|
|
325
386
|
var files;
|
|
326
|
-
try { files = fs.readdirSync(
|
|
387
|
+
try { files = fs.readdirSync(dir); } catch (e) { return; }
|
|
327
388
|
for (var i = 0; i < files.length; i++) {
|
|
328
|
-
var fp = path.join(
|
|
389
|
+
var fp = path.join(dir, files[i]);
|
|
329
390
|
try {
|
|
330
391
|
var stat = fs.statSync(fp);
|
|
331
392
|
if (now - stat.mtimeMs > PROCESSED_MAX_AGE_MS) {
|