@hyperwindmill/caretaker-cli 0.34.0 → 0.35.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.
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +16 -0
- package/dist/cli/orchestrator_demo.d.ts +39 -0
- package/dist/cli/orchestrator_demo.d.ts.map +1 -0
- package/dist/cli/orchestrator_demo.js +98 -0
- package/dist/cli/web/api_access.d.ts.map +1 -1
- package/dist/cli/web/api_access.js +1 -1
- package/dist/cli/web/openapi.d.ts +5 -0
- package/dist/cli/web/openapi.d.ts.map +1 -1
- package/dist/cli/web/openapi.js +37 -0
- package/dist/cli/web/orchestrator.d.ts +51 -0
- package/dist/cli/web/orchestrator.d.ts.map +1 -0
- package/dist/cli/web/orchestrator.js +596 -0
- package/dist/cli/web/orchestrator_core.d.ts +83 -0
- package/dist/cli/web/orchestrator_core.d.ts.map +1 -0
- package/dist/cli/web/orchestrator_core.js +219 -0
- package/dist/cli/web/save_config.d.ts +8 -0
- package/dist/cli/web/save_config.d.ts.map +1 -0
- package/dist/cli/web/save_config.js +9 -0
- package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -1
- package/dist/cli/web/scheduler/task_strategy.js +21 -2
- package/dist/cli/web/server.d.ts +3 -0
- package/dist/cli/web/server.d.ts.map +1 -1
- package/dist/cli/web/server.js +14 -16
- package/dist/lib/task_git.d.ts +3 -0
- package/dist/lib/task_git.d.ts.map +1 -1
- package/dist/lib/task_git.js +29 -0
- package/dist/store/orchestrator.d.ts +50 -0
- package/dist/store/orchestrator.d.ts.map +1 -0
- package/dist/store/orchestrator.js +127 -0
- package/dist/webview/standalone.css +159 -1
- package/dist/webview/standalone.css.map +2 -2
- package/dist/webview/standalone.js +784 -504
- package/dist/webview/standalone.js.map +4 -4
- package/package.json +3 -3
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { decrypt, encrypt } from '../../lib/encryption.js';
|
|
3
|
+
import { loadLedger, loadOrchestrator, saveLedger, saveOrchestrator, } from '../../store/orchestrator.js';
|
|
4
|
+
import { isDocumentedRoute } from './openapi.js';
|
|
5
|
+
import { endpointUrl, MAX_BODY_BYTES, mergeConfigSave, needsApproval, parseMessage, PROTOCOL_VERSION, recoverLedger, summarizeLedger, trimLedger, validateEndpoint, } from './orchestrator_core.js';
|
|
6
|
+
import { sameHost } from './voice_proxy.js';
|
|
7
|
+
const OUTBOUND_TIMEOUT_MS = 30_000;
|
|
8
|
+
let status = { state: 'off' };
|
|
9
|
+
let registered = false;
|
|
10
|
+
let recoveredThisProcess = false;
|
|
11
|
+
let ledgerMutex = Promise.resolve();
|
|
12
|
+
let loopTimer = null;
|
|
13
|
+
let loopGen = 0;
|
|
14
|
+
/** Bumped by every config save. A cycle that started under an older generation
|
|
15
|
+
* stops touching the ledger, the registration and the status: after a host
|
|
16
|
+
* change it must not file the old orchestrator's messages into the new ledger. */
|
|
17
|
+
let configGen = 0;
|
|
18
|
+
/** Cycles run one at a time, whoever starts them (the loop, a restart after a
|
|
19
|
+
* save): a slow cycle delays the next one, never overlaps it. */
|
|
20
|
+
let cycleChain = Promise.resolve();
|
|
21
|
+
function withLedgerLock(fn) {
|
|
22
|
+
const run = ledgerMutex.then(fn, fn);
|
|
23
|
+
ledgerMutex = run.then(() => undefined, () => undefined);
|
|
24
|
+
return run;
|
|
25
|
+
}
|
|
26
|
+
function cliVersion() {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')).version;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return '0.0.0';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function oneLineError(err) {
|
|
35
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
36
|
+
return msg.replace(/\s+/g, ' ').trim() || 'Unknown error';
|
|
37
|
+
}
|
|
38
|
+
async function ensureRecovered(now) {
|
|
39
|
+
if (recoveredThisProcess)
|
|
40
|
+
return;
|
|
41
|
+
await withLedgerLock(async () => {
|
|
42
|
+
if (recoveredThisProcess)
|
|
43
|
+
return;
|
|
44
|
+
const records = await loadLedger();
|
|
45
|
+
if (records.some((r) => r.state === 'applying')) {
|
|
46
|
+
await saveLedger(trimLedger(recoverLedger(records, now)));
|
|
47
|
+
}
|
|
48
|
+
recoveredThisProcess = true;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function encryptJson(value) {
|
|
52
|
+
return encrypt(JSON.stringify(value));
|
|
53
|
+
}
|
|
54
|
+
function decryptJson(blob) {
|
|
55
|
+
return JSON.parse(decrypt(blob));
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Runs one request against the in-process Hono app. Never throws.
|
|
59
|
+
* Refuses (404) when the normalized pathname is not documented in OpenAPI.
|
|
60
|
+
* Response bodies over MAX_BODY_BYTES become 413.
|
|
61
|
+
*/
|
|
62
|
+
export async function applyMessage(app, msg) {
|
|
63
|
+
let pathname;
|
|
64
|
+
try {
|
|
65
|
+
pathname = new URL(msg.path, 'http://x').pathname;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return { status: 400, body: { error: 'Invalid message path.' } };
|
|
69
|
+
}
|
|
70
|
+
if (!isDocumentedRoute(msg.method, pathname)) {
|
|
71
|
+
return { status: 404, body: { error: 'Route is not documented in OpenAPI.' } };
|
|
72
|
+
}
|
|
73
|
+
const init = { method: msg.method };
|
|
74
|
+
if (msg.body !== undefined && msg.method !== 'GET' && msg.method !== 'HEAD') {
|
|
75
|
+
init.headers = { 'content-type': 'application/json' };
|
|
76
|
+
init.body = JSON.stringify(msg.body);
|
|
77
|
+
}
|
|
78
|
+
let res;
|
|
79
|
+
try {
|
|
80
|
+
res = await app.request(msg.path, init);
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
return { status: 500, body: { error: oneLineError(err) } };
|
|
84
|
+
}
|
|
85
|
+
let text;
|
|
86
|
+
try {
|
|
87
|
+
text = await res.text();
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
return { status: 500, body: { error: oneLineError(err) } };
|
|
91
|
+
}
|
|
92
|
+
if (Buffer.byteLength(text, 'utf8') > MAX_BODY_BYTES) {
|
|
93
|
+
return { status: 413, body: { error: 'Response body exceeded 1 MB limit.' } };
|
|
94
|
+
}
|
|
95
|
+
if (text === '') {
|
|
96
|
+
return { status: res.status, body: null };
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
return { status: res.status, body: JSON.parse(text) };
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return { status: res.status, body: text };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* One register-if-needed + poll cycle. Never throws; failures land in status.
|
|
107
|
+
*/
|
|
108
|
+
export function runCycle(deps) {
|
|
109
|
+
const run = cycleChain.then(() => cycleOnce(deps));
|
|
110
|
+
cycleChain = run.catch(() => undefined);
|
|
111
|
+
return run;
|
|
112
|
+
}
|
|
113
|
+
async function cycleOnce(deps) {
|
|
114
|
+
const now = deps.now ? deps.now() : new Date();
|
|
115
|
+
const gen = configGen;
|
|
116
|
+
const stale = () => gen !== configGen;
|
|
117
|
+
try {
|
|
118
|
+
await ensureRecovered(now);
|
|
119
|
+
const cfg = await loadOrchestrator();
|
|
120
|
+
if (stale())
|
|
121
|
+
return;
|
|
122
|
+
if (!cfg.enabled) {
|
|
123
|
+
registered = false;
|
|
124
|
+
status = { state: 'off' };
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const token = cfg.token ? decrypt(cfg.token) : '';
|
|
128
|
+
if (!cfg.endpoint || !token) {
|
|
129
|
+
registered = false;
|
|
130
|
+
status = { state: 'error', lastError: 'Endpoint and token are required.' };
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const headers = {
|
|
134
|
+
authorization: `Bearer ${token}`,
|
|
135
|
+
'content-type': 'application/json',
|
|
136
|
+
};
|
|
137
|
+
if (!registered) {
|
|
138
|
+
status = {
|
|
139
|
+
state: 'registering',
|
|
140
|
+
...(status.orchestratorName ? { orchestratorName: status.orchestratorName } : {}),
|
|
141
|
+
...(status.lastPollAt ? { lastPollAt: status.lastPollAt } : {}),
|
|
142
|
+
};
|
|
143
|
+
const regRes = await deps.fetch(endpointUrl(cfg.endpoint, 'register'), {
|
|
144
|
+
method: 'POST',
|
|
145
|
+
headers,
|
|
146
|
+
body: JSON.stringify({
|
|
147
|
+
protocol: PROTOCOL_VERSION,
|
|
148
|
+
instanceId: cfg.instanceId,
|
|
149
|
+
name: cfg.name,
|
|
150
|
+
version: cliVersion(),
|
|
151
|
+
}),
|
|
152
|
+
signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
|
|
153
|
+
});
|
|
154
|
+
if (stale())
|
|
155
|
+
return;
|
|
156
|
+
if (!regRes.ok) {
|
|
157
|
+
status = { ...status, state: 'error', lastError: `Register failed: HTTP ${regRes.status}` };
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
let regData;
|
|
161
|
+
try {
|
|
162
|
+
regData = JSON.parse(await regRes.text());
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
if (stale())
|
|
166
|
+
return;
|
|
167
|
+
status = { ...status, state: 'error', lastError: 'Register returned non-JSON response.' };
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (stale())
|
|
171
|
+
return;
|
|
172
|
+
if (!regData || typeof regData !== 'object' || regData.ok !== true) {
|
|
173
|
+
status = { ...status, state: 'error', lastError: 'Register response did not confirm ok.' };
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const orchName = typeof regData.name === 'string'
|
|
177
|
+
? regData.name
|
|
178
|
+
: status.orchestratorName;
|
|
179
|
+
registered = true;
|
|
180
|
+
status = {
|
|
181
|
+
state: 'registering',
|
|
182
|
+
...(orchName !== undefined ? { orchestratorName: orchName } : {}),
|
|
183
|
+
...(status.lastPollAt ? { lastPollAt: status.lastPollAt } : {}),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const pendingResults = await withLedgerLock(async () => {
|
|
187
|
+
const records = await loadLedger();
|
|
188
|
+
return records
|
|
189
|
+
.filter((r) => r.state === 'done' && !r.delivered && r.result)
|
|
190
|
+
.map((r) => ({
|
|
191
|
+
id: r.id,
|
|
192
|
+
status: r.result.status,
|
|
193
|
+
body: r.result.body !== undefined ? decryptJson(r.result.body) : null,
|
|
194
|
+
}));
|
|
195
|
+
});
|
|
196
|
+
const pollRes = await deps.fetch(endpointUrl(cfg.endpoint, 'poll'), {
|
|
197
|
+
method: 'POST',
|
|
198
|
+
headers,
|
|
199
|
+
body: JSON.stringify({
|
|
200
|
+
instanceId: cfg.instanceId,
|
|
201
|
+
results: pendingResults,
|
|
202
|
+
}),
|
|
203
|
+
signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
|
|
204
|
+
});
|
|
205
|
+
if (stale())
|
|
206
|
+
return;
|
|
207
|
+
if (pollRes.status === 401 ||
|
|
208
|
+
pollRes.status === 403 ||
|
|
209
|
+
pollRes.status === 404 ||
|
|
210
|
+
pollRes.status === 409) {
|
|
211
|
+
registered = false;
|
|
212
|
+
status = { ...status, state: 'error', lastError: `Poll rejected: HTTP ${pollRes.status}` };
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (!pollRes.ok) {
|
|
216
|
+
status = { ...status, state: 'error', lastError: `Poll failed: HTTP ${pollRes.status}` };
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
let pollData;
|
|
220
|
+
try {
|
|
221
|
+
pollData = JSON.parse(await pollRes.text());
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
if (stale())
|
|
225
|
+
return;
|
|
226
|
+
status = { ...status, state: 'error', lastError: 'Poll returned non-JSON response.' };
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (stale())
|
|
230
|
+
return;
|
|
231
|
+
if (!pollData ||
|
|
232
|
+
typeof pollData !== 'object' ||
|
|
233
|
+
Array.isArray(pollData) ||
|
|
234
|
+
!Array.isArray(pollData.messages)) {
|
|
235
|
+
status = { ...status, state: 'error', lastError: 'Poll response missing messages array.' };
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (pendingResults.length > 0) {
|
|
239
|
+
const deliveredIds = new Set(pendingResults.map((r) => r.id));
|
|
240
|
+
await withLedgerLock(async () => {
|
|
241
|
+
const records = await loadLedger();
|
|
242
|
+
let changed = false;
|
|
243
|
+
for (const r of records) {
|
|
244
|
+
if (deliveredIds.has(r.id) && !r.delivered) {
|
|
245
|
+
r.delivered = true;
|
|
246
|
+
if (r.result)
|
|
247
|
+
delete r.result.body;
|
|
248
|
+
changed = true;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (changed) {
|
|
252
|
+
await saveLedger(trimLedger(records));
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
status = {
|
|
257
|
+
state: 'connected',
|
|
258
|
+
...(status.orchestratorName !== undefined ? { orchestratorName: status.orchestratorName } : {}),
|
|
259
|
+
lastPollAt: now.toISOString(),
|
|
260
|
+
};
|
|
261
|
+
const messages = pollData.messages;
|
|
262
|
+
for (const raw of messages) {
|
|
263
|
+
if (stale())
|
|
264
|
+
return;
|
|
265
|
+
const parsed = parseMessage(raw);
|
|
266
|
+
if (parsed === null) {
|
|
267
|
+
status = { ...status, lastError: 'The orchestrator sent a message without an id.' };
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if ('error' in parsed) {
|
|
271
|
+
await withLedgerLock(async () => {
|
|
272
|
+
const records = await loadLedger();
|
|
273
|
+
if (stale() || records.some((r) => r.id === parsed.id))
|
|
274
|
+
return;
|
|
275
|
+
records.push({
|
|
276
|
+
id: parsed.id,
|
|
277
|
+
method: '',
|
|
278
|
+
path: '',
|
|
279
|
+
receivedAt: now.toISOString(),
|
|
280
|
+
state: 'done',
|
|
281
|
+
result: { status: 400, body: encryptJson({ error: parsed.error }) },
|
|
282
|
+
resolvedAt: now.toISOString(),
|
|
283
|
+
delivered: false,
|
|
284
|
+
});
|
|
285
|
+
await saveLedger(trimLedger(records));
|
|
286
|
+
});
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
const pathname = new URL(parsed.path, 'http://x').pathname;
|
|
290
|
+
if (!isDocumentedRoute(parsed.method, pathname)) {
|
|
291
|
+
await withLedgerLock(async () => {
|
|
292
|
+
const records = await loadLedger();
|
|
293
|
+
if (stale() || records.some((r) => r.id === parsed.id))
|
|
294
|
+
return;
|
|
295
|
+
records.push({
|
|
296
|
+
id: parsed.id,
|
|
297
|
+
method: parsed.method,
|
|
298
|
+
path: parsed.path,
|
|
299
|
+
receivedAt: now.toISOString(),
|
|
300
|
+
state: 'done',
|
|
301
|
+
result: { status: 404, body: encryptJson({ error: 'Route is not documented in OpenAPI.' }) },
|
|
302
|
+
resolvedAt: now.toISOString(),
|
|
303
|
+
delivered: false,
|
|
304
|
+
});
|
|
305
|
+
await saveLedger(trimLedger(records));
|
|
306
|
+
});
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (needsApproval(cfg.policy, parsed.method)) {
|
|
310
|
+
await withLedgerLock(async () => {
|
|
311
|
+
const records = await loadLedger();
|
|
312
|
+
if (stale() || records.some((r) => r.id === parsed.id))
|
|
313
|
+
return;
|
|
314
|
+
records.push({
|
|
315
|
+
id: parsed.id,
|
|
316
|
+
method: parsed.method,
|
|
317
|
+
path: parsed.path,
|
|
318
|
+
...(parsed.body !== undefined ? { body: encryptJson(parsed.body) } : {}),
|
|
319
|
+
receivedAt: now.toISOString(),
|
|
320
|
+
state: 'pending',
|
|
321
|
+
delivered: false,
|
|
322
|
+
});
|
|
323
|
+
await saveLedger(trimLedger(records));
|
|
324
|
+
});
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
const claimed = await withLedgerLock(async () => {
|
|
328
|
+
const records = await loadLedger();
|
|
329
|
+
if (stale() || records.some((r) => r.id === parsed.id))
|
|
330
|
+
return false;
|
|
331
|
+
records.push({
|
|
332
|
+
id: parsed.id,
|
|
333
|
+
method: parsed.method,
|
|
334
|
+
path: parsed.path,
|
|
335
|
+
...(parsed.body !== undefined ? { body: encryptJson(parsed.body) } : {}),
|
|
336
|
+
receivedAt: now.toISOString(),
|
|
337
|
+
state: 'applying',
|
|
338
|
+
delivered: false,
|
|
339
|
+
});
|
|
340
|
+
await saveLedger(trimLedger(records));
|
|
341
|
+
return true;
|
|
342
|
+
});
|
|
343
|
+
if (!claimed)
|
|
344
|
+
continue;
|
|
345
|
+
const applied = await applyMessage(deps.app, parsed);
|
|
346
|
+
const resolvedAt = (deps.now ? deps.now() : new Date()).toISOString();
|
|
347
|
+
await withLedgerLock(async () => {
|
|
348
|
+
const records = await loadLedger();
|
|
349
|
+
const rec = records.find((r) => r.id === parsed.id);
|
|
350
|
+
if (!rec || rec.state !== 'applying')
|
|
351
|
+
return;
|
|
352
|
+
delete rec.body;
|
|
353
|
+
rec.state = 'done';
|
|
354
|
+
rec.resolvedAt = resolvedAt;
|
|
355
|
+
rec.result = { status: applied.status, body: encryptJson(applied.body) };
|
|
356
|
+
await saveLedger(trimLedger(records));
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
if (!stale())
|
|
362
|
+
status = { ...status, state: 'error', lastError: oneLineError(err) };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Approves or rejects a pending ledger message.
|
|
367
|
+
*/
|
|
368
|
+
export async function resolvePending(app, id, decision) {
|
|
369
|
+
const step = await withLedgerLock(async () => {
|
|
370
|
+
const records = await loadLedger();
|
|
371
|
+
const rec = records.find((r) => r.id === id);
|
|
372
|
+
if (!rec)
|
|
373
|
+
return { status: 'not_found' };
|
|
374
|
+
if (rec.state !== 'pending')
|
|
375
|
+
return { status: 'not_pending' };
|
|
376
|
+
if (decision === 'reject') {
|
|
377
|
+
delete rec.body;
|
|
378
|
+
rec.state = 'done';
|
|
379
|
+
rec.resolvedAt = new Date().toISOString();
|
|
380
|
+
rec.result = { status: 403, body: encryptJson({ error: 'Rejected by the user.' }) };
|
|
381
|
+
await saveLedger(trimLedger(records));
|
|
382
|
+
return { status: 'ok' };
|
|
383
|
+
}
|
|
384
|
+
rec.state = 'applying';
|
|
385
|
+
const msg = {
|
|
386
|
+
id: rec.id,
|
|
387
|
+
method: rec.method,
|
|
388
|
+
path: rec.path,
|
|
389
|
+
...(rec.body !== undefined ? { body: decryptJson(rec.body) } : {}),
|
|
390
|
+
};
|
|
391
|
+
await saveLedger(trimLedger(records));
|
|
392
|
+
return { status: 'apply', msg };
|
|
393
|
+
});
|
|
394
|
+
if (step.status !== 'apply')
|
|
395
|
+
return step.status;
|
|
396
|
+
const applied = await applyMessage(app, step.msg);
|
|
397
|
+
const resolvedAt = new Date().toISOString();
|
|
398
|
+
await withLedgerLock(async () => {
|
|
399
|
+
const records = await loadLedger();
|
|
400
|
+
const rec = records.find((r) => r.id === id);
|
|
401
|
+
if (!rec || rec.state !== 'applying')
|
|
402
|
+
return;
|
|
403
|
+
delete rec.body;
|
|
404
|
+
rec.state = 'done';
|
|
405
|
+
rec.resolvedAt = resolvedAt;
|
|
406
|
+
rec.result = { status: applied.status, body: encryptJson(applied.body) };
|
|
407
|
+
await saveLedger(trimLedger(records));
|
|
408
|
+
});
|
|
409
|
+
return 'ok';
|
|
410
|
+
}
|
|
411
|
+
export function orchestratorStatus() {
|
|
412
|
+
return { ...status };
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Config-save hook: forgets the registration and the status, and retires any
|
|
416
|
+
* cycle still running under the previous configuration. Leaves the boot
|
|
417
|
+
* recovery alone: it runs once per process, and re-running it would settle a
|
|
418
|
+
* message that is being applied right now as an interrupted one.
|
|
419
|
+
*/
|
|
420
|
+
export function resetOrchestrator() {
|
|
421
|
+
configGen++;
|
|
422
|
+
registered = false;
|
|
423
|
+
status = { state: 'off' };
|
|
424
|
+
}
|
|
425
|
+
/** Tests only: also re-arms the once-per-process boot recovery. */
|
|
426
|
+
export function resetOrchestratorForTests() {
|
|
427
|
+
resetOrchestrator();
|
|
428
|
+
recoveredThisProcess = false;
|
|
429
|
+
}
|
|
430
|
+
export function stopOrchestrator() {
|
|
431
|
+
loopGen++;
|
|
432
|
+
if (loopTimer !== null) {
|
|
433
|
+
clearTimeout(loopTimer);
|
|
434
|
+
loopTimer = null;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* (Re)starts the self-rescheduling poll loop from the saved config.
|
|
439
|
+
* Runs recoverLedger once per process before the first cycle.
|
|
440
|
+
*/
|
|
441
|
+
export function startOrchestrator(app, fetchImpl = fetch) {
|
|
442
|
+
stopOrchestrator();
|
|
443
|
+
const gen = loopGen;
|
|
444
|
+
const tick = async () => {
|
|
445
|
+
if (gen !== loopGen)
|
|
446
|
+
return;
|
|
447
|
+
try {
|
|
448
|
+
await ensureRecovered(new Date());
|
|
449
|
+
await runCycle({ app, fetch: fetchImpl });
|
|
450
|
+
}
|
|
451
|
+
catch (err) {
|
|
452
|
+
console.error('[orchestrator]', err);
|
|
453
|
+
}
|
|
454
|
+
if (gen !== loopGen)
|
|
455
|
+
return;
|
|
456
|
+
let delayMs = 15_000;
|
|
457
|
+
try {
|
|
458
|
+
const cfg = await loadOrchestrator();
|
|
459
|
+
if (!cfg.enabled)
|
|
460
|
+
return;
|
|
461
|
+
delayMs = cfg.pollSeconds * 1000;
|
|
462
|
+
}
|
|
463
|
+
catch (err) {
|
|
464
|
+
console.error('[orchestrator]', err);
|
|
465
|
+
}
|
|
466
|
+
if (gen !== loopGen)
|
|
467
|
+
return;
|
|
468
|
+
loopTimer = setTimeout(() => {
|
|
469
|
+
void tick();
|
|
470
|
+
}, delayMs);
|
|
471
|
+
};
|
|
472
|
+
void tick();
|
|
473
|
+
}
|
|
474
|
+
async function buildView() {
|
|
475
|
+
const cfg = await loadOrchestrator();
|
|
476
|
+
const ledger = await loadLedger();
|
|
477
|
+
return {
|
|
478
|
+
config: {
|
|
479
|
+
enabled: cfg.enabled,
|
|
480
|
+
name: cfg.name,
|
|
481
|
+
endpoint: cfg.endpoint,
|
|
482
|
+
hasToken: Boolean(cfg.token),
|
|
483
|
+
pollSeconds: cfg.pollSeconds,
|
|
484
|
+
policy: cfg.policy,
|
|
485
|
+
instanceId: cfg.instanceId,
|
|
486
|
+
},
|
|
487
|
+
status: orchestratorStatus(),
|
|
488
|
+
pending: ledger.filter((r) => r.state === 'pending').length,
|
|
489
|
+
messages: summarizeLedger(ledger),
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
export function registerOrchestrator(app, fetchImpl = fetch) {
|
|
493
|
+
app.get('/api/orchestrator', async (c) => {
|
|
494
|
+
return c.json(await buildView());
|
|
495
|
+
});
|
|
496
|
+
app.put('/api/orchestrator', async (c) => {
|
|
497
|
+
let body;
|
|
498
|
+
try {
|
|
499
|
+
body = (await c.req.json());
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
return c.json({ error: 'Invalid JSON body.' }, 400);
|
|
503
|
+
}
|
|
504
|
+
const saved = await loadOrchestrator();
|
|
505
|
+
const merged = mergeConfigSave(saved, body);
|
|
506
|
+
if ('error' in merged) {
|
|
507
|
+
return c.json({ error: merged.error }, 400);
|
|
508
|
+
}
|
|
509
|
+
// Retire the running loop and any in-flight cycle first, so nothing filed
|
|
510
|
+
// under the old configuration lands after the purge below.
|
|
511
|
+
stopOrchestrator();
|
|
512
|
+
resetOrchestrator();
|
|
513
|
+
await saveOrchestrator(merged.config);
|
|
514
|
+
if (merged.purgeLedger) {
|
|
515
|
+
await withLedgerLock(() => saveLedger([]));
|
|
516
|
+
}
|
|
517
|
+
startOrchestrator(app, fetchImpl);
|
|
518
|
+
return c.json(await buildView());
|
|
519
|
+
});
|
|
520
|
+
app.post('/api/orchestrator/test', async (c) => {
|
|
521
|
+
let body;
|
|
522
|
+
try {
|
|
523
|
+
body = (await c.req.json());
|
|
524
|
+
}
|
|
525
|
+
catch {
|
|
526
|
+
return c.json({ ok: false, error: 'Invalid JSON body.' });
|
|
527
|
+
}
|
|
528
|
+
const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : '';
|
|
529
|
+
if (!endpoint) {
|
|
530
|
+
return c.json({ ok: false, error: 'Endpoint is required.' });
|
|
531
|
+
}
|
|
532
|
+
const endpointErr = validateEndpoint(endpoint);
|
|
533
|
+
if (endpointErr) {
|
|
534
|
+
return c.json({ ok: false, error: endpointErr });
|
|
535
|
+
}
|
|
536
|
+
const saved = await loadOrchestrator();
|
|
537
|
+
const typedToken = typeof body.token === 'string' ? body.token.trim() : '';
|
|
538
|
+
let token = '';
|
|
539
|
+
if (typedToken) {
|
|
540
|
+
token = typedToken;
|
|
541
|
+
}
|
|
542
|
+
else if (sameHost(saved.endpoint, endpoint) && saved.token) {
|
|
543
|
+
try {
|
|
544
|
+
token = decrypt(saved.token);
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
token = '';
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (!token) {
|
|
551
|
+
return c.json({ ok: false, error: 'Token is required.' });
|
|
552
|
+
}
|
|
553
|
+
try {
|
|
554
|
+
const res = await fetchImpl(endpointUrl(endpoint, 'health'), {
|
|
555
|
+
method: 'GET',
|
|
556
|
+
headers: { authorization: `Bearer ${token}` },
|
|
557
|
+
signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
|
|
558
|
+
});
|
|
559
|
+
if (!res.ok) {
|
|
560
|
+
return c.json({ ok: false, error: `HTTP ${res.status}` });
|
|
561
|
+
}
|
|
562
|
+
const data = JSON.parse(await res.text());
|
|
563
|
+
if (data.protocol !== PROTOCOL_VERSION) {
|
|
564
|
+
return c.json({
|
|
565
|
+
ok: false,
|
|
566
|
+
protocol: data.protocol,
|
|
567
|
+
error: `Protocol mismatch: orchestrator reported ${String(data.protocol)}, expected ${PROTOCOL_VERSION}.`,
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
return c.json({
|
|
571
|
+
ok: true,
|
|
572
|
+
name: typeof data.name === 'string' ? data.name : '',
|
|
573
|
+
protocol: PROTOCOL_VERSION,
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
catch (err) {
|
|
577
|
+
return c.json({ ok: false, error: oneLineError(err) });
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
app.post('/api/orchestrator/messages/:id/approve', async (c) => {
|
|
581
|
+
const result = await resolvePending(app, c.req.param('id'), 'approve');
|
|
582
|
+
if (result === 'not_found')
|
|
583
|
+
return c.json({ error: 'Message not found.' }, 404);
|
|
584
|
+
if (result === 'not_pending')
|
|
585
|
+
return c.json({ error: 'Message is not pending.' }, 409);
|
|
586
|
+
return c.json({ ok: true });
|
|
587
|
+
});
|
|
588
|
+
app.post('/api/orchestrator/messages/:id/reject', async (c) => {
|
|
589
|
+
const result = await resolvePending(app, c.req.param('id'), 'reject');
|
|
590
|
+
if (result === 'not_found')
|
|
591
|
+
return c.json({ error: 'Message not found.' }, 404);
|
|
592
|
+
if (result === 'not_pending')
|
|
593
|
+
return c.json({ error: 'Message is not pending.' }, 409);
|
|
594
|
+
return c.json({ ok: true });
|
|
595
|
+
});
|
|
596
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { LedgerRecord, OrchestratorConfig, OrchestratorPolicy } from '../../store/orchestrator.js';
|
|
2
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
3
|
+
export declare const MAX_BODY_BYTES = 1048576;
|
|
4
|
+
export declare const LEDGER_SIZE = 500;
|
|
5
|
+
export interface RemoteMessage {
|
|
6
|
+
id: string;
|
|
7
|
+
method: string;
|
|
8
|
+
path: string;
|
|
9
|
+
body?: unknown;
|
|
10
|
+
}
|
|
11
|
+
export interface ConfigInput {
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
name: string;
|
|
14
|
+
endpoint: string;
|
|
15
|
+
token?: string;
|
|
16
|
+
pollSeconds: unknown;
|
|
17
|
+
policy: unknown;
|
|
18
|
+
}
|
|
19
|
+
export interface MessageSummary {
|
|
20
|
+
id: string;
|
|
21
|
+
method: string;
|
|
22
|
+
path: string;
|
|
23
|
+
receivedAt: string;
|
|
24
|
+
state: LedgerRecord['state'];
|
|
25
|
+
status?: number;
|
|
26
|
+
resolvedAt?: string;
|
|
27
|
+
delivered: boolean;
|
|
28
|
+
/** Present on pending records only; any `repositoryToken` key is masked. */
|
|
29
|
+
body?: unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Validates an orchestrator base URL: `https` anywhere, `http` only on loopback,
|
|
33
|
+
* and never with embedded userinfo. Returns null when valid, or an error string.
|
|
34
|
+
*/
|
|
35
|
+
export declare function validateEndpoint(endpoint: string): string | null;
|
|
36
|
+
/**
|
|
37
|
+
* Clamps poll interval in seconds to 5..3600, defaulting to 15.
|
|
38
|
+
*/
|
|
39
|
+
export declare function clampPollSeconds(value: unknown): number;
|
|
40
|
+
/**
|
|
41
|
+
* Builds `${endpoint without trailing slashes}/${call}`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function endpointUrl(endpoint: string, call: 'health' | 'register' | 'poll'): string;
|
|
44
|
+
/**
|
|
45
|
+
* Parses and normalizes an incoming orchestrator message.
|
|
46
|
+
* - `null`: no usable id (drop, not ledgered).
|
|
47
|
+
* - `{ id, error }`: ledger a 400 result.
|
|
48
|
+
* - `RemoteMessage`: `path` rewritten to normalized pathname + query.
|
|
49
|
+
*/
|
|
50
|
+
export declare function parseMessage(raw: unknown): RemoteMessage | {
|
|
51
|
+
id: string;
|
|
52
|
+
error: string;
|
|
53
|
+
} | null;
|
|
54
|
+
/**
|
|
55
|
+
* True when the policy requires manual approval for this HTTP method.
|
|
56
|
+
*/
|
|
57
|
+
export declare function needsApproval(policy: OrchestratorPolicy, method: string): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Boot recovery: every `applying` record becomes `done` with a 500 result
|
|
60
|
+
* and its request body removed.
|
|
61
|
+
*/
|
|
62
|
+
export declare function recoverLedger(records: LedgerRecord[], now: Date): LedgerRecord[];
|
|
63
|
+
/**
|
|
64
|
+
* Keeps every record that is not (done && delivered), then the newest
|
|
65
|
+
* done+delivered ones until the total is LEDGER_SIZE. Order preserved.
|
|
66
|
+
*/
|
|
67
|
+
export declare function trimLedger(records: LedgerRecord[]): LedgerRecord[];
|
|
68
|
+
/**
|
|
69
|
+
* Applies settings-save rules. A blank token keeps the stored blob unless the
|
|
70
|
+
* endpoint host changed (in which case the token is dropped and `purgeLedger` is true).
|
|
71
|
+
*/
|
|
72
|
+
export declare function mergeConfigSave(saved: OrchestratorConfig, input: ConfigInput): {
|
|
73
|
+
config: OrchestratorConfig;
|
|
74
|
+
purgeLedger: boolean;
|
|
75
|
+
} | {
|
|
76
|
+
error: string;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Returns ledger records as view summaries (newest first).
|
|
80
|
+
* Request body is included only for `pending` records, with `repositoryToken` masked.
|
|
81
|
+
*/
|
|
82
|
+
export declare function summarizeLedger(records: LedgerRecord[]): MessageSummary[];
|
|
83
|
+
//# sourceMappingURL=orchestrator_core.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrator_core.d.ts","sourceRoot":"","sources":["../../../src/cli/web/orchestrator_core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAGxG,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAClC,eAAO,MAAM,cAAc,UAAY,CAAC;AACxC,eAAO,MAAM,WAAW,MAAM,CAAC;AAE/B,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,MAAM,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,4EAA4E;IAC5E,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AASD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAiBhE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CASvD;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,UAAU,GAAG,MAAM,GAAG,MAAM,CAE1F;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,aAAa,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAqC/F;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAEjF;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,GAAG,EAAE,IAAI,GAAG,YAAY,EAAE,CAahF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE,CAmBlE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,kBAAkB,EACzB,KAAK,EAAE,WAAW,GACjB;IAAE,MAAM,EAAE,kBAAkB,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAyB1E;AAgBD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,cAAc,EAAE,CAwBzE"}
|