aegiscode 6.8.11 → 6.8.12
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/README.md +46 -13
- package/bin/aegiscode.js +92 -2
- package/package.json +2 -2
- package/scripts/predist.mjs +25 -0
- package/src/app.js +75 -3
- package/src/caps.js +325 -1
- package/src/cloudsync.js +51 -7
- package/src/commands.js +51 -4
- package/src/events.js +24 -0
- package/src/fingerprint.js +559 -0
- package/src/panels.js +1 -1
- package/src/presence.js +235 -0
- package/src/screens.js +11 -4
- package/src/theme.js +126 -6
- package/vendor/client/aegis.js +180 -18
- package/vendor/client/attest.js +439 -0
- package/vendor/client/authorship-key.js +366 -0
- package/vendor/client/device-fingerprint.js +85 -3
- package/vendor/client/fingerprint.js +1061 -0
- package/vendor/client/presence-constants.js +104 -0
- package/vendor/client/presence.js +435 -0
- package/vendor/client/record-vault.js +834 -0
- package/vendor/client/touch.js +455 -0
- package/vendor/desktop/lib/local/autonomous.js +1 -0
- package/vendor/desktop/lib/local/prompt.js +6 -0
- package/vendor/desktop/lib/settings.js +154 -1
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The wire contract and the sanitising helpers for the presence beacon
|
|
5
|
+
* (client/presence.js).
|
|
6
|
+
*
|
|
7
|
+
* These live in their own file for one reason: the widths and the app-name
|
|
8
|
+
* vocabulary below are not this client's invention, they are aegis1's
|
|
9
|
+
* (`_presence_token`, `_presence_app` and `PRESENCE_BEAT_INTERVAL_S` in
|
|
10
|
+
* aegis1/app.py, and the `client_presence` table in aegis1/db.py). A test can
|
|
11
|
+
* assert them without loading the network module, and if the server widens a
|
|
12
|
+
* column the mismatch is visible in one file instead of being spread through
|
|
13
|
+
* the beacon's request path.
|
|
14
|
+
*
|
|
15
|
+
* Kept dependency-free: plain Node, no Electron, no aegis.js — `presence.js`
|
|
16
|
+
* requires this, and the tests require both.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** aegis1: `@app.route("/api/v1/heartbeat", methods=["POST"])`. The v1 path is
|
|
20
|
+
* the client beacon; `/api/heartbeat` is the dashboard's own JS ping and is
|
|
21
|
+
* deliberately NOT used here — it takes no app/install field and writes no
|
|
22
|
+
* presence row. */
|
|
23
|
+
const PRESENCE_PATH = '/api/v1/heartbeat';
|
|
24
|
+
|
|
25
|
+
/** Fallback cadence, in ms, used until the server answers with its own.
|
|
26
|
+
* aegis1's PRESENCE_BEAT_INTERVAL_S is 300 (5 min) as this is written; if the
|
|
27
|
+
* two ever disagree the server's value wins at runtime, so this only bounds
|
|
28
|
+
* the very first beat. */
|
|
29
|
+
const DEFAULT_INTERVAL_MS = 300 * 1000;
|
|
30
|
+
|
|
31
|
+
/** One minute. `/api/heartbeat` and `/api/v1/heartbeat` are both
|
|
32
|
+
* `@login_required`, and that decorator throttles `_track_request()` to
|
|
33
|
+
* 1/min/user — beating faster than this would buy nothing but load. */
|
|
34
|
+
const MIN_INTERVAL_MS = 60 * 1000;
|
|
35
|
+
|
|
36
|
+
/** One hour: the ceiling the server may ask for, and the ceiling the backoff
|
|
37
|
+
* ladder may reach. Past this the panel's "online" window is meaningless. */
|
|
38
|
+
const MAX_INTERVAL_MS = 60 * 60 * 1000;
|
|
39
|
+
|
|
40
|
+
/** Failures slow the beacon down rather than retrying on the same rhythm. */
|
|
41
|
+
const BACKOFF_FACTOR = 2;
|
|
42
|
+
const MAX_BACKOFF_MS = 30 * 60 * 1000;
|
|
43
|
+
|
|
44
|
+
/** A beacon that has not answered in 20 s is a beacon that is not going to:
|
|
45
|
+
* the request body is ~120 bytes. Kept well under MIN_INTERVAL_MS so an
|
|
46
|
+
* in-flight beat can never overlap the next scheduled one. */
|
|
47
|
+
const REQUEST_TIMEOUT_MS = 20 * 1000;
|
|
48
|
+
|
|
49
|
+
/** The app vocabulary, copied EXACTLY from aegis1's `PRESENCE_APPS`
|
|
50
|
+
* (aegis1/app.py, right above `_presence_app`). This is not a suggestion: the
|
|
51
|
+
* server keeps a name only if it is in that tuple and maps everything else to
|
|
52
|
+
* 'other', so a client that sends a name of its own invention is a client the
|
|
53
|
+
* operator cannot identify in the panel — silently, with a 200 and no error
|
|
54
|
+
* anywhere. `test/cli-presence.test.mjs` parses PRESENCE_APPS out of app.py and
|
|
55
|
+
* fails if these two lists drift.
|
|
56
|
+
*
|
|
57
|
+
* The terminal host sends 'cli' rather than a product name for that reason:
|
|
58
|
+
* 'aegiscode' is not in the server's tuple, so it would land as 'other'. */
|
|
59
|
+
const APP_NAMES = Object.freeze(['desktop', 'cli', 'mcp', 'extension', 'web']);
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* One wire-safe token: trimmed, control characters and whitespace stripped,
|
|
63
|
+
* truncated to the width the server's `_presence_token()` will accept. Returns
|
|
64
|
+
* '' for anything that is not a usable string, so a caller can use the empty
|
|
65
|
+
* result as "omit this field" rather than sending `null`.
|
|
66
|
+
*
|
|
67
|
+
* The sanitising is done HERE rather than left to the server on purpose: the
|
|
68
|
+
* server sanitises so a bad field cannot 400 the beacon, but a client that
|
|
69
|
+
* relies on that ships a body it cannot describe. Truncating at the source
|
|
70
|
+
* means what this code sends and what the presence row stores are the same
|
|
71
|
+
* string.
|
|
72
|
+
*/
|
|
73
|
+
function saneToken(value, limit) {
|
|
74
|
+
try {
|
|
75
|
+
if (value == null) return '';
|
|
76
|
+
if (typeof value === 'number' && !Number.isFinite(value)) return '';
|
|
77
|
+
const text = String(value).replace(/[\u0000-\u001f\u007f\s]+/g, '');
|
|
78
|
+
const max = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.floor(Number(limit)) : 64;
|
|
79
|
+
return text.slice(0, max);
|
|
80
|
+
} catch {
|
|
81
|
+
return '';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A non-negative integer queue depth. aegis1 clamps to [0, 100000] itself;
|
|
86
|
+
* clamping here too means the two never disagree about what was sent. */
|
|
87
|
+
function saneCount(value) {
|
|
88
|
+
const n = Number(value);
|
|
89
|
+
if (!Number.isFinite(n) || n <= 0) return 0;
|
|
90
|
+
return Math.min(100000, Math.floor(n));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = {
|
|
94
|
+
PRESENCE_PATH,
|
|
95
|
+
DEFAULT_INTERVAL_MS,
|
|
96
|
+
MIN_INTERVAL_MS,
|
|
97
|
+
MAX_INTERVAL_MS,
|
|
98
|
+
BACKOFF_FACTOR,
|
|
99
|
+
MAX_BACKOFF_MS,
|
|
100
|
+
REQUEST_TIMEOUT_MS,
|
|
101
|
+
APP_NAMES,
|
|
102
|
+
saneToken,
|
|
103
|
+
saneCount,
|
|
104
|
+
};
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Client presence beacon — the client half of aegis1's `/api/v1/heartbeat`.
|
|
5
|
+
*
|
|
6
|
+
* WHAT IT IS FOR. aegis1 already had `/api/heartbeat` (the dashboard's own JS
|
|
7
|
+
* pinging to bump `users.last_active_at`). What it did NOT have was any way to
|
|
8
|
+
* answer "who is running aegiscode right now, which app, which build, how many
|
|
9
|
+
* machines?" — a user sitting in a session but not making model calls was
|
|
10
|
+
* invisible. `heartbeat_v1()` in aegis1/app.py closes that gap by writing a
|
|
11
|
+
* `client_presence` row keyed on (user_id, app, install), and this module is
|
|
12
|
+
* the beacon that feeds it. Same for both hosts: the CLI's `aegiscode` binary
|
|
13
|
+
* and the desktop's main process require this one file.
|
|
14
|
+
*
|
|
15
|
+
* THE SERVER CONTRACT (aegis1/app.py `heartbeat_v1`, do not change one side
|
|
16
|
+
* without the other):
|
|
17
|
+
*
|
|
18
|
+
* POST /api/v1/heartbeat X-API-Key: <the user's aegis key>
|
|
19
|
+
* {"app": "desktop", "version": "0.8.12", "platform": "linux",
|
|
20
|
+
* "install": "9f3c1a2b4d5e6f70", "queue": 2, "autonomous": false}
|
|
21
|
+
* -> 200 {"ok": true, "online": true, "seen_at": ..., "beat_interval_s": 300}
|
|
22
|
+
*
|
|
23
|
+
* Auth is the ordinary `@login_required`, which already accepts X-API-Key or
|
|
24
|
+
* Bearer — the same key every host signs in with. So the beacon introduces NO
|
|
25
|
+
* second credential and no new client secret, and a host with no key has
|
|
26
|
+
* nothing to beacon AT: `apiKey` absent means this module is inert by
|
|
27
|
+
* construction (see `disabledPresence()`), never a 401 loop.
|
|
28
|
+
*
|
|
29
|
+
* `install` IS THE FINGERPRINT. Not a second identifier invented here: it is
|
|
30
|
+
* `machineFingerprint()` from ./device-fingerprint.js, the same SHA-256 the
|
|
31
|
+
* device-registration path uses. That is deliberate and it is the property the
|
|
32
|
+
* admin panel needs — "how many machines does this user run" has to count
|
|
33
|
+
* machines, so the beacon must carry the machine's identity, not a random
|
|
34
|
+
* per-run token that would make one laptop look like fifty. It is a 64-char
|
|
35
|
+
* lowercase hex digest and aegis1's `_presence_token(install, 64)` accepts
|
|
36
|
+
* exactly that width. Note what this does and does not imply: it is a stable
|
|
37
|
+
* pseudonym for a machine, so a user's own rows join up; it is NOT a
|
|
38
|
+
* cross-account tracking device and the server never sees the raw machine id it
|
|
39
|
+
* was derived from.
|
|
40
|
+
*
|
|
41
|
+
* FOUR PROPERTIES, in order of importance — the same discipline
|
|
42
|
+
* `lib/local/telemetry.js` is built around, for the same reason:
|
|
43
|
+
*
|
|
44
|
+
* 1. It cannot break the host. `beat()` returns a boolean and NEVER throws,
|
|
45
|
+
* whatever the network, the DNS, the JSON, or an injected `fetch` does.
|
|
46
|
+
* A beacon that can take down a CLI session or an Electron main process
|
|
47
|
+
* is worse than no beacon at all.
|
|
48
|
+
* 2. It cannot leak. The request body is rebuilt field by field from the
|
|
49
|
+
* arguments — never spread, never `JSON.stringify(callerObject)` — and
|
|
50
|
+
* only `app`, `version`, `platform`, `install`, `queue`, `autonomous` can
|
|
51
|
+
* ever be sent. No conversation content, no file paths, no model output,
|
|
52
|
+
* no email, no prompt text. `sane()` additionally truncates each field to
|
|
53
|
+
* the same width the server enforces, so a caller cannot smuggle a blob
|
|
54
|
+
* through a field this module owns.
|
|
55
|
+
* 3. It cannot keep the process alive. The timer is `unref()`d, so `stop()`
|
|
56
|
+
* is a convenience, not a requirement: an interrupted CLI exits on time
|
|
57
|
+
* even if nobody ever calls it, and the desktop's quit path does not have
|
|
58
|
+
* to thread a handle through.
|
|
59
|
+
* 4. It cannot hammer. The cadence is the SERVER's (`beat_interval_s` in the
|
|
60
|
+
* response), so the beacon can be slowed or sped up without shipping a
|
|
61
|
+
* client release; failures back off exponentially instead of retrying on
|
|
62
|
+
* the same rhythm, which is what turns a dead endpoint from a client
|
|
63
|
+
* problem into a server problem.
|
|
64
|
+
*
|
|
65
|
+
* Nothing in this file may import Electron: it is plain Node so the CLI, the
|
|
66
|
+
* desktop main process and the tests can all drive the same code. Each host
|
|
67
|
+
* injects its own `app` name, version, platform and queue depth.
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
const {
|
|
71
|
+
PRESENCE_PATH,
|
|
72
|
+
DEFAULT_INTERVAL_MS,
|
|
73
|
+
MIN_INTERVAL_MS,
|
|
74
|
+
MAX_INTERVAL_MS,
|
|
75
|
+
BACKOFF_FACTOR,
|
|
76
|
+
MAX_BACKOFF_MS,
|
|
77
|
+
REQUEST_TIMEOUT_MS,
|
|
78
|
+
APP_NAMES,
|
|
79
|
+
saneToken,
|
|
80
|
+
saneCount,
|
|
81
|
+
} = require('./presence-constants.js');
|
|
82
|
+
|
|
83
|
+
const DEFAULT_API_BASE = 'https://aegiscloud.org';
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The store returned when there is nothing to beacon (no key, or a host that
|
|
87
|
+
* explicitly opted out). Every method answers, nothing happens, no timer is
|
|
88
|
+
* created and no request is made: `enabled` is false and `beat()` is a no-op
|
|
89
|
+
* that reports `false`. Checked by test/presence.test.mjs.
|
|
90
|
+
*/
|
|
91
|
+
function disabledPresence(reason) {
|
|
92
|
+
const state = {
|
|
93
|
+
enabled: false,
|
|
94
|
+
reason: String(reason || 'disabled'),
|
|
95
|
+
beats: 0,
|
|
96
|
+
failures: 0,
|
|
97
|
+
lastError: null,
|
|
98
|
+
lastSeenAt: null,
|
|
99
|
+
intervalMs: null,
|
|
100
|
+
install: null,
|
|
101
|
+
app: null,
|
|
102
|
+
running: false,
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
enabled: false,
|
|
106
|
+
reason: state.reason,
|
|
107
|
+
install: null,
|
|
108
|
+
beat: () => Promise.resolve(false),
|
|
109
|
+
start: () => false,
|
|
110
|
+
stop: () => false,
|
|
111
|
+
state: () => ({ ...state }),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** One ISO-8601 UTC string, or null. Never throws on a hostile clock. */
|
|
116
|
+
function isoOf(ms) {
|
|
117
|
+
try {
|
|
118
|
+
const n = Number(ms);
|
|
119
|
+
if (!Number.isFinite(n)) return null;
|
|
120
|
+
return new Date(n).toISOString();
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {object} opts
|
|
128
|
+
* @param {string} [opts.apiKey] the aegis key; absent ⇒ inert
|
|
129
|
+
* @param {string} [opts.baseUrl] defaults to https://aegiscloud.org
|
|
130
|
+
* @param {string} [opts.app] 'desktop' | 'cli' | ... (see APP_NAMES)
|
|
131
|
+
* @param {string} [opts.version] the host's own build string
|
|
132
|
+
* @param {string} [opts.platform] process.platform
|
|
133
|
+
* @param {string} [opts.install] machine fingerprint (default: computed)
|
|
134
|
+
* @param {number|function} [opts.queueDepth] pending queue tasks (may be a fn)
|
|
135
|
+
* @param {boolean|function} [opts.autonomous] a drain is running (may be a fn)
|
|
136
|
+
* @param {number} [opts.intervalMs] initial cadence before the server answers
|
|
137
|
+
* @param {boolean} [opts.enabled] explicit kill switch (default true)
|
|
138
|
+
* @param {string} [opts.clientVersion] X-AEGIS-Version header (version gate)
|
|
139
|
+
* @param {function} [opts.fetchImpl] fetch override (tests)
|
|
140
|
+
* @param {function} [opts.now] clock override (tests)
|
|
141
|
+
* @param {function} [opts.log] (level, message, err) => void
|
|
142
|
+
* @param {function} [opts.setTimer] setTimeout override (tests)
|
|
143
|
+
* @param {function} [opts.clearTimer] clearTimeout override (tests)
|
|
144
|
+
*/
|
|
145
|
+
function createPresence(opts = {}) {
|
|
146
|
+
const apiKey = typeof opts.apiKey === 'string' ? opts.apiKey.trim() : '';
|
|
147
|
+
if (!apiKey) return disabledPresence('no-api-key');
|
|
148
|
+
if (opts.enabled === false) return disabledPresence('disabled');
|
|
149
|
+
|
|
150
|
+
const log = typeof opts.log === 'function' ? opts.log : () => {};
|
|
151
|
+
// A logger that throws is not allowed to matter — same rule as telemetry.js.
|
|
152
|
+
function debugOnce(kind) {
|
|
153
|
+
if (logged.has(kind)) return;
|
|
154
|
+
logged.add(kind);
|
|
155
|
+
try {
|
|
156
|
+
log('debug', `presence: ${kind}`);
|
|
157
|
+
} catch {
|
|
158
|
+
/* a broken logger is not an error path */
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const logged = new Set();
|
|
162
|
+
|
|
163
|
+
const now = typeof opts.now === 'function' ? opts.now : () => Date.now();
|
|
164
|
+
const setTimer = typeof opts.setTimer === 'function' ? opts.setTimer : setTimeout;
|
|
165
|
+
const clearTimer = typeof opts.clearTimer === 'function' ? opts.clearTimer : clearTimeout;
|
|
166
|
+
|
|
167
|
+
// The fingerprint. Required lazily so a host that never beacons (the tests
|
|
168
|
+
// for the other modules) does not touch the filesystem at require time.
|
|
169
|
+
//
|
|
170
|
+
// An injected `fingerprint` is an IDENTITY SOURCE, not a first choice: when a
|
|
171
|
+
// host hands one in, that is the machine's identity and the built-in ladder
|
|
172
|
+
// is not consulted. That matters for the packaged hosts, which resolve the
|
|
173
|
+
// fingerprint once at their own call site (cli/src/presence.js, desktop
|
|
174
|
+
// main.js) and must be able to fail loudly if it cannot — a silent fallback
|
|
175
|
+
// here would hide a broken identity by substituting a different one, and the
|
|
176
|
+
// panel would count the same laptop as two machines.
|
|
177
|
+
let install = saneToken(opts.install, 64);
|
|
178
|
+
if (!install && typeof opts.fingerprint === 'function') {
|
|
179
|
+
try {
|
|
180
|
+
install = saneToken(opts.fingerprint(), 64);
|
|
181
|
+
} catch {
|
|
182
|
+
debugOnce('fingerprint');
|
|
183
|
+
}
|
|
184
|
+
} else if (!install) {
|
|
185
|
+
try {
|
|
186
|
+
install = saneToken(require('./device-fingerprint.js').machineFingerprint(), 64);
|
|
187
|
+
} catch {
|
|
188
|
+
debugOnce('fingerprint');
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!install) {
|
|
192
|
+
// No machine identity could be resolved at all (an exotic sandbox). A
|
|
193
|
+
// beacon without an install key would write a NEW presence row on every
|
|
194
|
+
// beat — one user, infinite machines in the panel. Better to stay out of
|
|
195
|
+
// the table than to poison it: see device-fingerprint.js for the ladder
|
|
196
|
+
// (machine id -> persisted install id -> hostname) that makes this rare.
|
|
197
|
+
return disabledPresence('no-install-identity');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const app = saneToken(opts.app, 24).toLowerCase() || 'other';
|
|
201
|
+
const version = saneToken(opts.version, 32);
|
|
202
|
+
const rawPlatform = saneToken(opts.platform, 16).toLowerCase();
|
|
203
|
+
const platform = rawPlatform || (typeof process !== 'undefined' && process.platform ? process.platform : '');
|
|
204
|
+
const baseUrl = String(opts.baseUrl || (typeof process !== 'undefined' && process.env && process.env.AEGIS_API_BASE) || DEFAULT_API_BASE).replace(/\/+$/, '');
|
|
205
|
+
const path = PRESENCE_PATH;
|
|
206
|
+
const fetchImpl =
|
|
207
|
+
typeof opts.fetchImpl === 'function'
|
|
208
|
+
? opts.fetchImpl
|
|
209
|
+
: typeof fetch === 'function'
|
|
210
|
+
? fetch
|
|
211
|
+
: null;
|
|
212
|
+
|
|
213
|
+
/** A caller passing a function is asking to be read at send time, so the
|
|
214
|
+
* beacon reports the LIVE queue depth rather than the depth at boot. */
|
|
215
|
+
function readDynamic(value, fallback) {
|
|
216
|
+
try {
|
|
217
|
+
return typeof value === 'function' ? value() : value;
|
|
218
|
+
} catch {
|
|
219
|
+
return fallback;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let intervalMs = clampInterval(opts.intervalMs);
|
|
224
|
+
const state = {
|
|
225
|
+
enabled: true,
|
|
226
|
+
reason: null,
|
|
227
|
+
beats: 0,
|
|
228
|
+
failures: 0,
|
|
229
|
+
lastError: null,
|
|
230
|
+
lastSeenAt: null,
|
|
231
|
+
intervalMs,
|
|
232
|
+
install,
|
|
233
|
+
app,
|
|
234
|
+
version: version || null,
|
|
235
|
+
platform: platform || null,
|
|
236
|
+
running: false,
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
let timer = null;
|
|
240
|
+
let inflight = null;
|
|
241
|
+
let backoffMs = 0;
|
|
242
|
+
let stopped = false;
|
|
243
|
+
|
|
244
|
+
function clampInterval(ms) {
|
|
245
|
+
const n = Number(ms);
|
|
246
|
+
if (!Number.isFinite(n) || n <= 0) return DEFAULT_INTERVAL_MS;
|
|
247
|
+
return Math.min(MAX_INTERVAL_MS, Math.max(MIN_INTERVAL_MS, Math.floor(n)));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The ONLY body shape this module can ever send. Field by field, on purpose. */
|
|
251
|
+
function body() {
|
|
252
|
+
return {
|
|
253
|
+
app,
|
|
254
|
+
version: version || undefined,
|
|
255
|
+
platform: platform || undefined,
|
|
256
|
+
install,
|
|
257
|
+
queue: saneCount(readDynamic(opts.queueDepth, 0)),
|
|
258
|
+
autonomous: Boolean(readDynamic(opts.autonomous, false)),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Send one beat. Resolves `true` when the server acknowledged, `false` on
|
|
264
|
+
* every other outcome — no key, offline, DNS failure, 500, a malformed body,
|
|
265
|
+
* an aborted request. It never rejects, so a caller may `void beat()` without
|
|
266
|
+
* an unhandled-rejection guard, and a concurrent call while one is in flight
|
|
267
|
+
* is answered by the in-flight promise rather than by a second request (two
|
|
268
|
+
* beacons racing would double-count `beats` on the server).
|
|
269
|
+
*/
|
|
270
|
+
function beat() {
|
|
271
|
+
if (stopped) return Promise.resolve(false);
|
|
272
|
+
if (inflight) return inflight;
|
|
273
|
+
if (!fetchImpl) {
|
|
274
|
+
debugOnce('no-fetch');
|
|
275
|
+
state.lastError = 'no fetch implementation';
|
|
276
|
+
state.failures += 1;
|
|
277
|
+
return Promise.resolve(false);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const startedAt = now();
|
|
281
|
+
inflight = (async () => {
|
|
282
|
+
let timedOut = false;
|
|
283
|
+
let cancel = null;
|
|
284
|
+
try {
|
|
285
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
286
|
+
if (controller) {
|
|
287
|
+
const t = setTimer(() => {
|
|
288
|
+
timedOut = true;
|
|
289
|
+
try {
|
|
290
|
+
controller.abort();
|
|
291
|
+
} catch {
|
|
292
|
+
/* already gone */
|
|
293
|
+
}
|
|
294
|
+
}, REQUEST_TIMEOUT_MS);
|
|
295
|
+
if (t && typeof t.unref === 'function') t.unref();
|
|
296
|
+
cancel = () => clearTimer(t);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const res = await fetchImpl(`${baseUrl}${path}`, {
|
|
300
|
+
method: 'POST',
|
|
301
|
+
headers: {
|
|
302
|
+
'Content-Type': 'application/json',
|
|
303
|
+
'X-API-Key': apiKey,
|
|
304
|
+
'X-AEGIS-Version': saneToken(opts.clientVersion, 32) || version || '',
|
|
305
|
+
},
|
|
306
|
+
body: JSON.stringify(body()),
|
|
307
|
+
...(controller ? { signal: controller.signal } : {}),
|
|
308
|
+
});
|
|
309
|
+
if (cancel) cancel();
|
|
310
|
+
|
|
311
|
+
// `ok` on the response, not `res.ok === true` semantics: a 404 (server
|
|
312
|
+
// predates the route) and a 401 (key revoked) are both just "not this
|
|
313
|
+
// time" — the beacon must not retry storm either of them.
|
|
314
|
+
if (!res || typeof res.status !== 'number' || res.status < 200 || res.status >= 300) {
|
|
315
|
+
state.failures += 1;
|
|
316
|
+
state.lastError = `http ${res && res.status ? res.status : 'error'}`;
|
|
317
|
+
backoffMs = nextBackoff(backoffMs);
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
let data = null;
|
|
322
|
+
try {
|
|
323
|
+
data = await res.json();
|
|
324
|
+
} catch {
|
|
325
|
+
// A 200 with an unreadable body is still a successful beat: the
|
|
326
|
+
// server wrote the row before it serialised the answer. Only the
|
|
327
|
+
// cadence hint is lost, and the current one stays in force.
|
|
328
|
+
data = null;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
state.beats += 1;
|
|
332
|
+
state.failures = 0;
|
|
333
|
+
state.lastError = null;
|
|
334
|
+
state.lastSeenAt = isoOf(now());
|
|
335
|
+
backoffMs = 0;
|
|
336
|
+
// The server owns the cadence. An unrecognised/hostile value is clamped
|
|
337
|
+
// rather than trusted: a `beat_interval_s` of 0 would be a hot loop.
|
|
338
|
+
if (data && typeof data === 'object' && data.beat_interval_s != null) {
|
|
339
|
+
const secs = Number(data.beat_interval_s);
|
|
340
|
+
if (Number.isFinite(secs) && secs > 0) intervalMs = clampInterval(secs * 1000);
|
|
341
|
+
}
|
|
342
|
+
state.intervalMs = intervalMs;
|
|
343
|
+
return true;
|
|
344
|
+
} catch (err) {
|
|
345
|
+
if (cancel) cancel();
|
|
346
|
+
state.failures += 1;
|
|
347
|
+
state.lastError = timedOut ? 'timeout' : String((err && err.message) || err || 'error').slice(0, 200);
|
|
348
|
+
backoffMs = nextBackoff(backoffMs);
|
|
349
|
+
if (state.failures === 1) debugOnce('beat-failed'); // once, then quiet
|
|
350
|
+
return false;
|
|
351
|
+
} finally {
|
|
352
|
+
inflight = null;
|
|
353
|
+
if (state.running) schedule(Math.max(0, intervalMs + backoffMs - (now() - startedAt)));
|
|
354
|
+
}
|
|
355
|
+
})();
|
|
356
|
+
|
|
357
|
+
return inflight;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function nextBackoff(current) {
|
|
361
|
+
const base = current > 0 ? current * BACKOFF_FACTOR : Math.max(MIN_INTERVAL_MS, intervalMs);
|
|
362
|
+
return Math.min(MAX_BACKOFF_MS, Math.floor(base));
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** One timer at a time, always unref'd, always cleared before replacing. */
|
|
366
|
+
function schedule(delayMs) {
|
|
367
|
+
if (stopped || typeof setTimer !== 'function') return;
|
|
368
|
+
if (timer) clearTimer(timer);
|
|
369
|
+
const delay = Math.max(1000, Math.floor(Number(delayMs) || intervalMs));
|
|
370
|
+
timer = setTimer(() => {
|
|
371
|
+
timer = null;
|
|
372
|
+
void beat();
|
|
373
|
+
}, delay);
|
|
374
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Start beaconing and send the FIRST beat immediately. A host that is opened
|
|
379
|
+
* and closed in under a minute still registers — waiting one full interval
|
|
380
|
+
* before the first beat would make the panel blind to exactly the short
|
|
381
|
+
* sessions the route was added for.
|
|
382
|
+
*/
|
|
383
|
+
function start() {
|
|
384
|
+
if (stopped) return false;
|
|
385
|
+
state.running = true;
|
|
386
|
+
void beat();
|
|
387
|
+
return true;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Stop beaconing. Idempotent, and safe to call when start() never ran. */
|
|
391
|
+
function stop() {
|
|
392
|
+
stopped = true;
|
|
393
|
+
state.running = false;
|
|
394
|
+
if (timer) {
|
|
395
|
+
try {
|
|
396
|
+
clearTimer(timer);
|
|
397
|
+
} catch {
|
|
398
|
+
/* a timer that already fired is not an error */
|
|
399
|
+
}
|
|
400
|
+
timer = null;
|
|
401
|
+
}
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return {
|
|
406
|
+
enabled: true,
|
|
407
|
+
app,
|
|
408
|
+
install,
|
|
409
|
+
beat,
|
|
410
|
+
start,
|
|
411
|
+
stop,
|
|
412
|
+
/**
|
|
413
|
+
* The in-flight beat, or null. Exposed for one reason: a SHORT-LIVED host
|
|
414
|
+
* (`aegiscode -p "…"`, `aegiscode autonomous run`) finishes its work in
|
|
415
|
+
* well under a second and calls `process.exit()`, which kills an in-flight
|
|
416
|
+
* request and loses the beat entirely — the machine is silently absent from
|
|
417
|
+
* the panel even though it just ran. The CLI awaits this before exiting
|
|
418
|
+
* (see `flush()` in cli/src/presence.js). A long-lived host can ignore it.
|
|
419
|
+
*/
|
|
420
|
+
pending: () => inflight,
|
|
421
|
+
state: () => ({ ...state, intervalMs }),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
module.exports = {
|
|
426
|
+
createPresence,
|
|
427
|
+
disabledPresence,
|
|
428
|
+
PRESENCE_PATH,
|
|
429
|
+
DEFAULT_INTERVAL_MS,
|
|
430
|
+
MIN_INTERVAL_MS,
|
|
431
|
+
MAX_INTERVAL_MS,
|
|
432
|
+
MAX_BACKOFF_MS,
|
|
433
|
+
REQUEST_TIMEOUT_MS,
|
|
434
|
+
APP_NAMES,
|
|
435
|
+
};
|