@wildo-ai/wildo-cli 1.1.12 → 1.1.13

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 (102) hide show
  1. package/dist/src/commands/config/sync.command.d.ts.map +1 -1
  2. package/dist/src/commands/config/sync.command.js +1 -0
  3. package/dist/src/commands/config/sync.command.js.map +1 -1
  4. package/dist/src/commands/context/journey.command.d.ts.map +1 -1
  5. package/dist/src/commands/context/journey.command.js +8 -0
  6. package/dist/src/commands/context/journey.command.js.map +1 -1
  7. package/dist/src/commands/creation/drive.command.d.ts.map +1 -1
  8. package/dist/src/commands/creation/drive.command.js +2 -0
  9. package/dist/src/commands/creation/drive.command.js.map +1 -1
  10. package/dist/src/commands/fwk/publish-all.command.d.ts.map +1 -1
  11. package/dist/src/commands/fwk/publish-all.command.js +8 -0
  12. package/dist/src/commands/fwk/publish-all.command.js.map +1 -1
  13. package/dist/src/commands/local/dev.command.d.ts +68 -0
  14. package/dist/src/commands/local/dev.command.d.ts.map +1 -1
  15. package/dist/src/commands/local/dev.command.js +216 -8
  16. package/dist/src/commands/local/dev.command.js.map +1 -1
  17. package/dist/src/commands/local/doctor.command.d.ts +22 -9
  18. package/dist/src/commands/local/doctor.command.d.ts.map +1 -1
  19. package/dist/src/commands/local/doctor.command.js +45 -42
  20. package/dist/src/commands/local/doctor.command.js.map +1 -1
  21. package/dist/src/commands/providers/connect.command.d.ts.map +1 -1
  22. package/dist/src/commands/providers/connect.command.js +11 -1
  23. package/dist/src/commands/providers/connect.command.js.map +1 -1
  24. package/dist/src/commands/seal/currency.command.d.ts +13 -0
  25. package/dist/src/commands/seal/currency.command.d.ts.map +1 -0
  26. package/dist/src/commands/seal/currency.command.js +52 -0
  27. package/dist/src/commands/seal/currency.command.js.map +1 -0
  28. package/dist/src/commands/seal/seal-admin-door.utils.d.ts.map +1 -1
  29. package/dist/src/commands/seal/seal-admin-door.utils.js +2 -0
  30. package/dist/src/commands/seal/seal-admin-door.utils.js.map +1 -1
  31. package/dist/src/commands/seal/verify.command.d.ts +5 -0
  32. package/dist/src/commands/seal/verify.command.d.ts.map +1 -1
  33. package/dist/src/commands/seal/verify.command.js +26 -2
  34. package/dist/src/commands/seal/verify.command.js.map +1 -1
  35. package/dist/src/services/application/content-guardrail-classifier.service.d.ts +19 -0
  36. package/dist/src/services/application/content-guardrail-classifier.service.d.ts.map +1 -1
  37. package/dist/src/services/application/content-guardrail-classifier.service.js +75 -11
  38. package/dist/src/services/application/content-guardrail-classifier.service.js.map +1 -1
  39. package/dist/src/services/application/local-provider-doubles.service.d.ts +98 -0
  40. package/dist/src/services/application/local-provider-doubles.service.d.ts.map +1 -0
  41. package/dist/src/services/application/local-provider-doubles.service.js +214 -0
  42. package/dist/src/services/application/local-provider-doubles.service.js.map +1 -0
  43. package/dist/src/services/application/system-of-record-simulators.service.d.ts +21 -2
  44. package/dist/src/services/application/system-of-record-simulators.service.d.ts.map +1 -1
  45. package/dist/src/services/application/system-of-record-simulators.service.js +21 -12
  46. package/dist/src/services/application/system-of-record-simulators.service.js.map +1 -1
  47. package/dist/src/services/companion/creation-drive.service.d.ts +32 -2
  48. package/dist/src/services/companion/creation-drive.service.d.ts.map +1 -1
  49. package/dist/src/services/companion/creation-drive.service.js +61 -4
  50. package/dist/src/services/companion/creation-drive.service.js.map +1 -1
  51. package/dist/src/services/credentials/credentials.schemas.d.ts +6 -0
  52. package/dist/src/services/credentials/credentials.schemas.d.ts.map +1 -1
  53. package/dist/src/services/credentials/credentials.schemas.js +7 -1
  54. package/dist/src/services/credentials/credentials.schemas.js.map +1 -1
  55. package/dist/src/services/credentials/provider-env-vars.utils.d.ts.map +1 -1
  56. package/dist/src/services/credentials/provider-env-vars.utils.js +11 -3
  57. package/dist/src/services/credentials/provider-env-vars.utils.js.map +1 -1
  58. package/dist/src/services/data-services/data-services.schemas.d.ts +9 -0
  59. package/dist/src/services/data-services/data-services.schemas.d.ts.map +1 -1
  60. package/dist/src/services/data-services/data-services.schemas.js +9 -0
  61. package/dist/src/services/data-services/data-services.schemas.js.map +1 -1
  62. package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts.map +1 -1
  63. package/dist/src/services/deployment/docker/docker-compose-generator.service.js +7 -2
  64. package/dist/src/services/deployment/docker/docker-compose-generator.service.js.map +1 -1
  65. package/dist/src/services/deployment/local-dev-session-lease.service.d.ts.map +1 -1
  66. package/dist/src/services/deployment/local-dev-session-lease.service.js +22 -1
  67. package/dist/src/services/deployment/local-dev-session-lease.service.js.map +1 -1
  68. package/dist/src/services/environment/authored-infra-config.utils.d.ts.map +1 -1
  69. package/dist/src/services/environment/authored-infra-config.utils.js +1 -0
  70. package/dist/src/services/environment/authored-infra-config.utils.js.map +1 -1
  71. package/dist/src/services/environment/authored-infra-member-authority.d.ts.map +1 -1
  72. package/dist/src/services/environment/authored-infra-member-authority.js +5 -0
  73. package/dist/src/services/environment/authored-infra-member-authority.js.map +1 -1
  74. package/dist/src/services/environment/env-configuration-generator.service.d.ts.map +1 -1
  75. package/dist/src/services/environment/env-configuration-generator.service.js +6 -3
  76. package/dist/src/services/environment/env-configuration-generator.service.js.map +1 -1
  77. package/dist/src/services/environment/env-vars-builder.service.d.ts +6 -0
  78. package/dist/src/services/environment/env-vars-builder.service.d.ts.map +1 -1
  79. package/dist/src/services/environment/env-vars-builder.service.js +24 -1
  80. package/dist/src/services/environment/env-vars-builder.service.js.map +1 -1
  81. package/dist/src/services/environment/environment-hydration.utils.d.ts.map +1 -1
  82. package/dist/src/services/environment/environment-hydration.utils.js +1 -0
  83. package/dist/src/services/environment/environment-hydration.utils.js.map +1 -1
  84. package/dist/src/services/environment/environment.schemas.d.ts +7 -1
  85. package/dist/src/services/environment/environment.schemas.d.ts.map +1 -1
  86. package/dist/src/services/environment/environment.schemas.js.map +1 -1
  87. package/dist/src/services/environment/runtime-bootstrap.service.d.ts +2 -0
  88. package/dist/src/services/environment/runtime-bootstrap.service.d.ts.map +1 -1
  89. package/dist/src/services/environment/runtime-bootstrap.service.js +4 -0
  90. package/dist/src/services/environment/runtime-bootstrap.service.js.map +1 -1
  91. package/dist/src/services/framework/framework-docker-publish.service.d.ts +13 -0
  92. package/dist/src/services/framework/framework-docker-publish.service.d.ts.map +1 -1
  93. package/dist/src/services/framework/framework-docker-publish.service.js +24 -7
  94. package/dist/src/services/framework/framework-docker-publish.service.js.map +1 -1
  95. package/dist/src/services/registry/provider-connect.service.d.ts +57 -1
  96. package/dist/src/services/registry/provider-connect.service.d.ts.map +1 -1
  97. package/dist/src/services/registry/provider-connect.service.js +63 -2
  98. package/dist/src/services/registry/provider-connect.service.js.map +1 -1
  99. package/dist/tsconfig.build.tsbuildinfo +1 -1
  100. package/package.json +18 -18
  101. package/scripts/app-dependency-alignment/propagated-engine-overrides.json +1 -1
  102. package/wildo-framework.info.json +1 -1
@@ -27,13 +27,19 @@
27
27
  * An environment whose secrets are not on this machine is named as not probed, never as served. A REMOTE environment's
28
28
  * secrets are rebuilt from its CI environment at deploy, so a local copy missing a secret is reported as such.
29
29
  *
30
+ * A provider can serve one guardrail and not the other (`openai-moderation` moderates output and does not screen), so
31
+ * whether it serves is answered PER GUARDRAIL the agents declare, from the provider's declared capabilities. And an
32
+ * environment may declare that it runs its agents unguarded where no classifier offers a guardrail
33
+ * (`agentContentGuardrails: { withoutClassifier: RUN_UNGUARDED, reason }`): such an environment is reported as running
34
+ * them UNGUARDED, with its reason, never as refusing, because that is what the backend does there.
35
+ *
30
36
  * The agents are application code, read from the running dev companion (the same read as the AI-use line). Without
31
37
  * them the line is a PASS that says the agent half was not probed, and lists the environments that could not serve a
32
38
  * guarded agent as information, as the AI-use line does. An organization's agent policy can switch a guardrail on for
33
39
  * one tenant; that is a database row, and the backend's boot report counts those.
34
40
  */
35
41
  import { existsSync, readFileSync } from 'node:fs';
36
- import { EngineCapability, FlowsActors_Agent_Status, PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY, isEngineCapabilityEnabled, describeCaughtError } from '@wildo-ai/saas-models';
42
+ import { AgentContentGuardrailsWithoutClassifier, BUILTIN_PROVIDER_CAPABILITY, EngineCapability, FlowsActors_Agent_Status, PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY, isEngineCapabilityEnabled, describeCaughtError, } from '@wildo-ai/saas-models';
37
43
  import { orderProvidersForEngineCapability } from '@wildo-ai/saas-backend-lib/assurance-derivations';
