@femtomc/mu-server 26.2.69 → 26.2.71

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.
Files changed (58) hide show
  1. package/README.md +7 -3
  2. package/dist/api/activities.d.ts +2 -0
  3. package/dist/api/activities.js +160 -0
  4. package/dist/api/config.d.ts +2 -0
  5. package/dist/api/config.js +45 -0
  6. package/dist/api/control_plane.d.ts +2 -0
  7. package/dist/api/control_plane.js +28 -0
  8. package/dist/api/cron.d.ts +2 -0
  9. package/dist/api/cron.js +182 -0
  10. package/dist/api/events.js +77 -19
  11. package/dist/api/forum.js +52 -18
  12. package/dist/api/heartbeats.d.ts +2 -0
  13. package/dist/api/heartbeats.js +211 -0
  14. package/dist/api/identities.d.ts +2 -0
  15. package/dist/api/identities.js +103 -0
  16. package/dist/api/issues.js +120 -33
  17. package/dist/api/runs.d.ts +2 -0
  18. package/dist/api/runs.js +207 -0
  19. package/dist/cli.js +58 -3
  20. package/dist/config.d.ts +4 -21
  21. package/dist/config.js +24 -75
  22. package/dist/control_plane.d.ts +7 -114
  23. package/dist/control_plane.js +238 -654
  24. package/dist/control_plane_bootstrap_helpers.d.ts +16 -0
  25. package/dist/control_plane_bootstrap_helpers.js +85 -0
  26. package/dist/control_plane_contract.d.ts +176 -0
  27. package/dist/control_plane_contract.js +1 -0
  28. package/dist/control_plane_reload.d.ts +63 -0
  29. package/dist/control_plane_reload.js +525 -0
  30. package/dist/control_plane_run_outbox.d.ts +7 -0
  31. package/dist/control_plane_run_outbox.js +52 -0
  32. package/dist/control_plane_run_queue_coordinator.d.ts +48 -0
  33. package/dist/control_plane_run_queue_coordinator.js +327 -0
  34. package/dist/control_plane_telegram_generation.d.ts +27 -0
  35. package/dist/control_plane_telegram_generation.js +520 -0
  36. package/dist/control_plane_wake_delivery.d.ts +50 -0
  37. package/dist/control_plane_wake_delivery.js +123 -0
  38. package/dist/cron_request.d.ts +8 -0
  39. package/dist/cron_request.js +65 -0
  40. package/dist/index.d.ts +7 -2
  41. package/dist/index.js +4 -1
  42. package/dist/run_queue.d.ts +95 -0
  43. package/dist/run_queue.js +817 -0
  44. package/dist/run_supervisor.d.ts +20 -0
  45. package/dist/run_supervisor.js +25 -1
  46. package/dist/server.d.ts +12 -49
  47. package/dist/server.js +365 -2128
  48. package/dist/server_program_orchestration.d.ts +38 -0
  49. package/dist/server_program_orchestration.js +254 -0
  50. package/dist/server_routing.d.ts +31 -0
  51. package/dist/server_routing.js +230 -0
  52. package/dist/server_runtime.d.ts +30 -0
  53. package/dist/server_runtime.js +43 -0
  54. package/dist/server_types.d.ts +3 -0
  55. package/dist/server_types.js +16 -0
  56. package/dist/session_lifecycle.d.ts +11 -0
  57. package/dist/session_lifecycle.js +149 -0
  58. package/package.json +7 -6
