aegiscode 6.8.12 → 6.8.14
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/bin/aegiscode.js +32 -0
- package/package.json +1 -1
- package/scripts/predist.mjs +22 -1
- package/src/app.js +10 -88
- package/src/caps.js +8 -1
- package/src/commands.js +63 -0
- package/src/entitlement.js +207 -1
- package/src/events.js +88 -11
- package/src/gate.js +45 -0
- package/src/panels.js +80 -10
- package/vendor/client/aegis.js +118 -6
- package/vendor/desktop/lib/local/entitlement.js +81 -0
- package/vendor/desktop/lib/local/local.js +54 -2
- package/vendor/desktop/lib/local/tools.js +113 -0
- package/vendor/tools/agent-gate.mjs +1063 -0
package/src/events.js
CHANGED
|
@@ -26,6 +26,29 @@ const { decodeEscSequence, decodePlain, KEY } = require('./keys.js');
|
|
|
26
26
|
const queue = [];
|
|
27
27
|
let waiting = [];
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Keys handed in from OUTSIDE the pump before any pump existed — the startup
|
|
31
|
+
* background probe is the only caller (see `feedKeys`).
|
|
32
|
+
*
|
|
33
|
+
* Why this is not just `queue`. A `resetKeyStream()` clears the queue on
|
|
34
|
+
* purpose: typed-ahead from a dead session must not land in the next one. But
|
|
35
|
+
* the probe runs BEFORE onboarding and BEFORE the session loop, and onboarding
|
|
36
|
+
* attaches a pump of its own and detaches it in a `finally` — so an early
|
|
37
|
+
* command was being queued, then wiped by that detach, and the session loop
|
|
38
|
+
* that followed waited forever for input that had already been read and
|
|
39
|
+
* thrown away.
|
|
40
|
+
*
|
|
41
|
+
* That is a real user-visible bug, not just a test artefact: anything typed
|
|
42
|
+
* while the CLI is still starting up was silently dropped. It also made
|
|
43
|
+
* `test/cli-platform-parity.test.mjs` fail roughly 4 runs in 10 on a SINGLE
|
|
44
|
+
* platform — same code, same machine — which is why "parity" kept being
|
|
45
|
+
* reported as broken and re-fixed for a day. Bytes captured before any session
|
|
46
|
+
* existed belong to the session that has not started yet, so they survive a
|
|
47
|
+
* session teardown and are delivered to the first consumer that asks.
|
|
48
|
+
*/
|
|
49
|
+
let preSessionKeys = [];
|
|
50
|
+
let everAttached = false;
|
|
51
|
+
|
|
29
52
|
/**
|
|
30
53
|
* Handed to every parked `nextKey()` waiter when the pump is reset, so a
|
|
31
54
|
* consumer can tell "the stream went away" from "the user pressed nothing".
|
|
@@ -61,7 +84,26 @@ function isKeyStreamSuspended() {
|
|
|
61
84
|
|
|
62
85
|
function attachKeyStream(stdin) {
|
|
63
86
|
attachedStdin = stdin;
|
|
87
|
+
everAttached = true;
|
|
64
88
|
onData = (chunk) => pushChars(String(chunk));
|
|
89
|
+
// Before the listener goes on, take anything the terminal already delivered
|
|
90
|
+
// while NOTHING owned the stream. That window is real: the startup background
|
|
91
|
+
// probe resumes stdin, then pauses it again when it finishes, so a command
|
|
92
|
+
// typed at launch can be sitting in the Readable's buffer — and `resume()`
|
|
93
|
+
// below emits from a state we do not control, which is why the pty sweep hung
|
|
94
|
+
// on 1 run in 10 with the frame fully drawn and no command ever seen. Pulling
|
|
95
|
+
// the buffer out first makes the handoff explicit instead of raced.
|
|
96
|
+
try {
|
|
97
|
+
if (typeof stdin.read === 'function') {
|
|
98
|
+
for (let i = 0; i < 64; i += 1) {
|
|
99
|
+
const buffered = stdin.read();
|
|
100
|
+
if (buffered === null) break;
|
|
101
|
+
feedKeys(String(buffered), { keystrokes: true });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
} catch {
|
|
105
|
+
/* a stream without the Readable surface: resume() is all we ever had */
|
|
106
|
+
}
|
|
65
107
|
// A non-TTY stdin has no setRawMode at all; guard it so callers degrade
|
|
66
108
|
// instead of throwing "stdin.setRawMode is not a function".
|
|
67
109
|
if (typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
|
|
@@ -138,8 +180,42 @@ function flushPaste() {
|
|
|
138
180
|
* receives. This runs through the queue instead, which `drainQueue`/`nextKey`
|
|
139
181
|
* consult regardless of the stream's state.
|
|
140
182
|
*/
|
|
141
|
-
function feedKeys(text) {
|
|
142
|
-
if (text)
|
|
183
|
+
function feedKeys(text, { keystrokes = false } = {}) {
|
|
184
|
+
if (!text) return;
|
|
185
|
+
const s = String(text);
|
|
186
|
+
// A handback from the startup probe is a burst of KEYSTROKES that raced the
|
|
187
|
+
// OSC-11 reply, not a paste — and the difference is not cosmetic. The probe
|
|
188
|
+
// reads whatever arrived before its 120ms deadline and hands it back as one
|
|
189
|
+
// string, so a command typed the instant the CLI started arrives as
|
|
190
|
+
// `"/exit\n\x04"` in a single call. `pushChars` sees the embedded newline,
|
|
191
|
+
// declares it a paste, and `flushPaste` collapses it into ONE `{name:'paste'}`
|
|
192
|
+
// key — so the session loop never receives the Enter and parks on `nextKey()`
|
|
193
|
+
// forever. Measured: 10/10 runs hung at 5029 bytes with the probe on, 10/10
|
|
194
|
+
// clean at 9113 bytes with it off. Replaying as keystrokes gives the loop the
|
|
195
|
+
// same sequence a `data` event would have: `/`, `e`, `x`, `i`, `t`, `enter`.
|
|
196
|
+
//
|
|
197
|
+
// The size guard keeps the other case honest: a real paste large enough to
|
|
198
|
+
// matter (or an explicit bracketed-paste frame) still takes the paste path,
|
|
199
|
+
// because feeding 10k characters through the decoder one at a time is the
|
|
200
|
+
// thing the heuristic exists to avoid.
|
|
201
|
+
if (keystrokes && s.length <= PASTE_LARGE && !s.includes('\x1b[200~')) {
|
|
202
|
+
feedChars(s);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
pushChars(s);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Decode a run of characters into keys, preserving multi-byte boundaries. */
|
|
209
|
+
function feedChars(s) {
|
|
210
|
+
buffer += s;
|
|
211
|
+
while (buffer.length) {
|
|
212
|
+
const cp = buffer.codePointAt(0);
|
|
213
|
+
const c = String.fromCodePoint(cp);
|
|
214
|
+
const units = c.length;
|
|
215
|
+
if (units > buffer.length) break; // incomplete multi-byte char
|
|
216
|
+
buffer = buffer.slice(units);
|
|
217
|
+
feed(c);
|
|
218
|
+
}
|
|
143
219
|
}
|
|
144
220
|
|
|
145
221
|
function pushChars(s) {
|
|
@@ -162,15 +238,7 @@ function pushChars(s) {
|
|
|
162
238
|
pasteTimer = setTimeout(flushPaste, PASTE_DEBOUNCE_MS);
|
|
163
239
|
return;
|
|
164
240
|
}
|
|
165
|
-
|
|
166
|
-
while (buffer.length) {
|
|
167
|
-
const cp = buffer.codePointAt(0);
|
|
168
|
-
const c = String.fromCodePoint(cp);
|
|
169
|
-
const units = c.length;
|
|
170
|
-
if (units > buffer.length) break; // incomplete multi-byte char
|
|
171
|
-
buffer = buffer.slice(units);
|
|
172
|
-
feed(c);
|
|
173
|
-
}
|
|
241
|
+
feedChars(s);
|
|
174
242
|
}
|
|
175
243
|
|
|
176
244
|
function feed(c) {
|
|
@@ -264,6 +332,10 @@ function dispatch(key) {
|
|
|
264
332
|
if (waiting.length) {
|
|
265
333
|
const w = waiting.shift();
|
|
266
334
|
w(key);
|
|
335
|
+
} else if (!everAttached) {
|
|
336
|
+
// Nothing has ever consumed keys, so this is startup input: hold it where a
|
|
337
|
+
// session reset cannot reach it.
|
|
338
|
+
preSessionKeys.push(key);
|
|
267
339
|
} else {
|
|
268
340
|
queue.push(key);
|
|
269
341
|
}
|
|
@@ -272,6 +344,7 @@ function dispatch(key) {
|
|
|
272
344
|
/** The next key, waiting as long as it takes. */
|
|
273
345
|
function nextKey() {
|
|
274
346
|
if (queue.length) return Promise.resolve(queue.shift());
|
|
347
|
+
if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
|
|
275
348
|
return new Promise((resolve) => waiting.push(resolve));
|
|
276
349
|
}
|
|
277
350
|
|
|
@@ -284,6 +357,7 @@ function nextKey() {
|
|
|
284
357
|
*/
|
|
285
358
|
function nextKeyTimeout(ms) {
|
|
286
359
|
if (queue.length) return Promise.resolve(queue.shift());
|
|
360
|
+
if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
|
|
287
361
|
return new Promise((resolve) => {
|
|
288
362
|
const timer = setTimeout(() => {
|
|
289
363
|
const i = waiting.indexOf(wrapper);
|
|
@@ -306,6 +380,9 @@ function requeueKeys(keys) {
|
|
|
306
380
|
}
|
|
307
381
|
|
|
308
382
|
function drainQueue() {
|
|
383
|
+
// Only this session's keys. `preSessionKeys` is deliberately left alone: it
|
|
384
|
+
// holds input captured before any session existed, and clearing it here is
|
|
385
|
+
// exactly the bug its comment describes.
|
|
309
386
|
queue.length = 0;
|
|
310
387
|
}
|
|
311
388
|
|
package/src/gate.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `aegiscode gate` — the agent-key gate, from an npm install with no git.
|
|
5
|
+
*
|
|
6
|
+
* The gate itself (`tools/agent-gate.mjs`: status/check/init/bind-machine/
|
|
7
|
+
* import-key/rotate/add-key/lock-status/hash/install-hooks) already worked in
|
|
8
|
+
* a source checkout of aegiscode-plugin. It did not work from `npm install -g
|
|
9
|
+
* aegiscode`, because `tools/` was never staged into the published package —
|
|
10
|
+
* the CLI's own admin machine could not run `bind-machine` against a gated
|
|
11
|
+
* tree without a git clone it was never going to have. This closes that gap:
|
|
12
|
+
* `resolveShared()` finds the same repo-relative path in both layouts (see
|
|
13
|
+
* `sharedpaths.js`), exactly like every other shared module this CLI uses.
|
|
14
|
+
*
|
|
15
|
+
* Loaded via dynamic `import()`, not `require()`: `agent-gate.mjs` is an ES
|
|
16
|
+
* module, and this file — like the rest of `src/` — is CommonJS. `deps.js`
|
|
17
|
+
* does not carry this path in its eager list for the same reason: `require()`
|
|
18
|
+
* cannot load an ES module synchronously, so the gate is resolved and
|
|
19
|
+
* imported lazily, here, only when `aegiscode gate` actually runs.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const path = require('node:path');
|
|
23
|
+
const { pathToFileURL } = require('node:url');
|
|
24
|
+
const { resolveShared } = require('./sharedpaths.js');
|
|
25
|
+
|
|
26
|
+
/** @returns {Promise<typeof import('../../tools/agent-gate.mjs')>} */
|
|
27
|
+
async function loadGate() {
|
|
28
|
+
const gatePath = resolveShared(path.join('tools', 'agent-gate.mjs'));
|
|
29
|
+
return import(pathToFileURL(gatePath).href);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {string} sub verb (status, check, init, bind-machine, import-key, …)
|
|
34
|
+
* @param {string[]} argv the subcommand's own flags — bin/aegiscode.js hands
|
|
35
|
+
* the tail of the line over verbatim, like `mcp` and
|
|
36
|
+
* `fingerprint`, since `--cwd`/`--paths a b c` are the
|
|
37
|
+
* gate's flags, not this CLI's.
|
|
38
|
+
* @returns {Promise<number>} exit code (0 allowed, 3 denied, 4 misconfigured)
|
|
39
|
+
*/
|
|
40
|
+
async function runGate(sub, argv = []) {
|
|
41
|
+
const { run } = await loadGate();
|
|
42
|
+
return run([String(sub || 'status'), ...argv]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { runGate, loadGate };
|
package/src/panels.js
CHANGED
|
@@ -60,6 +60,39 @@ function str(v) {
|
|
|
60
60
|
return v == null ? '' : String(v);
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Word-wrap one sentence into span rows, indented, so a long claim survives
|
|
65
|
+
* `padLine()`.
|
|
66
|
+
*
|
|
67
|
+
* Local rather than imported on purpose (see the header: this file stays
|
|
68
|
+
* self-contained apart from theme/screen). `screens.js` has a `wrapped()` that
|
|
69
|
+
* does the same job, but it lives behind the screen-drawing module, which
|
|
70
|
+
* requires this one — importing it here would close a require cycle to reuse
|
|
71
|
+
* fifteen lines.
|
|
72
|
+
*
|
|
73
|
+
* Anything one word longer than the terminal is emitted on its own row rather
|
|
74
|
+
* than dropped: `padLine()` clips it, which is what already happens today, and
|
|
75
|
+
* losing a word is better than losing the sentence.
|
|
76
|
+
*/
|
|
77
|
+
function wrapRows(text, indent, style, cols) {
|
|
78
|
+
const width = Math.max(20, (Number(cols) || 80) - 2 - indent);
|
|
79
|
+
const pad = ' '.repeat(indent);
|
|
80
|
+
const words = str(text).split(/\s+/).filter(Boolean);
|
|
81
|
+
const out = [];
|
|
82
|
+
let line = '';
|
|
83
|
+
for (const word of words) {
|
|
84
|
+
const next = line ? `${line} ${word}` : word;
|
|
85
|
+
if (line && next.length > width) {
|
|
86
|
+
out.push([span('', pad), span(style, line)]);
|
|
87
|
+
line = word;
|
|
88
|
+
} else {
|
|
89
|
+
line = next;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (line) out.push([span('', pad), span(style, line)]);
|
|
93
|
+
return out.length ? out : [[span('', pad), span(style, '')]];
|
|
94
|
+
}
|
|
95
|
+
|
|
63
96
|
/**
|
|
64
97
|
* The four token buckets these panels render, in the shared shape.
|
|
65
98
|
*
|
|
@@ -913,16 +946,53 @@ function buildBilling(state, ctx = {}) {
|
|
|
913
946
|
}
|
|
914
947
|
lines.push([span('', '')]);
|
|
915
948
|
lines.push([span(t.white, 'AEGIS pooled inference'), span(t.gray, ' metered against your token bank')]);
|
|
916
|
-
|
|
917
|
-
//
|
|
918
|
-
//
|
|
919
|
-
//
|
|
920
|
-
//
|
|
921
|
-
//
|
|
922
|
-
//
|
|
923
|
-
//
|
|
924
|
-
//
|
|
925
|
-
|
|
949
|
+
// ── the paid prompt ───────────────────────────────────────────────────────
|
|
950
|
+
// `/billing` is the one screen a free user reaches when they are already
|
|
951
|
+
// thinking about money, and it used to spend that moment saying "AEGIS has no
|
|
952
|
+
// subscription of its own" — a claim that contradicted the plan Pro is sold
|
|
953
|
+
// as, on the only surface where the contradiction could cost a sale. It is
|
|
954
|
+
// now the place the ONE reason to pay is stated, in the words the desktop's
|
|
955
|
+
// welcome panel and the drain's refusal both use (`state.payment`, built by
|
|
956
|
+
// `cli/src/entitlement.js` from the shared module, so a terminal and a GUI
|
|
957
|
+
// cannot pitch two different products).
|
|
958
|
+
//
|
|
959
|
+
// The panel stays pure: it renders the view it is handed and never probes,
|
|
960
|
+
// never decides entitlement, and never invents a link. A caller that passes
|
|
961
|
+
// no view gets the top-up row it always printed, minus the false claim.
|
|
962
|
+
const pay = s.payment && typeof s.payment === 'object' ? s.payment : null;
|
|
963
|
+
if (pay) {
|
|
964
|
+
const { cols } = getSize();
|
|
965
|
+
const mark = pay.paid ? '✔' : '✦';
|
|
966
|
+
lines.push(...wrapRows(`${mark} ${str(pay.label) || 'Pro'}: ${str(pay.reason)}`, 2, pay.paid ? t.green : t.gold, cols));
|
|
967
|
+
// The honesty line rides every paid prompt, wrapped rather than clipped —
|
|
968
|
+
// `padLine()` truncates, and a truncated honesty line would read as the
|
|
969
|
+
// promise alone.
|
|
970
|
+
lines.push(...wrapRows(str(pay.honesty), 2, t.gray, cols));
|
|
971
|
+
if (!pay.paid && pay.unlock) lines.push(...wrapRows(str(pay.unlock), 2, t.gray, cols));
|
|
972
|
+
// The relay's price, on the lane a BYOK user is actually billed on. Printed
|
|
973
|
+
// only when the server published a rate (`pay.byok` is '' otherwise) —
|
|
974
|
+
// a hardcoded fee here would be a client disagreeing with the ledger, and
|
|
975
|
+
// saying nothing is the only honest alternative to inventing one. Wrapped,
|
|
976
|
+
// never clipped: `padLine()` truncates, and a truncated fee line would read
|
|
977
|
+
// as a cheaper lane than the one that bills.
|
|
978
|
+
if (pay.byok) lines.push(...wrapRows(str(pay.byok), 2, t.gray, cols));
|
|
979
|
+
// `verified === false` is the module's "we did not get a real answer"
|
|
980
|
+
// (timeout, unreadable body, no key). The offer still renders — this panel
|
|
981
|
+
// is allowed to sell — but a timeout is not presented as a fact about the
|
|
982
|
+
// account, which is the difference between a prompt and a lie.
|
|
983
|
+
if (pay.verified === false) lines.push(...wrapRows('(account not confirmed this session — verdict may be stale)', 2, t.gray, cols));
|
|
984
|
+
if (pay.url) lines.push([span('', ' '), span(t.gray, str(pay.url))]);
|
|
985
|
+
} else {
|
|
986
|
+
// Was a literal `https://aegiscloud.org/billing`, which has never been a
|
|
987
|
+
// route on aegis1 — only `/billing/success` is real; the page is `/topup`.
|
|
988
|
+
// So the one row on the one screen that exists to convert a free user sent
|
|
989
|
+
// every user who reached it to a 404, and correcting a wrong path needed an
|
|
990
|
+
// npm release because it was compiled into the client. Now it points at
|
|
991
|
+
// `/go/topup`, a server-side indirection: the destination can change without
|
|
992
|
+
// a client release, and the click arrives tagged with the channel. 75 cells
|
|
993
|
+
// of 80 — measured, because `padLine()` truncates rather than wraps.
|
|
994
|
+
lines.push([span(t.gray, ` Top-ups and invoices: ${goUrl('topup', 'cost_screen')}`)]);
|
|
995
|
+
}
|
|
926
996
|
return lines;
|
|
927
997
|
}
|
|
928
998
|
|
package/vendor/client/aegis.js
CHANGED
|
@@ -65,6 +65,50 @@ function envIdleMs(name) {
|
|
|
65
65
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
/**
|
|
69
|
+
* DeepSeek's chat template wraps tool calls and turn boundaries in special
|
|
70
|
+
* tokens — fullwidth pipe (U+FF5C) delimiting an identifier that uses ▁
|
|
71
|
+
* (U+2581) as its word separator, e.g. |tool▁calls▁begin|, |tool▁call▁end|,
|
|
72
|
+
* |Assistant|, |begin▁of▁sentence|. These are chat-template internals, never
|
|
73
|
+
* user-facing text; when the provider's streaming tool-call path leaks them
|
|
74
|
+
* into `delta.content` they used to reach the screen verbatim — reported as
|
|
75
|
+
* the pasted "||DSML||" envelope on Windows/macOS. Returns a per-stream
|
|
76
|
+
* stripper closure with a short lookback buffer so a token split across two
|
|
77
|
+
* SSE chunks isn't half-rendered before its closing pipe arrives.
|
|
78
|
+
*/
|
|
79
|
+
const DEEPSEEK_ENVELOPE_RE = /|[A-Za-z][A-Za-z0-9]*(?:▁[A-Za-z0-9]+)*|/g;
|
|
80
|
+
function makeDeepSeekEnvelopeStripper() {
|
|
81
|
+
let buf = '';
|
|
82
|
+
const strip = (chunk) => {
|
|
83
|
+
buf += chunk;
|
|
84
|
+
buf = buf.replace(DEEPSEEK_ENVELOPE_RE, '');
|
|
85
|
+
const openIdx = buf.lastIndexOf('|');
|
|
86
|
+
if (openIdx !== -1) {
|
|
87
|
+
const tail = buf.slice(openIdx);
|
|
88
|
+
// Held back only while the tail still looks like an in-progress token
|
|
89
|
+
// (no closing pipe yet); a bare '|' or genuine prose flushes normally.
|
|
90
|
+
if (tail.length <= 60 && /^|[A-Za-z0-9▁]*$/.test(tail)) {
|
|
91
|
+
const out = buf.slice(0, openIdx);
|
|
92
|
+
buf = tail;
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const out = buf;
|
|
97
|
+
buf = '';
|
|
98
|
+
return out;
|
|
99
|
+
};
|
|
100
|
+
// Unconditional release of whatever is left buffered — called once the
|
|
101
|
+
// stream is fully drained, when a held-back '|…' is known to never close
|
|
102
|
+
// (dropped connection, or it was real prose all along) rather than an
|
|
103
|
+
// in-progress token.
|
|
104
|
+
strip.flush = () => {
|
|
105
|
+
const out = buf;
|
|
106
|
+
buf = '';
|
|
107
|
+
return out;
|
|
108
|
+
};
|
|
109
|
+
return strip;
|
|
110
|
+
}
|
|
111
|
+
|
|
68
112
|
/**
|
|
69
113
|
* UUID v4 that works everywhere: Web Crypto first (browsers, Node ≥ 19),
|
|
70
114
|
* then Node's CJS crypto module (Node < 19), then a Math.random fallback for
|
|
@@ -221,10 +265,26 @@ function createClient(opts = {}) {
|
|
|
221
265
|
}
|
|
222
266
|
throw err;
|
|
223
267
|
} finally {
|
|
268
|
+
// The timeout is time-to-*headers* only, so it is cleared the moment the
|
|
269
|
+
// response resolves: a long generation must never be cut off by it.
|
|
224
270
|
if (timer) clearTimeout(timer);
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
271
|
+
// …but the caller's abort bridge is deliberately NOT removed here.
|
|
272
|
+
//
|
|
273
|
+
// `fetch` resolves at the status line, while the RESPONSE BODY is still
|
|
274
|
+
// bound to `controller.signal` and keeps being read long after this
|
|
275
|
+
// function has returned. Unhooking the caller's signal at that point
|
|
276
|
+
// detached Stop/Escape from the stream it was supposed to stop: the
|
|
277
|
+
// engine's own controller really did abort — `engine.cancel()` answered
|
|
278
|
+
// `{ ok: true }`, so the right controller was found and `abort()` was
|
|
279
|
+
// really called — and nothing happened, because the only thing wired to
|
|
280
|
+
// the live body had already been told to stop listening. The turn then
|
|
281
|
+
// streamed to completion while the UI sat on "stopping…", never settled,
|
|
282
|
+
// and never produced the salvaged bubble, because no error ever reached
|
|
283
|
+
// the caller's catch.
|
|
284
|
+
//
|
|
285
|
+
// `once: true` plus one signal per turn bounds the cost of leaving it
|
|
286
|
+
// attached to a single listener per turn — a far smaller price than a
|
|
287
|
+
// cancel button that does nothing.
|
|
228
288
|
}
|
|
229
289
|
}
|
|
230
290
|
|
|
@@ -838,6 +898,15 @@ function createClient(opts = {}) {
|
|
|
838
898
|
// resolve with text only and the caller could never see the calls.
|
|
839
899
|
const toolCallsByIndex = new Map();
|
|
840
900
|
let finishReason = null;
|
|
901
|
+
// `fullText` above stays RAW (it is also the `seen` cursor the snapshot
|
|
902
|
+
// reconciliation below compares against the provider's own un-stripped
|
|
903
|
+
// snapshots); `cleanText` is what the caller actually receives — the same
|
|
904
|
+
// stream, with DeepSeek's chat-template envelope removed — and is what the
|
|
905
|
+
// final `message.content` below is built from, so a non-streaming caller
|
|
906
|
+
// reading the resolved result sees the same clean text a streaming caller
|
|
907
|
+
// already saw via `onStream`.
|
|
908
|
+
let cleanText = '';
|
|
909
|
+
const stripEnvelope = makeDeepSeekEnvelopeStripper();
|
|
841
910
|
|
|
842
911
|
// Idle watchdog: if the server holds the connection open without ever
|
|
843
912
|
// sending another byte (a stuck upstream call, a proxy that swallows the
|
|
@@ -863,6 +932,7 @@ function createClient(opts = {}) {
|
|
|
863
932
|
let keepAlives = 0;
|
|
864
933
|
async function readWithIdleTimeout() {
|
|
865
934
|
let timer;
|
|
935
|
+
let onAbort = null;
|
|
866
936
|
const remaining = Math.max(0, idleMs - (Date.now() - lastPayloadAt));
|
|
867
937
|
const timeout = new Promise((_, reject) => {
|
|
868
938
|
timer = setTimeout(() => {
|
|
@@ -873,10 +943,37 @@ function createClient(opts = {}) {
|
|
|
873
943
|
));
|
|
874
944
|
}, remaining);
|
|
875
945
|
});
|
|
946
|
+
// The caller's abort, raced against the read directly rather than trusted
|
|
947
|
+
// to propagate through the body stream.
|
|
948
|
+
//
|
|
949
|
+
// Whether an abort of the caller's signal reaches a response body that is
|
|
950
|
+
// already being read is a property of `boundedFetch`, not of this loop —
|
|
951
|
+
// and it is not a property this loop can observe. Racing here makes "the
|
|
952
|
+
// caller stopped" a fact the read loop establishes for itself, so Stop
|
|
953
|
+
// and Escape end the turn at the next chunk boundary regardless of how
|
|
954
|
+
// the request's signal was assembled. Without it an aborted turn kept
|
|
955
|
+
// consuming a stream nobody wanted and `chat()` never settled at all.
|
|
956
|
+
const aborted = signal && typeof signal.addEventListener === 'function'
|
|
957
|
+
? new Promise((_, reject) => {
|
|
958
|
+
onAbort = () => {
|
|
959
|
+
const e = new Error('The turn was stopped.');
|
|
960
|
+
e.name = 'AbortError';
|
|
961
|
+
e.code = 'ABORT_ERR';
|
|
962
|
+
reject(e);
|
|
963
|
+
};
|
|
964
|
+
if (signal.aborted) onAbort();
|
|
965
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
966
|
+
})
|
|
967
|
+
: null;
|
|
876
968
|
try {
|
|
877
|
-
return await
|
|
969
|
+
return await (aborted
|
|
970
|
+
? Promise.race([reader.read(), timeout, aborted])
|
|
971
|
+
: Promise.race([reader.read(), timeout]));
|
|
878
972
|
} finally {
|
|
879
973
|
clearTimeout(timer);
|
|
974
|
+
if (signal && onAbort && typeof signal.removeEventListener === 'function') {
|
|
975
|
+
signal.removeEventListener('abort', onAbort);
|
|
976
|
+
}
|
|
880
977
|
}
|
|
881
978
|
}
|
|
882
979
|
|
|
@@ -969,7 +1066,13 @@ function createClient(opts = {}) {
|
|
|
969
1066
|
choice && choice.delta && choice.delta.content,
|
|
970
1067
|
choice && choice.message && choice.message.content,
|
|
971
1068
|
fullText,
|
|
972
|
-
(chunk) =>
|
|
1069
|
+
(chunk) => {
|
|
1070
|
+
const clean = stripEnvelope(chunk);
|
|
1071
|
+
if (clean) {
|
|
1072
|
+
cleanText += clean;
|
|
1073
|
+
onStream({ delta: clean });
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
973
1076
|
);
|
|
974
1077
|
const fragments =
|
|
975
1078
|
(choice && choice.delta && choice.delta.tool_calls) ||
|
|
@@ -999,13 +1102,22 @@ function createClient(opts = {}) {
|
|
|
999
1102
|
throw err;
|
|
1000
1103
|
}
|
|
1001
1104
|
|
|
1105
|
+
// A trailing '|…' that never closed (stream ended right after it, or it
|
|
1106
|
+
// was real prose all along) is real content, not an unfinished envelope
|
|
1107
|
+
// token — release it rather than dropping it silently.
|
|
1108
|
+
const strayTail = stripEnvelope.flush();
|
|
1109
|
+
if (strayTail) {
|
|
1110
|
+
cleanText += strayTail;
|
|
1111
|
+
onStream({ delta: strayTail });
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1002
1114
|
// An id-less fragment stream still yields usable calls, but the caller
|
|
1003
1115
|
// needs *an* id to pair results back, so synthesize one.
|
|
1004
1116
|
const toolCalls = [...toolCallsByIndex.entries()]
|
|
1005
1117
|
.sort((a, b) => a[0] - b[0])
|
|
1006
1118
|
.map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
|
|
1007
1119
|
|
|
1008
|
-
const message = { content:
|
|
1120
|
+
const message = { content: cleanText };
|
|
1009
1121
|
if (toolCalls.length) message.tool_calls = toolCalls;
|
|
1010
1122
|
const result = {
|
|
1011
1123
|
model: resultModel,
|
|
@@ -90,6 +90,84 @@ const LEGACY_PLAN_ALIASES = Object.freeze({
|
|
|
90
90
|
const PRO_VALUE =
|
|
91
91
|
'Pro puts the drain in the cloud, so the job keeps running after you close the laptop';
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The honesty line — Phase 3's rule, and the second half of the same claim:
|
|
95
|
+
* everything that runs on the user's own machine stays free forever, and the
|
|
96
|
+
* cloud drain is the thing being sold. Both hosts that print a paid prompt
|
|
97
|
+
* print this beside it (the desktop keeps its own literal in
|
|
98
|
+
* `desktop/renderer/app.js`; the terminal reads it from here), because the
|
|
99
|
+
* promise without the honesty line is the four-bullet feature list again.
|
|
100
|
+
*
|
|
101
|
+
* Kept byte-identical to the renderer's `FREE_HONESTY`, and asserted verbatim
|
|
102
|
+
* by both hosts' tests, so the terminal and the GUI cannot come to disagree
|
|
103
|
+
* about what is free — a disagreement that would either overcharge a promise
|
|
104
|
+
* or undercut the offer, depending on which copy a user believed.
|
|
105
|
+
*/
|
|
106
|
+
const FREE_HONESTY =
|
|
107
|
+
'Everything on your machine is free, permanently. The cloud drain is what you pay for.';
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The BYOK lane's price, in words — built from the SERVER's published rate.
|
|
111
|
+
*
|
|
112
|
+
* The desktop README says the byok lane is "billed a flat handling fee" and
|
|
113
|
+
* aegis1 charges exactly that (services/pricing.price_byok_call), but no client
|
|
114
|
+
* surface said so: a user who pasted their own Anthropic key into AEGIS read
|
|
115
|
+
* "your provider's cost" and never learned AEGIS adds a fee. That is the one
|
|
116
|
+
* place in this product where the bill and the pitch disagreed, and it is the
|
|
117
|
+
* copy the desktop session flagged as an unresolved honesty conflict.
|
|
118
|
+
*
|
|
119
|
+
* `fee` is aegis1's own `/api/v1/byok/providers` payload — a live payload, never
|
|
120
|
+
* a hardcoded number, for the reason the engine already states: a client that
|
|
121
|
+
* hardcodes a fee is a client that can disagree with the ledger. No published
|
|
122
|
+
* fee (old server, offline, unauthenticated read that returned nothing) returns
|
|
123
|
+
* '' and every host then says NOTHING about the price, which is the only honest
|
|
124
|
+
* alternative to inventing one.
|
|
125
|
+
*
|
|
126
|
+
* `require_account` / `anonymous_daily_calls` come from the same payload and
|
|
127
|
+
* describe enforcement, not price: with the relay requiring an AEGIS account the
|
|
128
|
+
* sentence has to say so, or the user meets a 402 the client never warned about
|
|
129
|
+
* — the exact failure tests/test_byok_fee.py::test_the_published_gate_warning_is
|
|
130
|
+
* _true_whenever_the_gate_can_402 exists to prevent.
|
|
131
|
+
*/
|
|
132
|
+
const BYOK_FEE_NOTE =
|
|
133
|
+
'Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider\'s own bill.';
|
|
134
|
+
|
|
135
|
+
/** Per-million-token rendering of a published per-1k rate. */
|
|
136
|
+
function ratePerMillion(usdPer1k) {
|
|
137
|
+
return `$${(Number(usdPer1k) * 1000).toFixed(2)}/M`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function byokFeeLine(fee) {
|
|
141
|
+
const f = fee && typeof fee === 'object' ? fee : null;
|
|
142
|
+
if (!f) return '';
|
|
143
|
+
const inRate = Number(f.in_usd_per_1k);
|
|
144
|
+
const outRate = Number(f.out_usd_per_1k);
|
|
145
|
+
if (!Number.isFinite(inRate) || !Number.isFinite(outRate)) return '';
|
|
146
|
+
if (f.disabled === true) {
|
|
147
|
+
// The deployment switched the fee off; saying "free" is then the truth
|
|
148
|
+
// rather than a promise this client cannot keep.
|
|
149
|
+
return 'Bring your own key is relayed free on this deployment right now.';
|
|
150
|
+
}
|
|
151
|
+
// The price clause stands alone when the server published no enforcement
|
|
152
|
+
// detail — which is every server deployed before this change, and the
|
|
153
|
+
// default-off gate after it. Joined with ' — ' only when there IS a second
|
|
154
|
+
// clause: a sentence-ending dash with nothing after it ("…provider's bill —.")
|
|
155
|
+
// is what the first live run of this line actually printed.
|
|
156
|
+
const price = `Bring your own key: relayed through AEGIS, handled at `
|
|
157
|
+
+ `${ratePerMillion(inRate)} in / ${ratePerMillion(outRate)} out, `
|
|
158
|
+
+ `on top of your provider's bill`;
|
|
159
|
+
let clause = '';
|
|
160
|
+
if (f.require_account === true) {
|
|
161
|
+
clause = 'and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed';
|
|
162
|
+
} else {
|
|
163
|
+
const cap = Number(f.anonymous_daily_calls);
|
|
164
|
+
if (Number.isFinite(cap) && cap > 0) {
|
|
165
|
+
clause = `with ${cap} relayed turns/24h before an AEGIS account is required`;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return clause ? `${price} — ${clause}.` : `${price}.`;
|
|
169
|
+
}
|
|
170
|
+
|
|
93
171
|
/** Campaign id for this prompt (Phase 1's fixed ids; aegis1 keeps the slug). */
|
|
94
172
|
const CAMPAIGN = 'queue_cap';
|
|
95
173
|
|
|
@@ -478,6 +556,9 @@ module.exports = {
|
|
|
478
556
|
BALANCE_CAMPAIGN,
|
|
479
557
|
BALANCE_URL,
|
|
480
558
|
PRO_VALUE,
|
|
559
|
+
FREE_HONESTY,
|
|
560
|
+
BYOK_FEE_NOTE,
|
|
561
|
+
byokFeeLine,
|
|
481
562
|
DEFAULT_TTL_MS,
|
|
482
563
|
// Phase 7: the host seam + the builder the CLI binds itself to.
|
|
483
564
|
SIGNUP_SOURCES,
|
|
@@ -58,6 +58,45 @@ function baseOf(baseURL) {
|
|
|
58
58
|
return String(baseURL || DEFAULT_BASE).replace(/\/+$/, '');
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/**
|
|
62
|
+
* DeepSeek's chat template (also the one a locally-pulled `deepseek-*` Ollama
|
|
63
|
+
* model uses) wraps tool calls and turn boundaries in special tokens —
|
|
64
|
+
* fullwidth pipe (U+FF5C) delimiting an identifier that uses ▁ (U+2581) as its
|
|
65
|
+
* word separator, e.g. |tool▁calls▁begin|, |tool▁call▁end|, |Assistant|,
|
|
66
|
+
* |begin▁of▁sentence|. These are chat-template internals, never user-facing
|
|
67
|
+
* text; when the local daemon's tool-call path leaks them into `delta.content`
|
|
68
|
+
* they used to reach the screen verbatim — reported as the pasted
|
|
69
|
+
* "||DSML||" envelope. Returns a per-turn stripper closure with a short
|
|
70
|
+
* lookback buffer so a token split across two SSE chunks isn't half-rendered
|
|
71
|
+
* before its closing pipe arrives.
|
|
72
|
+
*/
|
|
73
|
+
const DEEPSEEK_ENVELOPE_RE = /|[A-Za-z][A-Za-z0-9]*(?:▁[A-Za-z0-9]+)*|/g;
|
|
74
|
+
function makeDeepSeekEnvelopeStripper() {
|
|
75
|
+
let buf = '';
|
|
76
|
+
const strip = (chunk) => {
|
|
77
|
+
buf += chunk;
|
|
78
|
+
buf = buf.replace(DEEPSEEK_ENVELOPE_RE, '');
|
|
79
|
+
const openIdx = buf.lastIndexOf('|');
|
|
80
|
+
if (openIdx !== -1) {
|
|
81
|
+
const tail = buf.slice(openIdx);
|
|
82
|
+
if (tail.length <= 60 && /^|[A-Za-z0-9▁]*$/.test(tail)) {
|
|
83
|
+
const out = buf.slice(0, openIdx);
|
|
84
|
+
buf = tail;
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const out = buf;
|
|
89
|
+
buf = '';
|
|
90
|
+
return out;
|
|
91
|
+
};
|
|
92
|
+
strip.flush = () => {
|
|
93
|
+
const out = buf;
|
|
94
|
+
buf = '';
|
|
95
|
+
return out;
|
|
96
|
+
};
|
|
97
|
+
return strip;
|
|
98
|
+
}
|
|
99
|
+
|
|
61
100
|
/**
|
|
62
101
|
* Whether a base URL addresses hardware on this machine (or on this private
|
|
63
102
|
* network) — the gate that decides whether the free lane exists at all.
|
|
@@ -369,6 +408,7 @@ async function chat({
|
|
|
369
408
|
let usage = null;
|
|
370
409
|
const toolCalls = [];
|
|
371
410
|
const byIndex = new Map();
|
|
411
|
+
const stripEnvelope = makeDeepSeekEnvelopeStripper();
|
|
372
412
|
|
|
373
413
|
await readSSE(
|
|
374
414
|
res,
|
|
@@ -378,8 +418,11 @@ async function chat({
|
|
|
378
418
|
if (!choice) return;
|
|
379
419
|
const delta = choice.delta || {};
|
|
380
420
|
if (typeof delta.content === 'string' && delta.content) {
|
|
381
|
-
|
|
382
|
-
if (
|
|
421
|
+
const clean = stripEnvelope(delta.content);
|
|
422
|
+
if (clean) {
|
|
423
|
+
content += clean;
|
|
424
|
+
if (typeof onDelta === 'function') onDelta({ text: clean });
|
|
425
|
+
}
|
|
383
426
|
}
|
|
384
427
|
const frags = delta.tool_calls || [];
|
|
385
428
|
for (const f of frags) {
|
|
@@ -399,6 +442,15 @@ async function chat({
|
|
|
399
442
|
{ idleTimeoutMs: SSE_IDLE_TIMEOUT_MS }
|
|
400
443
|
);
|
|
401
444
|
|
|
445
|
+
// A trailing '|…' that never closed (stream ended right after it, or it
|
|
446
|
+
// was real prose all along) is real content, not an unfinished envelope
|
|
447
|
+
// token — release it rather than dropping it silently.
|
|
448
|
+
const strayTail = stripEnvelope.flush();
|
|
449
|
+
if (strayTail) {
|
|
450
|
+
content += strayTail;
|
|
451
|
+
if (typeof onDelta === 'function') onDelta({ text: strayTail });
|
|
452
|
+
}
|
|
453
|
+
|
|
402
454
|
for (const [i, acc] of [...byIndex.entries()].sort((a, b) => a[0] - b[0])) {
|
|
403
455
|
if (!acc.function.name && !acc.function.arguments) continue;
|
|
404
456
|
// Ollama does not always mint an id; the engine's tool loop keys results
|