@wildo-ai/saas-minions-lib 1.1.3

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 (47) hide show
  1. package/LICENSE +34 -0
  2. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.d.ts +22 -0
  3. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.d.ts.map +1 -0
  4. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js +234 -0
  5. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js.map +1 -0
  6. package/dist/esm/index.d.ts +9 -0
  7. package/dist/esm/index.d.ts.map +1 -0
  8. package/dist/esm/index.js +9 -0
  9. package/dist/esm/index.js.map +1 -0
  10. package/dist/esm/inject/models/container.d.ts +7 -0
  11. package/dist/esm/inject/models/container.d.ts.map +1 -0
  12. package/dist/esm/inject/models/container.js +55 -0
  13. package/dist/esm/inject/models/container.js.map +1 -0
  14. package/dist/esm/inject/models/service-types.d.ts +7 -0
  15. package/dist/esm/inject/models/service-types.d.ts.map +1 -0
  16. package/dist/esm/inject/models/service-types.js +6 -0
  17. package/dist/esm/inject/models/service-types.js.map +1 -0
  18. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts +47 -0
  19. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts.map +1 -0
  20. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js +157 -0
  21. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js.map +1 -0
  22. package/dist/esm/runtime/services/define-minion-init.d.ts +98 -0
  23. package/dist/esm/runtime/services/define-minion-init.d.ts.map +1 -0
  24. package/dist/esm/runtime/services/define-minion-init.js +4 -0
  25. package/dist/esm/runtime/services/define-minion-init.js.map +1 -0
  26. package/dist/esm/runtime/services/own-schedule-reader.backend.service.d.ts +75 -0
  27. package/dist/esm/runtime/services/own-schedule-reader.backend.service.d.ts.map +1 -0
  28. package/dist/esm/runtime/services/own-schedule-reader.backend.service.js +124 -0
  29. package/dist/esm/runtime/services/own-schedule-reader.backend.service.js.map +1 -0
  30. package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts +48 -0
  31. package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts.map +1 -0
  32. package/dist/esm/runtime/services/start-minion-application.backend.service.js +304 -0
  33. package/dist/esm/runtime/services/start-minion-application.backend.service.js.map +1 -0
  34. package/dist/tsconfig.build.tsbuildinfo +1 -0
  35. package/package.json +56 -0
  36. package/src/base-classes/services/services/__tests__/minion-scoped-services-registry-handler.backend.service.test.ts +252 -0
  37. package/src/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.ts +337 -0
  38. package/src/index.ts +11 -0
  39. package/src/inject/models/__tests__/container.test.ts +30 -0
  40. package/src/inject/models/container.ts +68 -0
  41. package/src/inject/models/service-types.ts +11 -0
  42. package/src/runtime/queue/minion-tick-consumer.backend.service.ts +181 -0
  43. package/src/runtime/services/__tests__/own-schedule-reader.backend.service.test.ts +118 -0
  44. package/src/runtime/services/__tests__/start-minion-application.backend.service.test.ts +422 -0
  45. package/src/runtime/services/define-minion-init.ts +113 -0
  46. package/src/runtime/services/own-schedule-reader.backend.service.ts +146 -0
  47. package/src/runtime/services/start-minion-application.backend.service.ts +398 -0