@@ -0,0 +1,520 @@
1
+ import { TelegramControlPlaneAdapter, } from "@femtomc/mu-control-plane";
2
+ const TELEGRAM_GENERATION_SUPERVISOR_ID = "telegram-adapter";
3
+ const TELEGRAM_WARMUP_TIMEOUT_MS = 2_000;
4
+ const TELEGRAM_DRAIN_TIMEOUT_MS = 5_000;
5
+ function cloneControlPlaneConfig(config) {
6
+ return JSON.parse(JSON.stringify(config));
7
+ }
8
+ function controlPlaneNonTelegramFingerprint(config) {
9
+ return JSON.stringify({
10
+ adapters: {
11
+ slack: config.adapters.slack,
12
+ discord: config.adapters.discord,
13
+ },
14
+ operator: config.operator,
15
+ });
16
+ }
17
+ function telegramAdapterConfigFromControlPlane(config) {
18
+ const webhookSecret = config.adapters.telegram.webhook_secret;
19
+ if (!webhookSecret) {
20
+ return null;
21
+ }
22
+ return {
23
+ webhookSecret,
24
+ botToken: config.adapters.telegram.bot_token,
25
+ botUsername: config.adapters.telegram.bot_username,
26
+ };
27
+ }
28
+ function applyTelegramAdapterConfig(base, telegram) {
29
+ const next = cloneControlPlaneConfig(base);
30
+ next.adapters.telegram.webhook_secret = telegram?.webhookSecret ?? null;
31
+ next.adapters.telegram.bot_token = telegram?.botToken ?? null;
32
+ next.adapters.telegram.bot_username = telegram?.botUsername ?? null;
33
+ return next;
34
+ }
35
+ function cloneTelegramAdapterConfig(config) {
36
+ return {
37
+ webhookSecret: config.webhookSecret,
38
+ botToken: config.botToken,
39
+ botUsername: config.botUsername,
40
+ };
41
+ }
42
+ function describeError(err) {
43
+ if (err instanceof Error && err.message.trim().length > 0) {
44
+ return err.message;
45
+ }
46
+ return String(err);
47
+ }
48
+ async function runWithTimeout(opts) {
49
+ if (opts.timeoutMs <= 0) {
50
+ return await opts.run();
51
+ }
52
+ return await new Promise((resolve, reject) => {
53
+ let settled = false;
54
+ const timer = setTimeout(() => {
55
+ if (settled) {
56
+ return;
57
+ }
58
+ settled = true;
59
+ reject(new Error(opts.timeoutMessage));
60
+ }, opts.timeoutMs);
61
+ void opts
62
+ .run()
63
+ .then((value) => {
64
+ if (settled) {
65
+ return;
66
+ }
67
+ settled = true;
68
+ clearTimeout(timer);
69
+ resolve(value);
70
+ })
71
+ .catch((err) => {
72
+ if (settled) {
73
+ return;
74
+ }
75
+ settled = true;
76
+ clearTimeout(timer);
77
+ reject(err);
78
+ });
79
+ });
80
+ }
81
+ export class TelegramAdapterGenerationManager {
82
+ #pipeline;
83
+ #outbox;
84
+ #nowMs;
85
+ #onOutboxEnqueued;
86
+ #signalObserver;
87
+ #hooks;
88
+ #generationSeq = -1;
89
+ #active = null;
90
+ #previousConfig = null;
91
+ #activeControlPlaneConfig;
92
+ constructor(opts) {
93
+ this.#pipeline = opts.pipeline;
94
+ this.#outbox = opts.outbox;
95
+ this.#nowMs = opts.nowMs ?? Date.now;
96
+ this.#onOutboxEnqueued = opts.onOutboxEnqueued ?? null;
97
+ this.#signalObserver = opts.signalObserver ?? null;
98
+ this.#hooks = opts.hooks ?? null;
99
+ this.#activeControlPlaneConfig = cloneControlPlaneConfig(opts.initialConfig);
100
+ }
101
+ #nextGeneration() {
102
+ const nextSeq = this.#generationSeq + 1;
103
+ return {
104
+ generation_id: `${TELEGRAM_GENERATION_SUPERVISOR_ID}-gen-${nextSeq}`,
105
+ generation_seq: nextSeq,
106
+ };
107
+ }
108
+ #buildAdapter(config, opts) {
109
+ return new TelegramControlPlaneAdapter({
110
+ pipeline: this.#pipeline,
111
+ outbox: this.#outbox,
112
+ webhookSecret: config.webhookSecret,
113
+ botUsername: config.botUsername,
114
+ deferredIngress: true,
115
+ onOutboxEnqueued: this.#onOutboxEnqueued ?? undefined,
116
+ signalObserver: this.#signalObserver ?? undefined,
117
+ acceptIngress: opts.acceptIngress,
118
+ ingressDrainEnabled: opts.ingressDrainEnabled,
119
+ nowMs: this.#nowMs,
120
+ });
121
+ }
122
+ async initialize() {
123
+ const initial = telegramAdapterConfigFromControlPlane(this.#activeControlPlaneConfig);
124
+ if (!initial) {
125
+ return;
126
+ }
127
+ const generation = this.#nextGeneration();
128
+ const adapter = this.#buildAdapter(initial, {
129
+ acceptIngress: true,
130
+ ingressDrainEnabled: true,
131
+ });
132
+ await adapter.warmup();
133
+ const health = await adapter.healthCheck();
134
+ if (!health.ok) {
135
+ await adapter.stop({ force: true, reason: "startup_health_gate_failed" });
136
+ throw new Error(`telegram adapter warmup health failed: ${health.reason}`);
137
+ }
138
+ this.#active = {
139
+ generation,
140
+ config: cloneTelegramAdapterConfig(initial),
141
+ adapter,
142
+ };
143
+ this.#generationSeq = generation.generation_seq;
144
+ }
145
+ hasActiveGeneration() {
146
+ return this.#active != null;
147
+ }
148
+ activeGeneration() {
149
+ return this.#active ? { ...this.#active.generation } : null;
150
+ }
151
+ activeBotToken() {
152
+ return this.#active?.config.botToken ?? null;
153
+ }
154
+ activeAdapter() {
155
+ return this.#active?.adapter ?? null;
156
+ }
157
+ canHandleConfig(nextConfig, reason) {
158
+ if (reason === "rollback") {
159
+ return true;
160
+ }
161
+ return (controlPlaneNonTelegramFingerprint(nextConfig) ===
162
+ controlPlaneNonTelegramFingerprint(this.#activeControlPlaneConfig));
163
+ }
164
+ async #rollbackToPrevious(opts) {
165
+ if (!opts.previous) {
166
+ return { ok: false, error: "rollback_unavailable" };
167
+ }
168
+ try {
169
+ opts.previous.adapter.activateIngress();
170
+ this.#active = opts.previous;
171
+ this.#previousConfig = cloneTelegramAdapterConfig(opts.failedRecord.config);
172
+ await opts.failedRecord.adapter.stop({ force: true, reason: `rollback:${opts.reason}` });
173
+ this.#activeControlPlaneConfig = applyTelegramAdapterConfig(this.#activeControlPlaneConfig, opts.previous.config);
174
+ return { ok: true };
175
+ }
176
+ catch (err) {
177
+ return { ok: false, error: describeError(err) };
178
+ }
179
+ }
180
+ async reload(opts) {
181
+ if (!this.canHandleConfig(opts.config, opts.reason)) {
182
+ return {
183
+ handled: false,
184
+ ok: false,
185
+ reason: opts.reason,
186
+ route: "/webhooks/telegram",
187
+ from_generation: this.#active?.generation ?? null,
188
+ to_generation: null,
189
+ active_generation: this.#active?.generation ?? null,
190
+ warmup: null,
191
+ cutover: null,
192
+ drain: null,
193
+ rollback: {
194
+ requested: opts.reason === "rollback",
195
+ trigger: null,
196
+ attempted: false,
197
+ ok: true,
198
+ },
199
+ };
200
+ }
201
+ const rollbackRequested = opts.reason === "rollback";
202
+ let rollbackTrigger = rollbackRequested ? "manual" : null;
203
+ let rollbackAttempted = false;
204
+ let rollbackOk = true;
205
+ let rollbackError;
206
+ const fromGeneration = this.#active?.generation ?? null;
207
+ const previousRecord = this.#active;
208
+ const warmupTimeoutMs = Math.max(0, Math.trunc(opts.warmupTimeoutMs ?? TELEGRAM_WARMUP_TIMEOUT_MS));
209
+ const drainTimeoutMs = Math.max(0, Math.trunc(opts.drainTimeoutMs ?? TELEGRAM_DRAIN_TIMEOUT_MS));
210
+ const targetConfig = rollbackRequested
211
+ ? this.#previousConfig
212
+ : telegramAdapterConfigFromControlPlane(opts.config);
213
+ if (rollbackRequested && !targetConfig) {
214
+ return {
215
+ handled: true,
216
+ ok: false,
217
+ reason: opts.reason,
218
+ route: "/webhooks/telegram",
219
+ from_generation: fromGeneration,
220
+ to_generation: null,
221
+ active_generation: fromGeneration,
222
+ warmup: null,
223
+ cutover: null,
224
+ drain: null,
225
+ rollback: {
226
+ requested: true,
227
+ trigger: "rollback_unavailable",
228
+ attempted: false,
229
+ ok: false,
230
+ error: "rollback_unavailable",
231
+ },
232
+ error: "rollback_unavailable",
233
+ };
234
+ }
235
+ if (!targetConfig && !previousRecord) {
236
+ this.#activeControlPlaneConfig = cloneControlPlaneConfig(opts.config);
237
+ return {
238
+ handled: true,
239
+ ok: true,
240
+ reason: opts.reason,
241
+ route: "/webhooks/telegram",
242
+ from_generation: null,
243
+ to_generation: null,
244
+ active_generation: null,
245
+ warmup: null,
246
+ cutover: null,
247
+ drain: null,
248
+ rollback: {
249
+ requested: rollbackRequested,
250
+ trigger: rollbackTrigger,
251
+ attempted: false,
252
+ ok: true,
253
+ },
254
+ };
255
+ }
256
+ if (!targetConfig && previousRecord) {
257
+ const drainStartedAtMs = Math.trunc(this.#nowMs());
258
+ let forcedStop = false;
259
+ let drainError;
260
+ let drainTimedOut = false;
261
+ try {
262
+ previousRecord.adapter.beginDrain();
263
+ if (this.#hooks?.onDrain) {
264
+ await this.#hooks.onDrain({
265
+ generation: previousRecord.generation,
266
+ reason: opts.reason,
267
+ timeout_ms: drainTimeoutMs,
268
+ });
269
+ }
270
+ const drain = await runWithTimeout({
271
+ timeoutMs: drainTimeoutMs,
272
+ timeoutMessage: "telegram_drain_timeout",
273
+ run: async () => await previousRecord.adapter.drain({ timeoutMs: drainTimeoutMs, reason: opts.reason }),
274
+ });
275
+ drainTimedOut = drain.timed_out;
276
+ if (!drain.ok || drain.timed_out) {
277
+ forcedStop = true;
278
+ await previousRecord.adapter.stop({ force: true, reason: "disable_drain_timeout" });
279
+ }
280
+ else {
281
+ await previousRecord.adapter.stop({ force: false, reason: "disable" });
282
+ }
283
+ }
284
+ catch (err) {
285
+ drainError = describeError(err);
286
+ forcedStop = true;
287
+ drainTimedOut = drainError.includes("timeout");
288
+ await previousRecord.adapter.stop({ force: true, reason: "disable_drain_failed" });
289
+ }
290
+ this.#previousConfig = cloneTelegramAdapterConfig(previousRecord.config);
291
+ this.#active = null;
292
+ this.#activeControlPlaneConfig = applyTelegramAdapterConfig(this.#activeControlPlaneConfig, null);
293
+ return {
294
+ handled: true,
295
+ ok: drainError == null,
296
+ reason: opts.reason,
297
+ route: "/webhooks/telegram",
298
+ from_generation: fromGeneration,
299
+ to_generation: null,
300
+ active_generation: null,
301
+ warmup: null,
302
+ cutover: {
303
+ ok: true,
304
+ elapsed_ms: 0,
305
+ },
306
+ drain: {
307
+ ok: drainError == null && !drainTimedOut,
308
+ elapsed_ms: Math.max(0, Math.trunc(this.#nowMs()) - drainStartedAtMs),
309
+ timed_out: drainTimedOut,
310
+ forced_stop: forcedStop,
311
+ ...(drainError ? { error: drainError } : {}),
312
+ },
313
+ rollback: {
314
+ requested: rollbackRequested,
315
+ trigger: rollbackTrigger,
316
+ attempted: false,
317
+ ok: true,
318
+ },
319
+ ...(drainError ? { error: drainError } : {}),
320
+ };
321
+ }
322
+ const nextConfig = cloneTelegramAdapterConfig(targetConfig);
323
+ const toGeneration = this.#nextGeneration();
324
+ const nextAdapter = this.#buildAdapter(nextConfig, {
325
+ acceptIngress: false,
326
+ ingressDrainEnabled: false,
327
+ });
328
+ const nextRecord = {
329
+ generation: toGeneration,
330
+ config: nextConfig,
331
+ adapter: nextAdapter,
332
+ };
333
+ const warmupStartedAtMs = Math.trunc(this.#nowMs());
334
+ try {
335
+ if (this.#hooks?.onWarmup) {
336
+ await this.#hooks.onWarmup({ generation: toGeneration, reason: opts.reason });
337
+ }
338
+ await runWithTimeout({
339
+ timeoutMs: warmupTimeoutMs,
340
+ timeoutMessage: "telegram_warmup_timeout",
341
+ run: async () => {
342
+ await nextAdapter.warmup();
343
+ const health = await nextAdapter.healthCheck();
344
+ if (!health.ok) {
345
+ throw new Error(`telegram_health_gate_failed:${health.reason}`);
346
+ }
347
+ },
348
+ });
349
+ }
350
+ catch (err) {
351
+ const error = describeError(err);
352
+ rollbackTrigger = error.includes("health_gate") ? "health_gate_failed" : "warmup_failed";
353
+ await nextAdapter.stop({ force: true, reason: "warmup_failed" });
354
+ return {
355
+ handled: true,
356
+ ok: false,
357
+ reason: opts.reason,
358
+ route: "/webhooks/telegram",
359
+ from_generation: fromGeneration,
360
+ to_generation: toGeneration,
361
+ active_generation: fromGeneration,
362
+ warmup: {
363
+ ok: false,
364
+ elapsed_ms: Math.max(0, Math.trunc(this.#nowMs()) - warmupStartedAtMs),
365
+ error,
366
+ },
367
+ cutover: null,
368
+ drain: null,
369
+ rollback: {
370
+ requested: rollbackRequested,
371
+ trigger: rollbackTrigger,
372
+ attempted: false,
373
+ ok: true,
374
+ },
375
+ error,
376
+ };
377
+ }
378
+ const cutoverStartedAtMs = Math.trunc(this.#nowMs());
379
+ try {
380
+ if (this.#hooks?.onCutover) {
381
+ await this.#hooks.onCutover({
382
+ from_generation: fromGeneration,
383
+ to_generation: toGeneration,
384
+ reason: opts.reason,
385
+ });
386
+ }
387
+ nextAdapter.activateIngress();
388
+ if (previousRecord) {
389
+ previousRecord.adapter.beginDrain();
390
+ }
391
+ this.#active = nextRecord;
392
+ this.#generationSeq = toGeneration.generation_seq;
393
+ const postCutoverHealth = await nextAdapter.healthCheck();
394
+ if (!postCutoverHealth.ok) {
395
+ throw new Error(`telegram_post_cutover_health_failed:${postCutoverHealth.reason}`);
396
+ }
397
+ }
398
+ catch (err) {
399
+ const error = describeError(err);
400
+ rollbackTrigger = error.includes("post_cutover") ? "post_cutover_health_failed" : "cutover_failed";
401
+ rollbackAttempted = true;
402
+ const rollback = await this.#rollbackToPrevious({
403
+ failedRecord: nextRecord,
404
+ previous: previousRecord,
405
+ reason: opts.reason,
406
+ });
407
+ rollbackOk = rollback.ok;
408
+ rollbackError = rollback.error;
409
+ if (!rollback.ok) {
410
+ await nextAdapter.stop({ force: true, reason: "rollback_failed" });
411
+ this.#active = previousRecord ?? null;
412
+ this.#activeControlPlaneConfig = applyTelegramAdapterConfig(this.#activeControlPlaneConfig, previousRecord?.config ?? null);
413
+ }
414
+ return {
415
+ handled: true,
416
+ ok: false,
417
+ reason: opts.reason,
418
+ route: "/webhooks/telegram",
419
+ from_generation: fromGeneration,
420
+ to_generation: toGeneration,
421
+ active_generation: this.#active?.generation ?? fromGeneration,
422
+ warmup: {
423
+ ok: true,
424
+ elapsed_ms: Math.max(0, cutoverStartedAtMs - warmupStartedAtMs),
425
+ },
426
+ cutover: {
427
+ ok: false,
428
+ elapsed_ms: Math.max(0, Math.trunc(this.#nowMs()) - cutoverStartedAtMs),
429
+ error,
430
+ },
431
+ drain: null,
432
+ rollback: {
433
+ requested: rollbackRequested,
434
+ trigger: rollbackTrigger,
435
+ attempted: rollbackAttempted,
436
+ ok: rollbackOk,
437
+ ...(rollbackError ? { error: rollbackError } : {}),
438
+ },
439
+ error,
440
+ };
441
+ }
442
+ let drain = null;
443
+ if (previousRecord) {
444
+ const drainStartedAtMs = Math.trunc(this.#nowMs());
445
+ let forcedStop = false;
446
+ let drainTimedOut = false;
447
+ let drainError;
448
+ try {
449
+ if (this.#hooks?.onDrain) {
450
+ await this.#hooks.onDrain({
451
+ generation: previousRecord.generation,
452
+ reason: opts.reason,
453
+ timeout_ms: drainTimeoutMs,
454
+ });
455
+ }
456
+ const drained = await runWithTimeout({
457
+ timeoutMs: drainTimeoutMs,
458
+ timeoutMessage: "telegram_drain_timeout",
459
+ run: async () => await previousRecord.adapter.drain({ timeoutMs: drainTimeoutMs, reason: opts.reason }),
460
+ });
461
+ drainTimedOut = drained.timed_out;
462
+ if (!drained.ok || drained.timed_out) {
463
+ forcedStop = true;
464
+ await previousRecord.adapter.stop({ force: true, reason: "generation_drain_timeout" });
465
+ }
466
+ else {
467
+ await previousRecord.adapter.stop({ force: false, reason: "generation_drained" });
468
+ }
469
+ }
470
+ catch (err) {
471
+ drainError = describeError(err);
472
+ forcedStop = true;
473
+ drainTimedOut = drainError.includes("timeout");
474
+ await previousRecord.adapter.stop({ force: true, reason: "generation_drain_failed" });
475
+ }
476
+ drain = {
477
+ ok: drainError == null && !drainTimedOut,
478
+ elapsed_ms: Math.max(0, Math.trunc(this.#nowMs()) - drainStartedAtMs),
479
+ timed_out: drainTimedOut,
480
+ forced_stop: forcedStop,
481
+ ...(drainError ? { error: drainError } : {}),
482
+ };
483
+ }
484
+ this.#previousConfig = previousRecord ? cloneTelegramAdapterConfig(previousRecord.config) : this.#previousConfig;
485
+ this.#activeControlPlaneConfig = applyTelegramAdapterConfig(this.#activeControlPlaneConfig, nextConfig);
486
+ return {
487
+ handled: true,
488
+ ok: true,
489
+ reason: opts.reason,
490
+ route: "/webhooks/telegram",
491
+ from_generation: fromGeneration,
492
+ to_generation: toGeneration,
493
+ active_generation: toGeneration,
494
+ warmup: {
495
+ ok: true,
496
+ elapsed_ms: Math.max(0, cutoverStartedAtMs - warmupStartedAtMs),
497
+ },
498
+ cutover: {
499
+ ok: true,
500
+ elapsed_ms: Math.max(0, Math.trunc(this.#nowMs()) - cutoverStartedAtMs),
501
+ },
502
+ drain,
503
+ rollback: {
504
+ requested: rollbackRequested,
505
+ trigger: rollbackTrigger,
506
+ attempted: rollbackAttempted,
507
+ ok: rollbackOk,
508
+ ...(rollbackError ? { error: rollbackError } : {}),
509
+ },
510
+ };
511
+ }
512
+ async stop() {
513
+ const active = this.#active;
514
+ this.#active = null;
515
+ if (!active) {
516
+ return;
517
+ }
518
+ await active.adapter.stop({ force: true, reason: "shutdown" });
519
+ }
520
+ }
@@ -0,0 +1,50 @@
1
+ import type { Channel, IdentityBinding, OutboundEnvelope } from "@femtomc/mu-control-plane";
2
+ export type WakeFanoutSkipReasonCode = "channel_delivery_unsupported" | "telegram_bot_token_missing";
3
+ export type WakeFanoutContext = {
4
+ wakeId: string;
5
+ dedupeKey: string;
6
+ wakeSource: string | null;
7
+ programId: string | null;
8
+ sourceTsMs: number | null;
9
+ };
10
+ export type WakeDeliveryMetadata = {
11
+ wakeId: string;
12
+ wakeDedupeKey: string;
13
+ bindingId: string;
14
+ channel: Channel;
15
+ outboxId: string;
16
+ outboxDedupeKey: string;
17
+ };
18
+ export declare function wakeFanoutDedupeKey(opts: {
19
+ dedupeKey: string;
20
+ wakeId: string;
21
+ binding: Pick<IdentityBinding, "channel" | "binding_id">;
22
+ }): string;
23
+ export declare function resolveWakeFanoutCapability(opts: {
24
+ binding: IdentityBinding;
25
+ isChannelDeliverySupported: (channel: Channel) => boolean;
26
+ telegramBotToken: string | null;
27
+ }): {
28
+ ok: true;
29
+ } | {
30
+ ok: false;
31
+ reasonCode: WakeFanoutSkipReasonCode;
32
+ };
33
+ export declare function buildWakeOutboundEnvelope(opts: {
34
+ repoRoot: string;
35
+ nowMs: number;
36
+ message: string;
37
+ binding: IdentityBinding;
38
+ context: WakeFanoutContext;
39
+ metadata?: Record<string, unknown>;
40
+ }): OutboundEnvelope;
41
+ export declare function wakeDeliveryMetadataFromOutboxRecord(record: {
42
+ outbox_id: string;
43
+ dedupe_key: string;
44
+ envelope: Pick<OutboundEnvelope, "channel" | "metadata">;
45
+ }): WakeDeliveryMetadata | null;
46
+ export declare function wakeDispatchReasonCode(opts: {
47
+ state: "delivered" | "retried" | "dead_letter";
48
+ lastError: string | null;
49
+ deadLetterReason: string | null;
50
+ }): string;
@@ -0,0 +1,123 @@
1
+ function sha256Hex(input) {
2
+ const hasher = new Bun.CryptoHasher("sha256");
3
+ hasher.update(input);
4
+ return hasher.digest("hex");
5
+ }
6
+ function normalizeString(value) {
7
+ if (typeof value !== "string") {
8
+ return null;
9
+ }
10
+ const trimmed = value.trim();
11
+ return trimmed.length > 0 ? trimmed : null;
12
+ }
13
+ function normalizeChannel(value) {
14
+ switch (value) {
15
+ case "slack":
16
+ case "discord":
17
+ case "telegram":
18
+ case "terminal":
19
+ return value;
20
+ default:
21
+ return null;
22
+ }
23
+ }
24
+ export function wakeFanoutDedupeKey(opts) {
25
+ const base = opts.dedupeKey.trim().length > 0 ? opts.dedupeKey.trim() : `wake:${opts.wakeId}`;
26
+ return `${base}:wake:${opts.wakeId}:${opts.binding.channel}:${opts.binding.binding_id}`;
27
+ }
28
+ export function resolveWakeFanoutCapability(opts) {
29
+ const { binding } = opts;
30
+ if (!opts.isChannelDeliverySupported(binding.channel)) {
31
+ return { ok: false, reasonCode: "channel_delivery_unsupported" };
32
+ }
33
+ if (binding.channel === "telegram" && (!opts.telegramBotToken || opts.telegramBotToken.trim().length === 0)) {
34
+ return { ok: false, reasonCode: "telegram_bot_token_missing" };
35
+ }
36
+ return { ok: true };
37
+ }
38
+ export function buildWakeOutboundEnvelope(opts) {
39
+ const channelConversationId = opts.binding.channel_actor_id;
40
+ const requestId = `wake-req-${sha256Hex(`${opts.context.wakeId}:${opts.binding.binding_id}`).slice(0, 20)}`;
41
+ const responseId = `wake-resp-${sha256Hex(`${opts.context.wakeId}:${opts.binding.binding_id}:${opts.nowMs}`).slice(0, 20)}`;
42
+ return {
43
+ v: 1,
44
+ ts_ms: opts.nowMs,
45
+ channel: opts.binding.channel,
46
+ channel_tenant_id: opts.binding.channel_tenant_id,
47
+ channel_conversation_id: channelConversationId,
48
+ request_id: requestId,
49
+ response_id: responseId,
50
+ kind: "lifecycle",
51
+ body: opts.message,
52
+ correlation: {
53
+ command_id: `wake-${opts.context.wakeId}-${opts.binding.binding_id}`,
54
+ idempotency_key: `wake-idem-${opts.context.wakeId}-${opts.binding.binding_id}`,
55
+ request_id: requestId,
56
+ channel: opts.binding.channel,
57
+ channel_tenant_id: opts.binding.channel_tenant_id,
58
+ channel_conversation_id: channelConversationId,
59
+ actor_id: opts.binding.channel_actor_id,
60
+ actor_binding_id: opts.binding.binding_id,
61
+ assurance_tier: opts.binding.assurance_tier,
62
+ repo_root: opts.repoRoot,
63
+ scope_required: "cp.ops.admin",
64
+ scope_effective: "cp.ops.admin",
65
+ target_type: "operator_wake",
66
+ target_id: opts.context.wakeId,
67
+ attempt: 1,
68
+ state: "completed",
69
+ error_code: null,
70
+ operator_session_id: null,
71
+ operator_turn_id: null,
72
+ cli_invocation_id: null,
73
+ cli_command_kind: null,
74
+ run_root_id: null,
75
+ },
76
+ metadata: {
77
+ wake_delivery: true,
78
+ wake_id: opts.context.wakeId,
79
+ wake_dedupe_key: opts.context.dedupeKey,
80
+ wake_binding_id: opts.binding.binding_id,
81
+ wake_channel: opts.binding.channel,
82
+ wake_source: opts.context.wakeSource,
83
+ wake_program_id: opts.context.programId,
84
+ wake_source_ts_ms: opts.context.sourceTsMs,
85
+ ...(opts.metadata ?? {}),
86
+ },
87
+ };
88
+ }
89
+ export function wakeDeliveryMetadataFromOutboxRecord(record) {
90
+ const metadata = record.envelope.metadata;
91
+ if (metadata.wake_delivery !== true) {
92
+ return null;
93
+ }
94
+ const wakeId = normalizeString(metadata.wake_id);
95
+ const bindingId = normalizeString(metadata.wake_binding_id);
96
+ const wakeDedupeKey = normalizeString(metadata.wake_dedupe_key) ?? record.dedupe_key;
97
+ const metadataChannel = normalizeChannel(metadata.wake_channel);
98
+ const envelopeChannel = normalizeChannel(record.envelope.channel);
99
+ const channel = metadataChannel ?? envelopeChannel;
100
+ if (!wakeId || !bindingId || !channel) {
101
+ return null;
102
+ }
103
+ return {
104
+ wakeId,
105
+ wakeDedupeKey,
106
+ bindingId,
107
+ channel,
108
+ outboxId: record.outbox_id,
109
+ outboxDedupeKey: record.dedupe_key,
110
+ };
111
+ }
112
+ export function wakeDispatchReasonCode(opts) {
113
+ switch (opts.state) {
114
+ case "delivered":
115
+ return "outbox_delivered";
116
+ case "retried":
117
+ return opts.lastError && opts.lastError.trim().length > 0 ? opts.lastError : "outbox_retry";
118
+ case "dead_letter":
119
+ return opts.deadLetterReason && opts.deadLetterReason.trim().length > 0
120
+ ? opts.deadLetterReason
121
+ : "outbox_dead_letter";
122
+ }
123
+ }
@@ -0,0 +1,8 @@
1
+ import type { CronProgramTarget } from "./cron_programs.js";
2
+ export type ParsedCronTarget = {
3
+ target: CronProgramTarget | null;
4
+ error: string | null;
5
+ };
6
+ export declare function parseCronTarget(body: Record<string, unknown>): ParsedCronTarget;
7
+ export declare function hasCronScheduleInput(body: Record<string, unknown>): boolean;
8
+ export declare function cronScheduleInputFromBody(body: Record<string, unknown>): Record<string, unknown>;