@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,398 @@
1
+ import {
2
+ type AppConfiguration,
3
+ type AppConfigurationService,
4
+ ApplicationRuntimeProfile,
5
+ inject,
6
+ injectable,
7
+ type LoggerService,
8
+ type ProviderRuntimeArtifact,
9
+ type RuntimePrincipalBackendService,
10
+ type SystemAccessBackendService,
11
+ SAAS_SERVICE_TYPES,
12
+ type StartApplicationBackendService,
13
+ } from '@wildo-ai/saas-backend-lib';
14
+ import { ErrorCustomMessageReference, ErrorType } from '@wildo-ai/saas-models';
15
+ import { assertProviderRuntimeEnvInSync } from '@wildo-ai/platform-config-lib';
16
+ import { MinionScopedServicesRegistryHandlerBackendService } from '../../base-classes/services/services/minion-scoped-services-registry-handler.backend.service';
17
+ import { SAAS_MINIONS_SERVICE_TYPES } from '../../inject/models/service-types';
18
+ import type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';
19
+ import {
20
+ MinionTickConsumerBackendService,
21
+ type MinionTickHandler,
22
+ } from '../queue/minion-tick-consumer.backend.service';
23
+ import type {
24
+ MinionInitializationConfig,
25
+ MinionProviderRuntimeArtifact,
26
+ MinionTickAuthorHandler,
27
+ MinionTickContext,
28
+ } from './define-minion-init';
29
+
30
+ type MinionAwareAppConfiguration = AppConfiguration & {
31
+ minions?: Record<string, MinionRuntimeConfig>;
32
+ };
33
+
34
+ type MinionRuntimeConfig = NonNullable<NonNullable<AppConfiguration['minions']>[string]>;
35
+
36
+ @injectable()
37
+ export class StartMinionApplicationBackendService {
38
+ private tickConsumerStarted = false;
39
+
40
+ constructor(
41
+ @inject(SAAS_SERVICE_TYPES.StartApplicationService)
42
+ private readonly startApplicationService: StartApplicationBackendService,
43
+ @inject(SAAS_SERVICE_TYPES.AppConfigService)
44
+ private readonly appConfigService: AppConfigurationService,
45
+ @inject(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)
46
+ private readonly tickConsumer: MinionTickConsumerBackendService,
47
+ @inject(SAAS_SERVICE_TYPES.Logger)
48
+ private readonly logger: LoggerService,
49
+ @inject(SAAS_SERVICE_TYPES.RuntimePrincipalService)
50
+ private readonly runtimePrincipal: RuntimePrincipalBackendService,
51
+ @inject(SAAS_SERVICE_TYPES.SystemAccessService)
52
+ private readonly systemAccess: SystemAccessBackendService,
53
+ @inject(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)
54
+ private readonly ownScheduleReader: OwnScheduleReaderBackendService,
55
+ ) {}
56
+
57
+ public async initialize(config: MinionInitializationConfig): Promise<void> {
58
+ const {
59
+ minionName,
60
+ serviceIdentifier,
61
+ onTick,
62
+ ...startupConfig
63
+ } = config;
64
+ // Declare WHO this process is before anything can perform a privileged access.
65
+ //
66
+ // Established here, in framework-owned minion startup, rather than left to each
67
+ // minion author — attribution that an author can forget is attribution that will
68
+ // be missing exactly when an auditor needs it. Every minion therefore carries its
69
+ // identity structurally, by virtue of being a minion.
70
+ //
71
+ // Attribution only: this grants nothing. A minion's operations are governed by its
72
+ // role and its `resourceAccess` whitelist; its cross-tenant reach comes from the
73
+ // system-access door. See `.claude/plans/minion-runtime-scope.md` (D9).
74
+ //
75
+ // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged access by a non-human
76
+ // background runtime is attributable to that runtime.
77
+ this.runtimePrincipal.initialize({
78
+ runtimeProfile: ApplicationRuntimeProfile.MINION,
79
+ runtimeKey: minionName,
80
+ serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,
81
+ });
82
+
83
+ const normalizedProviderRuntime = this.normalizeProviderRuntime(
84
+ startupConfig.providerRuntime,
85
+ minionName,
86
+ );
87
+
88
+ // Boot-time fail-closed reconciliation between the typed
89
+ // `wildo-provider-runtime.generated.ts` artifact and the
90
+ // `.wildo-providers.env` file mounted into this process. Catches
91
+ // stale-sync drift (operator regenerated one surface but not the
92
+ // other) BEFORE the registry filter would silently boot with
93
+ // mismatched topology.
94
+ //
95
+ // Skipped when:
96
+ // - the artifact is absent (host authored zero providers AND no
97
+ // scope block in `wildo.saas.config.ts`); or
98
+ // - the artifact has zero `providerRefs` (host authored an
99
+ // explicit empty scope `providers: {}`). The CLI emitter
100
+ // deliberately does NOT write `.wildo-providers.env` in that
101
+ // case, so the env-vars are absent — running the assertion
102
+ // would raise a false-positive fail-closed.
103
+ // Defensive `?? []` — the schema marks `providerRefs` optional, so
104
+ // a hand-crafted artifact (test fixture / future format drift)
105
+ // could omit it. Without the fallback `.length` would TypeError
106
+ // before fail-closed produced its actionable message. Production
107
+ // CLI emit always defaults to `[]`, so this is hardening only.
108
+ const projectedProviderRefs = normalizedProviderRuntime?.providerRefs ?? [];
109
+ if (normalizedProviderRuntime && projectedProviderRefs.length > 0) {
110
+ assertProviderRuntimeEnvInSync({
111
+ artifactProviderRefs: projectedProviderRefs,
112
+ artifactSourceDigest: normalizedProviderRuntime.sourceDigest,
113
+ hostKind: 'minion',
114
+ hostKey: minionName,
115
+ });
116
+ }
117
+
118
+ await this.startApplicationService.initialize({
119
+ ...startupConfig,
120
+ providerRuntime: normalizedProviderRuntime,
121
+ headlessMode: true,
122
+ skipCronSync: true,
123
+ // A minion reuses the full backend startup lifecycle but is NOT a job
124
+ // worker for the shared application queues — it consumes ONLY its own
125
+ // `minion-tick.<name>` queue (subscribed below via `startTickConsumer`).
126
+ // Skipping the shared job consumers keeps RabbitMQ from round-robining
127
+ // scheduled-cron ticks onto this process (which would dead-letter every
128
+ // tick it can't interpret). The broker connection itself is still made,
129
+ // because the tick consumer depends on it.
130
+ skipJobConsumers: true,
131
+ serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,
132
+ afterResourcesRegistryInitialized: async ({
133
+ appConfig,
134
+ resourcesRegistryService,
135
+ errorBuilder,
136
+ }) => {
137
+ const minionConfig = this.getMinionRuntimeConfig(
138
+ appConfig as MinionAwareAppConfiguration,
139
+ minionName,
140
+ errorBuilder,
141
+ );
142
+ const resourceAccess = minionConfig.resourceAccess;
143
+ const knownResourceTypes = new Set(resourcesRegistryService.getResourceTypes());
144
+ const unknownResourceTypes = [
145
+ ...(resourceAccess?.read ?? []),
146
+ ...(resourceAccess?.write ?? []),
147
+ ].filter((resourceType, index, all) => (
148
+ resourceType !== '*'
149
+ && !knownResourceTypes.has(resourceType)
150
+ && all.indexOf(resourceType) === index
151
+ ));
152
+
153
+ if (unknownResourceTypes.length > 0) {
154
+ throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {
155
+ customMessageReference: ErrorCustomMessageReference.CONFIGURATION,
156
+ context: {
157
+ message:
158
+ `Minion '${minionName}' references unknown resources in resourceAccess: `
159
+ + `[${unknownResourceTypes.join(', ')}].`,
160
+ minionName,
161
+ unknownResourceTypes,
162
+ },
163
+ });
164
+ }
165
+ },
166
+ servicesRegistryDecoratorFactory: (registry, { appConfig, errorBuilder }) => (
167
+ new MinionScopedServicesRegistryHandlerBackendService(
168
+ registry as any,
169
+ minionName,
170
+ this.getMinionRuntimeConfig(
171
+ appConfig as MinionAwareAppConfiguration,
172
+ minionName,
173
+ errorBuilder,
174
+ ).resourceAccess,
175
+ ).asDecoratedRegistry()
176
+ ),
177
+ });
178
+
179
+ // KD-12 auto-wiring: every minion subscribes to its dedicated tick
180
+ // queue (`wildo.queue.<appId>.minion-tick.<minionName>`). Cron-mode
181
+ // minions receive ticks from `platform-crontabs-batches-manager`;
182
+ // always-up minions receive nothing on this queue under normal
183
+ // operation but the subscription is harmless (no message ⇒ no
184
+ // dispatch) and keeps the runtime contract symmetric across modes.
185
+ await this.startTickConsumer(minionName, onTick);
186
+ }
187
+
188
+ public async shutdown(): Promise<void> {
189
+ if (this.tickConsumerStarted) {
190
+ try {
191
+ await this.tickConsumer.stop();
192
+ } catch (error) {
193
+ this.logger.warn('Failed to stop minion tick consumer cleanly', {
194
+ error: error instanceof Error ? error.message : String(error),
195
+ });
196
+ } finally {
197
+ this.tickConsumerStarted = false;
198
+ }
199
+ }
200
+ await this.startApplicationService.shutdown();
201
+ }
202
+
203
+ public isApplicationInitialized(): boolean {
204
+ return this.startApplicationService.isApplicationInitialized();
205
+ }
206
+
207
+ private async startTickConsumer(
208
+ minionName: string,
209
+ onTick: MinionTickAuthorHandler | undefined,
210
+ ): Promise<void> {
211
+ // The surface the handler is ALLOWED to work with, assembled once at the tick
212
+ // boundary. Handed to the author rather than left for them to resolve from the
213
+ // container: `systemAccess` here is already contained by this minion's
214
+ // `resourceAccess` ACL, because startup rebinds the services registry to the
215
+ // scoped decorator before any tick can be delivered. An author who resolved the
216
+ // door themselves could bypass that; an author handed this one cannot.
217
+ const context: MinionTickContext = {
218
+ systemAccess: this.systemAccess,
219
+ minionName,
220
+ // Same reasoning as `systemAccess`: handed to the author rather than left
221
+ // to be resolved from the container. A reader an author constructs is a
222
+ // reader an author could construct with a different identity; this one is
223
+ // bound to the process's own attested principal and cannot be pointed
224
+ // elsewhere.
225
+ ownSchedule: this.ownScheduleReader,
226
+ };
227
+
228
+ const handler: MinionTickHandler = onTick
229
+ ? async (token) => onTick(token, context)
230
+ : async (token) => {
231
+ this.logger.warn(
232
+ 'Minion tick received but no onTick handler is registered — ' +
233
+ 'wire `defineMinionInit({ ..., onTick })` to route ticks into ' +
234
+ 'the locally-hosted actor system (per Q9 LOCKED).',
235
+ {
236
+ jobId: token.jobId,
237
+ minionName: token.minionName,
238
+ applicationId: token.applicationId,
239
+ },
240
+ );
241
+ };
242
+
243
+ await this.tickConsumer.start({
244
+ applicationId: this.appConfigService.applicationId,
245
+ minionName,
246
+ handler,
247
+ });
248
+ this.tickConsumerStarted = true;
249
+ }
250
+
251
+ private getMinionRuntimeConfig(
252
+ appConfig: MinionAwareAppConfiguration,
253
+ minionName: string,
254
+ errorBuilder?: {
255
+ buildError: (
256
+ errorType: ErrorType,
257
+ executionContext: undefined,
258
+ options: {
259
+ customMessageReference?: ErrorCustomMessageReference;
260
+ context?: Record<string, unknown>;
261
+ },
262
+ ) => unknown;
263
+ },
264
+ ): MinionRuntimeConfig {
265
+ const minionConfig = appConfig.minions?.[minionName];
266
+ if (minionConfig) {
267
+ return minionConfig;
268
+ }
269
+
270
+ if (!errorBuilder) {
271
+ throw new Error(`Minion '${minionName}' is missing from appConfig.minions.`);
272
+ }
273
+
274
+ throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {
275
+ customMessageReference: ErrorCustomMessageReference.CONFIGURATION,
276
+ context: {
277
+ message:
278
+ `Minion '${minionName}' is not declared in the managed runtime config. `
279
+ + 'Re-sync the application bootstrap material before starting the minion.',
280
+ minionName,
281
+ },
282
+ });
283
+ }
284
+
285
+ /**
286
+ * Bridge the per-minion materialized provider runtime artifact into the
287
+ * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`
288
+ * (and ultimately filtered by `BackendProviderRegistryBackendService`).
289
+ *
290
+ * Three accepted input shapes:
291
+ *
292
+ * 1. `{ artifactKind: 'backend', scope: ... }` — already projected to a
293
+ * backend-shaped single-scope artifact (e.g. produced by an
294
+ * embedding host that pre-selected the scope).
295
+ * 2. `{ artifactKind: 'minions', scope: ..., scopes: undefined }` —
296
+ * what `wildo config sync` writes to each minion's
297
+ * `src/generated/wildo-provider-runtime.generated.ts`. The CLI calls
298
+ * `selectScopedProviderRuntimeArtifact(artifacts.minions, minionKey)`
299
+ * so the file already carries only this minion's scope. We unwrap
300
+ * it here to the canonical backend-shaped artifact.
301
+ * 3. `{ artifactKind: 'minions', scopes: { [name]: ... } }` —
302
+ * multi-scope minion artifact (legacy / non-CLI-driven hosts that
303
+ * pass the unscoped artifact). We resolve `scopes[minionName]`.
304
+ *
305
+ * Anything else fails fast with a clear locator. Each minion process
306
+ * must only see its own scope — there is no fallback to other scopes,
307
+ * no merging across minions, and no silent recovery from a missing
308
+ * scope.
309
+ */
310
+ private normalizeProviderRuntime(
311
+ providerRuntime: MinionInitializationConfig['providerRuntime'],
312
+ minionName: string,
313
+ ): ProviderRuntimeArtifact | undefined {
314
+ if (!providerRuntime) {
315
+ return undefined;
316
+ }
317
+ if (providerRuntime.artifactKind === 'backend') {
318
+ return providerRuntime;
319
+ }
320
+ const artifactKind = providerRuntime.artifactKind;
321
+ if (artifactKind !== 'minions') {
322
+ throw new Error(
323
+ `Unsupported provider runtime artifactKind '${artifactKind}' for minion '${minionName}'.`,
324
+ );
325
+ }
326
+
327
+ return this.selectMinionProviderRuntimeScope(providerRuntime, minionName);
328
+ }
329
+
330
+ private selectMinionProviderRuntimeScope(
331
+ providerRuntime: MinionProviderRuntimeArtifact,
332
+ minionName: string,
333
+ ): ProviderRuntimeArtifact {
334
+ const preScopedScope = (providerRuntime as MinionProviderRuntimeArtifact & {
335
+ scope?: ProviderRuntimeArtifact['scope'];
336
+ }).scope;
337
+ const scopes = providerRuntime.scopes as
338
+ | Record<string, ProviderRuntimeArtifact['scope']>
339
+ | undefined;
340
+
341
+ let scope: ProviderRuntimeArtifact['scope'] | undefined;
342
+
343
+ if (preScopedScope && (!scopes || Object.keys(scopes).length === 0)) {
344
+ // Shape 2 — the CLI-emitted per-minion module.
345
+ scope = preScopedScope;
346
+ } else if (scopes) {
347
+ // Shape 3 — unscoped multi-scope artifact.
348
+ scope = scopes[minionName];
349
+ if (!scope) {
350
+ throw new Error(
351
+ `Provider runtime artifact does not contain a scope for minion '${minionName}'. `
352
+ + `Re-run \`wildo config sync\` and verify the minion is declared in `
353
+ + `wildo.saas.config.ts \`providers.scopes.minions\`.`,
354
+ );
355
+ }
356
+ }
357
+
358
+ if (!scope) {
359
+ throw new Error(
360
+ `Provider runtime artifact for minion '${minionName}' is missing both a `
361
+ + `pre-scoped \`scope\` and a multi-scope \`scopes\` map. The artifact is malformed.`,
362
+ );
363
+ }
364
+
365
+ // Recompute `providerRefs` from the projected per-host scope, NOT
366
+ // from the multi-scope union the parent artifact carries. The
367
+ // `buildMultiScopeArtifactMetadata` upstream computes
368
+ // `providerRefs` as the union across all hosts; preserving that
369
+ // here would make the boot-time `assertProviderRuntimeEnvInSync`
370
+ // guard treat sibling-scope refs as "this host has providers" and
371
+ // mistakenly run reconciliation on hosts whose own scope is empty.
372
+ // Mirrors `selectScopedProviderRuntimeArtifact` in
373
+ // `provider-runtime-artifacts.ts`.
374
+ const projectedProviderRefs = Object.keys(scope.providers ?? {}).sort();
375
+ // Narrowed with the refs, for the same reason (#330): the import map on a multi-scope artifact
376
+ // is the union across every host, and handing this host a sibling's package specifiers would
377
+ // tell it that it may load something it never declared.
378
+ const projectedProviderRuntimeImports = Object.fromEntries(
379
+ Object.entries(
380
+ providerRuntime.providerRuntimeImports ?? {},
381
+ ).filter(([providerRef]) => projectedProviderRefs.includes(providerRef)),
382
+ );
383
+
384
+ return {
385
+ __AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,
386
+ generatedBy: providerRuntime.generatedBy,
387
+ generatedAt: providerRuntime.generatedAt,
388
+ sourceDigest: providerRuntime.sourceDigest,
389
+ providerRefs: projectedProviderRefs,
390
+ providerRuntimeImports: projectedProviderRuntimeImports,
391
+ providerGraphDigest: providerRuntime.providerGraphDigest,
392
+ lockfileSectionDigest: providerRuntime.lockfileSectionDigest,
393
+ artifactKind: 'backend',
394
+ modules: providerRuntime.modules,
395
+ scope,
396
+ };
397
+ }
398
+ }