@@ -0,0 +1,68 @@
1
+ import {
2
+ type InversifyContainer,
3
+ resetGlobalContainer,
4
+ SAAS_SERVICE_TYPES,
5
+ setupSaasBackendInjection,
6
+ } from '@wildo-ai/saas-backend-lib';
7
+ import { StartMinionApplicationBackendService } from '../../runtime/services/start-minion-application.backend.service';
8
+ import { MinionTickConsumerBackendService } from '../../runtime/queue/minion-tick-consumer.backend.service';
9
+ import { OwnScheduleReaderBackendService } from '../../runtime/services/own-schedule-reader.backend.service';
10
+ import { SAAS_MINIONS_SERVICE_TYPES } from './service-types';
11
+
12
+ type Container = InversifyContainer;
13
+
14
+ let globalMinionsContainer: Container | undefined;
15
+
16
+ class SaasMinionsContainer {
17
+ constructor(private readonly container: Container) {
18
+ this.bindRuntimeServices();
19
+ }
20
+
21
+ public getContainer(): Container {
22
+ return this.container;
23
+ }
24
+
25
+ private bindRuntimeServices(): void {
26
+ if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)) {
27
+ this.container
28
+ .bind(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)
29
+ .to(StartMinionApplicationBackendService)
30
+ .inSingletonScope();
31
+ }
32
+ if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)) {
33
+ this.container
34
+ .bind(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)
35
+ .to(MinionTickConsumerBackendService)
36
+ .inSingletonScope();
37
+ }
38
+ if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)) {
39
+ this.container
40
+ .bind(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)
41
+ .to(OwnScheduleReaderBackendService)
42
+ .inSingletonScope();
43
+ }
44
+ }
45
+ }
46
+
47
+ export function setupSaasMinionInjection(existing?: Container): Container {
48
+ const container = existing ?? globalMinionsContainer ?? setupSaasBackendInjection();
49
+ if (existing && !container.isBound(SAAS_SERVICE_TYPES.StartApplicationService)) {
50
+ throw new Error(
51
+ 'setupSaasMinionInjection(existing) requires a container that already includes saas-backend-lib bindings.',
52
+ );
53
+ }
54
+ const minionsContainer = new SaasMinionsContainer(container);
55
+ if (!existing) {
56
+ globalMinionsContainer = minionsContainer.getContainer();
57
+ }
58
+ return minionsContainer.getContainer();
59
+ }
60
+
61
+ export function getGlobalMinionsContainer(): Container {
62
+ return globalMinionsContainer ?? setupSaasMinionInjection();
63
+ }
64
+
65
+ export function resetGlobalMinionsContainer(): void {
66
+ globalMinionsContainer = undefined;
67
+ resetGlobalContainer();
68
+ }
@@ -0,0 +1,11 @@
1
+ export interface SaasMinionsServiceTypes {
2
+ readonly StartMinionApplicationService: symbol;
3
+ readonly MinionTickConsumerService: symbol;
4
+ readonly OwnScheduleReaderService: symbol;
5
+ }
6
+
7
+ export const SAAS_MINIONS_SERVICE_TYPES: SaasMinionsServiceTypes = {
8
+ StartMinionApplicationService: Symbol.for('SaaS.Minions.StartMinionApplicationService'),
9
+ MinionTickConsumerService: Symbol.for('SaaS.Minions.MinionTickConsumerService'),
10
+ OwnScheduleReaderService: Symbol.for('SaaS.Minions.OwnScheduleReaderService'),
11
+ };
@@ -0,0 +1,181 @@
1
+ import { inject, injectable } from 'inversify';
2
+ import type { Channel, ConsumeMessage } from 'amqplib';
3
+ import {
4
+ describeCaughtError,
5
+ LoggerService,
6
+ RabbitMQAdapterBackendService,
7
+ SAAS_SERVICE_TYPES,
8
+ ScheduledMessageVerifierBackendService,
9
+ type MinionTickJobToken,
10
+ } from '@wildo-ai/saas-backend-lib';
11
+ import { QueueNamingUtils } from '@wildo-ai/saas-models';
12
+
13
+ /**
14
+ * Handler invoked once per verified minion tick. The handler is
15
+ * responsible for routing to the minion's locally-hosted actor system /
16
+ * flow registry. Returning resolves the message ack; throwing causes the
17
+ * consumer to NACK without requeue (per KD-6: minion ticks don't retry
18
+ * via the queue — they'll run again on the next cron cycle).
19
+ */
20
+ export type MinionTickHandler = (token: MinionTickJobToken) => Promise<void>;
21
+
22
+ /**
23
+ * Minion-side consumer for the per-minion tick queue
24
+ * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).
25
+ *
26
+ * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:
27
+ * - Subscribes only to the queue dedicated to THIS minion (no shared
28
+ * `scheduled` queue subscription, so the backend-api and minion don't
29
+ * compete on cron tick deliveries).
30
+ * - Verifies every inbound JWT through
31
+ * `ScheduledMessageVerifierBackendService.verifyAndExtractMinionTick(token, expectedMinionName)`
32
+ * — invalid signature, malformed payload, wrong issuer/audience, or
33
+ * wrong target minion all NACK without requeue.
34
+ * - Dispatches `MINION_TICK` tokens that match this minion's identity to
35
+ * the registered handler. The handler typically routes into the
36
+ * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.
37
+ *
38
+ * Backpressure / cron-overlap guarding (CC-10) is intentionally NOT done
39
+ * here — that's the handler's responsibility (Redis-backed advisory
40
+ * lease pattern documented in CC-10).
41
+ */
42
+ @injectable()
43
+ export class MinionTickConsumerBackendService {
44
+ private isConsuming = false;
45
+ private consumingQueueName?: string;
46
+
47
+ protected readonly logDebug: (message: string, context?: Record<string, unknown>) => void;
48
+
49
+ constructor(
50
+ @inject(SAAS_SERVICE_TYPES.RabbitMQAdapterService)
51
+ private readonly adapter: RabbitMQAdapterBackendService,
52
+ @inject(SAAS_SERVICE_TYPES.ScheduledMessageVerifierService)
53
+ private readonly scheduledMessageVerifier: ScheduledMessageVerifierBackendService,
54
+ @inject(SAAS_SERVICE_TYPES.Logger)
55
+ private readonly logger: LoggerService,
56
+ ) {
57
+ this.logDebug = this.logger.debugByType('MinionTickConsumerBackendService');
58
+ this.logger.setDebugTypeLogging('MinionTickConsumerBackendService', false);
59
+ }
60
+
61
+ public async start(input: {
62
+ applicationId: string;
63
+ minionName: string;
64
+ handler: MinionTickHandler;
65
+ }): Promise<void> {
66
+ if (this.isConsuming) {
67
+ throw new Error('MinionTickConsumerBackendService.start called while already consuming.');
68
+ }
69
+
70
+ const { applicationId, minionName, handler } = input;
71
+ const queueName = QueueNamingUtils.buildMinionTickQueueName(applicationId, minionName);
72
+
73
+ // M5 — adapter readiness guard. The minion entrypoint calls this
74
+ // method AFTER `StartApplicationBackendService.initialize`, which
75
+ // typically connects the RabbitMQ adapter. Throw a descriptive
76
+ // error if the adapter is not connected so a misconfigured
77
+ // bootstrap surfaces here rather than at the first cron tick.
78
+ if (!this.adapter.isConnected()) {
79
+ throw new Error(
80
+ 'MinionTickConsumerBackendService.start called before the RabbitMQ adapter connected. ' +
81
+ 'Ensure the minion bootstrap completes before subscribing to the tick queue.',
82
+ );
83
+ }
84
+
85
+ // H2 — the minion runtime OWNS and declares this per-minion tick queue.
86
+ // The crontabs-batches-manager publisher is a producer only and passively
87
+ // verifies the queue (`checkQueue`) rather than declaring it, so there is no
88
+ // publisher-side declaration whose args this must match — the minion is the
89
+ // sole topology owner here. `durable: true` + `x-queue-type: 'quorum'` is
90
+ // the minion's own chosen shape (durable so ticks survive a broker restart).
91
+ //
92
+ // Declared on the adapter's dedicated topology channel (not the primary
93
+ // publish/consume channel): a `406` arg-mismatch against a pre-existing
94
+ // incompatible queue closes only that channel, so it can't tear down the
95
+ // primary channel and crash-loop the minion bootstrap. The
96
+ // `x-queue-type: 'quorum'` argument is not modelled by `QueueAssertOptions`,
97
+ // so we declare directly on the channel rather than via `adapter.assertQueue`.
98
+ const channel = await this.adapter.getTopologyChannel();
99
+ await channel.assertQueue(queueName, {
100
+ durable: true,
101
+ arguments: {
102
+ 'x-queue-type': 'quorum',
103
+ },
104
+ });
105
+
106
+ await this.adapter.consume(queueName, async (msg: ConsumeMessage, channel: Channel) => {
107
+ await this.handleMessage(msg, channel, minionName, handler);
108
+ });
109
+
110
+ this.consumingQueueName = queueName;
111
+ this.isConsuming = true;
112
+ this.logger.info('Minion tick consumer started', {
113
+ queueName,
114
+ applicationId,
115
+ minionName,
116
+ });
117
+ }
118
+
119
+ public async stop(): Promise<void> {
120
+ if (!this.isConsuming || !this.consumingQueueName) {
121
+ return;
122
+ }
123
+ await this.adapter.cancelConsumer(this.consumingQueueName);
124
+ this.isConsuming = false;
125
+ this.consumingQueueName = undefined;
126
+ }
127
+
128
+ public isRunning(): boolean {
129
+ return this.isConsuming;
130
+ }
131
+
132
+ private async handleMessage(
133
+ msg: ConsumeMessage,
134
+ channel: Channel,
135
+ expectedMinionName: string,
136
+ handler: MinionTickHandler,
137
+ ): Promise<void> {
138
+ const token = msg.content.toString();
139
+ try {
140
+ const tickToken = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(
141
+ token,
142
+ expectedMinionName,
143
+ );
144
+
145
+ if (!tickToken) {
146
+ // Either a SCHEDULED_CRON token leaked into this queue (shouldn't
147
+ // happen given the publisher routing, but guard anyway) or the
148
+ // token targets a different minion name. Drop without requeue —
149
+ // and surface as a warning since either case represents a routing
150
+ // misconfiguration that operators should investigate.
151
+ this.logger.warn('Skipping non-actionable scheduled token on minion-tick queue', {
152
+ expectedMinionName,
153
+ });
154
+ channel.nack(msg, false, false);
155
+ return;
156
+ }
157
+
158
+ this.logger.info('Processing minion tick', {
159
+ jobId: tickToken.jobId,
160
+ minionName: tickToken.minionName,
161
+ applicationId: tickToken.applicationId,
162
+ });
163
+
164
+ await handler(tickToken);
165
+ channel.ack(msg);
166
+ } catch (error) {
167
+ // `WildoBackendError` is NOT `instanceof Error`, so the previous ternary reported
168
+ // literally 'Unknown error' for EVERY typed framework failure — including the
169
+ // verification rejection that is by far the most common cause here. Two masking
170
+ // layers stacked (this one and the verifier's) is why a tick that simply outlived
171
+ // its 5-minute token TTL looked identical to a forged one.
172
+ this.logger.error('Minion tick processing failed', {
173
+ expectedMinionName,
174
+ error: describeCaughtError(error),
175
+ });
176
+ // Per KD-6: scheduled jobs don't retry via queue — the next cron
177
+ // cycle re-publishes a fresh tick. NACK without requeue.
178
+ channel.nack(msg, false, false);
179
+ }
180
+ }
181
+ }
@@ -0,0 +1,118 @@
1
+ import 'reflect-metadata';
2
+
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+ import { WildoHeaderKeys } from '@wildo-ai/saas-models';
5
+
6
+ import { OwnScheduleReaderBackendService } from '../own-schedule-reader.backend.service';
7
+
8
+ /**
9
+ * The minion-side half of R4.
10
+ *
11
+ * The reader's job is narrow and its failure modes are all quiet: attach the
12
+ * attestation and nothing else, carry no selector, and never turn a refusal into
13
+ * an empty schedule. Each of those is invisible from the outside — a reader that
14
+ * sent the wrong credential, or that swallowed a 403, returns `[]` exactly like a
15
+ * correct one talking to a minion with no jobs.
16
+ */
17
+ describe('OwnScheduleReaderBackendService', () => {
18
+ const CRONTABS_URL = 'http://wildo-crontabs:4300';
19
+ const ATTESTATION = 'attestation-token';
20
+
21
+ function buildReader(fetchImpl: ReturnType<typeof vi.fn>, getAttestation?: ReturnType<typeof vi.fn>) {
22
+ vi.stubGlobal('fetch', fetchImpl);
23
+
24
+ const attestations = { getAttestation: getAttestation ?? vi.fn().mockResolvedValue(ATTESTATION) };
25
+ const reader = Object.create(OwnScheduleReaderBackendService.prototype) as Record<string, unknown> & {
26
+ read: () => Promise<unknown[]>;
27
+ };
28
+
29
+ reader.logger = { debug: vi.fn(), warn: vi.fn() };
30
+ reader.errorBuilder = {
31
+ buildError: vi.fn(
32
+ (_type: unknown, _cause: unknown, options: { context?: { message?: string } }) =>
33
+ new Error(options.context?.message ?? 'refused'),
34
+ ),
35
+ };
36
+ reader.appConfigService = {
37
+ config: { runtime: { endPoints: { platform_crontabs_batches_manager: { internalUrl: CRONTABS_URL } } } },
38
+ };
39
+ reader.attestations = attestations;
40
+ reader.baseUrl = null;
41
+
42
+ return { reader, attestations };
43
+ }
44
+
45
+ const okResponse = (jobs: unknown[]) => ({
46
+ ok: true,
47
+ status: 200,
48
+ json: async () => ({ jobs }),
49
+ });
50
+
51
+ afterEach(() => {
52
+ vi.unstubAllGlobals();
53
+ });
54
+
55
+ it('presents the attestation and NO other credential', async () => {
56
+ // The attestation is the whole credential. An `X-Service-Id` would claim to
57
+ // be a platform service, and an application JWT would carry an identity
58
+ // meaning "some runtime of this app" — attaching either invites the server to
59
+ // read the weaker of the two.
60
+ const fetchImpl = vi.fn().mockResolvedValue(okResponse([]));
61
+ const { reader } = buildReader(fetchImpl);
62
+
63
+ await reader.read();
64
+
65
+ const [, init] = fetchImpl.mock.calls[0] as [string, { headers: Record<string, string> }];
66
+ expect(init.headers[WildoHeaderKeys.RUNTIME_PRINCIPAL_TOKEN]).toBe(ATTESTATION);
67
+ expect(init.headers[WildoHeaderKeys.SERVICE_ID]).toBeUndefined();
68
+ expect(init.headers[WildoHeaderKeys.AUTHORIZATION]).toBeUndefined();
69
+ expect(init.headers[WildoHeaderKeys.PLATFORM_SECRET]).toBeUndefined();
70
+ });
71
+
72
+ it('requests a URL carrying NO selector', async () => {
73
+ // The by-shape property, asserted on the wire rather than trusted from the
74
+ // signature. A minion name, an application id or a job id appearing in the
75
+ // path or query would mean the subject had become something the caller
76
+ // supplies.
77
+ const fetchImpl = vi.fn().mockResolvedValue(okResponse([]));
78
+ const { reader } = buildReader(fetchImpl);
79
+
80
+ await reader.read();
81
+
82
+ const [url] = fetchImpl.mock.calls[0] as [string];
83
+ expect(url).toBe(`${CRONTABS_URL}/api/v1/runtime-self/cron-jobs`);
84
+ expect(url).not.toContain('?');
85
+ });
86
+
87
+ it('asks for an attestation bound to the crontabs audience', async () => {
88
+ // An attestation is verified against the target's own service id, so asking
89
+ // for the wrong audience produces a token the target must reject — a failure
90
+ // that reads as a signing problem rather than a wiring one.
91
+ const getAttestation = vi.fn().mockResolvedValue(ATTESTATION);
92
+ const { reader } = buildReader(vi.fn().mockResolvedValue(okResponse([])), getAttestation);
93
+
94
+ await reader.read();
95
+
96
+ expect(getAttestation).toHaveBeenCalledWith('platform_crontabs_batches_manager');
97
+ });
98
+
99
+ it('THROWS on a refusal instead of returning an empty schedule', async () => {
100
+ // The quietest possible bug. `[]` is a legitimate answer for a minion with no
101
+ // cron jobs, so swallowing a 403 would make a missing `platformAccess`
102
+ // declaration indistinguishable from a correctly-empty schedule — the one
103
+ // failure an author cannot debug from the result.
104
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: false, status: 403, json: async () => ({}) });
105
+ const { reader } = buildReader(fetchImpl);
106
+
107
+ await expect(reader.read()).rejects.toThrow(/refused/i);
108
+ });
109
+
110
+ it('returns the jobs the platform answered with', async () => {
111
+ // The positive complement: a reader that threw on everything would satisfy
112
+ // the refusal pin above and never deliver a schedule.
113
+ const entry = { job: { jobId: 'job-1' }, recentExecutions: [] };
114
+ const { reader } = buildReader(vi.fn().mockResolvedValue(okResponse([entry])));
115
+
116
+ await expect(reader.read()).resolves.toEqual([entry]);
117
+ });
118
+ });