synabun 2.4.5 → 2.4.7
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/CHANGELOG.md +38 -0
- package/README.md +1 -1
- package/docs/whatsapp.md +17 -1
- package/hooks/claude-code/session-start.mjs +21 -18
- package/lib/claude-global-config.js +214 -0
- package/lib/client-config-repair.js +17 -3
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +6 -1
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/tool-catalog.js +1 -1
- package/mcp-server/dist/services/tool-catalog.js.map +1 -1
- package/mcp-server/dist/tools/agents.d.ts +2 -0
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +11 -5
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
- package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
- package/mcp-server/dist/tools/skill-tools.js +88 -8
- package/mcp-server/dist/tools/skill-tools.js.map +1 -1
- package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
- package/mcp-server/dist/tools/tool-groups.js +19 -4
- package/mcp-server/dist/tools/tool-groups.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/index.ts +6 -1
- package/mcp-server/src/services/tool-catalog.ts +1 -1
- package/mcp-server/src/tools/agents.ts +11 -5
- package/mcp-server/src/tools/skill-tools.ts +82 -9
- package/mcp-server/src/tools/tool-groups.ts +19 -4
- package/neural-interface/i18n/en.json +153 -10
- package/neural-interface/i18n/pt-BR.json +153 -10
- package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
- package/neural-interface/lib/assistant-dispatch.js +15 -1
- package/neural-interface/lib/assistant-runtime.js +79 -8
- package/neural-interface/lib/assistant-user-context.js +7 -3
- package/neural-interface/lib/browser-background-tab.js +12 -0
- package/neural-interface/lib/browser-guard-cdp.js +2 -1
- package/neural-interface/lib/browser-network-guard.js +140 -3
- package/neural-interface/lib/browser-own-targets.js +350 -0
- package/neural-interface/lib/claude-agent-bridge.js +13 -2
- package/neural-interface/lib/codex-thread-history.js +144 -7
- package/neural-interface/lib/codex-worker-app-server.js +84 -30
- package/neural-interface/lib/db.js +26 -0
- package/neural-interface/lib/greeting/sources.js +7 -3
- package/neural-interface/lib/jsonl-lines.js +10 -11
- package/neural-interface/lib/launch-block-api.js +86 -0
- package/neural-interface/lib/line-buffer.js +88 -0
- package/neural-interface/lib/loop-stall.js +15 -1
- package/neural-interface/lib/memory-list-read.js +105 -0
- package/neural-interface/lib/memory-timers.js +4 -1
- package/neural-interface/lib/morelogin-launch-recovery.js +506 -0
- package/neural-interface/lib/morelogin-profile-failures.js +48 -1
- package/neural-interface/lib/morelogin.js +16 -2
- package/neural-interface/lib/native-loop-runtime.js +7 -3
- package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
- package/neural-interface/lib/skills/api-v2.js +18 -3
- package/neural-interface/lib/skills/bundle.js +2 -2
- package/neural-interface/lib/skills/deploy.js +169 -34
- package/neural-interface/lib/skills/digest.js +57 -3
- package/neural-interface/lib/skills/health.js +55 -1
- package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
- package/neural-interface/lib/skills/runtime-checks.js +7 -4
- package/neural-interface/lib/skills/scan-shell.js +56 -7
- package/neural-interface/lib/skills/scan.js +13 -12
- package/neural-interface/lib/skills/service.js +7 -2
- package/neural-interface/lib/skills/telemetry.js +2 -2
- package/neural-interface/lib/teams/README.md +12 -5
- package/neural-interface/lib/teams/api.js +15 -4
- package/neural-interface/lib/teams/index.js +2 -0
- package/neural-interface/lib/teams/landing.js +195 -75
- package/neural-interface/lib/teams/scheduler.js +31 -32
- package/neural-interface/lib/terminal-token-redaction.js +228 -58
- package/neural-interface/lib/terminal-tokens.js +18 -0
- package/neural-interface/lib/whatsapp/brain.js +21 -0
- package/neural-interface/lib/whatsapp/bridge.js +40 -4
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/index.html +117 -37
- package/neural-interface/public/shared/agents/studio/ax-api.js +11 -0
- package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
- package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
- package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
- package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
- package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
- package/neural-interface/public/shared/agents/studio/ax-teams-view.js +137 -39
- package/neural-interface/public/shared/agents/studio/ax-teams.js +219 -4
- package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
- package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
- package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
- package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
- package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
- package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
- package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
- package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
- package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
- package/neural-interface/public/shared/launch-block-view.js +124 -0
- package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
- package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
- package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
- package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
- package/neural-interface/public/shared/styles.css +17 -0
- package/neural-interface/public/shared/ui-launch-block-notice.js +155 -0
- package/neural-interface/public/shared/ui-navbar.js +11 -0
- package/neural-interface/public/shared/ui-sync.js +2 -0
- package/neural-interface/server.js +745 -270
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/skills/skill-forge/SKILL.md +7 -3
|
@@ -4,6 +4,67 @@ const CODEX_HISTORY_PAGE_TIMEOUT_MS = 15000;
|
|
|
4
4
|
const CODEX_TURN_PAGE_SIZE = 100;
|
|
5
5
|
const CODEX_ITEM_PAGE_SIZE = 500;
|
|
6
6
|
|
|
7
|
+
// ── Pages sized by what they weigh ──
|
|
8
|
+
// A page of items is one JSON-RPC reply: one line of the app-server's stdout, parsed and redacted in one go on the
|
|
9
|
+
// server's own thread. Asked for 500 items at a time, a thread of generated images answered with all of it at once
|
|
10
|
+
// (2026-11-29: 408 items, 171 MB, one line), and the server answered nobody for the time that took. The app-server
|
|
11
|
+
// has no way to leave image data out of an item, so the lever is the page: the first page asks for few items, and
|
|
12
|
+
// every next one for as many as fit the weight the last page showed (never more than CODEX_ITEM_PAGE_SIZE, and at
|
|
13
|
+
// most four times the last page). A thread of small items is read in pages of 500 again after two steps.
|
|
14
|
+
/** How many items the first page of a thread asks for. */
|
|
15
|
+
export const CODEX_ITEM_FIRST_PAGE = 32;
|
|
16
|
+
/** How many turns with their items the first page of the older, turn-by-turn reading asks for. */
|
|
17
|
+
export const CODEX_FULL_TURN_FIRST_PAGE = 8;
|
|
18
|
+
/** What a page should weigh at most, in characters of its strings (about its size as JSON). */
|
|
19
|
+
export const CODEX_PAGE_TARGET_CHARS = 16 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
// ── Inline generated images, as references ──
|
|
22
|
+
/** A generated image's inline data of this many characters or more is handed on as a reference, not as text. */
|
|
23
|
+
export const CODEX_INLINE_IMAGE_MIN_CHARS = 64 * 1024;
|
|
24
|
+
/** The mark an item carries for what was left out of it: `{ turnId, fields: { result: { chars, head } } }`. */
|
|
25
|
+
export const CODEX_DEFERRED_KEY = '_synabunDeferred';
|
|
26
|
+
/** How much of the beginning stays in the mark: what a card's head showed of the data (one short line). */
|
|
27
|
+
const CODEX_DEFERRED_HEAD_CHARS = 160;
|
|
28
|
+
|
|
29
|
+
/** The characters in every string of `value`, at any depth: what it weighs, about, as JSON. */
|
|
30
|
+
export function approximateChars(value) {
|
|
31
|
+
let chars = 0;
|
|
32
|
+
const stack = [value];
|
|
33
|
+
let nodes = 0;
|
|
34
|
+
while (stack.length && nodes++ < 2_000_000) {
|
|
35
|
+
const item = stack.pop();
|
|
36
|
+
if (typeof item === 'string') chars += item.length;
|
|
37
|
+
else if (Array.isArray(item)) for (let i = 0; i < item.length; i++) stack.push(item[i]);
|
|
38
|
+
else if (item && typeof item === 'object') for (const key in item) stack.push(item[key]);
|
|
39
|
+
}
|
|
40
|
+
return chars;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** How many entries the next page asks for, after a page of `count` entries that weighed `chars`. */
|
|
44
|
+
export function nextPageLimit(limit, count, chars, { max, target = CODEX_PAGE_TARGET_CHARS } = {}) {
|
|
45
|
+
if (!(count > 0)) return Math.min(max, limit);
|
|
46
|
+
const perEntry = Math.max(1, chars / count);
|
|
47
|
+
return Math.max(1, Math.min(max, limit * 4, Math.floor(target / perEntry)));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* `item` as the page gets it: a generated image's inline data (megabytes of base64 in `result`) is left out and
|
|
52
|
+
* marked, with the turn it belongs to, so the page can ask for it when somebody opens the item
|
|
53
|
+
* (readCodexThreadItem). Everything else of the item, and every other item, is handed on as it is.
|
|
54
|
+
*/
|
|
55
|
+
export function deferCodexInlineImage(item, turnId) {
|
|
56
|
+
if (!item || typeof item !== 'object' || item.type !== 'imageGeneration') return item;
|
|
57
|
+
if (typeof item.result !== 'string' || item.result.length < CODEX_INLINE_IMAGE_MIN_CHARS) return item;
|
|
58
|
+
return {
|
|
59
|
+
...item,
|
|
60
|
+
result: '',
|
|
61
|
+
[CODEX_DEFERRED_KEY]: {
|
|
62
|
+
turnId: turnId == null ? null : String(turnId),
|
|
63
|
+
fields: { result: { chars: item.result.length, head: item.result.slice(0, CODEX_DEFERRED_HEAD_CHARS) } },
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
7
68
|
function codexErrorText(error) {
|
|
8
69
|
if (!error) return '';
|
|
9
70
|
const parts = [
|
|
@@ -32,20 +93,31 @@ export function isCodexHistoryUnavailableBeforeFirstTurn(error) {
|
|
|
32
93
|
return /(?:not materialized yet|unavailable before first user message)/i.test(codexErrorText(error));
|
|
33
94
|
}
|
|
34
95
|
|
|
96
|
+
/**
|
|
97
|
+
* Every page of `method`, in order. `adaptive: { first, max, target }`: the first page asks for `first` entries and
|
|
98
|
+
* each next one for what the last page's weight allows (nextPageLimit); without it every page asks for
|
|
99
|
+
* `baseParams.limit`. `each(entry)`: what is kept of an entry (it may return a lighter one).
|
|
100
|
+
*/
|
|
35
101
|
async function paginateCodexHistory(request, method, baseParams, {
|
|
36
102
|
timeoutMs = CODEX_HISTORY_PAGE_TIMEOUT_MS,
|
|
103
|
+
adaptive = null,
|
|
104
|
+
each = null,
|
|
37
105
|
} = {}) {
|
|
38
106
|
const data = [];
|
|
39
107
|
const seenCursors = new Set();
|
|
40
108
|
let cursor = null;
|
|
109
|
+
let limit = adaptive ? Math.max(1, Math.min(adaptive.max, adaptive.first)) : baseParams.limit;
|
|
41
110
|
|
|
42
111
|
do {
|
|
43
|
-
const params =
|
|
112
|
+
const params = { ...baseParams, limit };
|
|
113
|
+
if (cursor != null) params.cursor = cursor;
|
|
44
114
|
const result = await request(method, params, timeoutMs);
|
|
45
115
|
if (!Array.isArray(result?.data)) {
|
|
46
116
|
throw historyProtocolError(`${method} returned an invalid page`);
|
|
47
117
|
}
|
|
48
|
-
data.
|
|
118
|
+
if (adaptive) limit = nextPageLimit(limit, result.data.length, approximateChars(result.data), adaptive);
|
|
119
|
+
if (each) for (const entry of result.data) data.push(each(entry));
|
|
120
|
+
else data.push(...result.data);
|
|
49
121
|
|
|
50
122
|
const nextCursor = result.nextCursor ?? null;
|
|
51
123
|
if (nextCursor == null) break;
|
|
@@ -62,21 +134,39 @@ async function paginateCodexHistory(request, method, baseParams, {
|
|
|
62
134
|
return data;
|
|
63
135
|
}
|
|
64
136
|
|
|
137
|
+
/** The item of an entry or of a turn passed through `transformItem` (hydrateCodexThreadHistory's option). */
|
|
138
|
+
const transformed = (transformItem, item, turnId) => (typeof transformItem === 'function' && item && typeof item === 'object' ? transformItem(item, turnId) : item);
|
|
139
|
+
|
|
65
140
|
async function listCodexTurns(request, threadId, itemsView, options) {
|
|
141
|
+
const full = itemsView === 'full';
|
|
66
142
|
return paginateCodexHistory(request, 'thread/turns/list', {
|
|
67
143
|
threadId,
|
|
68
144
|
limit: options.turnPageSize ?? CODEX_TURN_PAGE_SIZE,
|
|
69
145
|
sortDirection: 'asc',
|
|
70
146
|
itemsView,
|
|
71
|
-
},
|
|
147
|
+
}, {
|
|
148
|
+
timeoutMs: options.timeoutMs,
|
|
149
|
+
// Turns with their items weigh what their items weigh: sized like item pages. Turns alone are small.
|
|
150
|
+
adaptive: full ? { first: Math.min(options.turnPageSize ?? CODEX_TURN_PAGE_SIZE, options.firstFullTurnPage ?? CODEX_FULL_TURN_FIRST_PAGE), max: options.turnPageSize ?? CODEX_TURN_PAGE_SIZE, target: options.pageTargetChars } : null,
|
|
151
|
+
each: full && typeof options.transformItem === 'function'
|
|
152
|
+
? (turn) => (turn && Array.isArray(turn.items) ? { ...turn, items: turn.items.map((item) => transformed(options.transformItem, item, turn.id)) } : turn)
|
|
153
|
+
: null,
|
|
154
|
+
});
|
|
72
155
|
}
|
|
73
156
|
|
|
74
157
|
async function listCodexItems(request, threadId, options) {
|
|
158
|
+
const max = options.itemPageSize ?? CODEX_ITEM_PAGE_SIZE;
|
|
75
159
|
return paginateCodexHistory(request, 'thread/items/list', {
|
|
76
160
|
threadId,
|
|
77
|
-
limit:
|
|
161
|
+
limit: max,
|
|
78
162
|
sortDirection: 'asc',
|
|
79
|
-
},
|
|
163
|
+
}, {
|
|
164
|
+
timeoutMs: options.timeoutMs,
|
|
165
|
+
adaptive: { first: Math.min(max, options.firstItemPage ?? CODEX_ITEM_FIRST_PAGE), max, target: options.pageTargetChars },
|
|
166
|
+
each: typeof options.transformItem === 'function'
|
|
167
|
+
? (entry) => (entry && entry.item && typeof entry.item === 'object' ? { ...entry, item: transformed(options.transformItem, entry.item, entry.turnId) } : entry)
|
|
168
|
+
: null,
|
|
169
|
+
});
|
|
80
170
|
}
|
|
81
171
|
|
|
82
172
|
function mergeCodexItemsIntoTurns(turns, itemEntries) {
|
|
@@ -113,6 +203,12 @@ function mergeCodexItemsIntoTurns(turns, itemEntries) {
|
|
|
113
203
|
return hydratedTurns;
|
|
114
204
|
}
|
|
115
205
|
|
|
206
|
+
/**
|
|
207
|
+
* A thread's turns with their items, read in pages. `options.transformItem(item, turnId)`: what is kept of each item
|
|
208
|
+
* as its page arrives (the server passes deferCodexInlineImage, so a page's megabytes of image data are let go
|
|
209
|
+
* before the next page is asked for); `firstItemPage`, `itemPageSize`, `turnPageSize`, `pageTargetChars`,
|
|
210
|
+
* `timeoutMs`: the paging (the defaults are the constants above).
|
|
211
|
+
*/
|
|
116
212
|
export async function hydrateCodexThreadHistory(request, threadId, options = {}) {
|
|
117
213
|
if (typeof request !== 'function') throw new TypeError('request must be a function');
|
|
118
214
|
const targetThreadId = String(threadId || '');
|
|
@@ -143,8 +239,49 @@ export async function hydrateCodexThreadHistory(request, threadId, options = {})
|
|
|
143
239
|
}
|
|
144
240
|
}
|
|
145
241
|
|
|
242
|
+
/**
|
|
243
|
+
* One item of a thread, whole: what the page asks for when somebody opens an item whose image data was left out
|
|
244
|
+
* (deferCodexInlineImage). `thread/items/read` gives it directly; a Codex without that method is asked for the
|
|
245
|
+
* turn's items in pages (sized by weight, like the history) until the item comes by. null when the thread has no
|
|
246
|
+
* such item in that turn.
|
|
247
|
+
*/
|
|
248
|
+
export async function readCodexThreadItem(request, threadId, turnId, itemId, options = {}) {
|
|
249
|
+
if (typeof request !== 'function') throw new TypeError('request must be a function');
|
|
250
|
+
const thread = String(threadId || '');
|
|
251
|
+
const turn = String(turnId || '');
|
|
252
|
+
const target = String(itemId || '');
|
|
253
|
+
if (!thread || !turn || !target) throw new Error('A thread, a turn and an item are required.');
|
|
254
|
+
const timeoutMs = options.timeoutMs ?? CODEX_HISTORY_PAGE_TIMEOUT_MS;
|
|
255
|
+
const itemOf = (entry) => (entry?.item && typeof entry.item === 'object' ? entry.item : entry);
|
|
256
|
+
try {
|
|
257
|
+
const result = await request('thread/items/read', { threadId: thread, turnId: turn, itemIds: [target] }, timeoutMs);
|
|
258
|
+
const found = (Array.isArray(result?.data) ? result.data : []).map(itemOf).find((item) => String(item?.id ?? '') === target);
|
|
259
|
+
return found || null;
|
|
260
|
+
} catch (error) {
|
|
261
|
+
if (!isCodexItemsPaginationUnsupported(error)) throw error;
|
|
262
|
+
}
|
|
263
|
+
const max = options.itemPageSize ?? CODEX_ITEM_PAGE_SIZE;
|
|
264
|
+
let limit = Math.min(max, options.firstItemPage ?? CODEX_ITEM_FIRST_PAGE);
|
|
265
|
+
let cursor = null;
|
|
266
|
+
const seenCursors = new Set();
|
|
267
|
+
for (;;) {
|
|
268
|
+
const params = { threadId: thread, turnId: turn, limit, sortDirection: 'asc' };
|
|
269
|
+
if (cursor != null) params.cursor = cursor;
|
|
270
|
+
const result = await request('thread/items/list', params, timeoutMs);
|
|
271
|
+
if (!Array.isArray(result?.data)) throw historyProtocolError('thread/items/list returned an invalid page');
|
|
272
|
+
const found = result.data.map(itemOf).find((item) => String(item?.id ?? '') === target);
|
|
273
|
+
if (found) return found;
|
|
274
|
+
const nextCursor = result.nextCursor ?? null;
|
|
275
|
+
if (nextCursor == null) return null;
|
|
276
|
+
if (typeof nextCursor !== 'string' || !nextCursor || seenCursors.has(nextCursor)) throw historyProtocolError('thread/items/list returned an invalid nextCursor');
|
|
277
|
+
seenCursors.add(nextCursor);
|
|
278
|
+
cursor = nextCursor;
|
|
279
|
+
limit = nextPageLimit(limit, result.data.length, approximateChars(result.data), { max, target: options.pageTargetChars });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
146
283
|
/** 0.160 removed rollback; revert excludes a named turn and all later turns. */
|
|
147
|
-
export async function revertCodexThreadHistory(request, threadId, { numTurns = 1, beforeTurnId } = {}) {
|
|
284
|
+
export async function revertCodexThreadHistory(request, threadId, { numTurns = 1, beforeTurnId, history: historyOptions = {} } = {}) {
|
|
148
285
|
if (!threadId) throw new Error('No thread provided');
|
|
149
286
|
if (!Number.isSafeInteger(numTurns) || numTurns < 1) throw new Error('Turn count must be a positive integer.');
|
|
150
287
|
const turns = beforeTurnId ? null : await listCodexTurns(request, threadId, 'notLoaded', {});
|
|
@@ -160,6 +297,6 @@ export async function revertCodexThreadHistory(request, threadId, { numTurns = 1
|
|
|
160
297
|
if (!count) throw error;
|
|
161
298
|
return request('thread/rollback', { threadId, numTurns: count }, CODEX_HISTORY_PAGE_TIMEOUT_MS);
|
|
162
299
|
}
|
|
163
|
-
const history = await hydrateCodexThreadHistory(request, threadId);
|
|
300
|
+
const history = await hydrateCodexThreadHistory(request, threadId, historyOptions);
|
|
164
301
|
return { ...result, thread: { ...result.thread, turns: history.turns } };
|
|
165
302
|
}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// worker's event/usage contract while thread/resume reopens its durable thread.
|
|
3
3
|
import { spawn, execFileSync } from 'node:child_process';
|
|
4
4
|
import { StringDecoder } from 'node:string_decoder';
|
|
5
|
+
import { createLineBuffer } from './line-buffer.js';
|
|
6
|
+
import { sizedLabel, timeBlockingWork } from './loop-stall.js';
|
|
5
7
|
|
|
6
8
|
const toml = (v) => Array.isArray(v) ? `[${v.map(toml).join(',')}]`
|
|
7
9
|
: v && typeof v === 'object' ? `{${Object.entries(v).filter(([, x]) => x != null).map(([k, x]) => `${JSON.stringify(k)}=${toml(x)}`).join(',')}}`
|
|
@@ -26,8 +28,17 @@ export function codexWorkerConfigOverrides(config) {
|
|
|
26
28
|
return overrides;
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
// How long the next turn waits for a turn this client interrupted to end at the app-server (turn/completed).
|
|
32
|
+
export const CODEX_INTERRUPT_SETTLE_MS = 10_000;
|
|
33
|
+
|
|
34
|
+
/** The turn a notification belongs to (item/*, turn/*), or null. */
|
|
35
|
+
function notificationTurnId(params) {
|
|
36
|
+
const id = params?.turnId || params?.turn?.id || params?.item?.turnId || null;
|
|
37
|
+
return id ? String(id) : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
29
40
|
export class CodexWorkerAppServer {
|
|
30
|
-
constructor({ codexPathOverride, env, config = {}, configArgs = [], apiKey, signal, onProcess = () => {}, onRequest = null, permissionPolicy = 'auto' }) {
|
|
41
|
+
constructor({ codexPathOverride, env, config = {}, configArgs = [], apiKey, signal, onProcess = () => {}, onRequest = null, permissionPolicy = 'auto', interruptSettleMs = CODEX_INTERRUPT_SETTLE_MS }) {
|
|
31
42
|
this.onRequest = onRequest;
|
|
32
43
|
this.approvalPolicy = permissionPolicy === 'ask' ? 'untrusted' : 'never';
|
|
33
44
|
this.requestAbort = new AbortController();
|
|
@@ -37,6 +48,13 @@ export class CodexWorkerAppServer {
|
|
|
37
48
|
this.seq = 0;
|
|
38
49
|
this.listener = null;
|
|
39
50
|
this.failure = null;
|
|
51
|
+
// Turns this client interrupted (a steer, a stop): the app-server ends such a turn a moment after turn/interrupt
|
|
52
|
+
// (its tool call is cut first) with turn/completed { status: 'interrupted' }. Those last notifications belong to
|
|
53
|
+
// that turn and never reach the turn that follows it on the same thread, which would read them as its own end.
|
|
54
|
+
this.interruptedTurns = new Set();
|
|
55
|
+
// turnId → the wait for that end; the next turn/start goes only after it (bounded by interruptSettleMs).
|
|
56
|
+
this.interrupts = new Map();
|
|
57
|
+
this.interruptSettleMs = Math.max(0, Number(interruptSettleMs) || 0);
|
|
40
58
|
const args = [...configArgs];
|
|
41
59
|
for (const override of codexWorkerConfigOverrides(config)) args.push('-c', override);
|
|
42
60
|
// Run identity in the command line permits conservative orphan identification.
|
|
@@ -44,34 +62,43 @@ export class CodexWorkerAppServer {
|
|
|
44
62
|
this.proc = spawn(codexPathOverride, args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
45
63
|
this.exited = new Promise((r) => this.proc.once('close', r));
|
|
46
64
|
onProcess({ pid: this.proc.pid, startedAt: new Date().toISOString() });
|
|
47
|
-
|
|
65
|
+
// stdout cut into lines in time linear in what arrives (lib/line-buffer.js: a chunk is searched once, a long line
|
|
66
|
+
// joined once), and each line's parse and dispatch timed by name, so a stall of the server's thread names it.
|
|
67
|
+
const lines = createLineBuffer();
|
|
48
68
|
const decoder = new StringDecoder('utf8');
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (msg.method === '
|
|
72
|
-
|
|
73
|
-
this.listener?.(msg);
|
|
69
|
+
const handleLine = (line) => {
|
|
70
|
+
let msg; try { msg = JSON.parse(line); } catch { return; }
|
|
71
|
+
if (msg.id != null && !msg.method) {
|
|
72
|
+
const p = this.pending.get(msg.id); if (!p) return;
|
|
73
|
+
this.pending.delete(msg.id); clearTimeout(p.timer);
|
|
74
|
+
msg.error ? p.reject(new Error(msg.error.message || 'Codex RPC failed')) : p.resolve(msg.result);
|
|
75
|
+
} else if (msg.id != null) {
|
|
76
|
+
const controller = new AbortController();
|
|
77
|
+
this.incoming.set(msg.id, controller);
|
|
78
|
+
Promise.resolve().then(() => {
|
|
79
|
+
if (!this.onRequest) throw new Error('Worker has no interactive request handler');
|
|
80
|
+
return this.onRequest(msg, controller.signal);
|
|
81
|
+
}).then((reply) => {
|
|
82
|
+
if (!this.failure && !controller.signal.aborted) this.write({ id: msg.id, ...reply });
|
|
83
|
+
}, (error) => {
|
|
84
|
+
if (!this.failure && !controller.signal.aborted) this.write({ id: msg.id, error: { code: -32000, message: error.message } });
|
|
85
|
+
}).finally(() => this.incoming.delete(msg.id));
|
|
86
|
+
} else {
|
|
87
|
+
// The last words of a turn this client interrupted: its end settles the wait for it, nothing else sees them
|
|
88
|
+
// (not the turn that runs now, nor that turn's pending requests).
|
|
89
|
+
const turnOf = notificationTurnId(msg.params);
|
|
90
|
+
if (turnOf && this.interruptedTurns.has(turnOf)) {
|
|
91
|
+
if (msg.method === 'turn/completed') this.interrupts.get(turnOf)?.finish();
|
|
92
|
+
return;
|
|
74
93
|
}
|
|
94
|
+
if (msg.method === 'serverRequest/resolved') this.incoming.get(msg.params?.requestId)?.abort();
|
|
95
|
+
if (msg.method === 'turn/completed') { for (const pending of this.incoming.values()) pending.abort(); this.incoming.clear(); }
|
|
96
|
+
this.listener?.(msg);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
this.proc.stdout.on('data', (chunk) => {
|
|
100
|
+
for (const line of lines.push(decoder.write(chunk))) {
|
|
101
|
+
timeBlockingWork(sizedLabel('codex-worker:stdout-line', line.length), () => handleLine(line));
|
|
75
102
|
}
|
|
76
103
|
});
|
|
77
104
|
// Drain stderr without exposing credentials/config to the worker transcript.
|
|
@@ -96,8 +123,30 @@ export class CodexWorkerAppServer {
|
|
|
96
123
|
this.requestAbort.abort();
|
|
97
124
|
for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(error); }
|
|
98
125
|
this.pending.clear();
|
|
126
|
+
for (const wait of [...this.interrupts.values()]) wait.finish();
|
|
99
127
|
this.listener?.({ method: 'synabun/exit', error });
|
|
100
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Interrupt a turn in flight, once. From now on its notifications are its own (see the reader), and the next turn
|
|
131
|
+
* of the thread waits (settledInterrupts) until it ended: its turn/completed, a refused interrupt (the turn was not
|
|
132
|
+
* running any more), the process's exit, or interruptSettleMs.
|
|
133
|
+
*/
|
|
134
|
+
interruptTurn(threadId, turnId) {
|
|
135
|
+
const key = String(turnId);
|
|
136
|
+
if (this.interruptedTurns.has(key)) return;
|
|
137
|
+
this.interruptedTurns.add(key);
|
|
138
|
+
if (this.interruptedTurns.size > 100) this.interruptedTurns.delete(this.interruptedTurns.values().next().value);
|
|
139
|
+
let settle;
|
|
140
|
+
const wait = { done: new Promise((resolve) => { settle = resolve; }), timer: null };
|
|
141
|
+
wait.finish = () => { clearTimeout(wait.timer); if (this.interrupts.get(key) === wait) this.interrupts.delete(key); settle(); };
|
|
142
|
+
wait.timer = setTimeout(wait.finish, this.interruptSettleMs);
|
|
143
|
+
wait.timer.unref?.();
|
|
144
|
+
this.interrupts.set(key, wait);
|
|
145
|
+
if (this.failure) { wait.finish(); return; }
|
|
146
|
+
this.rpc('turn/interrupt', { threadId, turnId }).catch(wait.finish);
|
|
147
|
+
}
|
|
148
|
+
/** Every interrupted turn has ended (or stopped being waited for). */
|
|
149
|
+
settledInterrupts() { return Promise.all([...this.interrupts.values()].map((wait) => wait.done)); }
|
|
101
150
|
rpc(method, params) {
|
|
102
151
|
if (this.failure) return Promise.reject(this.failure);
|
|
103
152
|
return new Promise((resolve, reject) => {
|
|
@@ -129,15 +178,20 @@ export class CodexWorkerAppServer {
|
|
|
129
178
|
get id() { return id; }, ready: () => ready,
|
|
130
179
|
async runStreamed(prompt, { signal, outputSchema } = {}) {
|
|
131
180
|
await ready;
|
|
132
|
-
|
|
181
|
+
// A turn this client interrupted (a steer cuts a turn and sends the next at once) ends first at the app-server.
|
|
182
|
+
await owner.settledInterrupts();
|
|
183
|
+
const queue = []; const text = new Map(); let wake; let done = false; let failure; let turnId; let ended = false;
|
|
133
184
|
const push = (event) => { queue.push(event); wake?.(); };
|
|
134
185
|
const abort = () => {
|
|
135
186
|
failure = Object.assign(new Error('Codex turn aborted'), { name: 'AbortError' }); done = true; wake?.();
|
|
136
|
-
if (turnId) owner.
|
|
187
|
+
if (turnId && !ended) owner.interruptTurn(id, turnId);
|
|
137
188
|
};
|
|
138
189
|
owner.listener = (msg) => {
|
|
139
190
|
const p = msg.params || {};
|
|
140
191
|
if (p.threadId && p.threadId !== id) return;
|
|
192
|
+
// One turn's notifications only: another turn's (an earlier one) never ends or feeds this one.
|
|
193
|
+
const turnOf = notificationTurnId(p);
|
|
194
|
+
if (turnOf && turnId && turnOf !== String(turnId)) return;
|
|
141
195
|
if (msg.method === 'synabun/exit') { failure = msg.error; done = true; wake?.(); }
|
|
142
196
|
if (msg.method === 'item/agentMessage/delta') {
|
|
143
197
|
const value = (text.get(p.itemId) || '') + (p.delta || '');
|
|
@@ -153,7 +207,7 @@ export class CodexWorkerAppServer {
|
|
|
153
207
|
if (p.turn?.status === 'failed') push({ type: 'turn.failed', error: p.turn.error || { message: 'Codex turn failed' } });
|
|
154
208
|
else if (p.turn?.status === 'interrupted') failure = Object.assign(new Error('Codex turn interrupted'), { name: 'AbortError' });
|
|
155
209
|
else push({ type: 'turn.completed' }); // rollout meter is authoritative across resumes
|
|
156
|
-
done = true; wake?.();
|
|
210
|
+
ended = true; done = true; wake?.();
|
|
157
211
|
}
|
|
158
212
|
};
|
|
159
213
|
signal?.addEventListener('abort', abort, { once: true });
|
|
@@ -10,6 +10,7 @@ import { resolve, dirname } from 'path';
|
|
|
10
10
|
import { existsSync, mkdirSync } from 'fs';
|
|
11
11
|
import { getDb as sharedDb, closeDatabase, memoryVectors, chunkVectors, searchMemories as sharedSearch, searchSessionChunks as sharedSessionSearch, updatePayload as sharedUpdate, deleteMemory as sharedDelete } from '../../mcp-server/dist/services/sqlite.js';
|
|
12
12
|
import { readRows } from '../../mcp-server/dist/services/retrieval-reader.js';
|
|
13
|
+
import { createMemoryListReader } from './memory-list-read.js';
|
|
13
14
|
import { generateEmbedding, generateEmbeddingBatch, warmupEmbeddings, EMBEDDING_MODEL, EMBEDDING_DIMENSIONS } from '../../mcp-server/dist/services/local-embeddings.js';
|
|
14
15
|
export { memoryVectors, chunkVectors, warmupEmbeddings, EMBEDDING_MODEL };
|
|
15
16
|
export const EMBEDDING_DIMS = EMBEDDING_DIMENSIONS;
|
|
@@ -130,6 +131,7 @@ export function closeDb() {
|
|
|
130
131
|
}
|
|
131
132
|
memoryVectors.invalidate();
|
|
132
133
|
chunkVectors.invalidate();
|
|
134
|
+
memoryList.forget();
|
|
133
135
|
}
|
|
134
136
|
|
|
135
137
|
// --- In-memory vector caches (see vector-cache.js for coherence model) ---
|
|
@@ -596,6 +598,30 @@ export function getMemoriesPage({ offset = 0, limit } = {}) {
|
|
|
596
598
|
return { rows: rows.map((row) => ({ id: row.id, ...rowToPayload(row) })), total };
|
|
597
599
|
}
|
|
598
600
|
|
|
601
|
+
// The same two answers for the route that serves the page's list, read on the retrieval reader's thread and far
|
|
602
|
+
// cheaper a page (lib/memory-list-read.js): the two functions above held the server's only thread for 0.6-7.7 s a
|
|
603
|
+
// page on the owner's store while it was busy. Async; when the reader cannot serve a read it runs on this connection.
|
|
604
|
+
const memoryList = createMemoryListReader({
|
|
605
|
+
read: (sql, params = []) => { getDb(); return readRows(sql, params); }, // the store's refusal while it is closed or migrating first
|
|
606
|
+
toMemory: (row) => ({ id: row.id, ...rowToPayload(row) }),
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* getMemoriesPage(), off the server's thread. `stamp` is the list's stamp (lib/memory-list-stamp.js) when the caller
|
|
611
|
+
* has it: the pages of one unchanged list then share one read of the order.
|
|
612
|
+
* @param {{ offset?: number, limit: number }} page
|
|
613
|
+
* @param {{ stamp?: string | null }} [options]
|
|
614
|
+
* @returns {Promise<{ rows: Array<object>, total: number }>}
|
|
615
|
+
*/
|
|
616
|
+
export function readMemoriesPage(page, options) {
|
|
617
|
+
return memoryList.page(page, options);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** getAllMemories() (live memories, no vectors), off the server's thread. */
|
|
621
|
+
export function readAllMemories(options) {
|
|
622
|
+
return memoryList.all(options);
|
|
623
|
+
}
|
|
624
|
+
|
|
599
625
|
/**
|
|
600
626
|
* Get all memories with vectors for link computation.
|
|
601
627
|
*/
|
|
@@ -114,11 +114,15 @@ export function createGreetingSources({
|
|
|
114
114
|
return out.sort((a, b) => (ms(b.endedAt) ?? 0) - (ms(a.endedAt) ?? 0)).slice(0, FACTS.threads);
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
// Three reads below say `+trashed_at IS NULL` and `+lower(project) = lower(?)`: the plus keeps SQLite, which has no
|
|
118
|
+
// statistics here, from choosing the index of a whole project or of every live memory (13-21,000 rows read whole,
|
|
119
|
+
// 26-29 ms on an idle machine and up to 1.6 s on a busy one, on the server's thread). The category's index or the
|
|
120
|
+
// creation time's is used instead: the same rows in about a millisecond.
|
|
117
121
|
function summaryRows(project) {
|
|
118
122
|
const categories = [...new Set(safe(() => sessionCategories(), ['conversations']).map(String).filter((name) => name && name !== CATEGORIES.threads))];
|
|
119
123
|
if (!categories.length) return [];
|
|
120
124
|
const rows = safe(() => getDb().prepare(`SELECT id, content, created_at FROM memories
|
|
121
|
-
WHERE trashed_at IS NULL AND category IN (${marks(categories.length)}) AND lower(project) = lower(?) ORDER BY created_at DESC LIMIT ?`).all(...categories, project, FACTS.sessions * 3), []);
|
|
125
|
+
WHERE +trashed_at IS NULL AND category IN (${marks(categories.length)}) AND +lower(project) = lower(?) ORDER BY created_at DESC LIMIT ?`).all(...categories, project, FACTS.sessions * 3), []);
|
|
122
126
|
const out = [];
|
|
123
127
|
for (const row of rows) {
|
|
124
128
|
const parsed = parseSessionSummary(row.content);
|
|
@@ -134,7 +138,7 @@ export function createGreetingSources({
|
|
|
134
138
|
if (from == null) return [];
|
|
135
139
|
const skip = [...new Set([CATEGORIES.threads, CATEGORIES.knowledge, CATEGORIES.knowledgeParent, ...exclude])];
|
|
136
140
|
const rows = safe(() => getDb().prepare(`SELECT id, content, category, importance, created_at FROM memories
|
|
137
|
-
WHERE trashed_at IS NULL AND lower(project) = lower(?) AND importance >= ? AND created_at >= ? AND created_at <= ?
|
|
141
|
+
WHERE +trashed_at IS NULL AND +lower(project) = lower(?) AND importance >= ? AND created_at >= ? AND created_at <= ?
|
|
138
142
|
AND category NOT IN (${marks(skip.length)}) ORDER BY importance DESC, created_at DESC LIMIT ?`)
|
|
139
143
|
.all(project, FACTS.memoryImportance, new Date(from).toISOString(), new Date(to).toISOString(), ...skip, FACTS.memories), []);
|
|
140
144
|
return rows.map((row) => ({ id: String(row.id), title: firstLine(row.content).replace(/^#+\s*/, ''), excerpt: String(row.content || '').replace(/^#+\s*/gm, ''), category: row.category, importance: row.importance, at: row.created_at }));
|
|
@@ -242,7 +246,7 @@ export function createGreetingSources({
|
|
|
242
246
|
function recentProjects({ limit = 6 } = {}) {
|
|
243
247
|
const categories = [...new Set([CATEGORIES.threads, ...safe(() => sessionCategories(), ['conversations'])])];
|
|
244
248
|
const rows = safe(() => getDb().prepare(`SELECT lower(project) AS project, MAX(updated_at) AS at FROM memories
|
|
245
|
-
WHERE trashed_at IS NULL AND category IN (${marks(categories.length)}) GROUP BY lower(project) ORDER BY at DESC LIMIT ?`).all(...categories, limit), []);
|
|
249
|
+
WHERE +trashed_at IS NULL AND category IN (${marks(categories.length)}) GROUP BY lower(project) ORDER BY at DESC LIMIT ?`).all(...categories, limit), []);
|
|
246
250
|
return rows.map((row) => String(row.project || 'global')).filter(Boolean);
|
|
247
251
|
}
|
|
248
252
|
|
|
@@ -11,25 +11,24 @@
|
|
|
11
11
|
// "Failed to parse item"; the session-history endpoint silently dropped such
|
|
12
12
|
// transcript lines.
|
|
13
13
|
|
|
14
|
+
import { createLineBuffer } from './line-buffer.js';
|
|
15
|
+
|
|
14
16
|
/**
|
|
15
17
|
* Lines of a text stream (or any async iterable of string chunks), split on
|
|
16
18
|
* "\n" only; a trailing "\r" is removed. The last line is yielded even without
|
|
17
19
|
* a final newline.
|
|
18
20
|
*/
|
|
19
21
|
export async function* jsonlLines(chunks) {
|
|
20
|
-
|
|
22
|
+
// Each chunk is searched once and an unfinished line joined once (lib/line-buffer.js): a rollout line of several
|
|
23
|
+
// megabytes (an inline image) used to be searched again from its start for every chunk of it.
|
|
24
|
+
const buffer = createLineBuffer({ stripCr: true });
|
|
21
25
|
for await (const chunk of chunks) {
|
|
22
|
-
|
|
23
|
-
let start = 0;
|
|
24
|
-
let index;
|
|
25
|
-
while ((index = buffer.indexOf('\n', start)) !== -1) {
|
|
26
|
-
const line = buffer.slice(start, index);
|
|
27
|
-
start = index + 1;
|
|
28
|
-
yield line.endsWith('\r') ? line.slice(0, -1) : line;
|
|
29
|
-
}
|
|
30
|
-
buffer = buffer.slice(start);
|
|
26
|
+
for (const line of buffer.push(typeof chunk === 'string' ? chunk : String(chunk))) yield line;
|
|
31
27
|
}
|
|
32
|
-
|
|
28
|
+
// The last line, without a newline: yielded whenever something is left (a lone "\r" yields '', as it always did).
|
|
29
|
+
const left = buffer.pendingChars() > 0;
|
|
30
|
+
const rest = buffer.end();
|
|
31
|
+
if (left) yield rest;
|
|
33
32
|
}
|
|
34
33
|
|
|
35
34
|
function isRecord(text) {
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// ═══════════════════════════════════════════
|
|
2
|
+
// SynaBun — /api/system/launch-blocks: the notice that launches keep failing on a browser profile
|
|
3
|
+
// ═══════════════════════════════════════════
|
|
4
|
+
//
|
|
5
|
+
// GET /api/system/launch-blocks { ok, notices } the profiles whose launches failed in a row
|
|
6
|
+
// POST /api/system/launch-blocks/dismiss { id } { ok, notices }: what is left
|
|
7
|
+
//
|
|
8
|
+
// When the launches of one browser profile fail several times in a row (lib/morelogin-launch-recovery.js: two, after
|
|
9
|
+
// whatever restart SynaBun tried), the owner is told once: which profile, the error, what SynaBun did and what fixes
|
|
10
|
+
// it. Before 2026-11-29 nothing said so: on 2026-11-28 every schedule of one group failed for 40 hours, each with its
|
|
11
|
+
// own "Schedule failed" toast on a page nobody had open. The owner's pages ask when they load and every time their
|
|
12
|
+
// sync socket connects (public/shared/ui-launch-block-notice.js) and are told of a change at once
|
|
13
|
+
// (`schedule:launch-blocked` on the sync socket, which invite guests never get). A notice goes when a launch on the
|
|
14
|
+
// profile works again, or when the owner dismisses it (not shown again for that streak of failures).
|
|
15
|
+
//
|
|
16
|
+
// The owner's only, like the crash notice (lib/crash-notice-api.js): /api/system is admin-only
|
|
17
|
+
// (lib/request-gate.js), every route takes the owner's guard by itself and refuses an agent's request (uiOnly), and
|
|
18
|
+
// the dismissal is the owner's write from SynaBun's own page (X-SynaBun-UI: 1, a JSON body, this boot's page secret).
|
|
19
|
+
// A request names a notice's id, never a profile or a path.
|
|
20
|
+
|
|
21
|
+
import { Router } from 'express';
|
|
22
|
+
import { sendGuardError, uiOnly } from './http-guards.js';
|
|
23
|
+
|
|
24
|
+
const ID = /^[0-9a-f]{16,32}$/;
|
|
25
|
+
const KINDS = new Set(['guard-timeout', 'browser-unresponsive']);
|
|
26
|
+
const FIXES = new Set(['restart', 'start-limit', 'check']);
|
|
27
|
+
const OUTCOMES = new Set(['restarted', 'restarted-ok', 'restarted-retry-failed', 'stop-failed', 'start-failed']);
|
|
28
|
+
const line = (value, max) => (typeof value === 'string' ? value.replace(/[\u0000-\u001f]+/g, ' ').trim().slice(0, max) : '');
|
|
29
|
+
const time = (value) => (Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : null);
|
|
30
|
+
|
|
31
|
+
/** A notice as a page is shown it, field by field; null for anything that is not one. */
|
|
32
|
+
export function launchBlockNoticeOf(notice) {
|
|
33
|
+
if (!notice || typeof notice !== 'object' || typeof notice.id !== 'string' || !ID.test(notice.id)) return null;
|
|
34
|
+
const envId = line(String(notice.envId ?? ''), 128);
|
|
35
|
+
if (!envId) return null;
|
|
36
|
+
const recovery = notice.recovery && typeof notice.recovery === 'object' && OUTCOMES.has(notice.recovery.outcome) && time(notice.recovery.at)
|
|
37
|
+
? { at: time(notice.recovery.at), outcome: notice.recovery.outcome } : null;
|
|
38
|
+
return {
|
|
39
|
+
id: notice.id, envId, name: line(notice.name, 200) || null,
|
|
40
|
+
count: Number.isInteger(notice.count) && notice.count > 0 ? Math.min(notice.count, 9999) : 1,
|
|
41
|
+
firstAt: time(notice.firstAt), lastAt: time(notice.lastAt),
|
|
42
|
+
error: line(notice.error, 600), code: line(notice.code, 64) || null,
|
|
43
|
+
kind: KINDS.has(notice.kind) ? notice.kind : null,
|
|
44
|
+
fix: FIXES.has(notice.fix) ? notice.fix : 'check',
|
|
45
|
+
launches: (Array.isArray(notice.launches) ? notice.launches : []).map((name) => line(name, 120)).filter(Boolean).slice(0, 5),
|
|
46
|
+
recovery,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {object} deps
|
|
52
|
+
* @param {() => { notices(): object[], dismiss(id: string): boolean }} deps.recovery lib/morelogin-launch-recovery.js
|
|
53
|
+
* (read at each request: server.js makes it after the first routes are mounted)
|
|
54
|
+
* @param {import('express').RequestHandler} deps.guard the owner's guard (lib/http-guards.js ownerRouteGuard)
|
|
55
|
+
* @param {{ verify(req): boolean, require: import('express').RequestHandler }} [deps.pageSession] lib/page-session.js:
|
|
56
|
+
* the page secret a dismissal carries (without one, as in a unit test, none is asked)
|
|
57
|
+
*/
|
|
58
|
+
export function createLaunchBlockApi({ recovery, guard, pageSession = null, log = () => {} } = {}) {
|
|
59
|
+
if (typeof recovery !== 'function' || typeof guard !== 'function') throw new Error('createLaunchBlockApi needs the launch recovery and the owner\'s guard');
|
|
60
|
+
const router = Router();
|
|
61
|
+
const current = () => {
|
|
62
|
+
try { return (recovery()?.notices?.() || []).map(launchBlockNoticeOf).filter(Boolean); } catch { return []; }
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
router.use(guard, uiOnly, (req, res, next) => { res.set('Cache-Control', 'no-store'); next(); });
|
|
66
|
+
|
|
67
|
+
router.get('/', (req, res) => { res.json({ ok: true, notices: current() }); });
|
|
68
|
+
|
|
69
|
+
router.post('/dismiss', (req, res, next) => {
|
|
70
|
+
if (req.get('x-synabun-ui') !== '1') return sendGuardError(res, 403, 'UI_HEADER_REQUIRED', 'A notice is dismissed from SynaBun\'s own page.');
|
|
71
|
+
// The page secret: what a local process that merely sends the page's headers lacks.
|
|
72
|
+
if (pageSession && !pageSession.verify(req)) return pageSession.require(req, res, next);
|
|
73
|
+
next();
|
|
74
|
+
}, (req, res) => {
|
|
75
|
+
if (!req.is('application/json')) return res.status(415).json({ ok: false, code: 'JSON_REQUIRED', error: 'Send JSON.' });
|
|
76
|
+
const id = req.body?.id;
|
|
77
|
+
if (typeof id !== 'string' || !ID.test(id)) return res.status(400).json({ ok: false, code: 'BAD_REQUEST', error: 'Send { id } of the notice.' });
|
|
78
|
+
let dismissed = false;
|
|
79
|
+
try { dismissed = recovery()?.dismiss?.(id) === true; } catch { dismissed = false; }
|
|
80
|
+
if (dismissed) log(`[launch-block] dismissed ${id}`);
|
|
81
|
+
// The recovery announces the change itself (`schedule:launch-blocked`); every other window drops it then.
|
|
82
|
+
res.json({ ok: true, notices: current() });
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return router;
|
|
86
|
+
}
|