38
44
  import { LocalPreconditionCheckStatus } from '../../services/deployment/local-precondition-checks.schemas.js';
39
45
  export const CONTENT_GUARDRAIL_CLASSIFIER_CHECK_NAME = 'content-guardrail classifier';
@@ -74,6 +80,16 @@ export function readEnvironmentProviderEnv(path, fs = {
74
80
  }
75
81
  return { kind: EnvironmentProviderEnvReadingKind.READ, providerEnv: providerEnv };
76
82
  }
83
+ /** The guardrails the guarded agents declare, between them. `undefined` when the agents could not be read. */
84
+ export function guardrailsDeclaredBy(agents) {
85
+ if (agents.some((agent) => agent.promptInjectionScreening === undefined && agent.outputModeration === undefined))
86
+ return undefined;
87
+ const guarded = agents.filter((agent) => (agent.status == null || agent.status === FlowsActors_Agent_Status.ACTIVE) && agent.capability === EngineCapability.AI_LLM);
88
+ return {
89
+ promptInjection: guarded.some((agent) => agent.promptInjectionScreening != null),
90
+ outputModeration: guarded.some((agent) => agent.outputModeration != null),
91
+ };
92
+ }
77
93
  /**
78
94
  * The agents that can be refused for want of a classifier, by ref, or `undefined` when the projection cannot say (it
79
95
  * predates the guardrail fields, so absence there means NOT READ). An agent is left out when it is known not to run
@@ -106,6 +122,8 @@ export function readEnvironmentClassifiers(input) {
106
122
  return { envName: environment.envName, unreadable: environment.error instanceof Error ? environment.error.message : String(environment.error) };
107
123
  }
108
124
  const remote = environment.path.endsWith('wildo.infra.remote.config.ts') ? { remote: true } : {};
125
+ const declaration = environment.config.agentContentGuardrails;
126
+ const unguarded = declaration?.withoutClassifier === AgentContentGuardrailsWithoutClassifier.RUN_UNGUARDED ? { runsUnguardedBecause: declaration.reason } : {};
109
127
  const selectionOverride = environment.config.providerSelection?.[CAPABILITY];
110
128
  const [providerRef] = orderProvidersForEngineCapability({
111
129
  capability: CAPABILITY,
@@ -114,27 +132,65 @@ export function readEnvironmentClassifiers(input) {
114
132
  ...(selectionOverride ? { selectionOverride } : {}),
115
133
  });
116
134
  const secrets = input.providerEnvOf(environment.envName);
117
- if (providerRef === undefined)
118
- return { envName: environment.envName, providerRef: null, secrets, missingSecrets: [], ...remote };
135
+ if (providerRef === undefined) {
136
+ // As the runtime reads it (`declaresProviderForEngineCapability`): enabled, and the scope lists one or a selection names one.
137
+ const declaredButMissing = capabilityEnabled ? [...new Set([
138
+ ...Object.entries(runtimeScope?.providers ?? {}).filter(([, entry]) => (entry?.engineCapabilities ?? []).includes(CAPABILITY)).map(([ref]) => ref),
139
+ ...[selectionOverride?.primary, runtimeScope?.selection?.[CAPABILITY]?.primary].filter((ref) => typeof ref === 'string'),
140
+ ])].sort() : [];
141
+ return {
142
+ envName: environment.envName, providerRef: null, secrets, missingSecrets: [], offers: { promptInjection: false, outputModeration: false },
143
+ ...(declaredButMissing.length > 0 ? { declaredButMissing } : {}), ...remote, ...unguarded,
144
+ };
145
+ }
146
+ const declared = input.catalogue.get(providerRef)?.providerCapabilities ?? [];
147
+ const offers = {
148
+ promptInjection: declared.includes(BUILTIN_PROVIDER_CAPABILITY.PROMPT_INJECTION_SCREENING),
149
+ outputModeration: declared.includes(BUILTIN_PROVIDER_CAPABILITY.OUTPUT_MODERATION),
150
+ };
119
151
  const required = (input.catalogue.get(providerRef)?.secrets ?? []).filter((secret) => secret.required).map((secret) => secret.envVarName);
120
152
  const missingSecrets = secrets.kind === EnvironmentProviderEnvReadingKind.READ
121
153
  ? required.filter((name) => typeof secrets.providerEnv[name] !== 'string' || secrets.providerEnv[name] === '').sort()
122
154
  : [];
123
- return { envName: environment.envName, providerRef, secrets, missingSecrets, ...remote };
155
+ return { envName: environment.envName, providerRef, secrets, missingSecrets, offers, ...remote, ...unguarded };
124
156
  });
125
157
  }
126
158
  const quoted = (names) => names.map((name) => `\`${name}\``).join(', ');
127
- /** Each environment, sorted into what can be said of it. */
128
- function classify(readings) {
159
+ const GUARDRAIL_NAME = {
160
+ promptInjection: 'contentGuardrails.promptInjection',
161
+ outputModeration: 'contentGuardrails.outputModeration',
162
+ };
163
+ /** Each environment, sorted into what can be said of it, for the guardrails the agents need. */
164
+ function classify(readings, needs) {
129
165
  const unserved = [];
166
+ const unguarded = [];
130
167
  const notProbed = [];
131
168
  const served = [];
132
169
  for (const reading of readings) {
133
170
  if ('unreadable' in reading) {
134
171
  unserved.push(`${reading.envName}: its infrastructure configuration could not be read (${reading.unreadable})`);
172
+ continue;
173
+ }
174
+ // Per guardrail: one the provider (or no provider) does not offer refuses, unless the environment runs it unguarded.
175
+ const notOffered = Object.keys(GUARDRAIL_NAME).filter((guardrail) => needs[guardrail] && !reading.offers[guardrail]);
176
+ if (reading.providerRef === null && reading.declaredButMissing !== undefined && notOffered.length > 0) {
177
+ // Declared and not there: the runtime refuses it, under any declaration of the environment.
178
+ unserved.push(`${reading.envName}: ${quoted(reading.declaredButMissing)} ${reading.declaredButMissing.length === 1 ? 'is' : 'are'} declared for ${CAPABILITY} (scoped or selected) and cannot serve it here (not installed, or not in the backend scope with it)`);
179
+ continue;
135
180
  }
136
- else if (reading.providerRef === null) {
137
- unserved.push(`${reading.envName}: no provider serves ${CAPABILITY}`);
181
+ if (notOffered.length > 0) {
182
+ const what = reading.providerRef === null
183
+ ? `no provider serves ${CAPABILITY}`
184
+ : `\`${reading.providerRef}\` does not offer ${notOffered.map((guardrail) => GUARDRAIL_NAME[guardrail]).join(' or ')}`;
185
+ if (reading.runsUnguardedBecause !== undefined) {
186
+ unguarded.push(`${reading.envName} (${what}; agentContentGuardrails: "${reading.runsUnguardedBecause}")`);
187
+ }
188
+ else {
189
+ unserved.push(`${reading.envName}: ${what}`);
190
+ }
191
+ }
192
+ if (reading.providerRef === null || notOffered.length === Object.keys(GUARDRAIL_NAME).filter((guardrail) => needs[guardrail]).length) {
193
+ continue;
138
194
  }
139
195
  else if (reading.secrets.kind === EnvironmentProviderEnvReadingKind.UNREADABLE) {
140
196
  unserved.push(`${reading.envName}: its secrets file ${reading.secrets.path} could not be read (${reading.secrets.reason}), so \`${reading.providerRef}\`'s secrets are unknown`);
@@ -142,6 +198,12 @@ function classify(readings) {
142
198
  else if (reading.secrets.kind === EnvironmentProviderEnvReadingKind.ABSENT) {
143
199
  notProbed.push(`${reading.envName} (\`${reading.providerRef}\`; no secrets.json for it on this machine)`);
144
200
  }
201
+ else if (reading.missingSecrets.length > 0 && reading.runsUnguardedBecause !== undefined) {
202
+ // Its credentials are not authored here, and the environment declares it runs unguarded: absent, as the runtime reads it.
203
+ unguarded.push(reading.remote
204
+ ? `${reading.envName} (\`${reading.providerRef}\` has no ${quoted(reading.missingSecrets)} in this machine's copy of its secrets.json; its deployed secrets come from its CI environment, so it may be guarded there; agentContentGuardrails: "${reading.runsUnguardedBecause}")`
205
+ : `${reading.envName} (\`${reading.providerRef}\` has no ${quoted(reading.missingSecrets)} here; agentContentGuardrails: "${reading.runsUnguardedBecause}")`);
206
+ }
145
207
  else if (reading.missingSecrets.length > 0) {
146
208
  unserved.push(reading.remote
147
209
  ? `${reading.envName}: \`${reading.providerRef}\` has no ${quoted(reading.missingSecrets)} in this machine's copy of its secrets.json → providerEnv (its deployed secrets come from its CI environment: check them there)`
@@ -151,11 +213,12 @@ function classify(readings) {
151
213
  served.push(`${reading.envName} (\`${reading.providerRef}\`)`);
152
214
  }
153
215
  }
154
- return { unserved, notProbed, served };
216
+ return { unserved, unguarded, notProbed, served };
155
217
  }
156
218
  const FIX = `In each environment named, make a provider serve ${CAPABILITY} (enable the capability and list the provider in the backend scope with it; `
157
219
  + '`providerSelection` in its wildo.infra.<env>.config.ts only chooses among those) and author its required secrets in that environment\'s '
158
- + 'secrets.json → providerEnv; or remove the guardrail declaration from the agent. The backend also warns at startup, one line per agent it cannot serve.';
220
+ + 'secrets.json → providerEnv; or remove the guardrail declaration from the agent; or, deliberately, declare in that environment\'s infra config '
221
+ + '`agentContentGuardrails: { withoutClassifier: RUN_UNGUARDED, reason }` to run the agent unguarded there. The backend also warns at startup, one line per agent it cannot serve.';
159
222
  /**
160
223
  * The doctor line. WARN when a guarded agent was read and an environment cannot serve it (or could not be read); PASS
161
224
  * otherwise, saying which environments were probed and served, which were not probed, and, when the agents could not be
@@ -167,9 +230,10 @@ export function contentGuardrailClassifierCheck(input) {
167
230
  if (input.guardedAgents !== undefined && input.guardedAgents.length === 0) {
168
231
  return { name, status: LocalPreconditionCheckStatus.PASS, detail: 'no active agent declares contentGuardrails.promptInjection or contentGuardrails.outputModeration' };
169
232
  }
170
- const { unserved, notProbed, served } = classify(input.readings);
233
+ const { unserved, unguarded, notProbed, served } = classify(input.readings, input.guardrailsNeeded ?? { promptInjection: true, outputModeration: true });
171
234
  const tail = [
172
235
  served.length > 0 ? `Served (probed): ${served.join(', ')}.` : '',
236
+ unguarded.length > 0 ? `Runs guarded agents UNGUARDED, as the environment declares: ${unguarded.join(', ')}.` : '',
173
237
  notProbed.length > 0 ? `Not probed for secrets: ${notProbed.join(', ')}.` : '',
174
238
  ].filter(Boolean).join(' ');
175
239
  if (input.guardedAgents === undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"content-guardrail-classifier.service.js","sourceRoot":"","sources":["../../../../src/services/application/content-guardrail-classifier.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,wCAAwC,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAG7K,OAAO,EAAE,iCAAiC,EAAsC,MAAM,kDAAkD,CAAC;AAEzI,OAAO,EAAE,4BAA4B,EAAE,MAAM,kEAAkE,CAAC;AAKhH,MAAM,CAAC,MAAM,uCAAuC,GAAG,8B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AAC,MAAM,KAAK,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,IAAI,EAAE;QACrJ,GAAG,EAAE,GAAG;KACT,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Which of an application's environments can serve its agents' classifier-backed content guardrails (#2292) — the\n * `wildo local doctor` line.\n *\n * An agent declaring `contentGuardrails.promptInjection` or `contentGuardrails.outputModeration` needs a classifier, a\n * provider for `EngineCapability.AI_CONTENT_SAFETY`, and REFUSES EVERY TURN in an environment where none can serve it.\n * The backend's boot report says so for the environment it boots in (`reportUnservableAgentContentGuardrails`); this\n * says it for EVERY authored environment, offline, before anything is deployed, since the environment that cannot serve\n * is usually not the one on the developer's machine.\n *\n * ## The same rules as the backend, fed from the files\n *\n * Which provider serves the capability in an environment is the provider registry's own ordering rule\n * (`orderProvidersForEngineCapability`) over the engine's own enablement rule (`isEngineCapabilityEnabled`), not a copy\n * of either: a selection only REORDERS the providers in scope, so \"no `providerSelection` for this environment\" is not\n * \"no classifier\" (a provider in the backend scope still serves). Fed what the registry reads: the capability's\n * enablement, the backend provider scope, the configured providers, the providers the CLI can see (engine tier plus the\n * application's discovered packages), and the environment's selection.\n *\n * The provider asked first then needs its REQUIRED secrets (its API key, and its host when it reads one from the\n * environment) in that environment's `secrets.json → providerEnv`: the backend refuses a guarded agent's turn when\n * either is unset. Only the `providerEnv` keys are read, so an older-shape file that no longer validates still answers.\n *\n * ## What it says, and what it cannot see\n *\n * \"Served\" is said of an environment only when it was PROBED: its provider found and every required secret present.\n * An environment whose secrets are not on this machine is named as not probed, never as served. A REMOTE environment's\n * secrets are rebuilt from its CI environment at deploy, so a local copy missing a secret is reported as such.\n *\n * The agents are application code, read from the running dev companion (the same read as the AI-use line). Without\n * them the line is a PASS that says the agent half was not probed, and lists the environments that could not serve a\n * guarded agent as information, as the AI-use line does. An organization's agent policy can switch a guardrail on for\n * one tenant; that is a database row, and the backend's boot report counts those.\n */\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport { EngineCapability, FlowsActors_Agent_Status, PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY, isEngineCapabilityEnabled, describeCaughtError } from '@wildo-ai/saas-models';\nimport type { AgentAiUseDeclaration } from '@wildo-ai/saas-models';\nimport type { WildoSaasConfig } from '@wildo-ai/platform-config-lib';\nimport { orderProvidersForEngineCapability, type EngineCapabilityProviderScope } from '@wildo-ai/saas-backend-lib/assurance-derivations';\n\nimport { LocalPreconditionCheckStatus } from '~wildo-cli/services/deployment/local-precondition-checks.schemas';\nimport type { LocalPreconditionCheckResult } from '~wildo-cli/services/deployment/local-precondition-checks.schemas';\nimport type { ProviderSecretsCatalogueEntry } from '~wildo-cli/services/credentials/composed-provider-catalogue';\nimport type { SettledAuthoredInfraEnvConfig } from '~wildo-cli/services/environment/authored-infra-config.utils';\n\nexport const CONTENT_GUARDRAIL_CLASSIFIER_CHECK_NAME = 'content-guardrail classifier';\n\nconst CAPABILITY = EngineCapability.AI_CONTENT_SAFETY;\n\n/** What an environment's `secrets.json` said about `providerEnv`. */\nexport enum EnvironmentProviderEnvReadingKind {\n /** The file exists and its `providerEnv` (absent counts as empty) was read. */\n READ = 'read',\n /** No `secrets.json` for that environment on this machine. */\n ABSENT = 'absent',\n /** The file exists and could not be read as JSON, or its `providerEnv` is not an object of strings. */\n UNREADABLE = 'unreadable',\n}\n\nexport type EnvironmentProviderEnvReading =\n | { readonly kind: EnvironmentProviderEnvReadingKind.READ; readonly providerEnv: Readonly<Record<string, unknown>> }\n | { readonly kind: EnvironmentProviderEnvReadingKind.ABSENT }\n | { readonly kind: EnvironmentProviderEnvReadingKind.UNREADABLE; readonly path: string; readonly reason: string };\n\n/**\n * The `providerEnv` of the `secrets.json` at `path`, read WITHOUT validating the rest of the file: the question is only\n * which keys are present, and a file in an older shape (missing a block a later release added) answers it as well as a\n * current one. Values are never returned to a caller that prints them.\n */\nexport function readEnvironmentProviderEnv(path: string, fs: { exists: (path: string) => boolean; read: (path: string) => string } = {\n exists: existsSync,\n read: (file) => readFileSync(file, 'utf8'),\n}): EnvironmentProviderEnvReading {\n if (!fs.exists(path)) return { kind: EnvironmentProviderEnvReadingKind.ABSENT };\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.read(path));\n } catch (error) {\n return { kind: EnvironmentProviderEnvReadingKind.UNREADABLE, path, reason: describeCaughtError(error) };\n }\n const providerEnv = (parsed as { providerEnv?: unknown } | null)?.providerEnv;\n if (providerEnv === undefined) return { kind: EnvironmentProviderEnvReadingKind.READ, providerEnv: {} };\n if (providerEnv === null || typeof providerEnv !== 'object' || Array.isArray(providerEnv)) {\n return { kind: EnvironmentProviderEnvReadingKind.UNREADABLE, path, reason: '`providerEnv` is not an object' };\n }\n return { kind: EnvironmentProviderEnvReadingKind.READ, providerEnv: providerEnv as Record<string, unknown> };\n}\n\n/** One environment's answer: which provider would screen there, and whether its secrets were seen. */\nexport type EnvironmentClassifierReading =\n | { readonly envName: string; readonly unreadable: string }\n | {\n readonly envName: string;\n /** The provider the backend would ask first, `null` when none serves the capability there. */\n readonly providerRef: string | null;\n /** The environment's `providerEnv` as read. */\n readonly secrets: EnvironmentProviderEnvReading;\n /** Of the serving provider's required secrets, those absent from `providerEnv` (empty unless `secrets` was READ). */\n readonly missingSecrets: readonly string[];\n /**\n * A REMOTE environment (its authored file is `wildo.infra.remote.config.ts`): its deployed secrets are rebuilt from its\n * CI environment, so the `secrets.json` on this machine is a copy that may not be the whole of them.\n */\n readonly remote?: true;\n };\n\n/**\n * The agents that can be refused for want of a classifier, by ref, or `undefined` when the projection cannot say (it\n * predates the guardrail fields, so absence there means NOT READ). An agent is left out when it is known not to run\n * guardrails: inactive (never invoked), or not a language-model agent (guardrails apply to language-model agents only).\n */\nexport function guardedAgentRefs(agents: readonly AgentAiUseDeclaration[]): string[] | undefined {\n if (agents.some((agent) => agent.promptInjectionScreening === undefined && agent.outputModeration === undefined)) return undefined;\n return agents\n .filter((agent) => agent.status == null || agent.status === FlowsActors_Agent_Status.ACTIVE)\n .filter((agent) => agent.capability === EngineCapability.AI_LLM)\n .filter((agent) => agent.promptInjectionScreening != null || agent.outputModeration != null)\n .map((agent) => agent.ref)\n .sort();\n}\n\n/** Each authored environment's classifier reading. Pure: every file is read by the caller. */\nexport function readEnvironmentClassifiers(input: {\n readonly saasConfig: Pick<WildoSaasConfig, 'engineCapabilities' | 'providers' | 'providerConfigurations'>;\n readonly environments: readonly SettledAuthoredInfraEnvConfig[];\n /** Every provider the CLI can see (the composed catalogue, after discovery). */\n readonly catalogue: ReadonlyMap<string, ProviderSecretsCatalogueEntry>;\n /** The environment's `secrets.json → providerEnv`, as {@link readEnvironmentProviderEnv} reads it. */\n readonly providerEnvOf: (envName: string) => EnvironmentProviderEnvReading;\n}): EnvironmentClassifierReading[] {\n const capabilityEnabled = isEngineCapabilityEnabled(input.saasConfig.engineCapabilities as Parameters<typeof isEngineCapabilityEnabled>[0], CAPABILITY);\n // The backend's provider scope: the runtime a guarded agent runs in.\n const runtimeScope = (input.saasConfig.providers as { scopes?: Record<string, EngineCapabilityProviderScope | undefined> } | undefined)?.scopes?.backend;\n const configuredProviderRefs = new Set(Object.entries(input.saasConfig.providerConfigurations ?? {}).filter(([, value]) => Boolean(value)).map(([ref]) => ref));\n const registeredProviders = [...input.catalogue.values()].map((entry) => ({\n providerRef: entry.providerRef,\n engineCapabilities: [...new Set(entry.providerCapabilities\n .map((capability) => PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY[capability as keyof typeof PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY])\n .filter((capability): capability is EngineCapability => capability !== undefined))],\n }));\n\n return input.environments.map((environment): EnvironmentClassifierReading => {\n if ('error' in environment) {\n return { envName: environment.envName, unreadable: environment.error instanceof Error ? environment.error.message : String(environment.error) };\n }\n const remote = environment.path.endsWith('wildo.infra.remote.config.ts') ? { remote: true as const } : {};\n const selectionOverride = environment.config.providerSelection?.[CAPABILITY];\n const [providerRef] = orderProvidersForEngineCapability({\n capability: CAPABILITY,\n registeredProviders,\n configuration: { capabilityEnabled, runtimeScope, configuredProviderRefs },\n ...(selectionOverride ? { selectionOverride } : {}),\n });\n const secrets = input.providerEnvOf(environment.envName);\n if (providerRef === undefined) return { envName: environment.envName, providerRef: null, secrets, missingSecrets: [], ...remote };\n const required = (input.catalogue.get(providerRef)?.secrets ?? []).filter((secret) => secret.required).map((secret) => secret.envVarName);\n const missingSecrets = secrets.kind === EnvironmentProviderEnvReadingKind.READ\n ? required.filter((name) => typeof secrets.providerEnv[name] !== 'string' || secrets.providerEnv[name] === '').sort()\n : [];\n return { envName: environment.envName, providerRef, secrets, missingSecrets, ...remote };\n });\n}\n\nconst quoted = (names: readonly string[]): string => names.map((name) => `\\`${name}\\``).join(', ');\n\n/** Each environment, sorted into what can be said of it. */\nfunction classify(readings: readonly EnvironmentClassifierReading[]) {\n const unserved: string[] = [];\n const notProbed: string[] = [];\n const served: string[] = [];\n for (const reading of readings) {\n if ('unreadable' in reading) {\n unserved.push(`${reading.envName}: its infrastructure configuration could not be read (${reading.unreadable})`);\n } else if (reading.providerRef === null) {\n unserved.push(`${reading.envName}: no provider serves ${CAPABILITY}`);\n } else if (reading.secrets.kind === EnvironmentProviderEnvReadingKind.UNREADABLE) {\n unserved.push(`${reading.envName}: its secrets file ${reading.secrets.path} could not be read (${reading.secrets.reason}), so \\`${reading.providerRef}\\`'s secrets are unknown`);\n } else if (reading.secrets.kind === EnvironmentProviderEnvReadingKind.ABSENT) {\n notProbed.push(`${reading.envName} (\\`${reading.providerRef}\\`; no secrets.json for it on this machine)`);\n } else if (reading.missingSecrets.length > 0) {\n unserved.push(reading.remote\n ? `${reading.envName}: \\`${reading.providerRef}\\` has no ${quoted(reading.missingSecrets)} in this machine's copy of its secrets.json → providerEnv (its deployed secrets come from its CI environment: check them there)`\n : `${reading.envName}: \\`${reading.providerRef}\\` has no ${quoted(reading.missingSecrets)} in secrets.json → providerEnv`);\n } else {\n served.push(`${reading.envName} (\\`${reading.providerRef}\\`)`);\n }\n }\n return { unserved, notProbed, served };\n}\n\nconst FIX = `In each environment named, make a provider serve ${CAPABILITY} (enable the capability and list the provider in the backend scope with it; `\n + '`providerSelection` in its wildo.infra.<env>.config.ts only chooses among those) and author its required secrets in that environment\\'s '\n + 'secrets.json → providerEnv; or remove the guardrail declaration from the agent. The backend also warns at startup, one line per agent it cannot serve.';\n\n/**\n * The doctor line. WARN when a guarded agent was read and an environment cannot serve it (or could not be read); PASS\n * otherwise, saying which environments were probed and served, which were not probed, and, when the agents could not be\n * read, that the agent half was not probed. Never a FAIL: the runtime refuses the guarded agent's turns, the rest of the\n * application runs, and the remedy is a configuration edit.\n */\nexport function contentGuardrailClassifierCheck(input: {\n readonly readings: readonly EnvironmentClassifierReading[];\n /** The guarded agents, or `undefined` when the agents could not be read. */\n readonly guardedAgents: readonly string[] | undefined;\n readonly agentsNotReadBecause?: string;\n}): LocalPreconditionCheckResult {\n const name = CONTENT_GUARDRAIL_CLASSIFIER_CHECK_NAME;\n if (input.guardedAgents !== undefined && input.guardedAgents.length === 0) {\n return { name, status: LocalPreconditionCheckStatus.PASS, detail: 'no active agent declares contentGuardrails.promptInjection or contentGuardrails.outputModeration' };\n }\n const { unserved, notProbed, served } = classify(input.readings);\n const tail = [\n served.length > 0 ? `Served (probed): ${served.join(', ')}.` : '',\n notProbed.length > 0 ? `Not probed for secrets: ${notProbed.join(', ')}.` : '',\n ].filter(Boolean).join(' ');\n\n if (input.guardedAgents === undefined) {\n const because = input.agentsNotReadBecause ? ` (${input.agentsNotReadBecause})` : '';\n const information = unserved.length > 0\n ? ` An agent declaring contentGuardrails.promptInjection or .outputModeration would refuse every turn in: ${unserved.join('; ')}.`\n : '';\n return {\n name,\n status: LocalPreconditionCheckStatus.PASS,\n detail: `Not probed for agents${because}: run \\`wildo local doctor\\` with the dev companion up.${information} ${tail}`.trim(),\n };\n }\n\n const who = input.guardedAgents.length === 1\n ? `agent \\`${input.guardedAgents[0]}\\` REFUSES`\n : `agents ${quoted(input.guardedAgents)} REFUSE`;\n if (unserved.length === 0) {\n return { name, status: LocalPreconditionCheckStatus.PASS, detail: `${quoted(input.guardedAgents)}: no probed environment lacks a classifier. ${tail}`.trim() };\n }\n return {\n name,\n status: LocalPreconditionCheckStatus.WARN,\n detail: `${who} EVERY TURN where no classifier can serve ${input.guardedAgents.length === 1 ? 'it' : 'them'}: ${unserved.join('; ')}. ${tail}`.trim(),\n fix: FIX,\n };\n}\n"]}
1
+ {"version":3,"file":"content-guardrail-classifier.service.js","sourceRoot":"","sources":["../../../../src/services/application/content-guardrail-classifier.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EACL,uCAAuC,EACvC,2BAA2B,EAC3B,gBAAgB,EAChB,wBAAwB,EACxB,wCAAwC,EACxC,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,iCAAiC,EAAsC,MAAM,kDAAkD,CAAC;AAEzI,OAAO,EAAE,4BAA4B,EAAE,MAAM,kEAAkE,CAAC;AAKhH,MAAM,CAAC,MAAM,uCAAuC,GAAG,8BAA8B,CAAC;AAEtF,MAAM,UAAU,GAAG,gBAAgB,CAAC,iBAAiB,CAAC;AAEtD,qEAAqE;AACrE,MAAM,CAAN,IAAY,iCAOX;AAPD,WAAY,iCAAiC;IAC3C,+EAA+E;IAC/E,kDAAa,CAAA;IACb,8DAA8D;IAC9D,sDAAiB,CAAA;IACjB,uGAAuG;IACvG,8DAAyB,CAAA;AAC3B,CAAC,EAPW,iCAAiC,KAAjC,iCAAiC,QAO5C;AAOD;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,IAAY,EAAE,KAA4E;IACnI,MAAM,EAAE,UAAU;IAClB,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI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AI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC;IACjK,CAAC;IACD,OAAO;QACL,IAAI;QACJ,MAAM,EAAE,4BAA4B,CAAC,IAAI;QACzC,MAAM,EAAE,GAAG,GAAG,6CAA6C,KAAK,CAAC,aAAa,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,KAAK,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC,IAAI,EAAE;QACrJ,GAAG,EAAE,GAAG;KACT,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Which of an application's environments can serve its agents' classifier-backed content guardrails (#2292) — the\n * `wildo local doctor` line.\n *\n * An agent declaring `contentGuardrails.promptInjection` or `contentGuardrails.outputModeration` needs a classifier, a\n * provider for `EngineCapability.AI_CONTENT_SAFETY`, and REFUSES EVERY TURN in an environment where none can serve it.\n * The backend's boot report says so for the environment it boots in (`reportUnservableAgentContentGuardrails`); this\n * says it for EVERY authored environment, offline, before anything is deployed, since the environment that cannot serve\n * is usually not the one on the developer's machine.\n *\n * ## The same rules as the backend, fed from the files\n *\n * Which provider serves the capability in an environment is the provider registry's own ordering rule\n * (`orderProvidersForEngineCapability`) over the engine's own enablement rule (`isEngineCapabilityEnabled`), not a copy\n * of either: a selection only REORDERS the providers in scope, so \"no `providerSelection` for this environment\" is not\n * \"no classifier\" (a provider in the backend scope still serves). Fed what the registry reads: the capability's\n * enablement, the backend provider scope, the configured providers, the providers the CLI can see (engine tier plus the\n * application's discovered packages), and the environment's selection.\n *\n * The provider asked first then needs its REQUIRED secrets (its API key, and its host when it reads one from the\n * environment) in that environment's `secrets.json → providerEnv`: the backend refuses a guarded agent's turn when\n * either is unset. Only the `providerEnv` keys are read, so an older-shape file that no longer validates still answers.\n *\n * ## What it says, and what it cannot see\n *\n * \"Served\" is said of an environment only when it was PROBED: its provider found and every required secret present.\n * An environment whose secrets are not on this machine is named as not probed, never as served. A REMOTE environment's\n * secrets are rebuilt from its CI environment at deploy, so a local copy missing a secret is reported as such.\n *\n * A provider can serve one guardrail and not the other (`openai-moderation` moderates output and does not screen), so\n * whether it serves is answered PER GUARDRAIL the agents declare, from the provider's declared capabilities. And an\n * environment may declare that it runs its agents unguarded where no classifier offers a guardrail\n * (`agentContentGuardrails: { withoutClassifier: RUN_UNGUARDED, reason }`): such an environment is reported as running\n * them UNGUARDED, with its reason, never as refusing, because that is what the backend does there.\n *\n * The agents are application code, read from the running dev companion (the same read as the AI-use line). Without\n * them the line is a PASS that says the agent half was not probed, and lists the environments that could not serve a\n * guarded agent as information, as the AI-use line does. An organization's agent policy can switch a guardrail on for\n * one tenant; that is a database row, and the backend's boot report counts those.\n */\nimport { existsSync, readFileSync } from 'node:fs';\n\nimport {\n AgentContentGuardrailsWithoutClassifier,\n BUILTIN_PROVIDER_CAPABILITY,\n EngineCapability,\n FlowsActors_Agent_Status,\n PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY,\n isEngineCapabilityEnabled,\n describeCaughtError,\n} from '@wildo-ai/saas-models';\nimport type { AgentAiUseDeclaration } from '@wildo-ai/saas-models';\nimport type { WildoSaasConfig } from '@wildo-ai/platform-config-lib';\nimport { orderProvidersForEngineCapability, type EngineCapabilityProviderScope } from '@wildo-ai/saas-backend-lib/assurance-derivations';\n\nimport { LocalPreconditionCheckStatus } from '~wildo-cli/services/deployment/local-precondition-checks.schemas';\nimport type { LocalPreconditionCheckResult } from '~wildo-cli/services/deployment/local-precondition-checks.schemas';\nimport type { ProviderSecretsCatalogueEntry } from '~wildo-cli/services/credentials/composed-provider-catalogue';\nimport type { SettledAuthoredInfraEnvConfig } from '~wildo-cli/services/environment/authored-infra-config.utils';\n\nexport const CONTENT_GUARDRAIL_CLASSIFIER_CHECK_NAME = 'content-guardrail classifier';\n\nconst CAPABILITY = EngineCapability.AI_CONTENT_SAFETY;\n\n/** What an environment's `secrets.json` said about `providerEnv`. */\nexport enum EnvironmentProviderEnvReadingKind {\n /** The file exists and its `providerEnv` (absent counts as empty) was read. */\n READ = 'read',\n /** No `secrets.json` for that environment on this machine. */\n ABSENT = 'absent',\n /** The file exists and could not be read as JSON, or its `providerEnv` is not an object of strings. */\n UNREADABLE = 'unreadable',\n}\n\nexport type EnvironmentProviderEnvReading =\n | { readonly kind: EnvironmentProviderEnvReadingKind.READ; readonly providerEnv: Readonly<Record<string, unknown>> }\n | { readonly kind: EnvironmentProviderEnvReadingKind.ABSENT }\n | { readonly kind: EnvironmentProviderEnvReadingKind.UNREADABLE; readonly path: string; readonly reason: string };\n\n/**\n * The `providerEnv` of the `secrets.json` at `path`, read WITHOUT validating the rest of the file: the question is only\n * which keys are present, and a file in an older shape (missing a block a later release added) answers it as well as a\n * current one. Values are never returned to a caller that prints them.\n */\nexport function readEnvironmentProviderEnv(path: string, fs: { exists: (path: string) => boolean; read: (path: string) => string } = {\n exists: existsSync,\n read: (file) => readFileSync(file, 'utf8'),\n}): EnvironmentProviderEnvReading {\n if (!fs.exists(path)) return { kind: EnvironmentProviderEnvReadingKind.ABSENT };\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.read(path));\n } catch (error) {\n return { kind: EnvironmentProviderEnvReadingKind.UNREADABLE, path, reason: describeCaughtError(error) };\n }\n const providerEnv = (parsed as { providerEnv?: unknown } | null)?.providerEnv;\n if (providerEnv === undefined) return { kind: EnvironmentProviderEnvReadingKind.READ, providerEnv: {} };\n if (providerEnv === null || typeof providerEnv !== 'object' || Array.isArray(providerEnv)) {\n return { kind: EnvironmentProviderEnvReadingKind.UNREADABLE, path, reason: '`providerEnv` is not an object' };\n }\n return { kind: EnvironmentProviderEnvReadingKind.READ, providerEnv: providerEnv as Record<string, unknown> };\n}\n\n/** One environment's answer: which provider would screen there, and whether its secrets were seen. */\nexport type EnvironmentClassifierReading =\n | { readonly envName: string; readonly unreadable: string }\n | {\n readonly envName: string;\n /** The provider the backend would ask first, `null` when none serves the capability there. */\n readonly providerRef: string | null;\n /** The environment's `providerEnv` as read. */\n readonly secrets: EnvironmentProviderEnvReading;\n /** Of the serving provider's required secrets, those absent from `providerEnv` (empty unless `secrets` was READ). */\n readonly missingSecrets: readonly string[];\n /** Which guardrail the provider asked first offers, by its declared capabilities (both false when there is none). */\n readonly offers: GuardrailsOffered;\n /** The environment's reason, when it declares that its agents run unguarded where no classifier offers a guardrail. */\n readonly runsUnguardedBecause?: string;\n /**\n * With no provider found: the providers the backend scope or a selection DECLARE for the capability although none can\n * serve (not installed, or selected and not scoped with it). The runtime refuses such a declared classifier and never\n * waives it.\n */\n readonly declaredButMissing?: readonly string[];\n /**\n * A REMOTE environment (its authored file is `wildo.infra.remote.config.ts`): its deployed secrets are rebuilt from its\n * CI environment, so the `secrets.json` on this machine is a copy that may not be the whole of them.\n */\n readonly remote?: true;\n };\n\n/** Which classifier-backed guardrail something offers, or needs. */\nexport interface GuardrailsOffered {\n readonly promptInjection: boolean;\n readonly outputModeration: boolean;\n}\n\n/** The guardrails the guarded agents declare, between them. `undefined` when the agents could not be read. */\nexport function guardrailsDeclaredBy(agents: readonly AgentAiUseDeclaration[]): GuardrailsOffered | undefined {\n if (agents.some((agent) => agent.promptInjectionScreening === undefined && agent.outputModeration === undefined)) return undefined;\n const guarded = agents.filter((agent) => (agent.status == null || agent.status === FlowsActors_Agent_Status.ACTIVE) && agent.capability === EngineCapability.AI_LLM);\n return {\n promptInjection: guarded.some((agent) => agent.promptInjectionScreening != null),\n outputModeration: guarded.some((agent) => agent.outputModeration != null),\n };\n}\n\n/**\n * The agents that can be refused for want of a classifier, by ref, or `undefined` when the projection cannot say (it\n * predates the guardrail fields, so absence there means NOT READ). An agent is left out when it is known not to run\n * guardrails: inactive (never invoked), or not a language-model agent (guardrails apply to language-model agents only).\n */\nexport function guardedAgentRefs(agents: readonly AgentAiUseDeclaration[]): string[] | undefined {\n if (agents.some((agent) => agent.promptInjectionScreening === undefined && agent.outputModeration === undefined)) return undefined;\n return agents\n .filter((agent) => agent.status == null || agent.status === FlowsActors_Agent_Status.ACTIVE)\n .filter((agent) => agent.capability === EngineCapability.AI_LLM)\n .filter((agent) => agent.promptInjectionScreening != null || agent.outputModeration != null)\n .map((agent) => agent.ref)\n .sort();\n}\n\n/** Each authored environment's classifier reading. Pure: every file is read by the caller. */\nexport function readEnvironmentClassifiers(input: {\n readonly saasConfig: Pick<WildoSaasConfig, 'engineCapabilities' | 'providers' | 'providerConfigurations'>;\n readonly environments: readonly SettledAuthoredInfraEnvConfig[];\n /** Every provider the CLI can see (the composed catalogue, after discovery). */\n readonly catalogue: ReadonlyMap<string, ProviderSecretsCatalogueEntry>;\n /** The environment's `secrets.json → providerEnv`, as {@link readEnvironmentProviderEnv} reads it. */\n readonly providerEnvOf: (envName: string) => EnvironmentProviderEnvReading;\n}): EnvironmentClassifierReading[] {\n const capabilityEnabled = isEngineCapabilityEnabled(input.saasConfig.engineCapabilities as Parameters<typeof isEngineCapabilityEnabled>[0], CAPABILITY);\n // The backend's provider scope: the runtime a guarded agent runs in.\n const runtimeScope = (input.saasConfig.providers as { scopes?: Record<string, EngineCapabilityProviderScope | undefined> } | undefined)?.scopes?.backend;\n const configuredProviderRefs = new Set(Object.entries(input.saasConfig.providerConfigurations ?? {}).filter(([, value]) => Boolean(value)).map(([ref]) => ref));\n const registeredProviders = [...input.catalogue.values()].map((entry) => ({\n providerRef: entry.providerRef,\n engineCapabilities: [...new Set(entry.providerCapabilities\n .map((capability) => PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY[capability as keyof typeof PROVIDER_CAPABILITY_TO_ENGINE_CAPABILITY])\n .filter((capability): capability is EngineCapability => capability !== undefined))],\n }));\n\n return input.environments.map((environment): EnvironmentClassifierReading => {\n if ('error' in environment) {\n return { envName: environment.envName, unreadable: environment.error instanceof Error ? environment.error.message : String(environment.error) };\n }\n const remote = environment.path.endsWith('wildo.infra.remote.config.ts') ? { remote: true as const } : {};\n const declaration = environment.config.agentContentGuardrails;\n const unguarded = declaration?.withoutClassifier === AgentContentGuardrailsWithoutClassifier.RUN_UNGUARDED ? { runsUnguardedBecause: declaration.reason } : {};\n const selectionOverride = environment.config.providerSelection?.[CAPABILITY];\n const [providerRef] = orderProvidersForEngineCapability({\n capability: CAPABILITY,\n registeredProviders,\n configuration: { capabilityEnabled, runtimeScope, configuredProviderRefs },\n ...(selectionOverride ? { selectionOverride } : {}),\n });\n const secrets = input.providerEnvOf(environment.envName);\n if (providerRef === undefined) {\n // As the runtime reads it (`declaresProviderForEngineCapability`): enabled, and the scope lists one or a selection names one.\n const declaredButMissing = capabilityEnabled ? [...new Set([\n ...Object.entries(runtimeScope?.providers ?? {}).filter(([, entry]) => (entry?.engineCapabilities ?? []).includes(CAPABILITY)).map(([ref]) => ref),\n ...[selectionOverride?.primary, runtimeScope?.selection?.[CAPABILITY]?.primary].filter((ref): ref is string => typeof ref === 'string'),\n ])].sort() : [];\n return {\n envName: environment.envName, providerRef: null, secrets, missingSecrets: [], offers: { promptInjection: false, outputModeration: false },\n ...(declaredButMissing.length > 0 ? { declaredButMissing } : {}), ...remote, ...unguarded,\n };\n }\n const declared = input.catalogue.get(providerRef)?.providerCapabilities ?? [];\n const offers = {\n promptInjection: declared.includes(BUILTIN_PROVIDER_CAPABILITY.PROMPT_INJECTION_SCREENING),\n outputModeration: declared.includes(BUILTIN_PROVIDER_CAPABILITY.OUTPUT_MODERATION),\n };\n const required = (input.catalogue.get(providerRef)?.secrets ?? []).filter((secret) => secret.required).map((secret) => secret.envVarName);\n const missingSecrets = secrets.kind === EnvironmentProviderEnvReadingKind.READ\n ? required.filter((name) => typeof secrets.providerEnv[name] !== 'string' || secrets.providerEnv[name] === '').sort()\n : [];\n return { envName: environment.envName, providerRef, secrets, missingSecrets, offers, ...remote, ...unguarded };\n });\n}\n\nconst quoted = (names: readonly string[]): string => names.map((name) => `\\`${name}\\``).join(', ');\n\nconst GUARDRAIL_NAME: Readonly<Record<keyof GuardrailsOffered, string>> = {\n promptInjection: 'contentGuardrails.promptInjection',\n outputModeration: 'contentGuardrails.outputModeration',\n};\n\n/** Each environment, sorted into what can be said of it, for the guardrails the agents need. */\nfunction classify(readings: readonly EnvironmentClassifierReading[], needs: GuardrailsOffered) {\n const unserved: string[] = [];\n const unguarded: string[] = [];\n const notProbed: string[] = [];\n const served: string[] = [];\n for (const reading of readings) {\n if ('unreadable' in reading) {\n unserved.push(`${reading.envName}: its infrastructure configuration could not be read (${reading.unreadable})`);\n continue;\n }\n // Per guardrail: one the provider (or no provider) does not offer refuses, unless the environment runs it unguarded.\n const notOffered = (Object.keys(GUARDRAIL_NAME) as (keyof GuardrailsOffered)[]).filter((guardrail) => needs[guardrail] && !reading.offers[guardrail]);\n if (reading.providerRef === null && reading.declaredButMissing !== undefined && notOffered.length > 0) {\n // Declared and not there: the runtime refuses it, under any declaration of the environment.\n unserved.push(`${reading.envName}: ${quoted(reading.declaredButMissing)} ${reading.declaredButMissing.length === 1 ? 'is' : 'are'} declared for ${CAPABILITY} (scoped or selected) and cannot serve it here (not installed, or not in the backend scope with it)`);\n continue;\n }\n if (notOffered.length > 0) {\n const what = reading.providerRef === null\n ? `no provider serves ${CAPABILITY}`\n : `\\`${reading.providerRef}\\` does not offer ${notOffered.map((guardrail) => GUARDRAIL_NAME[guardrail]).join(' or ')}`;\n if (reading.runsUnguardedBecause !== undefined) {\n unguarded.push(`${reading.envName} (${what}; agentContentGuardrails: \"${reading.runsUnguardedBecause}\")`);\n } else {\n unserved.push(`${reading.envName}: ${what}`);\n }\n }\n if (reading.providerRef === null || notOffered.length === (Object.keys(GUARDRAIL_NAME) as (keyof GuardrailsOffered)[]).filter((guardrail) => needs[guardrail]).length) {\n continue;\n } else if (reading.secrets.kind === EnvironmentProviderEnvReadingKind.UNREADABLE) {\n unserved.push(`${reading.envName}: its secrets file ${reading.secrets.path} could not be read (${reading.secrets.reason}), so \\`${reading.providerRef}\\`'s secrets are unknown`);\n } else if (reading.secrets.kind === EnvironmentProviderEnvReadingKind.ABSENT) {\n notProbed.push(`${reading.envName} (\\`${reading.providerRef}\\`; no secrets.json for it on this machine)`);\n } else if (reading.missingSecrets.length > 0 && reading.runsUnguardedBecause !== undefined) {\n // Its credentials are not authored here, and the environment declares it runs unguarded: absent, as the runtime reads it.\n unguarded.push(reading.remote\n ? `${reading.envName} (\\`${reading.providerRef}\\` has no ${quoted(reading.missingSecrets)} in this machine's copy of its secrets.json; its deployed secrets come from its CI environment, so it may be guarded there; agentContentGuardrails: \"${reading.runsUnguardedBecause}\")`\n : `${reading.envName} (\\`${reading.providerRef}\\` has no ${quoted(reading.missingSecrets)} here; agentContentGuardrails: \"${reading.runsUnguardedBecause}\")`);\n } else if (reading.missingSecrets.length > 0) {\n unserved.push(reading.remote\n ? `${reading.envName}: \\`${reading.providerRef}\\` has no ${quoted(reading.missingSecrets)} in this machine's copy of its secrets.json → providerEnv (its deployed secrets come from its CI environment: check them there)`\n : `${reading.envName}: \\`${reading.providerRef}\\` has no ${quoted(reading.missingSecrets)} in secrets.json → providerEnv`);\n } else {\n served.push(`${reading.envName} (\\`${reading.providerRef}\\`)`);\n }\n }\n return { unserved, unguarded, notProbed, served };\n}\n\nconst FIX = `In each environment named, make a provider serve ${CAPABILITY} (enable the capability and list the provider in the backend scope with it; `\n + '`providerSelection` in its wildo.infra.<env>.config.ts only chooses among those) and author its required secrets in that environment\\'s '\n + 'secrets.json → providerEnv; or remove the guardrail declaration from the agent; or, deliberately, declare in that environment\\'s infra config '\n + '`agentContentGuardrails: { withoutClassifier: RUN_UNGUARDED, reason }` to run the agent unguarded there. The backend also warns at startup, one line per agent it cannot serve.';\n\n/**\n * The doctor line. WARN when a guarded agent was read and an environment cannot serve it (or could not be read); PASS\n * otherwise, saying which environments were probed and served, which were not probed, and, when the agents could not be\n * read, that the agent half was not probed. Never a FAIL: the runtime refuses the guarded agent's turns, the rest of the\n * application runs, and the remedy is a configuration edit.\n */\nexport function contentGuardrailClassifierCheck(input: {\n readonly readings: readonly EnvironmentClassifierReading[];\n /** The guarded agents, or `undefined` when the agents could not be read. */\n readonly guardedAgents: readonly string[] | undefined;\n /** The guardrails they declare between them ({@link guardrailsDeclaredBy}); both when absent or unknown. */\n readonly guardrailsNeeded?: GuardrailsOffered;\n readonly agentsNotReadBecause?: string;\n}): LocalPreconditionCheckResult {\n const name = CONTENT_GUARDRAIL_CLASSIFIER_CHECK_NAME;\n if (input.guardedAgents !== undefined && input.guardedAgents.length === 0) {\n return { name, status: LocalPreconditionCheckStatus.PASS, detail: 'no active agent declares contentGuardrails.promptInjection or contentGuardrails.outputModeration' };\n }\n const { unserved, unguarded, notProbed, served } = classify(input.readings, input.guardrailsNeeded ?? { promptInjection: true, outputModeration: true });\n const tail = [\n served.length > 0 ? `Served (probed): ${served.join(', ')}.` : '',\n unguarded.length > 0 ? `Runs guarded agents UNGUARDED, as the environment declares: ${unguarded.join(', ')}.` : '',\n notProbed.length > 0 ? `Not probed for secrets: ${notProbed.join(', ')}.` : '',\n ].filter(Boolean).join(' ');\n\n if (input.guardedAgents === undefined) {\n const because = input.agentsNotReadBecause ? ` (${input.agentsNotReadBecause})` : '';\n const information = unserved.length > 0\n ? ` An agent declaring contentGuardrails.promptInjection or .outputModeration would refuse every turn in: ${unserved.join('; ')}.`\n : '';\n return {\n name,\n status: LocalPreconditionCheckStatus.PASS,\n detail: `Not probed for agents${because}: run \\`wildo local doctor\\` with the dev companion up.${information} ${tail}`.trim(),\n };\n }\n\n const who = input.guardedAgents.length === 1\n ? `agent \\`${input.guardedAgents[0]}\\` REFUSES`\n : `agents ${quoted(input.guardedAgents)} REFUSE`;\n if (unserved.length === 0) {\n return { name, status: LocalPreconditionCheckStatus.PASS, detail: `${quoted(input.guardedAgents)}: no probed environment lacks a classifier. ${tail}`.trim() };\n }\n return {\n name,\n status: LocalPreconditionCheckStatus.WARN,\n detail: `${who} EVERY TURN where no classifier can serve ${input.guardedAgents.length === 1 ? 'it' : 'them'}: ${unserved.join('; ')}. ${tail}`.trim(),\n fix: FIX,\n };\n}\n"]}
@@ -0,0 +1,98 @@
1
+ import { type ProviderSimulatorsEntry, type ProviderSimulatorsLocation } from './system-of-record-simulators.service';
2
+ /** One provider a local double can stand in for. */
3
+ export interface LocalProviderDoubleDefinition {
4
+ /** The provider's ref, as the application's scope and selection name it. */
5
+ readonly providerRef: string;
6
+ /** The provider's host slot in `providerEnv`: `host:port` for a double. */
7
+ readonly hostEnvVarName: string;
8
+ /** The provider's API-key slot in `providerEnv`; the double is told to accept that key. */
9
+ readonly keyEnvVarName: string;
10
+ /** The simulators' command line for the double. */
11
+ readonly entry: ProviderSimulatorsEntry;
12
+ /** The double's own environment variable for the port to bind. */
13
+ readonly doublePortEnvVarName: string;
14
+ /** The double's own environment variable for the key it accepts. */
15
+ readonly doubleKeyEnvVarName: string;
16
+ /** What a person loses when the double is not running, for the one-line warning. */
17
+ readonly withoutIt: string;
18
+ }
19
+ /** Every provider a standalone double stands in for. See the module comment for why this is a table. */
20
+ export declare const LOCAL_PROVIDER_DOUBLES: readonly LocalProviderDoubleDefinition[];
21
+ /** A double this machine owes: the provider's definition, the port its host slot names, and the key it must accept. */
22
+ export interface PlannedLocalProviderDouble {
23
+ readonly definition: LocalProviderDoubleDefinition;
24
+ readonly port: number;
25
+ /** The provider's key slot, which the double must accept; absent means the double's own default key. */
26
+ readonly apiKey?: string;
27
+ }
28
+ /**
29
+ * The doubles a `providerEnv` owes, in table order. Pure. A host slot that is absent, not a string, not loopback, or
30
+ * carries no port owes nothing: the first three are a real vendor or no provider, and a loopback host without a port
31
+ * names no place to serve.
32
+ */
33
+ export declare function planLocalProviderDoubles(providerEnv: Readonly<Record<string, unknown>>): PlannedLocalProviderDouble[];
34
+ /** The port of a `host:port` slot value whose host is this machine; `undefined` otherwise (a bare host included). */
35
+ export declare function loopbackPortOf(hostSlotValue: string): number | undefined;
36
+ /**
37
+ * Whether something already accepts connections on `127.0.0.1:<port>`. A double already running (started by hand, or by
38
+ * another stack of the same application) is left alone rather than raced for the port.
39
+ */
40
+ export declare function isLoopbackPortAnswering(port: number, timeoutMs?: number): Promise<boolean>;
41
+ /** How to run one planned double: the simulators' command line, with the port and key in its environment. */
42
+ export interface LocalProviderDoubleLaunch {
43
+ readonly command: string;
44
+ readonly args: readonly string[];
45
+ readonly cwd: string;
46
+ readonly env: NodeJS.ProcessEnv;
47
+ readonly origin: ProviderSimulatorsLocation['origin'];
48
+ }
49
+ /**
50
+ * The launch for a planned double. Throws `SystemOfRecordSimulatorsUnavailableError` (the simulators' shared refusal,
51
+ * whose message names the devDependency to add) when neither the application nor a framework checkout has the package.
52
+ */
53
+ export declare function resolveLocalProviderDoubleLaunch(input: {
54
+ readonly saasRoot: string;
55
+ readonly frameworkRoot: string | null;
56
+ readonly planned: PlannedLocalProviderDouble;
57
+ readonly baseEnv?: NodeJS.ProcessEnv;
58
+ }): LocalProviderDoubleLaunch;
59
+ /** A running double, as the supervisor sees it: something that ends. */
60
+ export interface LocalProviderDoubleGeneration {
61
+ readonly exit: Promise<number>;
62
+ }
63
+ /** What the supervisor reports, so the caller decides how to word it. */
64
+ export declare enum LocalProviderDoubleEvent {
65
+ /** Another process answers on the port; this stack watches it and starts nothing. */
66
+ SERVED_ELSEWHERE = "served-elsewhere",
67
+ /** This stack starts its own double (first start, or the port stopped answering). */
68
+ STARTING = "starting",
69
+ /** This stack's double exited while the stack runs; the port is probed again before anything is restarted. */
70
+ EXITED = "exited"
71
+ }
72
+ export interface LocalProviderDoubleSupervisor {
73
+ stop(): void;
74
+ }
75
+ /** How often a port served by somebody else is checked, and the cap on the delay after repeated exits. */
76
+ export declare const LOCAL_PROVIDER_DOUBLE_WATCH_INTERVAL_MS = 10000;
77
+ /**
78
+ * Keep one port served for as long as the stack runs (see the module comment). `start` spawns this stack's double;
79
+ * `onEvent` is told when the port is served elsewhere, when a double is started, and when one exits (with the exit code
80
+ * and the number of consecutive short-lived exits, which a caller can use to decide when to warn). Never throws.
81
+ */
82
+ export declare function superviseLocalProviderDouble<TGeneration extends LocalProviderDoubleGeneration>(options: {
83
+ readonly port: number;
84
+ readonly start: () => TGeneration;
85
+ readonly onStarted: (generation: TGeneration) => void;
86
+ readonly onEnded: (generation: TGeneration) => void;
87
+ readonly onEvent: (event: LocalProviderDoubleEvent, detail: {
88
+ readonly exitCode?: number;
89
+ readonly consecutiveFailures: number;
90
+ }) => void;
91
+ readonly probe?: (port: number) => Promise<boolean>;
92
+ readonly sleep?: (ms: number, signal: {
93
+ readonly stopped: boolean;
94
+ }) => Promise<void>;
95
+ readonly now?: () => number;
96
+ readonly watchIntervalMs?: number;
97
+ }): LocalProviderDoubleSupervisor;
98
+ //# sourceMappingURL=local-provider-doubles.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-provider-doubles.service.d.ts","sourceRoot":"","sources":["../../../../src/services/application/local-provider-doubles.service.ts"],"names":[],"mappings":"AA4CA,OAAO,EAA4B,KAAK,uBAAuB,EAAE,KAAK,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AAEhJ,oDAAoD;AACpD,MAAM,WAAW,6BAA6B;IAC5C,4EAA4E;IAC5E,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,2EAA2E;IAC3E,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,2FAA2F;IAC3F,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,mDAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,uBAAuB,CAAC;IACxC,kEAAkE;IAClE,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,oEAAoE;IACpE,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,oFAAoF;IACpF,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED,wGAAwG;AACxG,eAAO,MAAM,sBAAsB,EAAE,SAAS,6BAA6B,EAe1E,CAAC;AAKF,uHAAuH;AACvH,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,UAAU,EAAE,6BAA6B,CAAC;IACnD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;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GAA8G;IAC9G,MAAM,WAAW;CAClB;AAED,MAAM,WAAW,6BAA6B;IAC5C,IAAI,IAAI,IAAI,CAAC;CACd;AAED,0GAA0G;AAC1G,eAAO,MAAM,uCAAuC,QAAS,CAAC;AAI9D;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,WAAW,SAAS,6BAA6B,EAAE,OAAO,EAAE;IACvG,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,WAAW,CAAC;IAClC,QAAQ,CAAC,SAAS,EAAE,CAAC,UAAU,EAAE,WAAW,KAAK,IAAI,CAAC;IACtD,QAAQ,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,KAAK,IAAI,CAAC;IACpD,QAAQ,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,wBAAwB,EAAE,MAAM,EAAE;QAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IAC1I,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACpD,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE;QAAE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtF,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CACnC,GAAG,6BAA6B,CAwDhC"}
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The local doubles a developer machine owes its application: a provider whose LOCAL secrets point its host at this
3
+ * machine is served by a process that `wildo local dev` starts and keeps running.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * Wonder Todos selects `azure-content-safety` for local development and points its host slot at the provider-simulators
8
+ * double (`AZURE_CONTENT_SAFETY_HOST=127.0.0.1:18309`). Until this service, that double was started BY HAND, so after
9
+ * every reboot nothing listened on the port, the classifier call failed with `ECONNREFUSED`, and every guarded agent's
10
+ * reply was withheld as `OUTPUT_NOT_MODERATED` ("This reply couldn't be checked against the content policy"). The guard
11
+ * was right to fail closed; the stack was wrong to leave the classifier it was told to use unstarted. Measured in four
12
+ * separate sessions before this landed (2026-11-11 was the fifth).
13
+ *
14
+ * ## What it derives, and from what
15
+ *
16
+ * Nothing is authored for it. The local `secrets.json → providerEnv` already says where each provider is reached; a host
17
+ * slot naming a loopback address WITH a port is a statement that this machine serves that provider, and the port is
18
+ * where. A host naming anything else (a real vendor resource) is left alone: that is the developer's decision to use
19
+ * the real service. A double is started only for a provider this table knows a double for.
20
+ *
21
+ * ## The table, and why it is a table
22
+ *
23
+ * {@link LOCAL_PROVIDER_DOUBLES} maps a provider to its double: which host and key slots the provider reads, and which
24
+ * command line of `@wildo-ai/provider-simulators` stands in for it. The simulators import nothing from Wildo and this CLI
25
+ * does not depend on them, so the join is written here and pinned by a test against both sides (the provider module's
26
+ * slot names, the double's environment variables). Add a row when a new standalone double is added to the simulators.
27
+ * The systems-of-record fleet is NOT a row: it is a separate plan (`wildo local sor-simulators`, #3039).
28
+ *
29
+ * ## Where the double comes from
30
+ *
31
+ * The same order as the fleet (`locateProviderSimulators`): the application's own `@wildo-ai/provider-simulators`
32
+ * devDependency, then a framework checkout's source. An application with neither is TOLD, once, how to get one; the stack
33
+ * still starts, and the guarded agents refuse their turns exactly as they would have.
34
+ *
35
+ * ## Who serves the port, and for how long
36
+ *
37
+ * Two applications on one machine may name the SAME port (Wonder Todos and Wonder Ledger both use 127.0.0.1:18309, with
38
+ * one key). So a port that already answers is not a reason to give up on it: {@link superviseLocalProviderDouble} watches
39
+ * it, and starts this stack's own double the moment it stops answering (the other stack stopped, or a double started by
40
+ * hand died). A double of ours that exits is replaced only after the port is probed again, so a race for the port ends
41
+ * with whoever holds it rather than a restart loop. The supervisor never kills a process it did not start.
42
+ */
43
+ import { connect } from 'node:net';
44
+ import { locateProviderSimulators } from './system-of-record-simulators.service.js';
45
+ /** Every provider a standalone double stands in for. See the module comment for why this is a table. */
46
+ export const LOCAL_PROVIDER_DOUBLES = [
47
+ {
48
+ providerRef: 'azure-content-safety',
49
+ hostEnvVarName: 'AZURE_CONTENT_SAFETY_HOST',
50
+ keyEnvVarName: 'AZURE_CONTENT_SAFETY_KEY',
51
+ entry: {
52
+ checkoutEntry: 'src/content-safety/main.ts',
53
+ bin: 'wildo-provider-simulators-content-safety',
54
+ purpose: 'run the content-safety classifier double locally',
55
+ otherwise: 'Or point AZURE_CONTENT_SAFETY_HOST at a real Azure AI Content Safety resource with `wildo secrets set`.',
56
+ },
57
+ doublePortEnvVarName: 'CONTENT_SAFETY_MOCK_PORT',
58
+ doubleKeyEnvVarName: 'CONTENT_SAFETY_MOCK_API_KEY',
59
+ withoutIt: 'every agent declaring contentGuardrails.promptInjection or outputModeration refuses or withholds its turns (OUTPUT_NOT_MODERATED)',
60
+ },
61
+ ];
62
+ /** Hosts that mean "this machine". `[::1]` is not one: the doubles bind IPv4 loopback. */
63
+ const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost']);
64
+ /**
65
+ * The doubles a `providerEnv` owes, in table order. Pure. A host slot that is absent, not a string, not loopback, or
66
+ * carries no port owes nothing: the first three are a real vendor or no provider, and a loopback host without a port
67
+ * names no place to serve.
68
+ */
69
+ export function planLocalProviderDoubles(providerEnv) {
70
+ const planned = [];
71
+ for (const definition of LOCAL_PROVIDER_DOUBLES) {
72
+ const host = providerEnv[definition.hostEnvVarName];
73
+ if (typeof host !== 'string' || host.trim() === '')
74
+ continue;
75
+ const port = loopbackPortOf(host.trim());
76
+ if (port === undefined)
77
+ continue;
78
+ const apiKey = providerEnv[definition.keyEnvVarName];
79
+ planned.push({ definition, port, ...(typeof apiKey === 'string' && apiKey !== '' ? { apiKey } : {}) });
80
+ }
81
+ return planned;
82
+ }
83
+ /** The port of a `host:port` slot value whose host is this machine; `undefined` otherwise (a bare host included). */
84
+ export function loopbackPortOf(hostSlotValue) {
85
+ let url;
86
+ try {
87
+ // The slot holds a bare `host:port` (the engine refuses a scheme or a path); an accidental scheme is read too.
88
+ url = new URL(/^[a-z]+:\/\//i.test(hostSlotValue) ? hostSlotValue : `http://${hostSlotValue}`);
89
+ }
90
+ catch {
91
+ return undefined;
92
+ }
93
+ if (!LOOPBACK_HOSTNAMES.has(url.hostname) || url.port === '')
94
+ return undefined;
95
+ const port = Number(url.port);
96
+ return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : undefined;
97
+ }
98
+ /**
99
+ * Whether something already accepts connections on `127.0.0.1:<port>`. A double already running (started by hand, or by
100
+ * another stack of the same application) is left alone rather than raced for the port.
101
+ */
102
+ export function isLoopbackPortAnswering(port, timeoutMs = 750) {
103
+ return new Promise((resolve) => {
104
+ const socket = connect({ host: '127.0.0.1', port });
105
+ const settle = (answering) => {
106
+ socket.removeAllListeners();
107
+ socket.destroy();
108
+ resolve(answering);
109
+ };
110
+ socket.setTimeout(timeoutMs, () => settle(false));
111
+ socket.once('connect', () => settle(true));
112
+ socket.once('error', () => settle(false));
113
+ });
114
+ }
115
+ /**
116
+ * The launch for a planned double. Throws `SystemOfRecordSimulatorsUnavailableError` (the simulators' shared refusal,
117
+ * whose message names the devDependency to add) when neither the application nor a framework checkout has the package.
118
+ */
119
+ export function resolveLocalProviderDoubleLaunch(input) {
120
+ const { definition, port, apiKey } = input.planned;
121
+ const location = locateProviderSimulators({ saasRoot: input.saasRoot, frameworkRoot: input.frameworkRoot, entry: definition.entry });
122
+ return {
123
+ command: location.command,
124
+ args: [...location.launchArguments],
125
+ cwd: location.cwd,
126
+ origin: location.origin,
127
+ env: {
128
+ ...(input.baseEnv ?? process.env),
129
+ [definition.doublePortEnvVarName]: String(port),
130
+ ...(apiKey === undefined ? {} : { [definition.doubleKeyEnvVarName]: apiKey }),
131
+ },
132
+ };
133
+ }
134
+ /** What the supervisor reports, so the caller decides how to word it. */
135
+ export var LocalProviderDoubleEvent;
136
+ (function (LocalProviderDoubleEvent) {
137
+ /** Another process answers on the port; this stack watches it and starts nothing. */
138
+ LocalProviderDoubleEvent["SERVED_ELSEWHERE"] = "served-elsewhere";
139
+ /** This stack starts its own double (first start, or the port stopped answering). */
140
+ LocalProviderDoubleEvent["STARTING"] = "starting";
141
+ /** This stack's double exited while the stack runs; the port is probed again before anything is restarted. */
142
+ LocalProviderDoubleEvent["EXITED"] = "exited";
143
+ })(LocalProviderDoubleEvent || (LocalProviderDoubleEvent = {}));
144
+ /** How often a port served by somebody else is checked, and the cap on the delay after repeated exits. */
145
+ export const LOCAL_PROVIDER_DOUBLE_WATCH_INTERVAL_MS = 10_000;
146
+ const LOCAL_PROVIDER_DOUBLE_MAX_BACKOFF_MS = 30_000;
147
+ const LOCAL_PROVIDER_DOUBLE_HEALTHY_UPTIME_MS = 30_000;
148
+ /**
149
+ * Keep one port served for as long as the stack runs (see the module comment). `start` spawns this stack's double;
150
+ * `onEvent` is told when the port is served elsewhere, when a double is started, and when one exits (with the exit code
151
+ * and the number of consecutive short-lived exits, which a caller can use to decide when to warn). Never throws.
152
+ */
153
+ export function superviseLocalProviderDouble(options) {
154
+ const probe = options.probe ?? isLoopbackPortAnswering;
155
+ const now = options.now ?? Date.now;
156
+ const watchIntervalMs = options.watchIntervalMs ?? LOCAL_PROVIDER_DOUBLE_WATCH_INTERVAL_MS;
157
+ const state = { stopped: false };
158
+ let wake;
159
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => {
160
+ const timer = setTimeout(() => { wake = undefined; resolve(); }, ms);
161
+ timer.unref?.();
162
+ wake = () => { clearTimeout(timer); wake = undefined; resolve(); };
163
+ }));
164
+ const run = async () => {
165
+ let servedElsewhereReported = false;
166
+ let consecutiveFailures = 0;
167
+ while (!state.stopped) {
168
+ let answering = false;
169
+ try {
170
+ answering = await probe(options.port);
171
+ }
172
+ catch {
173
+ answering = false;
174
+ }
175
+ if (state.stopped)
176
+ return;
177
+ if (answering) {
178
+ if (!servedElsewhereReported)
179
+ options.onEvent(LocalProviderDoubleEvent.SERVED_ELSEWHERE, { consecutiveFailures });
180
+ servedElsewhereReported = true;
181
+ await sleep(watchIntervalMs, state);
182
+ continue;
183
+ }
184
+ servedElsewhereReported = false;
185
+ options.onEvent(LocalProviderDoubleEvent.STARTING, { consecutiveFailures });
186
+ const startedAt = now();
187
+ let generation;
188
+ try {
189
+ generation = options.start();
190
+ }
191
+ catch {
192
+ consecutiveFailures += 1;
193
+ await sleep(Math.min(1_000 * 2 ** (consecutiveFailures - 1), LOCAL_PROVIDER_DOUBLE_MAX_BACKOFF_MS), state);
194
+ continue;
195
+ }
196
+ options.onStarted(generation);
197
+ const exitCode = await generation.exit;
198
+ options.onEnded(generation);
199
+ if (state.stopped)
200
+ return;
201
+ consecutiveFailures = now() - startedAt >= LOCAL_PROVIDER_DOUBLE_HEALTHY_UPTIME_MS ? 1 : consecutiveFailures + 1;
202
+ options.onEvent(LocalProviderDoubleEvent.EXITED, { exitCode, consecutiveFailures });
203
+ await sleep(Math.min(1_000 * 2 ** (consecutiveFailures - 1), LOCAL_PROVIDER_DOUBLE_MAX_BACKOFF_MS), state);
204
+ }
205
+ };
206
+ void run();
207
+ return {
208
+ stop() {
209
+ state.stopped = true;
210
+ wake?.();
211
+ },
212
+ };
213
+ }
214
+ //# sourceMappingURL=local-provider-doubles.service.js.map