@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,157 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { inject, injectable } from 'inversify';
14
+ import { describeCaughtError, LoggerService, RabbitMQAdapterBackendService, SAAS_SERVICE_TYPES, ScheduledMessageVerifierBackendService, } from '@wildo-ai/saas-backend-lib';
15
+ import { QueueNamingUtils } from '@wildo-ai/saas-models';
16
+ /**
17
+ * Minion-side consumer for the per-minion tick queue
18
+ * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).
19
+ *
20
+ * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:
21
+ * - Subscribes only to the queue dedicated to THIS minion (no shared
22
+ * `scheduled` queue subscription, so the backend-api and minion don't
23
+ * compete on cron tick deliveries).
24
+ * - Verifies every inbound JWT through
25
+ * `ScheduledMessageVerifierBackendService.verifyAndExtractMinionTick(token, expectedMinionName)`
26
+ * — invalid signature, malformed payload, wrong issuer/audience, or
27
+ * wrong target minion all NACK without requeue.
28
+ * - Dispatches `MINION_TICK` tokens that match this minion's identity to
29
+ * the registered handler. The handler typically routes into the
30
+ * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.
31
+ *
32
+ * Backpressure / cron-overlap guarding (CC-10) is intentionally NOT done
33
+ * here — that's the handler's responsibility (Redis-backed advisory
34
+ * lease pattern documented in CC-10).
35
+ */
36
+ let MinionTickConsumerBackendService = class MinionTickConsumerBackendService {
37
+ adapter;
38
+ scheduledMessageVerifier;
39
+ logger;
40
+ isConsuming = false;
41
+ consumingQueueName;
42
+ logDebug;
43
+ constructor(adapter, scheduledMessageVerifier, logger) {
44
+ this.adapter = adapter;
45
+ this.scheduledMessageVerifier = scheduledMessageVerifier;
46
+ this.logger = logger;
47
+ this.logDebug = this.logger.debugByType('MinionTickConsumerBackendService');
48
+ this.logger.setDebugTypeLogging('MinionTickConsumerBackendService', false);
49
+ }
50
+ async start(input) {
51
+ if (this.isConsuming) {
52
+ throw new Error('MinionTickConsumerBackendService.start called while already consuming.');
53
+ }
54
+ const { applicationId, minionName, handler } = input;
55
+ const queueName = QueueNamingUtils.buildMinionTickQueueName(applicationId, minionName);
56
+ // M5 — adapter readiness guard. The minion entrypoint calls this
57
+ // method AFTER `StartApplicationBackendService.initialize`, which
58
+ // typically connects the RabbitMQ adapter. Throw a descriptive
59
+ // error if the adapter is not connected so a misconfigured
60
+ // bootstrap surfaces here rather than at the first cron tick.
61
+ if (!this.adapter.isConnected()) {
62
+ throw new Error('MinionTickConsumerBackendService.start called before the RabbitMQ adapter connected. ' +
63
+ 'Ensure the minion bootstrap completes before subscribing to the tick queue.');
64
+ }
65
+ // H2 — the minion runtime OWNS and declares this per-minion tick queue.
66
+ // The crontabs-batches-manager publisher is a producer only and passively
67
+ // verifies the queue (`checkQueue`) rather than declaring it, so there is no
68
+ // publisher-side declaration whose args this must match — the minion is the
69
+ // sole topology owner here. `durable: true` + `x-queue-type: 'quorum'` is
70
+ // the minion's own chosen shape (durable so ticks survive a broker restart).
71
+ //
72
+ // Declared on the adapter's dedicated topology channel (not the primary
73
+ // publish/consume channel): a `406` arg-mismatch against a pre-existing
74
+ // incompatible queue closes only that channel, so it can't tear down the
75
+ // primary channel and crash-loop the minion bootstrap. The
76
+ // `x-queue-type: 'quorum'` argument is not modelled by `QueueAssertOptions`,
77
+ // so we declare directly on the channel rather than via `adapter.assertQueue`.
78
+ const channel = await this.adapter.getTopologyChannel();
79
+ await channel.assertQueue(queueName, {
80
+ durable: true,
81
+ arguments: {
82
+ 'x-queue-type': 'quorum',
83
+ },
84
+ });
85
+ await this.adapter.consume(queueName, async (msg, channel) => {
86
+ await this.handleMessage(msg, channel, minionName, handler);
87
+ });
88
+ this.consumingQueueName = queueName;
89
+ this.isConsuming = true;
90
+ this.logger.info('Minion tick consumer started', {
91
+ queueName,
92
+ applicationId,
93
+ minionName,
94
+ });
95
+ }
96
+ async stop() {
97
+ if (!this.isConsuming || !this.consumingQueueName) {
98
+ return;
99
+ }
100
+ await this.adapter.cancelConsumer(this.consumingQueueName);
101
+ this.isConsuming = false;
102
+ this.consumingQueueName = undefined;
103
+ }
104
+ isRunning() {
105
+ return this.isConsuming;
106
+ }
107
+ async handleMessage(msg, channel, expectedMinionName, handler) {
108
+ const token = msg.content.toString();
109
+ try {
110
+ const tickToken = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(token, expectedMinionName);
111
+ if (!tickToken) {
112
+ // Either a SCHEDULED_CRON token leaked into this queue (shouldn't
113
+ // happen given the publisher routing, but guard anyway) or the
114
+ // token targets a different minion name. Drop without requeue —
115
+ // and surface as a warning since either case represents a routing
116
+ // misconfiguration that operators should investigate.
117
+ this.logger.warn('Skipping non-actionable scheduled token on minion-tick queue', {
118
+ expectedMinionName,
119
+ });
120
+ channel.nack(msg, false, false);
121
+ return;
122
+ }
123
+ this.logger.info('Processing minion tick', {
124
+ jobId: tickToken.jobId,
125
+ minionName: tickToken.minionName,
126
+ applicationId: tickToken.applicationId,
127
+ });
128
+ await handler(tickToken);
129
+ channel.ack(msg);
130
+ }
131
+ catch (error) {
132
+ // `WildoBackendError` is NOT `instanceof Error`, so the previous ternary reported
133
+ // literally 'Unknown error' for EVERY typed framework failure — including the
134
+ // verification rejection that is by far the most common cause here. Two masking
135
+ // layers stacked (this one and the verifier's) is why a tick that simply outlived
136
+ // its 5-minute token TTL looked identical to a forged one.
137
+ this.logger.error('Minion tick processing failed', {
138
+ expectedMinionName,
139
+ error: describeCaughtError(error),
140
+ });
141
+ // Per KD-6: scheduled jobs don't retry via queue — the next cron
142
+ // cycle re-publishes a fresh tick. NACK without requeue.
143
+ channel.nack(msg, false, false);
144
+ }
145
+ }
146
+ };
147
+ MinionTickConsumerBackendService = __decorate([
148
+ injectable(),
149
+ __param(0, inject(SAAS_SERVICE_TYPES.RabbitMQAdapterService)),
150
+ __param(1, inject(SAAS_SERVICE_TYPES.ScheduledMessageVerifierService)),
151
+ __param(2, inject(SAAS_SERVICE_TYPES.Logger)),
152
+ __metadata("design:paramtypes", [RabbitMQAdapterBackendService,
153
+ ScheduledMessageVerifierBackendService,
154
+ LoggerService])
155
+ ], MinionTickConsumerBackendService);
156
+ export { MinionTickConsumerBackendService };
157
+ //# sourceMappingURL=minion-tick-consumer.backend.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"minion-tick-consumer.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/queue/minion-tick-consumer.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,6BAA6B,EAC7B,kBAAkB,EAClB,sCAAsC,GAEvC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAWzD;;;;;;;;;;;;;;;;;;;GAmBG;AAEI,IAAM,gCAAgC,GAAtC,MAAM,gCAAgC;IAQxB;IAEA;IAEA;IAXX,WAAW,GAAG,KAAK,CAAC;IACpB,kBAAkB,CAAU;IAEjB,QAAQ,CAA+D;IAE1F,YAEmB,OAAsC,EAEtC,wBAAgE,EAEhE,MAAqB;QAJrB,YAAO,GAAP,OAAO,CAA+B;QAEtC,6BAAwB,GAAxB,wBAAwB,CAAwC;QAEhE,WAAM,GAAN,MAAM,CAAe;QAEtC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,kCAAkC,CAAC,CAAC;QAC5E,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;IAC7E,CAAC;IAEM,KAAK,CAAC,KAAK,CAAC,KAIlB;QACC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC5F,CAAC;QAED,MAAM,EAAE,aAAa,EAAE,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E,gFAAgF;YAChF,kFAAkF;YAClF,2DAA2D;YAC3D,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE;gBACjD,kBAAkB;gBAClB,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC;aAClC,CAAC,CAAC;YACH,iEAAiE;YACjE,yDAAyD;YACzD,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CACF,CAAA;AA1IY,gCAAgC;IAD5C,UAAU,EAAE;IAQR,WAAA,MAAM,CAAC,kBAAkB,CAAC,sBAAsB,CAAC,CAAA;IAEjD,WAAA,MAAM,CAAC,kBAAkB,CAAC,+BAA+B,CAAC,CAAA;IAE1D,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;qCAHR,6BAA6B;QAEZ,sCAAsC;QAExD,aAAa;GAZ7B,gCAAgC,CA0I5C","sourcesContent":["import { inject, injectable } from 'inversify';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport {\n describeCaughtError,\n LoggerService,\n RabbitMQAdapterBackendService,\n SAAS_SERVICE_TYPES,\n ScheduledMessageVerifierBackendService,\n type MinionTickJobToken,\n} from '@wildo-ai/saas-backend-lib';\nimport { QueueNamingUtils } from '@wildo-ai/saas-models';\n\n/**\n * Handler invoked once per verified minion tick. The handler is\n * responsible for routing to the minion's locally-hosted actor system /\n * flow registry. Returning resolves the message ack; throwing causes the\n * consumer to NACK without requeue (per KD-6: minion ticks don't retry\n * via the queue — they'll run again on the next cron cycle).\n */\nexport type MinionTickHandler = (token: MinionTickJobToken) => Promise<void>;\n\n/**\n * Minion-side consumer for the per-minion tick queue\n * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).\n *\n * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:\n * - Subscribes only to the queue dedicated to THIS minion (no shared\n * `scheduled` queue subscription, so the backend-api and minion don't\n * compete on cron tick deliveries).\n * - Verifies every inbound JWT through\n * `ScheduledMessageVerifierBackendService.verifyAndExtractMinionTick(token, expectedMinionName)`\n * — invalid signature, malformed payload, wrong issuer/audience, or\n * wrong target minion all NACK without requeue.\n * - Dispatches `MINION_TICK` tokens that match this minion's identity to\n * the registered handler. The handler typically routes into the\n * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.\n *\n * Backpressure / cron-overlap guarding (CC-10) is intentionally NOT done\n * here — that's the handler's responsibility (Redis-backed advisory\n * lease pattern documented in CC-10).\n */\n@injectable()\nexport class MinionTickConsumerBackendService {\n private isConsuming = false;\n private consumingQueueName?: string;\n\n protected readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.RabbitMQAdapterService)\n private readonly adapter: RabbitMQAdapterBackendService,\n @inject(SAAS_SERVICE_TYPES.ScheduledMessageVerifierService)\n private readonly scheduledMessageVerifier: ScheduledMessageVerifierBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n ) {\n this.logDebug = this.logger.debugByType('MinionTickConsumerBackendService');\n this.logger.setDebugTypeLogging('MinionTickConsumerBackendService', false);\n }\n\n public async start(input: {\n applicationId: string;\n minionName: string;\n handler: MinionTickHandler;\n }): Promise<void> {\n if (this.isConsuming) {\n throw new Error('MinionTickConsumerBackendService.start called while already consuming.');\n }\n\n const { applicationId, minionName, handler } = input;\n const queueName = QueueNamingUtils.buildMinionTickQueueName(applicationId, minionName);\n\n // M5 — adapter readiness guard. The minion entrypoint calls this\n // method AFTER `StartApplicationBackendService.initialize`, which\n // typically connects the RabbitMQ adapter. Throw a descriptive\n // error if the adapter is not connected so a misconfigured\n // bootstrap surfaces here rather than at the first cron tick.\n if (!this.adapter.isConnected()) {\n throw new Error(\n 'MinionTickConsumerBackendService.start called before the RabbitMQ adapter connected. ' +\n 'Ensure the minion bootstrap completes before subscribing to the tick queue.',\n );\n }\n\n // H2 — the minion runtime OWNS and declares this per-minion tick queue.\n // The crontabs-batches-manager publisher is a producer only and passively\n // verifies the queue (`checkQueue`) rather than declaring it, so there is no\n // publisher-side declaration whose args this must match — the minion is the\n // sole topology owner here. `durable: true` + `x-queue-type: 'quorum'` is\n // the minion's own chosen shape (durable so ticks survive a broker restart).\n //\n // Declared on the adapter's dedicated topology channel (not the primary\n // publish/consume channel): a `406` arg-mismatch against a pre-existing\n // incompatible queue closes only that channel, so it can't tear down the\n // primary channel and crash-loop the minion bootstrap. The\n // `x-queue-type: 'quorum'` argument is not modelled by `QueueAssertOptions`,\n // so we declare directly on the channel rather than via `adapter.assertQueue`.\n const channel = await this.adapter.getTopologyChannel();\n await channel.assertQueue(queueName, {\n durable: true,\n arguments: {\n 'x-queue-type': 'quorum',\n },\n });\n\n await this.adapter.consume(queueName, async (msg: ConsumeMessage, channel: Channel) => {\n await this.handleMessage(msg, channel, minionName, handler);\n });\n\n this.consumingQueueName = queueName;\n this.isConsuming = true;\n this.logger.info('Minion tick consumer started', {\n queueName,\n applicationId,\n minionName,\n });\n }\n\n public async stop(): Promise<void> {\n if (!this.isConsuming || !this.consumingQueueName) {\n return;\n }\n await this.adapter.cancelConsumer(this.consumingQueueName);\n this.isConsuming = false;\n this.consumingQueueName = undefined;\n }\n\n public isRunning(): boolean {\n return this.isConsuming;\n }\n\n private async handleMessage(\n msg: ConsumeMessage,\n channel: Channel,\n expectedMinionName: string,\n handler: MinionTickHandler,\n ): Promise<void> {\n const token = msg.content.toString();\n try {\n const tickToken = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(\n token,\n expectedMinionName,\n );\n\n if (!tickToken) {\n // Either a SCHEDULED_CRON token leaked into this queue (shouldn't\n // happen given the publisher routing, but guard anyway) or the\n // token targets a different minion name. Drop without requeue —\n // and surface as a warning since either case represents a routing\n // misconfiguration that operators should investigate.\n this.logger.warn('Skipping non-actionable scheduled token on minion-tick queue', {\n expectedMinionName,\n });\n channel.nack(msg, false, false);\n return;\n }\n\n this.logger.info('Processing minion tick', {\n jobId: tickToken.jobId,\n minionName: tickToken.minionName,\n applicationId: tickToken.applicationId,\n });\n\n await handler(tickToken);\n channel.ack(msg);\n } catch (error) {\n // `WildoBackendError` is NOT `instanceof Error`, so the previous ternary reported\n // literally 'Unknown error' for EVERY typed framework failure — including the\n // verification rejection that is by far the most common cause here. Two masking\n // layers stacked (this one and the verifier's) is why a tick that simply outlived\n // its 5-minute token TTL looked identical to a forged one.\n this.logger.error('Minion tick processing failed', {\n expectedMinionName,\n error: describeCaughtError(error),\n });\n // Per KD-6: scheduled jobs don't retry via queue — the next cron\n // cycle re-publishes a fresh tick. NACK without requeue.\n channel.nack(msg, false, false);\n }\n }\n}\n"]}
@@ -0,0 +1,98 @@
1
+ import type { ProjectedMinionInitializationConfig, ProviderRuntimeArtifact, SystemAccessBackendService } from '@wildo-ai/saas-backend-lib';
2
+ import type { MinionTickHandler } from '../queue/minion-tick-consumer.backend.service';
3
+ import type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';
4
+ type ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];
5
+ type ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];
6
+ export interface MinionProviderRuntimeArtifact {
7
+ __AUTOGENERATED__: string;
8
+ generatedBy: ProviderRuntimeArtifact['generatedBy'];
9
+ generatedAt: string;
10
+ sourceDigest: string;
11
+ providerRefs?: ProviderRuntimeArtifact['providerRefs'];
12
+ /**
13
+ * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).
14
+ *
15
+ * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the
16
+ * CLI emits and this shape omits is a field the projection can only reach through a cast —
17
+ * which would assert, across a package boundary, the very thing nobody checked.
18
+ */
19
+ providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];
20
+ providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];
21
+ lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];
22
+ artifactKind: 'minions';
23
+ modules: ProviderRuntimeModules;
24
+ scopes: Record<string, ProviderRuntimeScope>;
25
+ }
26
+ /**
27
+ * The surface a minion's tick handler is given to do its work with.
28
+ *
29
+ * Handed to the handler rather than left for each author to resolve from the
30
+ * container, for the same reason the runtime identity is established in
31
+ * framework-owned startup: a boundary an author has to find is a boundary an author
32
+ * can get wrong. What arrives here is already the CONTAINED surface —
33
+ * `systemAccess` routes through the minion's `resourceAccess` ACL proxy, because
34
+ * minion startup rebinds the services registry to the scoped decorator before any
35
+ * tick is delivered.
36
+ *
37
+ * So a minion's effective authority is the INTERSECTION of two independent doors
38
+ * (see `.claude/plans/minion-runtime-scope.md` D6):
39
+ *
40
+ * - `resourceAccess` — operator-declared containment, enforced by the DI proxy;
41
+ * - the system-access door — the sanctioned per-tenant-authorization bypass, which
42
+ * for a minion is fail-closed on audit (D9 + OQ-5b): audited, or refused.
43
+ *
44
+ * Neither subsumes the other. A resource the ACL forbids is refused even though the
45
+ * system-access door would have allowed it, and a read the ACL permits is still
46
+ * refused if it cannot be recorded.
47
+ */
48
+ export interface MinionTickContext {
49
+ /**
50
+ * The sanctioned privileged-access door, already contained by this minion's
51
+ * `resourceAccess` whitelist.
52
+ *
53
+ * Use this — never a repository directly (the `no-direct-repo-from-minion` ESLint
54
+ * rule enforces that) — so every access stays inside both doors and leaves an
55
+ * attributable audit record naming this minion.
56
+ */
57
+ systemAccess: SystemAccessBackendService;
58
+ /** This minion's name, as declared in `wildo.saas.config.ts > minions`. */
59
+ minionName: string;
60
+ /**
61
+ * Read this minion's OWN cron schedule and recent runs (R4).
62
+ *
63
+ * Present only when the application declared the `own_cron_records` scope in
64
+ * this minion's `platformAccess`; otherwise the platform refuses and `read()`
65
+ * rejects. It is deliberately NOT absent from the type in that case — the
66
+ * authority decision belongs to the platform, and a client-side `undefined`
67
+ * would be this process guessing at it, which drifts the moment the
68
+ * declaration changes under a running minion.
69
+ *
70
+ * `read()` takes no arguments, and that is the contract rather than a
71
+ * convenience: the subject is derived from this runtime's attested identity,
72
+ * so another minion's schedule is not something this call could be asked for.
73
+ */
74
+ ownSchedule: OwnScheduleReaderBackendService;
75
+ }
76
+ /**
77
+ * Tick handler invoked by `MinionTickConsumerBackendService` once per verified
78
+ * `MINION_TICK` token addressed to this minion (KD-12).
79
+ */
80
+ export type MinionTickAuthorHandler = (token: Parameters<MinionTickHandler>[0], context: MinionTickContext) => Promise<void>;
81
+ export type MinionInitializationConfig = Omit<ProjectedMinionInitializationConfig, 'providerRuntime'> & {
82
+ providerRuntime?: ProviderRuntimeArtifact | MinionProviderRuntimeArtifact;
83
+ /**
84
+ * Tick handler invoked once per verified `MINION_TICK` token addressed to this
85
+ * minion (KD-12), receiving the framework-supplied {@link MinionTickContext}.
86
+ *
87
+ * Minion authors typically route the tick into the locally-hosted
88
+ * `flowsActorsRegistry` (per Q9 LOCKED — per-minion-local actor
89
+ * catalog). If omitted, the consumer still subscribes to the
90
+ * per-minion queue but logs a warning on every tick — useful as a
91
+ * fail-loud signal that ticks are arriving while the minion has not
92
+ * registered any tick-handling logic yet.
93
+ */
94
+ onTick?: MinionTickAuthorHandler;
95
+ };
96
+ export declare function defineMinionInit(config: MinionInitializationConfig): MinionInitializationConfig;
97
+ export {};
98
+ //# sourceMappingURL=define-minion-init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define-minion-init.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,uBAAuB,EACvB,0BAA0B,EAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAE7F,KAAK,oBAAoB,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC7D,KAAK,sBAAsB,GAAG,uBAAuB,CAAC,SAAS,CAAC,CAAC;AAEjE,MAA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0,0 +1,4 @@
1
+ export function defineMinionInit(config) {
2
+ return config;
3
+ }
4
+ //# sourceMappingURL=define-minion-init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define-minion-init.js","sourceRoot":"","sources":["../../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AA4GA,MAAM,UAAU,gBAAgB,CAC9B,MAAkC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ProjectedMinionInitializationConfig,\n ProviderRuntimeArtifact,\n SystemAccessBackendService,\n} from '@wildo-ai/saas-backend-lib';\nimport type { MinionTickHandler } from '../queue/minion-tick-consumer.backend.service';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\n\ntype ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];\ntype ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];\n\nexport interface MinionProviderRuntimeArtifact {\n __AUTOGENERATED__: string;\n generatedBy: ProviderRuntimeArtifact['generatedBy'];\n generatedAt: string;\n sourceDigest: string;\n providerRefs?: ProviderRuntimeArtifact['providerRefs'];\n /**\n * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).\n *\n * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the\n * CLI emits and this shape omits is a field the projection can only reach through a cast —\n * which would assert, across a package boundary, the very thing nobody checked.\n */\n providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];\n providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];\n lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];\n artifactKind: 'minions';\n modules: ProviderRuntimeModules;\n scopes: Record<string, ProviderRuntimeScope>;\n}\n\n/**\n * The surface a minion's tick handler is given to do its work with.\n *\n * Handed to the handler rather than left for each author to resolve from the\n * container, for the same reason the runtime identity is established in\n * framework-owned startup: a boundary an author has to find is a boundary an author\n * can get wrong. What arrives here is already the CONTAINED surface —\n * `systemAccess` routes through the minion's `resourceAccess` ACL proxy, because\n * minion startup rebinds the services registry to the scoped decorator before any\n * tick is delivered.\n *\n * So a minion's effective authority is the INTERSECTION of two independent doors\n * (see `.claude/plans/minion-runtime-scope.md` D6):\n *\n * - `resourceAccess` — operator-declared containment, enforced by the DI proxy;\n * - the system-access door — the sanctioned per-tenant-authorization bypass, which\n * for a minion is fail-closed on audit (D9 + OQ-5b): audited, or refused.\n *\n * Neither subsumes the other. A resource the ACL forbids is refused even though the\n * system-access door would have allowed it, and a read the ACL permits is still\n * refused if it cannot be recorded.\n */\nexport interface MinionTickContext {\n /**\n * The sanctioned privileged-access door, already contained by this minion's\n * `resourceAccess` whitelist.\n *\n * Use this — never a repository directly (the `no-direct-repo-from-minion` ESLint\n * rule enforces that) — so every access stays inside both doors and leaves an\n * attributable audit record naming this minion.\n */\n systemAccess: SystemAccessBackendService;\n /** This minion's name, as declared in `wildo.saas.config.ts > minions`. */\n minionName: string;\n /**\n * Read this minion's OWN cron schedule and recent runs (R4).\n *\n * Present only when the application declared the `own_cron_records` scope in\n * this minion's `platformAccess`; otherwise the platform refuses and `read()`\n * rejects. It is deliberately NOT absent from the type in that case — the\n * authority decision belongs to the platform, and a client-side `undefined`\n * would be this process guessing at it, which drifts the moment the\n * declaration changes under a running minion.\n *\n * `read()` takes no arguments, and that is the contract rather than a\n * convenience: the subject is derived from this runtime's attested identity,\n * so another minion's schedule is not something this call could be asked for.\n */\n ownSchedule: OwnScheduleReaderBackendService;\n}\n\n/**\n * Tick handler invoked by `MinionTickConsumerBackendService` once per verified\n * `MINION_TICK` token addressed to this minion (KD-12).\n */\nexport type MinionTickAuthorHandler = (\n token: Parameters<MinionTickHandler>[0],\n context: MinionTickContext,\n) => Promise<void>;\n\nexport type MinionInitializationConfig = Omit<ProjectedMinionInitializationConfig, 'providerRuntime'> & {\n providerRuntime?: ProviderRuntimeArtifact | MinionProviderRuntimeArtifact;\n /**\n * Tick handler invoked once per verified `MINION_TICK` token addressed to this\n * minion (KD-12), receiving the framework-supplied {@link MinionTickContext}.\n *\n * Minion authors typically route the tick into the locally-hosted\n * `flowsActorsRegistry` (per Q9 LOCKED — per-minion-local actor\n * catalog). If omitted, the consumer still subscribes to the\n * per-minion queue but logs a warning on every tick — useful as a\n * fail-loud signal that ticks are arriving while the minion has not\n * registered any tick-handling logic yet.\n */\n onTick?: MinionTickAuthorHandler;\n};\n\nexport function defineMinionInit(\n config: MinionInitializationConfig,\n): MinionInitializationConfig {\n return config;\n}\n"]}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A minion reading its OWN cron records from the platform (R4).
3
+ *
4
+ * ## The client is as selector-free as the route
5
+ *
6
+ * `read()` takes no arguments. Not a minion name, not an application id, not a
7
+ * job id — there is nothing to pass, so there is nothing an author could pass
8
+ * wrongly and nothing a later caller could parameterise. The route it calls
9
+ * derives its subject from the attestation, and this client's shape mirrors that
10
+ * rather than merely respecting it.
11
+ *
12
+ * That symmetry is deliberate. A client with a `minionName` argument that always
13
+ * happens to be filled with the caller's own name is one refactor away from being
14
+ * filled with something else, and the server would still be correct while every
15
+ * reader of this file had been taught the wrong mental model.
16
+ *
17
+ * ## Authority, and where it is decided
18
+ *
19
+ * Nothing here checks `platformAccess`. Two other places do, and both are better
20
+ * placed: apps-manager refuses to mint an attestation for a minion whose
21
+ * application declared no scope, and crontabs re-checks the scope before it
22
+ * queries. A third check here would be a client-side guess about a server-side
23
+ * decision — it would drift, and the day it drifted it would either refuse work
24
+ * the platform allows or promise work the platform refuses.
25
+ *
26
+ * So a minion without the scope gets a refusal from the platform, which is the
27
+ * party that knows.
28
+ */
29
+ import 'reflect-metadata';
30
+ import { AppConfigurationService, RuntimePrincipalAttestationBackendService, type ErrorBuilderBackendService, type LoggerService } from '@wildo-ai/saas-backend-lib';
31
+ /**
32
+ * One cron job that ticks this minion, with its recent runs.
33
+ *
34
+ * Typed structurally rather than importing the platform's `CronJob` — a minion
35
+ * runtime has no dependency on `platform-shared-lib` and giving it one to name a
36
+ * response body would be a package boundary crossed for a type alias.
37
+ */
38
+ export interface OwnScheduleEntry {
39
+ job: {
40
+ jobId: string;
41
+ name?: string;
42
+ schedule?: {
43
+ cron: string;
44
+ timezone?: string;
45
+ enabled?: boolean;
46
+ };
47
+ status?: string;
48
+ [field: string]: unknown;
49
+ };
50
+ recentExecutions: Array<{
51
+ status?: string;
52
+ startTime?: string;
53
+ endTime?: string;
54
+ error?: string;
55
+ [field: string]: unknown;
56
+ }>;
57
+ }
58
+ export declare class OwnScheduleReaderBackendService {
59
+ private readonly logger;
60
+ private readonly errorBuilder;
61
+ private readonly appConfigService;
62
+ private readonly attestations;
63
+ private baseUrl;
64
+ constructor(logger: LoggerService, errorBuilder: ErrorBuilderBackendService, appConfigService: AppConfigurationService, attestations: RuntimePrincipalAttestationBackendService);
65
+ /**
66
+ * This minion's cron job definitions and their recent runs.
67
+ *
68
+ * The attestation is fetched per call rather than held: the exchange caches it,
69
+ * so this costs nothing, and a client that cached it itself would eventually
70
+ * present an expired one.
71
+ */
72
+ read(): Promise<OwnScheduleEntry[]>;
73
+ private resolveBaseUrl;
74
+ }
75
+ //# sourceMappingURL=own-schedule-reader.backend.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"own-schedule-reader.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/own-schedule-reader.backend.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,kBAAkB,CAAC;AAK1B,OAAO,EACL,uBAAuB,EAEvB,yCAAyC,EAEzC,KAAK,0BAA0B,EAC/B,KAAK,aAAa,EACnB,MAAM,4BAA4B,CAAC;AAEpC;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE;QACH,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,OAAO,CAAA;SAAE,CAAC;QAClE,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC;IACF,gBAAgB,EAAE,KAAK,CAAC;QACtB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC,CAAC;CACJ;AAID,qBACa,+BAA+B;IAIL,OAAO,CAAC,QAAQ,CAAC,MAAM;IACV,OAAO,CAAC,QAAQ,CAAC,YAAY;IAChC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAE9E,OAAO,CAAC,QAAQ,CAAC,YAAY;IAP/B,OAAO,CAAC,OAAO,CAAuB;gBAGgB,MAAM,EAAE,aAAa,EACR,YAAY,EAAE,0BAA0B,EAC3C,gBAAgB,EAAE,uBAAuB,EAEtF,YAAY,EAAE,yCAAyC;IAG1E;;;;;;OAMG;IACU,IAAI,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAoChD,OAAO,CAAC,cAAc;CAqBvB"}
@@ -0,0 +1,124 @@
1
+ /**
2
+ * A minion reading its OWN cron records from the platform (R4).
3
+ *
4
+ * ## The client is as selector-free as the route
5
+ *
6
+ * `read()` takes no arguments. Not a minion name, not an application id, not a
7
+ * job id — there is nothing to pass, so there is nothing an author could pass
8
+ * wrongly and nothing a later caller could parameterise. The route it calls
9
+ * derives its subject from the attestation, and this client's shape mirrors that
10
+ * rather than merely respecting it.
11
+ *
12
+ * That symmetry is deliberate. A client with a `minionName` argument that always
13
+ * happens to be filled with the caller's own name is one refactor away from being
14
+ * filled with something else, and the server would still be correct while every
15
+ * reader of this file had been taught the wrong mental model.
16
+ *
17
+ * ## Authority, and where it is decided
18
+ *
19
+ * Nothing here checks `platformAccess`. Two other places do, and both are better
20
+ * placed: apps-manager refuses to mint an attestation for a minion whose
21
+ * application declared no scope, and crontabs re-checks the scope before it
22
+ * queries. A third check here would be a client-side guess about a server-side
23
+ * decision — it would drift, and the day it drifted it would either refuse work
24
+ * the platform allows or promise work the platform refuses.
25
+ *
26
+ * So a minion without the scope gets a refusal from the platform, which is the
27
+ * party that knows.
28
+ */
29
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
30
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
31
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
32
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
33
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
34
+ };
35
+ var __metadata = (this && this.__metadata) || function (k, v) {
36
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
37
+ };
38
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
39
+ return function (target, key) { decorator(target, key, paramIndex); }
40
+ };
41
+ import 'reflect-metadata';
42
+ import { inject, injectable } from 'inversify';
43
+ import { ErrorCustomMessageReference, ErrorType, WildoHeaderKeys } from '@wildo-ai/saas-models';
44
+ import { AppConfigurationService, PlatformApplicationType, RuntimePrincipalAttestationBackendService, SAAS_SERVICE_TYPES, } from '@wildo-ai/saas-backend-lib';
45
+ const OWN_SCHEDULE_PATH = '/api/v1/runtime-self/cron-jobs';
46
+ let OwnScheduleReaderBackendService = class OwnScheduleReaderBackendService {
47
+ logger;
48
+ errorBuilder;
49
+ appConfigService;
50
+ attestations;
51
+ baseUrl = null;
52
+ constructor(logger, errorBuilder, appConfigService, attestations) {
53
+ this.logger = logger;
54
+ this.errorBuilder = errorBuilder;
55
+ this.appConfigService = appConfigService;
56
+ this.attestations = attestations;
57
+ }
58
+ /**
59
+ * This minion's cron job definitions and their recent runs.
60
+ *
61
+ * The attestation is fetched per call rather than held: the exchange caches it,
62
+ * so this costs nothing, and a client that cached it itself would eventually
63
+ * present an expired one.
64
+ */
65
+ async read() {
66
+ const baseUrl = this.resolveBaseUrl();
67
+ const attestation = await this.attestations.getAttestation(PlatformApplicationType.PLATFORM_CRONTABS_BATCHES_MANAGER);
68
+ const response = await fetch(`${baseUrl}${OWN_SCHEDULE_PATH}`, {
69
+ method: 'GET',
70
+ headers: {
71
+ [WildoHeaderKeys.CONTENT_TYPE]: 'application/json',
72
+ // Deliberately the ONLY credential. A minion is not a platform service,
73
+ // so no `X-Service-Id`; and an application JWT would carry an identity
74
+ // meaning "some runtime of this app" — attaching one as well would only
75
+ // invite the server to read the weaker of the two.
76
+ [WildoHeaderKeys.RUNTIME_PRINCIPAL_TOKEN]: attestation,
77
+ },
78
+ });
79
+ if (!response.ok) {
80
+ // Surfaced rather than swallowed into an empty schedule. A refusal and "you
81
+ // have no jobs" are different answers, and returning `[]` for both would
82
+ // make a missing `platformAccess` declaration look like a correctly-empty
83
+ // schedule — the one failure an author cannot debug from the result.
84
+ throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, undefined, {
85
+ customMessageReference: ErrorCustomMessageReference.AUTHORIZATION,
86
+ context: {
87
+ message: 'The platform refused this runtime\'s own-schedule read',
88
+ status: response.status,
89
+ },
90
+ });
91
+ }
92
+ const body = (await response.json());
93
+ return body?.jobs ?? [];
94
+ }
95
+ resolveBaseUrl() {
96
+ if (this.baseUrl)
97
+ return this.baseUrl;
98
+ const baseUrl = this.appConfigService.config.runtime.endPoints[PlatformApplicationType.PLATFORM_CRONTABS_BATCHES_MANAGER]
99
+ ?.internalUrl;
100
+ if (!baseUrl) {
101
+ // A CONFIGURATION failure, not an authorization one. Blurring them would
102
+ // send an operator to inspect the minion's `platformAccess` declaration
103
+ // over what is really a missing endpoint in this deployment's topology.
104
+ throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {
105
+ customMessageReference: ErrorCustomMessageReference.CONFIGURATION,
106
+ context: { message: 'The crontabs-manager endpoint is not configured for this runtime' },
107
+ });
108
+ }
109
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
110
+ this.logger.debug?.('Own-schedule reader bound to the crontabs endpoint', { baseUrl: this.baseUrl });
111
+ return this.baseUrl;
112
+ }
113
+ };
114
+ OwnScheduleReaderBackendService = __decorate([
115
+ injectable(),
116
+ __param(0, inject(SAAS_SERVICE_TYPES.Logger)),
117
+ __param(1, inject(SAAS_SERVICE_TYPES.ErrorBuilderService)),
118
+ __param(2, inject(SAAS_SERVICE_TYPES.AppConfigService)),
119
+ __param(3, inject(SAAS_SERVICE_TYPES.RuntimePrincipalAttestationService)),
120
+ __metadata("design:paramtypes", [Function, Function, AppConfigurationService,
121
+ RuntimePrincipalAttestationBackendService])
122
+ ], OwnScheduleReaderBackendService);
123
+ export { OwnScheduleReaderBackendService };
124
+ //# sourceMappingURL=own-schedule-reader.backend.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"own-schedule-reader.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/services/own-schedule-reader.backend.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;;;;;;;;;;;;;AAEH,OAAO,kBAAkB,CAAC;AAE1B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAChG,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,yCAAyC,EACzC,kBAAkB,GAGnB,MAAM,4BAA4B,CAAC;AA0BpC,MAAM,iBAAiB,GAAG,gCAAgC,CAAC;AAGpD,IAAM,+BAA+B,GAArC,MAAM,+BAA+B;IAIY;IACa;IACH;IAE7C;IAPX,OAAO,GAAkB,IAAI,CAAC;IAEtC,YACsD,MAA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AAO;YAAE,OAAO,IAAI,CAAC,OAAO,CAAC;QAEtC,MAAM,OAAO,GACX,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,uBAAuB,CAAC,iCAAiC,CAAC;YACvG,EAAE,WAAW,CAAC;QAElB,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,yEAAyE;YACzE,wEAAwE;YACxE,wEAAwE;YACxE,MAAM,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,SAAS,CAAC,aAAa,EAAE,SAAS,EAAE;gBACrE,sBAAsB,EAAE,2BAA2B,CAAC,aAAa;gBACjE,OAAO,EAAE,EAAE,OAAO,EAAE,kEAAkE,EAAE;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,oDAAoD,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QACrG,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF,CAAA;AA3EY,+BAA+B;IAD3C,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IACjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;IAC9C,WAAA,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAA;IAC3C,WAAA,MAAM,CAAC,kBAAkB,CAAC,kCAAkC,CAAC,CAAA;yDADkB,uBAAuB;QAExE,yCAAyC;GAR/D,+BAA+B,CA2E3C","sourcesContent":["/**\n * A minion reading its OWN cron records from the platform (R4).\n *\n * ## The client is as selector-free as the route\n *\n * `read()` takes no arguments. Not a minion name, not an application id, not a\n * job id — there is nothing to pass, so there is nothing an author could pass\n * wrongly and nothing a later caller could parameterise. The route it calls\n * derives its subject from the attestation, and this client's shape mirrors that\n * rather than merely respecting it.\n *\n * That symmetry is deliberate. A client with a `minionName` argument that always\n * happens to be filled with the caller's own name is one refactor away from being\n * filled with something else, and the server would still be correct while every\n * reader of this file had been taught the wrong mental model.\n *\n * ## Authority, and where it is decided\n *\n * Nothing here checks `platformAccess`. Two other places do, and both are better\n * placed: apps-manager refuses to mint an attestation for a minion whose\n * application declared no scope, and crontabs re-checks the scope before it\n * queries. A third check here would be a client-side guess about a server-side\n * decision — it would drift, and the day it drifted it would either refuse work\n * the platform allows or promise work the platform refuses.\n *\n * So a minion without the scope gets a refusal from the platform, which is the\n * party that knows.\n */\n\nimport 'reflect-metadata';\n\nimport { inject, injectable } from 'inversify';\n\nimport { ErrorCustomMessageReference, ErrorType, WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport {\n AppConfigurationService,\n PlatformApplicationType,\n RuntimePrincipalAttestationBackendService,\n SAAS_SERVICE_TYPES,\n type ErrorBuilderBackendService,\n type LoggerService,\n} from '@wildo-ai/saas-backend-lib';\n\n/**\n * One cron job that ticks this minion, with its recent runs.\n *\n * Typed structurally rather than importing the platform's `CronJob` — a minion\n * runtime has no dependency on `platform-shared-lib` and giving it one to name a\n * response body would be a package boundary crossed for a type alias.\n */\nexport interface OwnScheduleEntry {\n job: {\n jobId: string;\n name?: string;\n schedule?: { cron: string; timezone?: string; enabled?: boolean };\n status?: string;\n [field: string]: unknown;\n };\n recentExecutions: Array<{\n status?: string;\n startTime?: string;\n endTime?: string;\n error?: string;\n [field: string]: unknown;\n }>;\n}\n\nconst OWN_SCHEDULE_PATH = '/api/v1/runtime-self/cron-jobs';\n\n@injectable()\nexport class OwnScheduleReaderBackendService {\n private baseUrl: string | null = null;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_SERVICE_TYPES.RuntimePrincipalAttestationService)\n private readonly attestations: RuntimePrincipalAttestationBackendService,\n ) {}\n\n /**\n * This minion's cron job definitions and their recent runs.\n *\n * The attestation is fetched per call rather than held: the exchange caches it,\n * so this costs nothing, and a client that cached it itself would eventually\n * present an expired one.\n */\n public async read(): Promise<OwnScheduleEntry[]> {\n const baseUrl = this.resolveBaseUrl();\n const attestation = await this.attestations.getAttestation(\n PlatformApplicationType.PLATFORM_CRONTABS_BATCHES_MANAGER,\n );\n\n const response = await fetch(`${baseUrl}${OWN_SCHEDULE_PATH}`, {\n method: 'GET',\n headers: {\n [WildoHeaderKeys.CONTENT_TYPE]: 'application/json',\n // Deliberately the ONLY credential. A minion is not a platform service,\n // so no `X-Service-Id`; and an application JWT would carry an identity\n // meaning \"some runtime of this app\" — attaching one as well would only\n // invite the server to read the weaker of the two.\n [WildoHeaderKeys.RUNTIME_PRINCIPAL_TOKEN]: attestation,\n },\n });\n\n if (!response.ok) {\n // Surfaced rather than swallowed into an empty schedule. A refusal and \"you\n // have no jobs\" are different answers, and returning `[]` for both would\n // make a missing `platformAccess` declaration look like a correctly-empty\n // schedule — the one failure an author cannot debug from the result.\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATION,\n context: {\n message: 'The platform refused this runtime\\'s own-schedule read',\n status: response.status,\n },\n });\n }\n\n const body = (await response.json()) as { jobs?: OwnScheduleEntry[] } | null;\n return body?.jobs ?? [];\n }\n\n private resolveBaseUrl(): string {\n if (this.baseUrl) return this.baseUrl;\n\n const baseUrl =\n this.appConfigService.config.runtime.endPoints[PlatformApplicationType.PLATFORM_CRONTABS_BATCHES_MANAGER]\n ?.internalUrl;\n\n if (!baseUrl) {\n // A CONFIGURATION failure, not an authorization one. Blurring them would\n // send an operator to inspect the minion's `platformAccess` declaration\n // over what is really a missing endpoint in this deployment's topology.\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: 'The crontabs-manager endpoint is not configured for this runtime' },\n });\n }\n\n this.baseUrl = baseUrl.replace(/\\/+$/, '');\n this.logger.debug?.('Own-schedule reader bound to the crontabs endpoint', { baseUrl: this.baseUrl });\n return this.baseUrl;\n }\n}\n"]}
@@ -0,0 +1,48 @@
1
+ import { type AppConfigurationService, type LoggerService, type RuntimePrincipalBackendService, type SystemAccessBackendService, type StartApplicationBackendService } from '@wildo-ai/saas-backend-lib';
2
+ import type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';
3
+ import { MinionTickConsumerBackendService } from '../queue/minion-tick-consumer.backend.service';
4
+ import type { MinionInitializationConfig } from './define-minion-init';
5
+ export declare class StartMinionApplicationBackendService {
6
+ private readonly startApplicationService;
7
+ private readonly appConfigService;
8
+ private readonly tickConsumer;
9
+ private readonly logger;
10
+ private readonly runtimePrincipal;
11
+ private readonly systemAccess;
12
+ private readonly ownScheduleReader;
13
+ private tickConsumerStarted;
14
+ constructor(startApplicationService: StartApplicationBackendService, appConfigService: AppConfigurationService, tickConsumer: MinionTickConsumerBackendService, logger: LoggerService, runtimePrincipal: RuntimePrincipalBackendService, systemAccess: SystemAccessBackendService, ownScheduleReader: OwnScheduleReaderBackendService);
15
+ initialize(config: MinionInitializationConfig): Promise<void>;
16
+ shutdown(): Promise<void>;
17
+ isApplicationInitialized(): boolean;
18
+ private startTickConsumer;
19
+ private getMinionRuntimeConfig;
20
+ /**
21
+ * Bridge the per-minion materialized provider runtime artifact into the
22
+ * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`
23
+ * (and ultimately filtered by `BackendProviderRegistryBackendService`).
24
+ *
25
+ * Three accepted input shapes:
26
+ *
27
+ * 1. `{ artifactKind: 'backend', scope: ... }` — already projected to a
28
+ * backend-shaped single-scope artifact (e.g. produced by an
29
+ * embedding host that pre-selected the scope).
30
+ * 2. `{ artifactKind: 'minions', scope: ..., scopes: undefined }` —
31
+ * what `wildo config sync` writes to each minion's
32
+ * `src/generated/wildo-provider-runtime.generated.ts`. The CLI calls
33
+ * `selectScopedProviderRuntimeArtifact(artifacts.minions, minionKey)`
34
+ * so the file already carries only this minion's scope. We unwrap
35
+ * it here to the canonical backend-shaped artifact.
36
+ * 3. `{ artifactKind: 'minions', scopes: { [name]: ... } }` —
37
+ * multi-scope minion artifact (legacy / non-CLI-driven hosts that
38
+ * pass the unscoped artifact). We resolve `scopes[minionName]`.
39
+ *
40
+ * Anything else fails fast with a clear locator. Each minion process
41
+ * must only see its own scope — there is no fallback to other scopes,
42
+ * no merging across minions, and no silent recovery from a missing
43
+ * scope.
44
+ */
45
+ private normalizeProviderRuntime;
46
+ private selectMinionProviderRuntimeScope;
47
+ }
48
+ //# sourceMappingURL=start-minion-application.backend.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-minion-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAI5B,KAAK,aAAa,EAElB,KAAK,8BAA8B,EACnC,KAAK,0BAA0B,EAE/B,KAAK,8BAA8B,EACpC,MAAM,4BAA4B,CAAC;AAKpC,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EACL,gCAAgC,EAEjC,MAAM,+CAA+C,CAAC;AACvD,OAAO,KAAK,EACV,0BAA0B,EAI3B,MAAM,sBAAsB,CAAC;AAQ9B,qBACa,oCAAoC;IAK7C,OAAO,CAAC,QAAQ,CAAC,uBAAuB;IAExC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAhBpC,OAAO,CAAC,mBAAmB,CAAS;gBAIjB,uBAAuB,EAAE,8BAA8B,EAEvD,gBAAgB,EAAE,uBAAuB,EAEzC,YAAY,EAAE,gCAAgC,EAE9C,MAAM,EAAE,aAAa,EAErB,gBAAgB,EAAE,8BAA8B,EAEhD,YAAY,EAAE,0BAA0B,EAExC,iBAAiB,EAAE,+BAA+B;IAGxD,UAAU,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO,CAAC,IAAI,CAAC;IAmI7D,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAe/B,wBAAwB,IAAI,OAAO;YAI5B,iBAAiB;IA4C/B,OAAO,CAAC,sBAAsB;IAkC9B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,gCAAgC;CAoEzC"}