aegiscode 6.6.0 → 6.7.0

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.
@@ -0,0 +1,205 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Session-scoped tool-round ledger.
5
+ *
6
+ * The engine's tool-round cap used to be a wall. A turn that reached it ended
7
+ * mid-investigation with `[stopped at 24 tool rounds…]`, and because the
8
+ * accounting lived only for the duration of that call, the next turn in the
9
+ * same conversation started from zero: it knew nothing about the horizon that
10
+ * had just cut it off, so a long job could be truncated by the cap forever
11
+ * without ever being finished.
12
+ *
13
+ * This makes the cap *session* state instead of turn state:
14
+ *
15
+ * - a turn that reaches its horizon records the unfinished work against the
16
+ * session key (rounds spent, tokens, the note the user saw, and the
17
+ * tool-call transcript itself — see `record`'s `messages`);
18
+ * - the next turn in that session takes the record — consuming it, so one
19
+ * resume per interruption and a chain of interruptions is a chain of
20
+ * deliberate asks, never an automatic loop — and gets a continuation
21
+ * preamble plus a small round bonus, so re-orientation does not eat the
22
+ * new horizon before any work happens;
23
+ * - an entry nobody comes back for expires after TTL_MS.
24
+ *
25
+ * State is module-level, so it outlives a turn, a `send()` and whichever
26
+ * engine instance the desktop happens to be using. It never leaves the
27
+ * process and is never written to disk.
28
+ */
29
+
30
+ /** How long an unclaimed interruption stays resumable (30 min). */
31
+ const TTL_MS = 30 * 60 * 1000;
32
+ /** Bound on live entries: a long-lived app must not grow without limit. */
33
+ const MAX_ENTRIES = 64;
34
+
35
+ const entries = new Map(); // key -> { rounds, tokens, note, at, interruptions }
36
+ const historyKeys = new WeakMap(); // history[] -> key
37
+ let historyKeySeq = 0;
38
+
39
+ /** Drop expired entries, then the oldest ones past the bound. */
40
+ function prune(now = Date.now()) {
41
+ for (const [key, entry] of entries) {
42
+ if (now - entry.at > TTL_MS) entries.delete(key);
43
+ }
44
+ while (entries.size > MAX_ENTRIES) {
45
+ // Map iteration is insertion-ordered and `record` re-inserts on write, so
46
+ // the first key is the oldest.
47
+ const oldest = entries.keys().next();
48
+ if (oldest.done) break;
49
+ entries.delete(oldest.value);
50
+ }
51
+ return entries.size;
52
+ }
53
+
54
+ /**
55
+ * The key an interruption is filed under. A caller that states its session
56
+ * (desktop payloads carry an id) gets an exact match; otherwise the working
57
+ * directory, then the identity of the history array, then a single shared
58
+ * bucket. `adopt` covers the remaining case — a caller that mints a fresh key
59
+ * every turn.
60
+ */
61
+ function keyFor(payload, history) {
62
+ const p = payload && typeof payload === 'object' ? payload : {};
63
+ const stated = p.sessionKey || p.sessionId || p.chatId || p.threadId || p.conversationId;
64
+ if (typeof stated === 'string' && stated.trim()) return `s:${stated.trim()}`;
65
+ if (typeof p.cwd === 'string' && p.cwd.trim()) return `cwd:${p.cwd.trim()}`;
66
+ if (history && typeof history === 'object') {
67
+ let key = historyKeys.get(history);
68
+ if (!key) {
69
+ historyKeySeq += 1;
70
+ key = `hist-${historyKeySeq}`;
71
+ historyKeys.set(history, key);
72
+ }
73
+ return key;
74
+ }
75
+ return 'default';
76
+ }
77
+
78
+ /**
79
+ * Extra rounds granted to a resuming turn. Deliberately small and bounded: the
80
+ * point of resuming is to *continue* work that already exists, not to hand out
81
+ * a second full horizon (every round re-sends the whole conversation, so this
82
+ * is the cheapest way to make the cap non-fatal).
83
+ */
84
+ function bonus(base) {
85
+ const n = Number.isFinite(base) && base > 0 ? base : 0;
86
+ return Math.max(4, Math.ceil(n / 4));
87
+ }
88
+
89
+ /** Peek without consuming — the entry stays resumable. */
90
+ function peek(key, now = Date.now()) {
91
+ prune(now);
92
+ return entries.get(key) || null;
93
+ }
94
+
95
+ /** Claim the interruption for `key`, if any. Consuming: a second call gets null. */
96
+ function take(key, now = Date.now()) {
97
+ prune(now);
98
+ const entry = entries.get(key);
99
+ if (!entry) return null;
100
+ entries.delete(key);
101
+ return entry;
102
+ }
103
+
104
+ /**
105
+ * Claim the most recent interruption filed under ANY key. This is the bridge
106
+ * for a caller whose key does not survive between turns: the next turn on this
107
+ * process adopts the held work rather than losing it. Bounded by `maxAgeMs` so
108
+ * an unrelated new conversation is not handed yesterday's job.
109
+ */
110
+ function adopt({ now = Date.now(), maxAgeMs = 10 * 60 * 1000 } = {}) {
111
+ prune(now);
112
+ let bestKey = null;
113
+ let best = null;
114
+ for (const [key, entry] of entries) {
115
+ if (now - entry.at > maxAgeMs) continue;
116
+ if (!best || entry.at > best.at) {
117
+ best = entry;
118
+ bestKey = key;
119
+ }
120
+ }
121
+ if (!best) return null;
122
+ entries.delete(bestKey);
123
+ return { key: bestKey, entry: best };
124
+ }
125
+
126
+ /**
127
+ * File an interruption. `chain` carries the count forward from the entry this
128
+ * turn resumed, so `interruptions` reports how many times one job has been cut
129
+ * off — visible in the note and useful when deciding to raise the horizon.
130
+ *
131
+ * `messages` is the interrupted turn's own tool-call transcript (its live
132
+ * `history` array at the moment it hit the horizon) — real memory of what was
133
+ * already done, not just a rounds/tokens count of it. Without it a caller
134
+ * that supplies no conversation of its own (a queue task's fresh dispatch)
135
+ * resumes with an empty history: the model is told "continue, don't restart"
136
+ * with nothing to continue FROM, which is a cold start wearing a note.
137
+ * Stored as a defensive copy — the caller's `history` array keeps being
138
+ * mutated by the turn that is returning it.
139
+ */
140
+ function record(key, { rounds, tokens, note, chain, messages, added } = {}, now = Date.now()) {
141
+ prune(now);
142
+ const prior = entries.get(key);
143
+ const entry = {
144
+ rounds: Number.isFinite(rounds) ? rounds : 0,
145
+ tokens: Number.isFinite(tokens) ? tokens : 0,
146
+ note: typeof note === 'string' ? note : '',
147
+ at: now,
148
+ interruptions: (Number.isFinite(chain) ? chain : prior && prior.interruptions) || 0,
149
+ messages: Array.isArray(messages) ? messages.slice() : [],
150
+ // And what the interrupted turn added on TOP of what its caller already
151
+ // had. A resuming caller who brings its own conversation (an interactive
152
+ // chat) must get this half, not `messages` — pushing the full transcript
153
+ // into a history that already holds its first half duplicates the user's
154
+ // own turns back to the model.
155
+ added: Array.isArray(added) ? added.slice() : [],
156
+ };
157
+ entry.interruptions += 1;
158
+ entries.delete(key);
159
+ entries.set(key, entry); // re-insert so Map order stays age order
160
+ prune(now);
161
+ return entry;
162
+ }
163
+
164
+ /** The instruction that turns a cold start into a continuation. */
165
+ function resumePreamble(entry) {
166
+ const rounds = entry && entry.rounds ? entry.rounds : 'the previous turn\'s';
167
+ const tokens = entry && entry.tokens ? ` (${entry.tokens.toLocaleString()} tokens)` : '';
168
+ return (
169
+ `[session resume] The previous turn in this conversation was cut off at ${rounds} tool rounds${tokens} ` +
170
+ 'because it reached the round horizon, so the work it started is unfinished. Continue that work now: ' +
171
+ 'do not restart, do not re-do steps that already completed, and do not treat the interruption as a ' +
172
+ 'failure to report. Pick up the next unfinished step and finish with a written answer.'
173
+ );
174
+ }
175
+
176
+ /** Read-only snapshot for the UI (and for tests). */
177
+ function state(now = Date.now()) {
178
+ prune(now);
179
+ return {
180
+ size: entries.size,
181
+ ttlMs: TTL_MS,
182
+ maxEntries: MAX_ENTRIES,
183
+ entries: [...entries].map(([key, entry]) => ({ key, ...entry })),
184
+ };
185
+ }
186
+
187
+ /** Test hook: forget everything. */
188
+ function reset() {
189
+ entries.clear();
190
+ return entries.size;
191
+ }
192
+
193
+ module.exports = {
194
+ TTL_MS,
195
+ MAX_ENTRIES,
196
+ keyFor,
197
+ bonus,
198
+ peek,
199
+ take,
200
+ adopt,
201
+ record,
202
+ resumePreamble,
203
+ state,
204
+ reset,
205
+ };