aegis-desktop 1.0.13 → 1.0.15
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/SOURCE-OFFER.txt +9 -0
- package/bin/aegis.js +1 -32
- package/lib/account-key.js +1 -56
- package/lib/auto.js +1 -430
- package/lib/avatar/companion.js +1 -698
- package/lib/avatar/cosmetics.js +1 -532
- package/lib/avatar/events.js +1 -344
- package/lib/avatar/holder-turn.js +1 -350
- package/lib/avatar/holders.js +1 -612
- package/lib/avatar/identity.js +1 -641
- package/lib/avatar/level.js +1 -368
- package/lib/avatar/mirror.js +1 -524
- package/lib/avatar/persona.js +1 -388
- package/lib/avatar/profile.js +1 -977
- package/lib/avatar/register.js +1 -307
- package/lib/avatar/store.js +1 -472
- package/lib/avatar/tiers.js +1 -38
- package/lib/avatar/transfer.js +1 -415
- package/lib/avatar/turn.js +1 -216
- package/lib/avatar/voice.js +1 -328
- package/lib/avatar/xp.js +1 -404
- package/lib/deep-link.js +1 -120
- package/lib/fingerprint.js +2 -347
- package/lib/google-connect.js +1 -169
- package/lib/local/agents.js +1 -105
- package/lib/local/autonomous.js +1 -1045
- package/lib/local/claude-pro.js +1 -993
- package/lib/local/context.js +1 -95
- package/lib/local/engine.js +1 -3228
- package/lib/local/entitlement.js +1 -654
- package/lib/local/git-scope.js +1 -228
- package/lib/local/local.js +1 -2135
- package/lib/local/prompt.js +1 -275
- package/lib/local/queue.js +1 -560
- package/lib/local/session-rounds.js +1 -208
- package/lib/local/shell.js +1 -680
- package/lib/local/telemetry.js +1 -470
- package/lib/local/tools.js +1 -1238
- package/lib/local/turn-guard.js +1 -300
- package/lib/local/worktree-lock.js +1 -235
- package/lib/provider-key-mirror.js +1 -252
- package/lib/quick-launcher.js +1 -84
- package/lib/settings.js +1 -890
- package/lib/sync/memory-queue.js +1 -60
- package/lib/sync/persist-gate.js +1 -148
- package/lib/sync/sessions.js +1 -106
- package/lib/window-state.js +1 -66
- package/main.js +3 -4390
- package/package.json +3 -5
- package/preload.js +3 -628
- package/renderer/app.js +1 -6560
- package/renderer/avatar/assemble.js +1 -335
- package/renderer/avatar/avatar.js +1 -380
- package/renderer/avatar/cards.js +1 -141
- package/renderer/avatar/hud.js +1 -206
- package/renderer/avatar/machine.js +1 -213
- package/renderer/avatar/pane.js +1 -439
- package/renderer/avatar/parts.js +1 -437
- package/renderer/budget.js +1 -168
- package/renderer/companion.js +1 -223
- package/renderer/diff.js +1 -359
- package/renderer/diffview.js +1 -336
- package/renderer/fingerprint.js +3 -720
- package/renderer/markdown.js +1 -168
- package/renderer/provider-toolbar.js +1 -134
- package/renderer/providers.js +1 -259
- package/renderer/quick.js +1 -191
- package/renderer/stream-policy.js +1 -306
- package/renderer/transcript-view.js +1 -323
- package/renderer/usage.js +1 -1239
- package/vendor/aegis.js +1 -2054
- package/vendor/attest.js +1 -442
- package/vendor/authorship-key.js +1 -410
- package/vendor/auto-provision.js +1 -134
- package/vendor/brain-catalog.js +1 -268
- package/vendor/byok-catalog.js +1 -230
- package/vendor/credentials.js +1 -494
- package/vendor/device-fingerprint.js +1 -141
- package/vendor/drive-connect.js +1 -85
- package/vendor/drive-upload.js +1 -174
- package/vendor/env-file.js +1 -1273
- package/vendor/fingerprint.js +1 -1064
- package/vendor/foreign-memory.js +1 -669
- package/vendor/google-signin.js +1 -125
- package/vendor/hooks.js +1 -430
- package/vendor/model-discovery.js +1 -330
- package/vendor/platform.js +1 -937
- package/vendor/prefs.js +1 -351
- package/vendor/presence-constants.js +1 -107
- package/vendor/presence.js +1 -438
- package/vendor/record-vault.js +3 -1055
- package/vendor/session-store.js +1 -548
- package/vendor/topup.js +1 -297
- package/vendor/touch.js +1 -458
- package/vendor/update.js +1 -704
- package/vendor/user-models.js +1 -381
package/lib/avatar/xp.js
CHANGED
|
@@ -1,406 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* xp.js — the avatar's XP ledger: what earns XP, what provably cannot, and the
|
|
10
|
-
* pure replay that turns a ledger into a level.
|
|
11
|
-
*
|
|
12
|
-
* The design constraint comes first, because it is the whole reason this file
|
|
13
|
-
* exists rather than a counter incremented somewhere in main:
|
|
14
|
-
*
|
|
15
|
-
* XP IS PAID FOR MEMORY THAT WAS RETRIEVED AND USED, NEVER FOR VOLUME.
|
|
16
|
-
*
|
|
17
|
-
* A counter that grows with tokens, turns, messages or time-in-app rewards the
|
|
18
|
-
* chattiest user, and a level that means "you typed a lot" means nothing. So
|
|
19
|
-
* the paid events are the ones on the existing memory path (save / recall /
|
|
20
|
-
* reinforce / correct / import) plus two that require work to have happened (a
|
|
21
|
-
* green build, a logged idea). Everything else pays zero — by omission, which
|
|
22
|
-
* is the only kind of rule that survives a new event kind being added.
|
|
23
|
-
*
|
|
24
|
-
* Three properties are load-bearing:
|
|
25
|
-
*
|
|
26
|
-
* 1. LEVEL IS DERIVED, NOT STORED. `evaluate()` replays the ledger from the
|
|
27
|
-
* rules every time. The `xp` field written into each ledger line is
|
|
28
|
-
* ADVISORY (a convenience for tools and for humans reading the file), and
|
|
29
|
-
* replay deliberately ignores it. That makes a hand-edited ledger — or a
|
|
30
|
-
* buggy writer — unable to inflate a level, and it makes the anti-farming
|
|
31
|
-
* rules apply at replay time as well as append time.
|
|
32
|
-
*
|
|
33
|
-
* 2. DIMINISHING RETURNS ARE A HARD CEILING, NOT A VIBE. The Nth paid event of
|
|
34
|
-
* a day pays `base * 0.5^(N/20)`. That geometric series converges, so one
|
|
35
|
-
* day can never pay more than `MAX_BASE * 29.36 ≈ 587 XP` no matter how many
|
|
36
|
-
* events are thrown at it. Since L5 costs 800, "farm a single day" is
|
|
37
|
-
* mathematically impossible rather than merely discouraged. `SINGLE_DAY_XP_
|
|
38
|
-
* CEILING` is exported so the fuzz test can assert the bound rather than
|
|
39
|
-
* trusting this comment.
|
|
40
|
-
*
|
|
41
|
-
* 3. CAPS ARE PER-IDENTITY, NOT PER-CALL. Five recalls per turn, two hundred
|
|
42
|
-
* imports per source. Without the second one, importing ten foreign tools
|
|
43
|
-
* would jump ten levels in an afternoon.
|
|
44
|
-
*
|
|
45
|
-
* Pure: no fs, no Electron, no clock of its own. Every function takes the
|
|
46
|
-
* ledger, entries and timestamps from the caller, so the whole module is
|
|
47
|
-
* testable in plain `node --test`, exactly like `lib/sync/*`.
|
|
48
|
-
*/
|
|
49
|
-
|
|
50
|
-
const { tierFor } = require('./tiers.js');
|
|
51
|
-
|
|
52
|
-
/** Paid events and their base rate. Anything not listed here pays zero. */
|
|
53
|
-
const XP_TABLE = Object.freeze({
|
|
54
|
-
'memory.saved': 10,
|
|
55
|
-
'memory.queued': 3,
|
|
56
|
-
'memory.recalled': 1,
|
|
57
|
-
'memory.reinforced': 5,
|
|
58
|
-
'memory.corrected': 15,
|
|
59
|
-
'memory.imported': 2,
|
|
60
|
-
'idea.logged': 10,
|
|
61
|
-
'build.green': 20,
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Kinds that look like activity and pay nothing. Not needed for correctness
|
|
66
|
-
* (the table above already omits them) — they are named so the intent is
|
|
67
|
-
* explicit and so a test can pin each one at zero. If someone later adds
|
|
68
|
-
* `turn.completed: 1` to XP_TABLE, that test fails.
|
|
69
|
-
*/
|
|
70
|
-
const VOLUME_KINDS = Object.freeze([
|
|
71
|
-
'token.spent',
|
|
72
|
-
'turn.started',
|
|
73
|
-
'turn.completed',
|
|
74
|
-
'message.sent',
|
|
75
|
-
'time.elapsed',
|
|
76
|
-
'app.opened',
|
|
77
|
-
'keystroke',
|
|
78
|
-
'scroll',
|
|
79
|
-
]);
|
|
80
|
-
|
|
81
|
-
/** At most this many recall events pay per turn. */
|
|
82
|
-
const RECALL_PER_TURN_CAP = 5;
|
|
83
|
-
/** At most this many imports pay per foreign source. */
|
|
84
|
-
const IMPORT_PER_SOURCE_CAP = 200;
|
|
85
|
-
/** The Nth paid event of a day is scaled by 0.5^(N / this). */
|
|
86
|
-
const DAILY_SOFT_CAP = 20;
|
|
87
|
-
|
|
88
|
-
/** Ledger line schema version. */
|
|
89
|
-
const LEDGER_VERSION = 1;
|
|
90
|
-
|
|
91
|
-
/** Curve: xpForLevel(n) = 100*(n-1) + 25*(n-1)^2 → L2=125, L5=800, L10=2925. */
|
|
92
|
-
const CURVE_LINEAR = 100;
|
|
93
|
-
const CURVE_QUADRATIC = 25;
|
|
94
|
-
|
|
95
|
-
const MAX_BASE = Math.max(...Object.values(XP_TABLE));
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Geometric sum of the per-day decay factors: sum(0.5^(i/20)) for i=0..∞.
|
|
99
|
-
* ~29.357. Multiplied by the largest base rate it bounds a single day's XP no
|
|
100
|
-
* matter how many events are recorded.
|
|
101
|
-
*/
|
|
102
|
-
const DAY_CEILING_MULTIPLE = 1 / (1 - 2 ** (-1 / DAILY_SOFT_CAP));
|
|
103
|
-
const SINGLE_DAY_XP_CEILING = MAX_BASE * DAY_CEILING_MULTIPLE;
|
|
104
|
-
|
|
105
|
-
// ---------------------------------------------------------------------------
|
|
106
|
-
// small helpers
|
|
107
|
-
// ---------------------------------------------------------------------------
|
|
108
|
-
|
|
109
|
-
function num(v) {
|
|
110
|
-
return typeof v === 'number' && Number.isFinite(v) ? v : 0;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function str(v) {
|
|
114
|
-
return typeof v === 'string' && v ? v : null;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** UTC calendar day key. Invalid timestamps share the 'unknown' bucket. */
|
|
118
|
-
function dayKey(t) {
|
|
119
|
-
const ms = num(t);
|
|
120
|
-
if (!ms) return 'unknown';
|
|
121
|
-
const d = new Date(ms);
|
|
122
|
-
if (Number.isNaN(d.getTime())) return 'unknown';
|
|
123
|
-
return d.toISOString().slice(0, 10);
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** Base rate for a kind, 0 for anything unpaid (including unknown kinds). */
|
|
127
|
-
function xpFor(kind) {
|
|
128
|
-
return XP_TABLE[String(kind)] ?? 0;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Decay factor applied to the (n+1)-th paid event of a day, n 0-based.
|
|
133
|
-
* Exported because the tests assert the bound analytically, not by sampling.
|
|
134
|
-
*/
|
|
135
|
-
function dayScale(n) {
|
|
136
|
-
const i = Math.max(0, Math.floor(num(n)));
|
|
137
|
-
return 0.5 ** (i / DAILY_SOFT_CAP);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// ---------------------------------------------------------------------------
|
|
141
|
-
// the curve
|
|
142
|
-
// ---------------------------------------------------------------------------
|
|
143
|
-
|
|
144
|
-
/** Total XP required to reach `level`. L1 = 0. */
|
|
145
|
-
function xpForLevel(level) {
|
|
146
|
-
const n = Math.max(1, Math.floor(num(level) || 1)) - 1;
|
|
147
|
-
return CURVE_LINEAR * n + CURVE_QUADRATIC * n * n;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Inverse of `xpForLevel`, closed-form then nudged. The closed form is exact
|
|
152
|
-
* for integers but floating point can land a hair either side of a boundary
|
|
153
|
-
* (xp == 125 must be L2, never L1), so the nudge loop corrects it. Bounded to
|
|
154
|
-
* a couple of iterations in practice.
|
|
155
|
-
*/
|
|
156
|
-
function levelForXp(xp) {
|
|
157
|
-
const total = Math.max(0, num(xp));
|
|
158
|
-
let n = Math.floor((-CURVE_LINEAR + Math.sqrt(CURVE_LINEAR ** 2 + 4 * CURVE_QUADRATIC * total)) / (2 * CURVE_QUADRATIC));
|
|
159
|
-
if (!Number.isFinite(n) || n < 0) n = 0;
|
|
160
|
-
while (xpForLevel(n + 2) <= total) n += 1;
|
|
161
|
-
while (n > 0 && xpForLevel(n + 1) > total) n -= 1;
|
|
162
|
-
return n + 1;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** Progress into the current level, 0..1, with the numbers the HUD shows. */
|
|
166
|
-
function progressAt(xp) {
|
|
167
|
-
const total = Math.max(0, num(xp));
|
|
168
|
-
const level = levelForXp(total);
|
|
169
|
-
const floorAt = xpForLevel(level);
|
|
170
|
-
const nextAt = xpForLevel(level + 1);
|
|
171
|
-
const span = Math.max(1, nextAt - floorAt);
|
|
172
|
-
return {
|
|
173
|
-
level,
|
|
174
|
-
xp: total,
|
|
175
|
-
xpIntoLevel: total - floorAt,
|
|
176
|
-
xpForNext: nextAt - floorAt,
|
|
177
|
-
nextAt,
|
|
178
|
-
progress: Math.min(1, Math.max(0, (total - floorAt) / span)),
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// ---------------------------------------------------------------------------
|
|
183
|
-
// replay — the single source of truth
|
|
184
|
-
// ---------------------------------------------------------------------------
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Replay a ledger into { xp, level, ... }.
|
|
188
|
-
*
|
|
189
|
-
* @param {Array<object>} entries ledger lines, any order
|
|
190
|
-
* @param {object} [opts]
|
|
191
|
-
* @param {Set<string>|Array<string>} [opts.liveRefs] currently-live memory entry
|
|
192
|
-
* ids. When supplied, `memory.recalled` credit for refs that no longer exist
|
|
193
|
-
* is dropped (§1.4 decay) while *savings* survive — you did that work, and it
|
|
194
|
-
* stays done. Omit to score every recall in the ledger.
|
|
195
|
-
* @param {object} [opts.held] { level, session } from the current session
|
|
196
|
-
* @param {string} [opts.session] the session being evaluated
|
|
197
|
-
*/
|
|
198
|
-
function evaluate(entries, opts = {}) {
|
|
199
|
-
const list = Array.isArray(entries) ? entries.slice() : [];
|
|
200
|
-
// Deterministic replay: the same set of lines always scores the same, in the
|
|
201
|
-
// same order, regardless of how they were read off disk.
|
|
202
|
-
list.sort((a, b) => num(a && a.t) - num(b && b.t));
|
|
203
|
-
|
|
204
|
-
const liveRefs = opts.liveRefs instanceof Set
|
|
205
|
-
? opts.liveRefs
|
|
206
|
-
: Array.isArray(opts.liveRefs)
|
|
207
|
-
? new Set(opts.liveRefs.map(String))
|
|
208
|
-
: null;
|
|
209
|
-
|
|
210
|
-
const dayCount = new Map();
|
|
211
|
-
const turnCount = new Map();
|
|
212
|
-
const sourceCount = new Map();
|
|
213
|
-
const lastRecall = new Map();
|
|
214
|
-
|
|
215
|
-
const byKind = Object.create(null);
|
|
216
|
-
const byDay = Object.create(null);
|
|
217
|
-
const reasons = Object.create(null);
|
|
218
|
-
|
|
219
|
-
let total = 0;
|
|
220
|
-
let unpaid = 0;
|
|
221
|
-
let suppressed = 0;
|
|
222
|
-
let dropped = 0;
|
|
223
|
-
|
|
224
|
-
for (const raw of list) {
|
|
225
|
-
const e = raw && typeof raw === 'object' ? raw : {};
|
|
226
|
-
const kind = String(e.kind ?? '');
|
|
227
|
-
const base = xpFor(kind);
|
|
228
|
-
const day = dayKey(e.t);
|
|
229
|
-
let reason = 'ok';
|
|
230
|
-
let gain = 0;
|
|
231
|
-
|
|
232
|
-
if (base <= 0) {
|
|
233
|
-
reason = 'unpaid-kind';
|
|
234
|
-
} else if (kind === 'memory.recalled') {
|
|
235
|
-
const ref = str(e.ref);
|
|
236
|
-
if (liveRefs && ref && !liveRefs.has(ref)) {
|
|
237
|
-
// §1.4 — the entry this recall was paid for is gone.
|
|
238
|
-
reason = 'ref-gone';
|
|
239
|
-
dropped += 1;
|
|
240
|
-
} else {
|
|
241
|
-
const turn = str(e.turn) ?? str(e.session) ?? '(unknown-turn)';
|
|
242
|
-
if ((turnCount.get(turn) ?? 0) >= RECALL_PER_TURN_CAP) {
|
|
243
|
-
reason = 'turn-cap';
|
|
244
|
-
} else if (ref && lastRecall.get(ref) === str(e.session)) {
|
|
245
|
-
// One fact must not be a slot machine: the same entry recalled twice
|
|
246
|
-
// from the same session pays once.
|
|
247
|
-
reason = 'duplicate-session';
|
|
248
|
-
} else {
|
|
249
|
-
turnCount.set(turn, (turnCount.get(turn) ?? 0) + 1);
|
|
250
|
-
if (ref) lastRecall.set(ref, str(e.session));
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
} else if (kind === 'memory.imported') {
|
|
254
|
-
const src = str(e.source) ?? '(unknown-source)';
|
|
255
|
-
if ((sourceCount.get(src) ?? 0) >= IMPORT_PER_SOURCE_CAP) {
|
|
256
|
-
reason = 'source-cap';
|
|
257
|
-
} else {
|
|
258
|
-
sourceCount.set(src, (sourceCount.get(src) ?? 0) + 1);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
if (reason === 'ok') {
|
|
263
|
-
const n = dayCount.get(day) ?? 0;
|
|
264
|
-
dayCount.set(day, n + 1);
|
|
265
|
-
gain = base * dayScale(n);
|
|
266
|
-
total += gain;
|
|
267
|
-
byKind[kind] = (byKind[kind] ?? 0) + gain;
|
|
268
|
-
byDay[day] = (byDay[day] ?? 0) + gain;
|
|
269
|
-
} else if (reason === 'unpaid-kind') {
|
|
270
|
-
unpaid += 1;
|
|
271
|
-
} else {
|
|
272
|
-
suppressed += 1;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
reasons[reason] = (reasons[reason] ?? 0) + 1;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
const rounded = Math.floor(total);
|
|
279
|
-
const projection = progressAt(rounded);
|
|
280
|
-
|
|
281
|
-
// §1.4 held-level semantics: a level never silently regresses *while the user
|
|
282
|
-
// is watching*. If this session already showed a higher level, report that
|
|
283
|
-
// one and flag it; the next session settles to the derived value.
|
|
284
|
-
const held = opts.held && typeof opts.held === 'object' ? opts.held : null;
|
|
285
|
-
const sameSession = held && held.session != null && opts.session != null
|
|
286
|
-
? held.session === opts.session
|
|
287
|
-
: false;
|
|
288
|
-
const heldLevel = held ? Math.max(1, Math.floor(num(held.level) || 1)) : 1;
|
|
289
|
-
const isHeld = Boolean(sameSession && heldLevel > projection.level);
|
|
290
|
-
|
|
291
|
-
return Object.assign({}, projection, {
|
|
292
|
-
xp: rounded,
|
|
293
|
-
rawXp: total,
|
|
294
|
-
rawLevel: projection.level,
|
|
295
|
-
level: isHeld ? heldLevel : projection.level,
|
|
296
|
-
held: isHeld,
|
|
297
|
-
settledLevel: projection.level,
|
|
298
|
-
tier: tierFor(isHeld ? heldLevel : projection.level).name,
|
|
299
|
-
byKind,
|
|
300
|
-
byDay,
|
|
301
|
-
reasons,
|
|
302
|
-
events: list.length,
|
|
303
|
-
unpaidEvents: unpaid,
|
|
304
|
-
suppressedEvents: suppressed,
|
|
305
|
-
droppedEvents: dropped,
|
|
306
|
-
days: Object.keys(byDay).length,
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
/** Alias — the spec calls the replay "derive"; both names read well. */
|
|
311
|
-
const derive = evaluate;
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* The held-level record to persist after rendering a projection, so the next
|
|
315
|
-
* render in the same session keeps showing the same number.
|
|
316
|
-
*/
|
|
317
|
-
function nextHeld(projection, session) {
|
|
318
|
-
return {
|
|
319
|
-
level: Math.max(1, Math.floor(num(projection && projection.level) || 1)),
|
|
320
|
-
session: session ?? null,
|
|
321
|
-
};
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
// ---------------------------------------------------------------------------
|
|
325
|
-
// ledger lines
|
|
326
|
-
// ---------------------------------------------------------------------------
|
|
327
|
-
|
|
328
|
-
/**
|
|
329
|
-
* Build a ledger line. `xp` is advisory — see the header — and is recorded on
|
|
330
|
-
* the line so a human (or `jq`) can see what the event was worth at the time.
|
|
331
|
-
*/
|
|
332
|
-
function makeEntry(kind, fields = {}, opts = {}) {
|
|
333
|
-
const k = String(kind ?? '');
|
|
334
|
-
const t = num(opts.t) || num(fields.t) || 0;
|
|
335
|
-
const entry = {
|
|
336
|
-
v: LEDGER_VERSION,
|
|
337
|
-
t,
|
|
338
|
-
kind: k,
|
|
339
|
-
xp: xpFor(k),
|
|
340
|
-
};
|
|
341
|
-
for (const key of ['ref', 'session', 'turn', 'source', 'note', 'metrics']) {
|
|
342
|
-
if (fields[key] !== undefined && fields[key] !== null) entry[key] = fields[key];
|
|
343
|
-
}
|
|
344
|
-
return entry;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/** Serialize ledger lines to jsonl. Unparseable lines are skipped, not written. */
|
|
348
|
-
function formatLedger(entries) {
|
|
349
|
-
if (!Array.isArray(entries)) return '';
|
|
350
|
-
return entries
|
|
351
|
-
.filter((e) => e && typeof e === 'object' && typeof e.kind === 'string')
|
|
352
|
-
.map((e) => JSON.stringify(e))
|
|
353
|
-
.join('\n')
|
|
354
|
-
.concat(entries.length ? '\n' : '');
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
/**
|
|
358
|
-
* Parse jsonl into ledger lines. Tolerant on purpose: a truncated final line is
|
|
359
|
-
* the normal result of a process killed mid-append, and losing the whole level
|
|
360
|
-
* to it would be absurd.
|
|
361
|
-
*/
|
|
362
|
-
function parseLedger(text) {
|
|
363
|
-
if (typeof text !== 'string' || !text) return { entries: [], corrupt: 0 };
|
|
364
|
-
const entries = [];
|
|
365
|
-
let corrupt = 0;
|
|
366
|
-
for (const line of text.split('\n')) {
|
|
367
|
-
const trimmed = line.trim();
|
|
368
|
-
if (!trimmed) continue;
|
|
369
|
-
try {
|
|
370
|
-
const parsed = JSON.parse(trimmed);
|
|
371
|
-
if (parsed && typeof parsed === 'object' && typeof parsed.kind === 'string') {
|
|
372
|
-
entries.push(parsed);
|
|
373
|
-
} else {
|
|
374
|
-
corrupt += 1;
|
|
375
|
-
}
|
|
376
|
-
} catch {
|
|
377
|
-
corrupt += 1;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
return { entries, corrupt };
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
module.exports = {
|
|
384
|
-
XP_TABLE,
|
|
385
|
-
VOLUME_KINDS,
|
|
386
|
-
RECALL_PER_TURN_CAP,
|
|
387
|
-
IMPORT_PER_SOURCE_CAP,
|
|
388
|
-
DAILY_SOFT_CAP,
|
|
389
|
-
LEDGER_VERSION,
|
|
390
|
-
MAX_BASE,
|
|
391
|
-
DAY_CEILING_MULTIPLE,
|
|
392
|
-
SINGLE_DAY_XP_CEILING,
|
|
393
|
-
xpFor,
|
|
394
|
-
dayScale,
|
|
395
|
-
dayKey,
|
|
396
|
-
xpForLevel,
|
|
397
|
-
levelForXp,
|
|
398
|
-
progressAt,
|
|
399
|
-
tierFor,
|
|
400
|
-
evaluate,
|
|
401
|
-
derive,
|
|
402
|
-
nextHeld,
|
|
403
|
-
makeEntry,
|
|
404
|
-
formatLedger,
|
|
405
|
-
parseLedger,
|
|
406
|
-
};
|
|
3
|
+
"use strict";const{tierFor:tierFor}=require("./tiers.js"),XP_TABLE=Object.freeze({"memory.saved":10,"memory.queued":3,"memory.recalled":1,"memory.reinforced":5,"memory.corrected":15,"memory.imported":2,"idea.logged":10,"build.green":20}),VOLUME_KINDS=Object.freeze(["token.spent","turn.started","turn.completed","message.sent","time.elapsed","app.opened","keystroke","scroll"]),RECALL_PER_TURN_CAP=5,IMPORT_PER_SOURCE_CAP=200,DAILY_SOFT_CAP=20,LEDGER_VERSION=1,CURVE_LINEAR=100,CURVE_QUADRATIC=25,MAX_BASE=Math.max(...Object.values(XP_TABLE)),DAY_CEILING_MULTIPLE=1/(1-2**(-1/DAILY_SOFT_CAP)),SINGLE_DAY_XP_CEILING=MAX_BASE*DAY_CEILING_MULTIPLE;function num(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function str(e){return"string"==typeof e&&e?e:null}function dayKey(e){const t=num(e);if(!t)return"unknown";const r=new Date(t);return Number.isNaN(r.getTime())?"unknown":r.toISOString().slice(0,10)}function xpFor(e){return XP_TABLE[String(e)]??0}function dayScale(e){return.5**(Math.max(0,Math.floor(num(e)))/DAILY_SOFT_CAP)}function xpForLevel(e){const t=Math.max(1,Math.floor(num(e)||1))-1;return CURVE_LINEAR*t+CURVE_QUADRATIC*t*t}function levelForXp(e){const t=Math.max(0,num(e));let r=Math.floor((-CURVE_LINEAR+Math.sqrt(CURVE_LINEAR**2+4*CURVE_QUADRATIC*t))/(2*CURVE_QUADRATIC));for((!Number.isFinite(r)||r<0)&&(r=0);xpForLevel(r+2)<=t;)r+=1;for(;r>0&&xpForLevel(r+1)>t;)r-=1;return r+1}function progressAt(e){const t=Math.max(0,num(e)),r=levelForXp(t),n=xpForLevel(r),o=xpForLevel(r+1),s=Math.max(1,o-n);return{level:r,xp:t,xpIntoLevel:t-n,xpForNext:o-n,nextAt:o,progress:Math.min(1,Math.max(0,(t-n)/s))}}function evaluate(e,t={}){const r=Array.isArray(e)?e.slice():[];r.sort(((e,t)=>num(e&&e.t)-num(t&&t.t)));const n=t.liveRefs instanceof Set?t.liveRefs:Array.isArray(t.liveRefs)?new Set(t.liveRefs.map(String)):null,o=new Map,s=new Map,l=new Map,a=new Map,i=Object.create(null),u=Object.create(null),c=Object.create(null);let p=0,_=0,f=0,m=0;for(const e of r){const t=e&&"object"==typeof e?e:{},r=String(t.kind??""),A=xpFor(r),E=dayKey(t.t);let d="ok",L=0;if(A<=0)d="unpaid-kind";else if("memory.recalled"===r){const e=str(t.ref);if(n&&e&&!n.has(e))d="ref-gone",m+=1;else{const r=str(t.turn)??str(t.session)??"(unknown-turn)";(s.get(r)??0)>=5?d="turn-cap":e&&a.get(e)===str(t.session)?d="duplicate-session":(s.set(r,(s.get(r)??0)+1),e&&a.set(e,str(t.session)))}}else if("memory.imported"===r){const e=str(t.source)??"(unknown-source)";(l.get(e)??0)>=200?d="source-cap":l.set(e,(l.get(e)??0)+1)}if("ok"===d){const e=o.get(E)??0;o.set(E,e+1),L=A*dayScale(e),p+=L,i[r]=(i[r]??0)+L,u[E]=(u[E]??0)+L}else"unpaid-kind"===d?_+=1:f+=1;c[d]=(c[d]??0)+1}const A=Math.floor(p),E=progressAt(A),d=t.held&&"object"==typeof t.held?t.held:null,L=!(!d||null==d.session||null==t.session)&&d.session===t.session,y=d?Math.max(1,Math.floor(num(d.level)||1)):1,v=Boolean(L&&y>E.level);return Object.assign({},E,{xp:A,rawXp:p,rawLevel:E.level,level:v?y:E.level,held:v,settledLevel:E.level,tier:tierFor(v?y:E.level).name,byKind:i,byDay:u,reasons:c,events:r.length,unpaidEvents:_,suppressedEvents:f,droppedEvents:m,days:Object.keys(u).length})}const derive=evaluate;function nextHeld(e,t){return{level:Math.max(1,Math.floor(num(e&&e.level)||1)),session:t??null}}function makeEntry(e,t={},r={}){const n=String(e??""),o={v:1,t:num(r.t)||num(t.t)||0,kind:n,xp:xpFor(n)};for(const e of["ref","session","turn","source","note","metrics"])void 0!==t[e]&&null!==t[e]&&(o[e]=t[e]);return o}function formatLedger(e){return Array.isArray(e)?e.filter((e=>e&&"object"==typeof e&&"string"==typeof e.kind)).map((e=>JSON.stringify(e))).join("\n").concat(e.length?"\n":""):""}function parseLedger(e){if("string"!=typeof e||!e)return{entries:[],corrupt:0};const t=[];let r=0;for(const n of e.split("\n")){const e=n.trim();if(e)try{const n=JSON.parse(e);n&&"object"==typeof n&&"string"==typeof n.kind?t.push(n):r+=1}catch{r+=1}}return{entries:t,corrupt:r}}module.exports={XP_TABLE:XP_TABLE,VOLUME_KINDS:VOLUME_KINDS,RECALL_PER_TURN_CAP:5,IMPORT_PER_SOURCE_CAP:200,DAILY_SOFT_CAP:DAILY_SOFT_CAP,LEDGER_VERSION:1,MAX_BASE:MAX_BASE,DAY_CEILING_MULTIPLE:DAY_CEILING_MULTIPLE,SINGLE_DAY_XP_CEILING:SINGLE_DAY_XP_CEILING,xpFor:xpFor,dayScale:dayScale,dayKey:dayKey,xpForLevel:xpForLevel,levelForXp:levelForXp,progressAt:progressAt,tierFor:tierFor,evaluate:evaluate,derive:derive,nextHeld:nextHeld,makeEntry:makeEntry,formatLedger:formatLedger,parseLedger:parseLedger};
|
package/lib/deep-link.js
CHANGED
|
@@ -1,122 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* deep-link.js — aegis:// URL parsing (native desktop plumbing).
|
|
10
|
-
* Pure functions, no Electron import, so this unit-tests without the
|
|
11
|
-
* Electron binary. main.js wires the result into IPC; this module only
|
|
12
|
-
* turns a raw URL/argv list into `{ action, ... }` or null.
|
|
13
|
-
*
|
|
14
|
-
* Supported shapes:
|
|
15
|
-
* aegis://open?session=<id> -> { action: 'open', sessionId }
|
|
16
|
-
* aegis://new?prompt=<text> -> { action: 'new', prompt }
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
const PROTOCOL = 'aegis';
|
|
20
|
-
const SCHEME_PREFIX = `${PROTOCOL}://`;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Ceilings on the two values a *remote* caller controls.
|
|
24
|
-
*
|
|
25
|
-
* Any web page or any other app on the machine can hand the OS an `aegis://`
|
|
26
|
-
* URL, so both fields are attacker-chosen input on a channel nobody authenticates
|
|
27
|
-
* (there is no "is this link from the user?" check, and there cannot be one for
|
|
28
|
-
* a custom scheme). Bounding them keeps a hostile link from parking megabytes of
|
|
29
|
-
* text in the composer, from filling the window with a wall of pre-filled prompt,
|
|
30
|
-
* or from using the deep link as a bulk data channel into a session that can run
|
|
31
|
-
* tools. The renderer pre-fills rather than auto-sends (renderer/app.js
|
|
32
|
-
* handleDeepLink), so the cost is bounded, but a pre-filled prompt is still the
|
|
33
|
-
* most direct route from "a page I visited" to "text the user is invited to send
|
|
34
|
-
* to a model with tools on".
|
|
35
|
-
*
|
|
36
|
-
* These are generous on purpose: a real hand-written link is a sentence or two.
|
|
37
|
-
*/
|
|
38
|
-
const MAX_PROMPT_LENGTH = 2000;
|
|
39
|
-
/** Session ids are uuids (36 chars); the slack is for a future format, not a payload. */
|
|
40
|
-
const MAX_SESSION_ID_LENGTH = 128;
|
|
41
|
-
/**
|
|
42
|
-
* …and the charset is pinned too, because this id does not stay a string: the
|
|
43
|
-
* renderer's `open` handler hands it to openSession(), which loads the session
|
|
44
|
-
* by name. A hostile link could otherwise offer `../../…` or an absolute path
|
|
45
|
-
* and have the *renderer* ask main to open whatever that resolves to. Ids this
|
|
46
|
-
* app mints are `[0-9a-f-]`; anything outside a conservative id alphabet is not
|
|
47
|
-
* one of ours, so it is rejected rather than escaped or repaired.
|
|
48
|
-
*/
|
|
49
|
-
const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
/** True for any string that looks like our protocol, cheap enough to filter
|
|
53
|
-
* argv with before the full URL parse (which throws on most argv entries —
|
|
54
|
-
* flags, file paths — so callers should not run it against every arg). */
|
|
55
|
-
function isDeepLinkUrl(value) {
|
|
56
|
-
return typeof value === 'string' && value.toLowerCase().startsWith(SCHEME_PREFIX);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Parse a raw `aegis://...` URL into a routable action, or null for anything
|
|
61
|
-
* unparseable or from a scheme/action this app doesn't recognise. Never
|
|
62
|
-
* throws — a malformed or malicious URL (e.g. handed to the OS by another
|
|
63
|
-
* app) just yields null.
|
|
64
|
-
*/
|
|
65
|
-
function parseDeepLinkUrl(url) {
|
|
66
|
-
if (!isDeepLinkUrl(url)) return null;
|
|
67
|
-
let parsed;
|
|
68
|
-
try {
|
|
69
|
-
parsed = new URL(url);
|
|
70
|
-
} catch {
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
if (parsed.protocol !== `${PROTOCOL}:`) return null;
|
|
74
|
-
|
|
75
|
-
// For a non-special scheme like "aegis:", "//host" still parses into
|
|
76
|
-
// `.hostname` — aegis://open?session=x -> hostname "open".
|
|
77
|
-
const action = (parsed.hostname || '').toLowerCase();
|
|
78
|
-
|
|
79
|
-
if (action === 'open') {
|
|
80
|
-
const sessionId = parsed.searchParams.get('session');
|
|
81
|
-
if (!sessionId) return null;
|
|
82
|
-
if (sessionId.length > MAX_SESSION_ID_LENGTH) return null;
|
|
83
|
-
if (!SESSION_ID_PATTERN.test(sessionId)) return null;
|
|
84
|
-
return { action: 'open', sessionId };
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (action === 'new') {
|
|
88
|
-
const prompt = parsed.searchParams.get('prompt') || '';
|
|
89
|
-
if (prompt.length > MAX_PROMPT_LENGTH) return null;
|
|
90
|
-
return { action: 'new', prompt };
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Find the deep-link URL among a process's argv, handling the Linux quirk
|
|
98
|
-
* where the OS hands the URL to the app as a bare positional argument (no
|
|
99
|
-
* `--url=` flag, no special marker) — it can land anywhere after the
|
|
100
|
-
* executable/script path, so every entry is checked rather than assuming a
|
|
101
|
-
* fixed index.
|
|
102
|
-
*/
|
|
103
|
-
function extractDeepLinkUrl(argv) {
|
|
104
|
-
if (!Array.isArray(argv)) return null;
|
|
105
|
-
for (const arg of argv) {
|
|
106
|
-
if (isDeepLinkUrl(arg)) return arg;
|
|
107
|
-
}
|
|
108
|
-
return null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Convenience: argv -> parsed action in one call, or null at either step. */
|
|
112
|
-
function parseDeepLinkArgv(argv) {
|
|
113
|
-
return parseDeepLinkUrl(extractDeepLinkUrl(argv));
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
module.exports = {
|
|
117
|
-
PROTOCOL,
|
|
118
|
-
isDeepLinkUrl,
|
|
119
|
-
parseDeepLinkUrl,
|
|
120
|
-
extractDeepLinkUrl,
|
|
121
|
-
parseDeepLinkArgv,
|
|
122
|
-
};
|
|
3
|
+
"use strict";const PROTOCOL="aegis",SCHEME_PREFIX=`${PROTOCOL}://`,MAX_PROMPT_LENGTH=2e3,MAX_SESSION_ID_LENGTH=128,SESSION_ID_PATTERN=/^[A-Za-z0-9_-]{1,128}$/;function isDeepLinkUrl(e){return"string"==typeof e&&e.toLowerCase().startsWith(SCHEME_PREFIX)}function parseDeepLinkUrl(e){if(!isDeepLinkUrl(e))return null;let r;try{r=new URL(e)}catch{return null}if(r.protocol!==`${PROTOCOL}:`)return null;const n=(r.hostname||"").toLowerCase();if("open"===n){const e=r.searchParams.get("session");return e?e.length>MAX_SESSION_ID_LENGTH?null:SESSION_ID_PATTERN.test(e)?{action:"open",sessionId:e}:null:null}if("new"===n){const e=r.searchParams.get("prompt")||"";return e.length>MAX_PROMPT_LENGTH?null:{action:"new",prompt:e}}return null}function extractDeepLinkUrl(e){if(!Array.isArray(e))return null;for(const r of e)if(isDeepLinkUrl(r))return r;return null}function parseDeepLinkArgv(e){return parseDeepLinkUrl(extractDeepLinkUrl(e))}module.exports={PROTOCOL:PROTOCOL,isDeepLinkUrl:isDeepLinkUrl,parseDeepLinkUrl:parseDeepLinkUrl,extractDeepLinkUrl:extractDeepLinkUrl,parseDeepLinkArgv:parseDeepLinkArgv};
|