@clagentic/console 1.12.0-beta.1 → 1.12.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.
- package/LICENSES/README.md +5 -0
- package/README.md +1 -0
- package/bin/cli.js +5 -2
- package/lib/agent-roster-ws.js +84 -0
- package/lib/agent-roster.js +312 -0
- package/lib/auth-required-notify.js +42 -0
- package/lib/build-changes.js +8 -2
- package/lib/build-sha.json +2 -2
- package/lib/build-update-notify.js +45 -0
- package/lib/build-update-offer.js +34 -11
- package/lib/build-update-standing.js +34 -14
- package/lib/claude-settings-env.js +142 -0
- package/lib/cli/duration.js +27 -0
- package/lib/cli/schedule-input-subcommands.js +1 -22
- package/lib/cli/session-subcommands.js +60 -11
- package/lib/client-address.js +44 -0
- package/lib/daemon.js +31 -10
- package/lib/idle-compaction-setting.js +203 -0
- package/lib/mcp-bridge-credential.js +41 -0
- package/lib/notification-prefs.js +18 -22
- package/lib/notify/core.js +210 -0
- package/lib/notify/index.js +31 -0
- package/lib/notify/live-prompts.js +36 -0
- package/lib/notify/payload.js +62 -0
- package/lib/notify/target.js +5 -0
- package/lib/notify/type-registry.js +81 -0
- package/lib/notify/types.js +57 -0
- package/lib/open-sockets.js +27 -0
- package/lib/outbound-access.js +85 -0
- package/lib/outbound-entry.js +116 -0
- package/lib/outbound-ledger.js +306 -0
- package/lib/outbound-query.js +153 -0
- package/lib/pending-prompts.js +31 -16
- package/lib/project-connection.js +48 -8
- package/lib/project-filesystem.js +43 -5
- package/lib/project-http.js +9 -1
- package/lib/project-loop.js +38 -26
- package/lib/project-notifications.js +122 -39
- package/lib/project-prompt-responses.js +1 -1
- package/lib/project-sessions.js +11 -1
- package/lib/project-user-mention.js +22 -34
- package/lib/project-user-message.js +208 -4
- package/lib/project-user-shell.js +298 -0
- package/lib/project.js +41 -5
- package/lib/prompt-answer.js +145 -0
- package/lib/prompt-expiry.js +50 -0
- package/lib/prompt-registry.js +98 -25
- package/lib/prompt-reminders.js +38 -33
- package/lib/prompt-source.js +59 -8
- package/lib/public/app.js +32 -2
- package/lib/public/css/agent-messages.css +96 -0
- package/lib/public/css/agent-roster.css +93 -0
- package/lib/public/css/diagnostics.css +29 -1
- package/lib/public/css/home-hub.css +12 -0
- package/lib/public/css/icon-strip.css +9 -0
- package/lib/public/css/input.css +20 -141
- package/lib/public/css/login-panel.css +73 -0
- package/lib/public/css/menus.css +2 -2
- package/lib/public/css/mobile-nav.css +11 -0
- package/lib/public/css/sidebar.css +18 -0
- package/lib/public/css/team-panel.css +1 -6
- package/lib/public/css/team-view.css +101 -0
- package/lib/public/css/title-bar.css +10 -0
- package/lib/public/css/user-shell.css +144 -0
- package/lib/public/index.html +44 -7
- package/lib/public/modules/activity-state.js +20 -4
- package/lib/public/modules/agent-avatar-picker.js +162 -0
- package/lib/public/modules/agent-avatar.js +153 -0
- package/lib/public/modules/agent-messages.js +285 -0
- package/lib/public/modules/agent-roster.js +157 -0
- package/lib/public/modules/app-connection.js +34 -5
- package/lib/public/modules/app-messages.js +55 -16
- package/lib/public/modules/app-notifications.js +104 -75
- package/lib/public/modules/app-panels.js +26 -3
- package/lib/public/modules/app-projects.js +3 -1
- package/lib/public/modules/app-rate-limit.js +8 -165
- package/lib/public/modules/app-rendering.js +32 -7
- package/lib/public/modules/build-update-sessions.js +81 -0
- package/lib/public/modules/collapsible-text.js +33 -18
- package/lib/public/modules/compaction-state.js +34 -0
- package/lib/public/modules/custom-icons.js +23 -5
- package/lib/public/modules/diagnostics.js +61 -57
- package/lib/public/modules/env-shadow-notice.js +34 -0
- package/lib/public/modules/injected-identity.js +24 -21
- package/lib/public/modules/input.js +176 -15
- package/lib/public/modules/login-panel.js +136 -0
- package/lib/public/modules/login-parser.js +73 -0
- package/lib/public/modules/login-tab.js +66 -0
- package/lib/public/modules/notifications.js +9 -1
- package/lib/public/modules/notify-client.js +246 -0
- package/lib/public/modules/pending-term-request.js +30 -0
- package/lib/public/modules/project-icon.js +22 -2
- package/lib/public/modules/project-settings.js +5 -0
- package/lib/public/modules/prompt-state.js +3 -3
- package/lib/public/modules/prompts.js +1 -1
- package/lib/public/modules/queued-button.js +11 -0
- package/lib/public/modules/scheduled-input-actions.js +12 -4
- package/lib/public/modules/scheduled-outbox.js +230 -0
- package/lib/public/modules/send-now.js +200 -0
- package/lib/public/modules/server-settings.js +50 -1
- package/lib/public/modules/shell-card.js +76 -0
- package/lib/public/modules/shell-line.js +49 -0
- package/lib/public/modules/shell-queue.js +253 -0
- package/lib/public/modules/shell-settings-controls.js +76 -0
- package/lib/public/modules/sidebar-mobile.js +3 -3
- package/lib/public/modules/sidebar-sessions.js +8 -0
- package/lib/public/modules/sidebar-users.js +5 -7
- package/lib/public/modules/team-panel.js +30 -88
- package/lib/public/modules/team-view.js +211 -0
- package/lib/public/modules/terminal-links.js +193 -0
- package/lib/public/modules/terminal.js +84 -107
- package/lib/public/modules/tools.js +19 -0
- package/lib/public/modules/user-shell.js +824 -0
- package/lib/public/notify-sw-logic.js +252 -0
- package/lib/public/notify-target.js +157 -0
- package/lib/public/style.css +5 -0
- package/lib/public/sw.js +20 -69
- package/lib/push.js +63 -19
- package/lib/queued-chat.js +392 -0
- package/lib/runtime-env.js +1 -0
- package/lib/scheduled-input/ws.js +67 -9
- package/lib/sdk-bridge.js +184 -73
- package/lib/sdk-message-processor.js +124 -76
- package/lib/server-auth.js +6 -4
- package/lib/server-dm.js +11 -20
- package/lib/server-settings.js +39 -1
- package/lib/server.js +112 -16
- package/lib/session-directory.js +39 -12
- package/lib/session-end.js +97 -0
- package/lib/session-input-ipc.js +37 -1
- package/lib/session-input.js +263 -21
- package/lib/session-liveness.js +53 -0
- package/lib/session-reclaim.js +37 -2
- package/lib/session-resume.js +1 -0
- package/lib/session-settings-file.js +53 -0
- package/lib/sessions.js +80 -9
- package/lib/team-traffic-ws.js +68 -0
- package/lib/team-traffic.js +318 -0
- package/lib/usage-store.js +36 -7
- package/lib/user-shell-settings.js +105 -0
- package/lib/vendor-auth.js +33 -2
- package/lib/ws-schema.js +33 -5
- package/lib/yoke/adapters/claude-capabilities.js +2 -0
- package/lib/yoke/adapters/claude-vendor.js +17 -1
- package/lib/yoke/adapters/claude-worker.js +39 -11
- package/lib/yoke/adapters/claude.js +225 -6
- package/lib/yoke/adapters/codex-capabilities.js +6 -1
- package/lib/yoke/adapters/codex-user-shell.js +265 -0
- package/lib/yoke/adapters/codex-vendor.js +7 -0
- package/lib/yoke/adapters/codex.js +186 -52
- package/lib/yoke/auth-checks.js +17 -2
- package/lib/yoke/codex-app-server.js +8 -2
- package/lib/yoke/index.js +21 -3
- package/lib/yoke/interface.js +54 -1
- package/lib/yoke/mcp-bridge-server.js +12 -8
- package/lib/yoke/provider-credentials.js +24 -0
- package/lib/yoke/registry.js +40 -1
- package/lib/yoke/user-shell.js +224 -0
- package/package.json +2 -2
- package/scripts/check-test-count.js +14 -0
- package/lib/public/modules/build-notice-gate.js +0 -73
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
var SESSION_TITLE_MAX = 80;
|
|
12
12
|
var liveAgentTasks = require('./session-reclaim').liveAgentTasks;
|
|
13
|
+
var liveness = require('./session-liveness');
|
|
13
14
|
|
|
14
15
|
function oneLine(text, max, fallback) {
|
|
15
16
|
if (typeof text !== 'string') return fallback;
|
|
@@ -26,13 +27,14 @@ function isLive(session) {
|
|
|
26
27
|
* Everything a restart now would end, across every project.
|
|
27
28
|
*
|
|
28
29
|
* @param {Array<{slug: string, sm: {sessions: Map}}>} projects
|
|
29
|
-
* @returns {{sessions: Array<object>, sessionCount: number, processingCount: number, agentCount: number, keys: string[]}}
|
|
30
|
+
* @returns {{sessions: Array<object>, sessionCount: number, processingCount: number, waitingCount: number, agentCount: number, keys: string[]}}
|
|
30
31
|
*/
|
|
31
32
|
function collectInterruptions(projects) {
|
|
32
33
|
var sessions = [];
|
|
33
34
|
var keys = [];
|
|
34
35
|
var agentCount = 0;
|
|
35
36
|
var processingCount = 0;
|
|
37
|
+
var waitingCount = 0;
|
|
36
38
|
(projects || []).forEach(function (proj) {
|
|
37
39
|
if (!proj || !proj.sm || !proj.sm.sessions) return;
|
|
38
40
|
proj.sm.sessions.forEach(function (session) {
|
|
@@ -40,19 +42,24 @@ function collectInterruptions(projects) {
|
|
|
40
42
|
var key = proj.slug + '#' + session.localId;
|
|
41
43
|
var agents = liveAgentTasks(session);
|
|
42
44
|
var processing = !!session.isProcessing;
|
|
45
|
+
var activity = liveness.activityOf(session);
|
|
46
|
+
var waiting = activity === liveness.ACTIVITY.WAITING;
|
|
43
47
|
keys.push(key);
|
|
44
48
|
// Busy state is part of what the operator was shown: a session offered as
|
|
45
|
-
// idle that starts a turn afterwards is not covered.
|
|
49
|
+
// idle that starts a turn, or blocks on a prompt, afterwards is not covered.
|
|
46
50
|
if (processing) keys.push(key + '#busy');
|
|
51
|
+
if (waiting) keys.push(key + '#waiting');
|
|
47
52
|
agents.forEach(function (a) { keys.push(key + '#' + a.id); });
|
|
48
53
|
agentCount += agents.length;
|
|
49
54
|
if (processing) processingCount += 1;
|
|
55
|
+
if (waiting) waitingCount += 1;
|
|
50
56
|
sessions.push({
|
|
51
57
|
key: key,
|
|
52
58
|
slug: proj.slug,
|
|
53
59
|
localId: session.localId,
|
|
54
60
|
title: oneLine(session.title, SESSION_TITLE_MAX, 'Untitled session'),
|
|
55
61
|
processing: processing,
|
|
62
|
+
activity: activity,
|
|
56
63
|
agents: agents.map(function (a) { return a.label; }),
|
|
57
64
|
});
|
|
58
65
|
});
|
|
@@ -61,15 +68,32 @@ function collectInterruptions(projects) {
|
|
|
61
68
|
sessions: sessions,
|
|
62
69
|
sessionCount: sessions.length,
|
|
63
70
|
processingCount: processingCount,
|
|
71
|
+
waitingCount: waitingCount,
|
|
64
72
|
agentCount: agentCount,
|
|
65
73
|
keys: keys,
|
|
66
74
|
};
|
|
67
75
|
}
|
|
68
76
|
|
|
77
|
+
// The three words the card uses; a reaped session is not on the card.
|
|
78
|
+
var ACTIVITY_LABEL = {
|
|
79
|
+
running: 'running a turn',
|
|
80
|
+
waiting: 'waiting on a prompt',
|
|
81
|
+
idle: 'idle',
|
|
82
|
+
};
|
|
83
|
+
|
|
69
84
|
function plural(n, word) {
|
|
70
85
|
return n + ' ' + word + (n === 1 ? '' : 's');
|
|
71
86
|
}
|
|
72
87
|
|
|
88
|
+
/** One session as the card words it: "[slug] title (state; background agents: ...)". */
|
|
89
|
+
function describeSession(s) {
|
|
90
|
+
var state = ACTIVITY_LABEL[s.activity] || (s.processing ? ACTIVITY_LABEL.running : ACTIVITY_LABEL.idle);
|
|
91
|
+
var agents = s.agents.length > 0
|
|
92
|
+
? '; background agents: ' + s.agents.map(function (l) { return '"' + l + '"'; }).join(', ')
|
|
93
|
+
: '';
|
|
94
|
+
return '[' + s.slug + '] ' + s.title + ' (' + state + agents + ')';
|
|
95
|
+
}
|
|
96
|
+
|
|
73
97
|
/** The operator-facing statement of what a restart ends. */
|
|
74
98
|
function describeInterruptions(i) {
|
|
75
99
|
if (i.sessionCount === 0) {
|
|
@@ -80,11 +104,7 @@ function describeInterruptions(i) {
|
|
|
80
104
|
(i.agentCount > 0 ? ' and ' + plural(i.agentCount, 'background agent') : '') + '.',
|
|
81
105
|
];
|
|
82
106
|
i.sessions.forEach(function (s) {
|
|
83
|
-
|
|
84
|
-
var agents = s.agents.length > 0
|
|
85
|
-
? '; background agents: ' + s.agents.map(function (l) { return '"' + l + '"'; }).join(', ')
|
|
86
|
-
: '';
|
|
87
|
-
lines.push('- [' + s.slug + '] ' + s.title + ' (' + state + agents + ')');
|
|
107
|
+
lines.push('- ' + describeSession(s));
|
|
88
108
|
});
|
|
89
109
|
lines.push('Restarting ends these sessions and any that start before the restart happens. ' +
|
|
90
110
|
'Ended sessions resume when you send them a message.');
|
|
@@ -110,6 +130,9 @@ function buildOffer(o) {
|
|
|
110
130
|
sessions: o.interruptions.sessions,
|
|
111
131
|
sessionCount: o.interruptions.sessionCount,
|
|
112
132
|
agentCount: o.interruptions.agentCount,
|
|
133
|
+
// The same wording the message carries, so the client can set the list
|
|
134
|
+
// apart from the message without parsing it.
|
|
135
|
+
lines: o.interruptions.sessions.map(describeSession),
|
|
113
136
|
};
|
|
114
137
|
offer.interruptionText = describeInterruptions(o.interruptions);
|
|
115
138
|
}
|
|
@@ -126,7 +149,7 @@ function summarizeOffer(a) {
|
|
|
126
149
|
var DEFAULT_NOTICE_COOLDOWN_MS = 60 * 60 * 1000;
|
|
127
150
|
|
|
128
151
|
/**
|
|
129
|
-
* How long a
|
|
152
|
+
* How long a declined build-update offer stays quiet. `raw` is the
|
|
130
153
|
* CLAGENTIC_CONSOLE_BUILD_NOTICE_COOLDOWN_MS value; unset, empty or invalid
|
|
131
154
|
* (not a non-negative number) falls back to the default. 0 disables the quiet period.
|
|
132
155
|
*/
|
|
@@ -136,8 +159,8 @@ function noticeCooldownFrom(raw) {
|
|
|
136
159
|
return isFinite(n) && n >= 0 ? n : DEFAULT_NOTICE_COOLDOWN_MS;
|
|
137
160
|
}
|
|
138
161
|
|
|
139
|
-
/** The standing
|
|
140
|
-
function composeNotice(assessment, changes
|
|
162
|
+
/** The standing offer, as the page builds its diagnostics entry from it. */
|
|
163
|
+
function composeNotice(assessment, changes) {
|
|
141
164
|
return {
|
|
142
165
|
type: 'diagnostic',
|
|
143
166
|
severity: 'warning',
|
|
@@ -145,7 +168,6 @@ function composeNotice(assessment, changes, cooldownMs) {
|
|
|
145
168
|
message: summarizeOffer(assessment) + ' Restart to apply it when it suits you; nothing restarts on its own.',
|
|
146
169
|
buildUpdate: buildOffer({ assessment: assessment, changes: changes }),
|
|
147
170
|
actionable: { label: 'Restart to apply update', action: 'restart_for_build_update' },
|
|
148
|
-
noticeCooldownMs: cooldownMs,
|
|
149
171
|
};
|
|
150
172
|
}
|
|
151
173
|
|
|
@@ -174,6 +196,7 @@ module.exports = {
|
|
|
174
196
|
composeNotice: composeNotice,
|
|
175
197
|
collectInterruptions: collectInterruptions,
|
|
176
198
|
describeInterruptions: describeInterruptions,
|
|
199
|
+
describeSession: describeSession,
|
|
177
200
|
buildOffer: buildOffer,
|
|
178
201
|
summarizeOffer: summarizeOffer,
|
|
179
202
|
liveAgentTasks: liveAgentTasks,
|
|
@@ -14,7 +14,10 @@
|
|
|
14
14
|
// place when a read succeeds. A slow, failed or throwing read never removes or
|
|
15
15
|
// withholds the restart action.
|
|
16
16
|
//
|
|
17
|
-
// It
|
|
17
|
+
// It raises and withdraws the offer through the notification core (the caller's
|
|
18
|
+
// show and retract); the core collapses a repeat into the one offer on every
|
|
19
|
+
// surface, so what is kept here is only what was last asked for, to know when
|
|
20
|
+
// the state changed. It never restarts anything (that is
|
|
18
21
|
// lib/build-update-restart.js, on a confirmed click).
|
|
19
22
|
|
|
20
23
|
var SOURCE = 'build-update';
|
|
@@ -44,7 +47,10 @@ function readKeyOf(a) {
|
|
|
44
47
|
* @param {object} o
|
|
45
48
|
* @param {function(object): Promise<object>} o.listChanges — ({fromSha, toSha}) -> changes
|
|
46
49
|
* @param {function(object, object): object} o.compose — (assessment, changes) -> diagnostic message
|
|
47
|
-
* @param {function(object): void} o.
|
|
50
|
+
* @param {function(object, {refresh: boolean}): void} o.show — raises the offer (the
|
|
51
|
+
* composed message); refresh: true when the same build's offer is updated in place
|
|
52
|
+
* @param {function(): void} o.retract — withdraws the offer everywhere
|
|
53
|
+
* @param {number} [o.quietMs] — how long a declined offer stays quiet; 0 disables
|
|
48
54
|
* @param {function(): ?object} o.desired — the CURRENT desired assessment (confirmed stale) or null
|
|
49
55
|
* @param {number} [o.retryAfterMs] — minimum time between retries of a failed read
|
|
50
56
|
* @param {function(): number} [o.now]
|
|
@@ -54,10 +60,14 @@ function createStandingOffer(o) {
|
|
|
54
60
|
var log = typeof o.log === 'function' ? o.log : function () {};
|
|
55
61
|
var now = typeof o.now === 'function' ? o.now : Date.now;
|
|
56
62
|
var retryAfterMs = o.retryAfterMs >= 0 ? o.retryAfterMs : 30 * 60 * 1000;
|
|
63
|
+
var quietMs = o.quietMs >= 0 ? o.quietMs : 0;
|
|
57
64
|
|
|
58
65
|
// What clients were last shown: {offerKey, changeListStatus, message}, set only
|
|
59
66
|
// after the broadcast succeeded.
|
|
60
67
|
var shown = null;
|
|
68
|
+
// The offer the operator declined and when: it is not raised again until
|
|
69
|
+
// quietMs has passed or the offer changes.
|
|
70
|
+
var declined = null;
|
|
61
71
|
// readKey -> {status, changes, reason, failedAt, inFlight}
|
|
62
72
|
var reads = {};
|
|
63
73
|
|
|
@@ -111,7 +121,7 @@ function createStandingOffer(o) {
|
|
|
111
121
|
}
|
|
112
122
|
|
|
113
123
|
function retract() {
|
|
114
|
-
o.
|
|
124
|
+
o.retract();
|
|
115
125
|
shown = null;
|
|
116
126
|
}
|
|
117
127
|
|
|
@@ -123,11 +133,19 @@ function createStandingOffer(o) {
|
|
|
123
133
|
|
|
124
134
|
function reconcileUnsafe(desired) {
|
|
125
135
|
if (!desired) {
|
|
136
|
+
declined = null;
|
|
126
137
|
if (shown !== null) retract();
|
|
127
138
|
prune(null);
|
|
128
139
|
return;
|
|
129
140
|
}
|
|
130
141
|
var offerKey = offerKeyOf(desired);
|
|
142
|
+
if (declined !== null) {
|
|
143
|
+
if (declined.offerKey === offerKey && now() - declined.at < quietMs) {
|
|
144
|
+
prune(null);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
declined = null;
|
|
148
|
+
}
|
|
131
149
|
var readKey = readKeyOf(desired);
|
|
132
150
|
var entry = reads[readKey];
|
|
133
151
|
if (!entry) {
|
|
@@ -144,14 +162,11 @@ function createStandingOffer(o) {
|
|
|
144
162
|
}
|
|
145
163
|
|
|
146
164
|
var message = o.compose(desired, changesFor(entry));
|
|
147
|
-
// A different build replaces the offer
|
|
148
|
-
//
|
|
165
|
+
// A different build replaces the offer and the same build is refreshed: the
|
|
166
|
+
// core collapses either into the single offer, so the restart action is
|
|
167
|
+
// never retracted first (it would flicker).
|
|
149
168
|
var refresh = shown !== null && shown.offerKey === summary.offerKey;
|
|
150
|
-
|
|
151
|
-
// The stored copy, replayed to a client that connects later, is a plain
|
|
152
|
-
// diagnostic; `refresh` tells a client already holding the entry to update it
|
|
153
|
-
// and not to bring back one the operator dismissed.
|
|
154
|
-
o.broadcast(refresh ? Object.assign({}, message, { refresh: true }) : message);
|
|
169
|
+
o.show(message, { refresh: refresh });
|
|
155
170
|
shown = { offerKey: summary.offerKey, changeListStatus: summary.changeListStatus, message: message };
|
|
156
171
|
prune(readKey);
|
|
157
172
|
}
|
|
@@ -172,11 +187,16 @@ function createStandingOffer(o) {
|
|
|
172
187
|
|
|
173
188
|
return {
|
|
174
189
|
reconcile: reconcile,
|
|
175
|
-
/**
|
|
190
|
+
/** The offer last raised, or null when none stands. */
|
|
176
191
|
current: function () { return shown === null ? null : shown.message; },
|
|
177
|
-
/**
|
|
178
|
-
|
|
179
|
-
|
|
192
|
+
/**
|
|
193
|
+
* The operator closed the offer on some client: it stays quiet for the
|
|
194
|
+
* quiet period, then comes back if the build is still stale.
|
|
195
|
+
*/
|
|
196
|
+
declined: function () {
|
|
197
|
+
if (shown === null) return;
|
|
198
|
+
declined = { offerKey: shown.offerKey, at: now() };
|
|
199
|
+
shown = null;
|
|
180
200
|
},
|
|
181
201
|
};
|
|
182
202
|
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// claude-settings-env.js - the variables the Claude user settings file sets in
|
|
2
|
+
// its own "env" block, and which of them a Settings environment text names too.
|
|
3
|
+
//
|
|
4
|
+
// Claude Code applies that block to its own environment at startup, after the
|
|
5
|
+
// environment it was handed, so for a key present in both the settings file
|
|
6
|
+
// wins over the value saved in Settings. The editor warns about those keys
|
|
7
|
+
// rather than letting a saved value silently have no effect. Names only: no
|
|
8
|
+
// value is read out of the file into a result.
|
|
9
|
+
|
|
10
|
+
var fs = require("fs");
|
|
11
|
+
var os = require("os");
|
|
12
|
+
var path = require("path");
|
|
13
|
+
var runtimeEnv = require("./runtime-env");
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The one settings file the daemon reads, located from the daemon's own
|
|
17
|
+
* environment alone: its CLAUDE_CONFIG_DIR if it has one, else its home. Text
|
|
18
|
+
* saved in Settings (shared or per project) is written by other people and
|
|
19
|
+
* never chooses the path, so the daemon cannot be pointed at another account's
|
|
20
|
+
* file. Null means "read nothing": under os-users mode the session runs as
|
|
21
|
+
* another account whose file the daemon does not read.
|
|
22
|
+
*
|
|
23
|
+
* @param {{osUsers?: boolean, homeDir?: string}} [opts]
|
|
24
|
+
* @returns {?string}
|
|
25
|
+
*/
|
|
26
|
+
function resolveSettingsFile(opts) {
|
|
27
|
+
opts = opts || {};
|
|
28
|
+
if (opts.osUsers) return null;
|
|
29
|
+
var configDir = process.env.CLAUDE_CONFIG_DIR;
|
|
30
|
+
if (configDir) return path.join(configDir, "settings.json");
|
|
31
|
+
return path.join(opts.homeDir || os.homedir(), ".claude", "settings.json");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function userSettingsEnvBlock(opts) {
|
|
35
|
+
opts = opts || {};
|
|
36
|
+
var file = resolveSettingsFile(opts);
|
|
37
|
+
if (!file) return null;
|
|
38
|
+
var parsed;
|
|
39
|
+
try {
|
|
40
|
+
parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
41
|
+
} catch (e) {
|
|
42
|
+
// No file, or one that is not valid JSON, sets nothing the runtime can see.
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
var block = parsed && typeof parsed === "object" ? parsed.env : null;
|
|
46
|
+
if (!block || typeof block !== "object" || Array.isArray(block)) return null;
|
|
47
|
+
return block;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A cheap change stamp for the settings file, for cache keys: mtime and size,
|
|
52
|
+
* no content read and nothing of it logged.
|
|
53
|
+
*
|
|
54
|
+
* @param {{osUsers?: boolean, homeDir?: string}} [opts]
|
|
55
|
+
* @returns {string} "" when no file is read or it does not exist
|
|
56
|
+
*/
|
|
57
|
+
function settingsFileStamp(opts) {
|
|
58
|
+
var file = resolveSettingsFile(opts);
|
|
59
|
+
if (!file) return "";
|
|
60
|
+
try {
|
|
61
|
+
var st = fs.statSync(file);
|
|
62
|
+
return st.mtimeMs + ":" + st.size;
|
|
63
|
+
} catch (e) {
|
|
64
|
+
// An absent file is a stable, distinct state; creating it changes the stamp.
|
|
65
|
+
return "";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param {{osUsers?: boolean, homeDir?: string}} [opts]
|
|
71
|
+
* @returns {string[]} the names in the settings file's env block; [] when the
|
|
72
|
+
* file is absent or unreadable, or under os-users mode
|
|
73
|
+
*/
|
|
74
|
+
function userSettingsEnvKeys(opts) {
|
|
75
|
+
var block = userSettingsEnvBlock(opts);
|
|
76
|
+
return block ? Object.keys(block) : [];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The environment the Claude CLI actually sees: the one it was handed with the
|
|
81
|
+
* settings file's env block applied over it (the file wins). Used to decide
|
|
82
|
+
* what the CLI will do (which provider it talks to), never to hand a value on:
|
|
83
|
+
* the result is for in-process classification and is not logged or sent.
|
|
84
|
+
*
|
|
85
|
+
* Under os-users mode the file belongs to another account and is not read, so
|
|
86
|
+
* the result is the given environment unchanged: a provider selected only in
|
|
87
|
+
* that account's own settings file is not seen by the console there.
|
|
88
|
+
* @param {object} env the composed environment the runtime is started with
|
|
89
|
+
* @param {{homeDir?: string, osUsers?: boolean}} [opts]
|
|
90
|
+
* @returns {object} a new object; env is not modified
|
|
91
|
+
*/
|
|
92
|
+
function applyUserSettingsEnv(env, opts) {
|
|
93
|
+
var out = Object.assign({}, env);
|
|
94
|
+
var block = userSettingsEnvBlock(opts);
|
|
95
|
+
if (!block) return out;
|
|
96
|
+
Object.keys(block).forEach(function (key) {
|
|
97
|
+
var value = block[key];
|
|
98
|
+
if (typeof value === "string") out[key] = value;
|
|
99
|
+
else if (typeof value === "number" || typeof value === "boolean") out[key] = String(value);
|
|
100
|
+
});
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* @param {string} envText a Settings environment text
|
|
106
|
+
* @param {{homeDir?: string, osUsers?: boolean}} [opts]
|
|
107
|
+
* @returns {string[]} names the text sets that the settings file also sets; []
|
|
108
|
+
* under os-users mode, where the file is not read
|
|
109
|
+
*/
|
|
110
|
+
function shadowedKeys(envText, opts) {
|
|
111
|
+
var fileKeys = userSettingsEnvKeys(opts);
|
|
112
|
+
if (fileKeys.length === 0) return [];
|
|
113
|
+
var inFile = new Set(fileKeys);
|
|
114
|
+
var seen = new Set();
|
|
115
|
+
return runtimeEnv.scanEnvText(envText).entries
|
|
116
|
+
.map(function (entry) { return entry.key; })
|
|
117
|
+
.filter(function (key) {
|
|
118
|
+
if (!inFile.has(key) || seen.has(key)) return false;
|
|
119
|
+
seen.add(key);
|
|
120
|
+
return true;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @param {string} envText a Settings environment text
|
|
126
|
+
* @returns {boolean} whether it sets CLAUDE_CONFIG_DIR, which the console never
|
|
127
|
+
* reads a path from (the editor says its check covers one file only)
|
|
128
|
+
*/
|
|
129
|
+
function setsConfigDir(envText) {
|
|
130
|
+
return runtimeEnv.scanEnvText(envText).entries.some(function (entry) {
|
|
131
|
+
return entry.key === "CLAUDE_CONFIG_DIR";
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
module.exports = {
|
|
136
|
+
setsConfigDir: setsConfigDir,
|
|
137
|
+
resolveSettingsFile: resolveSettingsFile,
|
|
138
|
+
settingsFileStamp: settingsFileStamp,
|
|
139
|
+
userSettingsEnvKeys: userSettingsEnvKeys,
|
|
140
|
+
applyUserSettingsEnv: applyUserSettingsEnv,
|
|
141
|
+
shadowedKeys: shadowedKeys,
|
|
142
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// lib/cli/duration.js - the duration a CLI flag takes ("10m", "1h30m", "90").
|
|
2
|
+
// Shared by schedule-input (--in, --every) and list-outbound (--since).
|
|
3
|
+
|
|
4
|
+
var UNIT_MS = Object.freeze({ s: 1000, m: 60000, h: 3600000, d: 86400000 });
|
|
5
|
+
|
|
6
|
+
var DURATION_RE = /^(?:\d+[smhd])+$/;
|
|
7
|
+
var DURATION_PART_RE = /(\d+)([smhd])/g;
|
|
8
|
+
|
|
9
|
+
// A bare number is minutes, the unit the person's own field uses.
|
|
10
|
+
// Returns { ms } or { error }.
|
|
11
|
+
function parseDuration(raw) {
|
|
12
|
+
var text = typeof raw === "string" ? raw.trim().toLowerCase() : "";
|
|
13
|
+
if (/^\d+$/.test(text)) text += "m";
|
|
14
|
+
if (!DURATION_RE.test(text)) {
|
|
15
|
+
return { error: "not a duration: " + JSON.stringify(String(raw).slice(0, 32)) + " (use for example 90, 10m, 2h, 1h30m)" };
|
|
16
|
+
}
|
|
17
|
+
var total = 0;
|
|
18
|
+
var part;
|
|
19
|
+
DURATION_PART_RE.lastIndex = 0;
|
|
20
|
+
while ((part = DURATION_PART_RE.exec(text)) !== null) {
|
|
21
|
+
total += parseInt(part[1], 10) * UNIT_MS[part[2]];
|
|
22
|
+
}
|
|
23
|
+
if (!Number.isSafeInteger(total) || total <= 0) return { error: "a duration must be longer than zero" };
|
|
24
|
+
return { ms: total };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = { parseDuration: parseDuration };
|
|
@@ -28,6 +28,7 @@ var fs = require("fs");
|
|
|
28
28
|
var senderRef = require("../sender-ref");
|
|
29
29
|
var { LIMITS, isCount } = require("../scheduled-input/records");
|
|
30
30
|
var { requestDaemon, withSenderRef, EXIT } = require("./session-subcommands");
|
|
31
|
+
var { parseDuration } = require("./duration");
|
|
31
32
|
|
|
32
33
|
// --- The time inputs: a duration ("10m", "1h30m"), a local clock time ("20:01")
|
|
33
34
|
// and a local date-time ("2026-03-01T20:01"). Pure: each takes the current time
|
|
@@ -35,31 +36,9 @@ var { requestDaemon, withSenderRef, EXIT } = require("./session-subcommands");
|
|
|
35
36
|
// (lib/public/modules/schedule-time.js) because it cannot load this CommonJS
|
|
36
37
|
// file; test/scheduled-input-client.test.js feeds both the same cases.
|
|
37
38
|
|
|
38
|
-
var UNIT_MS = Object.freeze({ s: 1000, m: 60000, h: 3600000, d: 86400000 });
|
|
39
|
-
|
|
40
|
-
var DURATION_RE = /^(?:\d+[smhd])+$/;
|
|
41
|
-
var DURATION_PART_RE = /(\d+)([smhd])/g;
|
|
42
39
|
var CLOCK_RE = /^(\d{1,2}):(\d{2})$/;
|
|
43
40
|
var DATE_TIME_RE = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})$/;
|
|
44
41
|
|
|
45
|
-
// A bare number is minutes, the unit the person's own field uses.
|
|
46
|
-
// Returns { ms } or { error }.
|
|
47
|
-
function parseDuration(raw) {
|
|
48
|
-
var text = typeof raw === "string" ? raw.trim().toLowerCase() : "";
|
|
49
|
-
if (/^\d+$/.test(text)) text += "m";
|
|
50
|
-
if (!DURATION_RE.test(text)) {
|
|
51
|
-
return { error: "not a duration: " + JSON.stringify(String(raw).slice(0, 32)) + " (use for example 90, 10m, 2h, 1h30m)" };
|
|
52
|
-
}
|
|
53
|
-
var total = 0;
|
|
54
|
-
var part;
|
|
55
|
-
DURATION_PART_RE.lastIndex = 0;
|
|
56
|
-
while ((part = DURATION_PART_RE.exec(text)) !== null) {
|
|
57
|
-
total += parseInt(part[1], 10) * UNIT_MS[part[2]];
|
|
58
|
-
}
|
|
59
|
-
if (!Number.isSafeInteger(total) || total <= 0) return { error: "a duration must be longer than zero" };
|
|
60
|
-
return { ms: total };
|
|
61
|
-
}
|
|
62
|
-
|
|
63
42
|
function validClock(hours, minutes) {
|
|
64
43
|
return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59;
|
|
65
44
|
}
|
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
// lib/cli/session-subcommands.js
|
|
2
2
|
//
|
|
3
|
-
// `clagentic-console open-session`, `send-input`
|
|
4
|
-
// session in a project, send input
|
|
5
|
-
//
|
|
3
|
+
// `clagentic-console open-session`, `send-input`, `end-session`, `answer-prompt`,
|
|
4
|
+
// `list-sessions` and `list-outbound`: open a session in a project, send input
|
|
5
|
+
// to one, stand one down, answer one of its pending prompts, list the sessions, or list what one session sent out, through the running daemon's IPC
|
|
6
|
+
// socket. Each prints the daemon's result as JSON on stdout.
|
|
6
7
|
//
|
|
7
8
|
// Exit codes (documented in docs/guides/AGENT-GUIDE.md):
|
|
8
|
-
// 0 the request was acted on (opened, delivered, resumed-and-delivered, listed
|
|
9
|
+
// 0 the request was acted on (opened, delivered, resumed-and-delivered, listed,
|
|
10
|
+
// ended, already-ended)
|
|
9
11
|
// 1 refused, error, or not-found for a request that named a session id
|
|
10
|
-
// 3 ambiguous: an address named several sessions
|
|
12
|
+
// 3 ambiguous: an address named several sessions (or, for list-outbound, a
|
|
13
|
+
// session id several projects hold); the candidates are in the JSON
|
|
11
14
|
// 4 not-found for a request that gave an address (--to) or --reply
|
|
12
15
|
|
|
13
16
|
var fs = require("fs");
|
|
17
|
+
var path = require("path");
|
|
14
18
|
|
|
15
19
|
var { loadConfig, socketPath, isDaemonAliveAsync } = require("../config");
|
|
16
20
|
var { sendIPCCommand } = require("../ipc");
|
|
17
21
|
var senderRef = require("../sender-ref");
|
|
22
|
+
var { parseDuration } = require("./duration");
|
|
18
23
|
|
|
19
24
|
// A resumed session starts a runtime before the call answers: longer than the
|
|
20
25
|
// IPC default.
|
|
@@ -33,10 +38,16 @@ var FLAGS = {
|
|
|
33
38
|
"--state": "state",
|
|
34
39
|
"--visibility": "sessionVisibility",
|
|
35
40
|
"--permission-mode": "permissionMode",
|
|
41
|
+
"--settings": "settingsFile",
|
|
36
42
|
"--initiator": "initiator",
|
|
37
43
|
"--context-note": "contextNote",
|
|
38
44
|
"--from": "from",
|
|
39
45
|
"--from-session": "fromSession",
|
|
46
|
+
"--reason": "reason",
|
|
47
|
+
"--since": "since",
|
|
48
|
+
"--kind": "kind",
|
|
49
|
+
"--request": "requestId",
|
|
50
|
+
"--decision": "decision",
|
|
40
51
|
};
|
|
41
52
|
|
|
42
53
|
// Kept apart from FLAGS because the parser reads a value after every FLAGS
|
|
@@ -46,34 +57,50 @@ var SWITCHES = {
|
|
|
46
57
|
};
|
|
47
58
|
|
|
48
59
|
var USAGE = {
|
|
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>]",
|
|
60
|
+
"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>] [--settings <path>] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>]",
|
|
50
61
|
"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>]",
|
|
62
|
+
"end-session": "Usage: clagentic-console end-session (--project <slug> --session <id> | --to <address>) [--from <name>] [--from-session <id>] [--reason <text>]",
|
|
63
|
+
"answer-prompt": "Usage: clagentic-console answer-prompt (--project <slug> --session <id> | --to <address>) --request <id> --decision <allow|deny|allow_always|text> [--from <name>] [--from-session <id>]",
|
|
51
64
|
"list-sessions": "Usage: clagentic-console list-sessions [--project <slug>] [--agent <name>] [--vendor <id>] [--state live|idle|reaped|any]",
|
|
65
|
+
"list-outbound": "Usage: clagentic-console list-outbound --session <vendor-session-id> [--project <slug>] [--since <dur>] [--kind sent|opens]",
|
|
52
66
|
};
|
|
53
67
|
|
|
54
68
|
var ALLOWED = {
|
|
55
|
-
"open-session": ["projectSlug", "to", "prompt", "vendor", "agentName", "sessionName", "sessionVisibility", "permissionMode", "initiator", "contextNote", "from", "fromSession"],
|
|
69
|
+
"open-session": ["projectSlug", "to", "prompt", "vendor", "agentName", "sessionName", "sessionVisibility", "permissionMode", "settingsFile", "initiator", "contextNote", "from", "fromSession"],
|
|
56
70
|
"send-input": ["projectSlug", "sessionId", "to", "reply", "prompt", "initiator", "contextNote", "from", "fromSession"],
|
|
71
|
+
"end-session": ["projectSlug", "sessionId", "to", "reason", "from", "fromSession"],
|
|
72
|
+
"answer-prompt": ["projectSlug", "sessionId", "to", "requestId", "decision", "from", "fromSession"],
|
|
57
73
|
"list-sessions": ["projectSlug", "agentName", "vendor", "state"],
|
|
74
|
+
"list-outbound": ["sessionId", "projectSlug", "since", "kind"],
|
|
58
75
|
};
|
|
59
76
|
|
|
60
77
|
var REQUIRED = {
|
|
61
78
|
"open-session": ["prompt"],
|
|
62
79
|
"send-input": ["prompt"],
|
|
80
|
+
"end-session": [],
|
|
81
|
+
"answer-prompt": ["requestId", "decision"],
|
|
63
82
|
"list-sessions": [],
|
|
83
|
+
"list-outbound": ["sessionId"],
|
|
64
84
|
};
|
|
65
85
|
|
|
66
86
|
var TARGET_HINT = {
|
|
67
87
|
"open-session": "--project, or --to",
|
|
68
88
|
"send-input": "--session (with --project), or --to, or --reply",
|
|
89
|
+
"end-session": "--session (with --project), or --to",
|
|
90
|
+
"answer-prompt": "--session (with --project), or --to",
|
|
69
91
|
};
|
|
70
92
|
|
|
71
93
|
var IPC_COMMAND = {
|
|
72
94
|
"open-session": "open_session",
|
|
73
95
|
"send-input": "send_session_input",
|
|
96
|
+
"end-session": "end_session",
|
|
97
|
+
"answer-prompt": "answer_prompt",
|
|
74
98
|
"list-sessions": "list_sessions",
|
|
99
|
+
"list-outbound": "list_outbound",
|
|
75
100
|
};
|
|
76
101
|
|
|
102
|
+
var OUTBOUND_KINDS = ["sent", "opens"];
|
|
103
|
+
|
|
77
104
|
function flagOf(key) {
|
|
78
105
|
var all = Object.keys(FLAGS).concat(Object.keys(SWITCHES));
|
|
79
106
|
return all.filter(function (f) { return FLAGS[f] === key || SWITCHES[f] === key; })[0];
|
|
@@ -94,13 +121,29 @@ function checkTarget(verb, request) {
|
|
|
94
121
|
if (given("reply")) return given("projectSlug") || given("sessionId") ? conflict : null;
|
|
95
122
|
if (!given("projectSlug") && !given("sessionId")) return "Missing the target: " + TARGET_HINT[verb];
|
|
96
123
|
if (!given("projectSlug")) return "Missing required option --project";
|
|
97
|
-
if (verb === "send-input" && !given("sessionId")) return "Missing required option --session";
|
|
124
|
+
if ((verb === "send-input" || verb === "end-session" || verb === "answer-prompt") && !given("sessionId")) return "Missing required option --session";
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// list-outbound: --since is a duration back from now, sent to the daemon as the
|
|
129
|
+
// absolute time; --kind is one of the two. Returns an error string or null.
|
|
130
|
+
function resolveOutboundOptions(request, now) {
|
|
131
|
+
if (request.kind !== undefined && OUTBOUND_KINDS.indexOf(request.kind) === -1) {
|
|
132
|
+
return "Unknown --kind " + JSON.stringify(String(request.kind).slice(0, 32)) + " (accepted: " + OUTBOUND_KINDS.join(", ") + ")";
|
|
133
|
+
}
|
|
134
|
+
if (request.since !== undefined) {
|
|
135
|
+
var dur = parseDuration(request.since);
|
|
136
|
+
if (dur.error) return "--since: " + dur.error;
|
|
137
|
+
request.sinceMs = now - dur.ms;
|
|
138
|
+
delete request.since;
|
|
139
|
+
}
|
|
98
140
|
return null;
|
|
99
141
|
}
|
|
100
142
|
|
|
101
143
|
// Parses the arguments after the verb. Returns { request } or { error }.
|
|
102
|
-
// Pure: reading a "-" prompt from stdin is the handler's job.
|
|
103
|
-
|
|
144
|
+
// Pure: reading a "-" prompt from stdin is the handler's job. `now` (ms) is for
|
|
145
|
+
// tests.
|
|
146
|
+
function parseSessionArgs(verb, args, now) {
|
|
104
147
|
var allowed = ALLOWED[verb];
|
|
105
148
|
var request = {};
|
|
106
149
|
for (var i = 0; i < args.length; i++) {
|
|
@@ -114,6 +157,8 @@ function parseSessionArgs(verb, args) {
|
|
|
114
157
|
if (!key || allowed.indexOf(key) === -1) return { error: "Unknown option for " + verb + ": " + args[i] };
|
|
115
158
|
if (i + 1 >= args.length) return { error: "Missing value for " + args[i] };
|
|
116
159
|
request[key] = args[++i];
|
|
160
|
+
// The daemon runs elsewhere: a relative path means nothing to it.
|
|
161
|
+
if (key === "settingsFile" && request[key]) request[key] = path.resolve(request[key]);
|
|
117
162
|
}
|
|
118
163
|
var required = REQUIRED[verb];
|
|
119
164
|
for (var r = 0; r < required.length; r++) {
|
|
@@ -121,6 +166,10 @@ function parseSessionArgs(verb, args) {
|
|
|
121
166
|
}
|
|
122
167
|
var targetError = checkTarget(verb, request);
|
|
123
168
|
if (targetError) return { error: targetError };
|
|
169
|
+
if (verb === "list-outbound") {
|
|
170
|
+
var outboundError = resolveOutboundOptions(request, now === undefined ? Date.now() : now);
|
|
171
|
+
if (outboundError) return { error: outboundError };
|
|
172
|
+
}
|
|
124
173
|
return { request: request };
|
|
125
174
|
}
|
|
126
175
|
|
|
@@ -172,7 +221,7 @@ function runSessionVerb(verb, args) {
|
|
|
172
221
|
request.prompt = fs.readFileSync(0, "utf8").replace(/\n$/, "");
|
|
173
222
|
}
|
|
174
223
|
request.cmd = IPC_COMMAND[verb];
|
|
175
|
-
if (verb
|
|
224
|
+
if (verb === "open-session" || verb === "send-input" || verb === "end-session" || verb === "answer-prompt") withSenderRef(request, process.env);
|
|
176
225
|
|
|
177
226
|
requestDaemon(request).then(function (res) {
|
|
178
227
|
console.log(JSON.stringify(res, null, 2));
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// client-address.js — one answer to "who is this client, and is it local?".
|
|
2
|
+
//
|
|
3
|
+
// The TCP peer is the client only when nothing sits in front of the daemon.
|
|
4
|
+
// Behind a same-host reverse proxy every client is the loopback peer, which
|
|
5
|
+
// collapses rate-limit buckets and audit records into one and makes proxied
|
|
6
|
+
// sockets look local.
|
|
7
|
+
//
|
|
8
|
+
// Address: with trustedProxy declared, X-Forwarded-For is used only when it is
|
|
9
|
+
// a single valid IP literal. A multi-valued chain, an invalid value or an
|
|
10
|
+
// absent header falls back to the peer; no hop is ever picked, for the same
|
|
11
|
+
// reason as lib/effective-protocol.js (trustedProxy is one boolean and cannot
|
|
12
|
+
// say which hop to trust). Without trustedProxy the header is ignored.
|
|
13
|
+
//
|
|
14
|
+
// Locality: a loopback peer with no forwarding header at all, whatever
|
|
15
|
+
// trustedProxy says, since a forwarding header means someone else is the client.
|
|
16
|
+
|
|
17
|
+
var net = require("net");
|
|
18
|
+
|
|
19
|
+
var LOOPBACK = ["127.0.0.1", "::1", "::ffff:127.0.0.1"];
|
|
20
|
+
var FORWARDING_HEADERS = ["x-forwarded-for", "forwarded", "x-real-ip"];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {Object} req - http.IncomingMessage (or an object with headers/socket)
|
|
24
|
+
* @param {boolean} trustedProxy - operator-declared proxy trust boundary
|
|
25
|
+
* @returns {{address: string, local: boolean}}
|
|
26
|
+
*/
|
|
27
|
+
function resolveClientAddress(req, trustedProxy) {
|
|
28
|
+
var headers = (req && req.headers) || {};
|
|
29
|
+
var peer = (req && req.socket && req.socket.remoteAddress) || "";
|
|
30
|
+
var address = peer;
|
|
31
|
+
|
|
32
|
+
if (trustedProxy) {
|
|
33
|
+
var xff = headers["x-forwarded-for"];
|
|
34
|
+
if (typeof xff === "string" && xff.indexOf(",") === -1) {
|
|
35
|
+
var candidate = xff.trim();
|
|
36
|
+
if (net.isIP(candidate)) address = candidate;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
var forwarded = FORWARDING_HEADERS.some(function (h) { return headers[h] !== undefined; });
|
|
41
|
+
return { address: address, local: LOOPBACK.indexOf(peer) !== -1 && !forwarded };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = { resolveClientAddress: resolveClientAddress };
|