@pikku/core 0.12.93 → 0.12.95

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 (56) hide show
  1. package/CHANGELOG.md +157 -0
  2. package/dist/services/email-template.d.ts +43 -0
  3. package/dist/services/email-template.js +139 -0
  4. package/dist/services/http-personas.d.ts +6 -1
  5. package/dist/services/http-personas.js +4 -1
  6. package/dist/services/index.d.ts +1 -0
  7. package/dist/services/index.js +1 -0
  8. package/dist/wirings/agent/agent-prepare.d.ts +14 -0
  9. package/dist/wirings/agent/agent-prepare.js +24 -0
  10. package/dist/wirings/agent/index.d.ts +1 -1
  11. package/dist/wirings/agent/index.js +1 -1
  12. package/dist/wirings/persona/index.d.ts +1 -0
  13. package/dist/wirings/persona/index.js +1 -0
  14. package/dist/wirings/persona/persona-app-scopes.d.ts +41 -0
  15. package/dist/wirings/persona/persona-app-scopes.js +61 -0
  16. package/dist/wirings/scheduler/scheduler-runner.js +0 -1
  17. package/dist/wirings/virtual-user/index.d.ts +1 -0
  18. package/dist/wirings/virtual-user/index.js +1 -0
  19. package/dist/wirings/virtual-user/virtual-user-derive.js +9 -0
  20. package/dist/wirings/virtual-user/virtual-user-scaffold.d.ts +267 -0
  21. package/dist/wirings/virtual-user/virtual-user-scaffold.js +400 -0
  22. package/dist/wirings/workflow/index.d.ts +1 -0
  23. package/dist/wirings/workflow/index.js +1 -0
  24. package/dist/wirings/workflow/pikku-workflow-service.js +3 -9
  25. package/dist/wirings/workflow/workflow-queue-routing.d.ts +18 -0
  26. package/dist/wirings/workflow/workflow-queue-routing.js +35 -0
  27. package/dist/wirings/workflow/workflow-status-stream.d.ts +28 -0
  28. package/dist/wirings/workflow/workflow-status-stream.js +105 -0
  29. package/package.json +1 -1
  30. package/src/public-surface.json +20 -1
  31. package/src/services/email-template.test.ts +311 -0
  32. package/src/services/email-template.ts +254 -0
  33. package/src/services/http-personas.ts +10 -2
  34. package/src/services/index.ts +8 -0
  35. package/src/services/persona-sign-in.test.ts +22 -0
  36. package/src/wirings/agent/agent-helpers.test.ts +63 -0
  37. package/src/wirings/agent/agent-prepare.ts +25 -0
  38. package/src/wirings/agent/index.ts +1 -0
  39. package/src/wirings/persona/index.ts +5 -0
  40. package/src/wirings/persona/persona-app-scopes.test.ts +47 -0
  41. package/src/wirings/persona/persona-app-scopes.ts +74 -0
  42. package/src/wirings/scheduler/scheduler-runner.test.ts +178 -0
  43. package/src/wirings/scheduler/scheduler-runner.ts +0 -1
  44. package/src/wirings/virtual-user/index.ts +20 -0
  45. package/src/wirings/virtual-user/virtual-user-derive.test.ts +28 -0
  46. package/src/wirings/virtual-user/virtual-user-derive.ts +9 -0
  47. package/src/wirings/virtual-user/virtual-user-scaffold.test.ts +795 -0
  48. package/src/wirings/virtual-user/virtual-user-scaffold.ts +634 -0
  49. package/src/wirings/workflow/index.ts +4 -0
  50. package/src/wirings/workflow/pikku-workflow-service.test.ts +71 -2
  51. package/src/wirings/workflow/pikku-workflow-service.ts +5 -11
  52. package/src/wirings/workflow/workflow-child-run-session.test.ts +79 -0
  53. package/src/wirings/workflow/workflow-queue-routing.ts +44 -0
  54. package/src/wirings/workflow/workflow-status-stream.test.ts +354 -0
  55. package/src/wirings/workflow/workflow-status-stream.ts +144 -0
  56. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,634 @@
1
+ import type { Logger } from '../../services/logger.js'
2
+ import type { MetaService } from '../../services/meta-service.js'
3
+ import type { VariablesService } from '../../services/variables-service.js'
4
+ import type { AgentRunnerService } from '../../services/agent-runner-service.js'
5
+ import type { HttpPersonasConfig } from '../../services/http-personas.js'
6
+ import type {
7
+ ResolvedPersona,
8
+ ScenarioPersonas,
9
+ } from '../../services/personas-service.js'
10
+ import { prepareVirtualUserRun } from './prepare-virtual-user-run.js'
11
+ import { runVirtualUser as runVirtualUserEngine } from './run-virtual-user.js'
12
+ import { personaVirtualUserTarget } from './virtual-user-target.js'
13
+ import type { SchemaMap } from './virtual-user-derive.js'
14
+ import { PRODUCTION_DISPOSITION } from './virtual-user.types.js'
15
+ import type {
16
+ StepRecord,
17
+ VirtualUserDisposition,
18
+ } from './virtual-user.types.js'
19
+ import type {
20
+ VirtualUserRunRecord,
21
+ VirtualUserRunStore,
22
+ } from './virtual-user-run-store.js'
23
+ import type {
24
+ VirtualUserScheduleRecord,
25
+ VirtualUserScheduleStore,
26
+ } from './virtual-user-schedule-store.js'
27
+ import type { VirtualUserTickResult } from './virtual-user-schedule.js'
28
+
29
+ /**
30
+ * The bodies behind the scaffolded virtual-user RPCs.
31
+ *
32
+ * The scaffold emits the *wirings* — the `pikkuFunc` shells whose `input`,
33
+ * `output` and `scopes` the CLI reads back by AST, and the `rpc.invoke` calls
34
+ * typed off the app's own RPC map. None of the work inside them varies by
35
+ * application, so it lives here instead of inside a template string: type
36
+ * checked when core builds, unit tested next to the engine it drives, and fixed
37
+ * once rather than in every generated copy of it.
38
+ *
39
+ * What an application does supply arrives as a parameter — its declared
40
+ * personas, its `createPersonas`, its config — because those are the only
41
+ * things codegen knows that this cannot.
42
+ */
43
+
44
+ /** Persona id → the declaration, which is what `personaConfigs` is. */
45
+ export type ScaffoldPersonas = Record<string, ResolvedPersona>
46
+
47
+ /**
48
+ * The variables a scaffolded run reads.
49
+ *
50
+ * Names rather than values, and read through `VariablesService` at run time, so
51
+ * a stage says where it lives without anything being baked into generated code.
52
+ */
53
+ export const VIRTUAL_USER_VARIABLES = {
54
+ /**
55
+ * Where the virtual user signs in. Its own variable rather than a guess at
56
+ * the host's origin: a run drives real traffic through the real front door,
57
+ * and a server that cannot name its own public URL would be signing in
58
+ * somewhere it only assumed was itself.
59
+ */
60
+ apiUrl: 'VIRTUAL_USER_API_URL',
61
+ secret: 'SCENARIO_ACTOR_SECRET',
62
+ model: 'VIRTUAL_USER_MODEL',
63
+ /**
64
+ * The same two variables a scenario run reads, because a virtual user signs
65
+ * in and calls through exactly the doors a scenario does. An app that mounts
66
+ * auth somewhere other than the root — `/api/auth` is the common one — has no
67
+ * other way to say so, and without them the run signs in against a 404 and
68
+ * spends its whole budget thinking about why nothing works.
69
+ */
70
+ signInPath: 'SCENARIO_SIGN_IN_PATH',
71
+ rpcPath: 'SCENARIO_RPC_PATH',
72
+ /**
73
+ * The deployed way in. A Fabric operator token is asymmetric — a stage can
74
+ * verify one and can never mint one — so unlike the actor secret it is safe
75
+ * for a run against a real environment. Read from the environment only as the
76
+ * fallback for a run nobody handed a token to, which is what a schedule is.
77
+ */
78
+ operatorToken: 'FABRIC_OPERATOR_TOKEN',
79
+ createMissing: 'PIKKU_PERSONA_CREATE_MISSING',
80
+ } as const
81
+
82
+ /**
83
+ * Which door under the auth mount, given the credential in hand.
84
+ *
85
+ * Both are better-auth plugins mounted side by side, so `SCENARIO_SIGN_IN_PATH`
86
+ * names the mount and the last segment is ours to pick — an app that moved auth
87
+ * to `/api/auth` says so once and both paths follow. A path that names neither
88
+ * plugin is left alone, since it was configured deliberately.
89
+ */
90
+ export const signInPathFor = (
91
+ configured: string | undefined,
92
+ plugin: 'actor' | 'fabric'
93
+ ): string | undefined => {
94
+ if (!configured) {
95
+ return undefined
96
+ }
97
+ const mount = configured.replace(/\/sign-in\/(actor|fabric)$/, '')
98
+ return mount === configured ? configured : `${mount}/sign-in/${plugin}`
99
+ }
100
+
101
+ /**
102
+ * The declared persona behind an id, refused unless it is one a run may be.
103
+ *
104
+ * An acted-upon persona has no session of its own, and running one would race
105
+ * whatever scenario acts on it.
106
+ */
107
+ export const runnablePersona = (
108
+ personas: ScaffoldPersonas,
109
+ personaId: string
110
+ ): ResolvedPersona => {
111
+ const persona = personas[personaId]
112
+ if (!persona) {
113
+ throw new Error(
114
+ `Unknown persona "${personaId}" — declare it with definePersonas()`
115
+ )
116
+ }
117
+ if (!persona.runnable) {
118
+ throw new Error(
119
+ `Persona "${personaId}" is declared as acted upon, never run`
120
+ )
121
+ }
122
+ return persona
123
+ }
124
+
125
+ const MISSING_RUN_STORE =
126
+ 'No virtualUserRunStore is wired — a run has nowhere to be recorded. ' +
127
+ 'Wire KyselyVirtualUserRunStore from @pikku/kysely, or your own implementation of VirtualUserRunStore.'
128
+
129
+ const MISSING_RUN_STORE_READ =
130
+ 'No virtualUserRunStore is wired — there are no runs to read.'
131
+
132
+ const MISSING_SCHEDULE_STORE =
133
+ 'No virtualUserScheduleStore is wired — a cadence has nowhere to live. ' +
134
+ 'Wire KyselyVirtualUserScheduleStore from @pikku/kysely, or your own implementation of VirtualUserScheduleStore.'
135
+
136
+ /** The store, or the error naming the one to wire. */
137
+ export const requireVirtualUserRunStore = (
138
+ store: VirtualUserRunStore | undefined,
139
+ reading = false
140
+ ): VirtualUserRunStore => {
141
+ if (!store) {
142
+ throw new Error(reading ? MISSING_RUN_STORE_READ : MISSING_RUN_STORE)
143
+ }
144
+ return store
145
+ }
146
+
147
+ export const requireVirtualUserScheduleStore = (
148
+ store: VirtualUserScheduleStore | undefined
149
+ ): VirtualUserScheduleStore => {
150
+ if (!store) {
151
+ throw new Error(MISSING_SCHEDULE_STORE)
152
+ }
153
+ return store
154
+ }
155
+
156
+ /** What a caller asked for, before the declaration fills in what it left out. */
157
+ export interface StartVirtualUserRunParams {
158
+ store: VirtualUserRunStore | undefined
159
+ personas: ScaffoldPersonas
160
+ /**
161
+ * The app's config, read only for `nodeEnv` — structural because an
162
+ * application's Config is its own interface and need not declare it at all.
163
+ */
164
+ config: { nodeEnv?: string } | undefined
165
+ persona: string
166
+ disposition?: string
167
+ seed?: number
168
+ goals?: string[]
169
+ memory?: Record<string, string>
170
+ /** Whoever the session says, which for a scheduled tick is the platform user. */
171
+ startedBy?: string | null
172
+ }
173
+
174
+ /** The recorded run, and the values the dispatch has to carry unchanged. */
175
+ export interface StartedVirtualUserRun {
176
+ runId: string
177
+ persona: string
178
+ disposition: VirtualUserDisposition
179
+ seed: number
180
+ goals: string[]
181
+ memory: Record<string, string>
182
+ }
183
+
184
+ /**
185
+ * Resolves a request against the declaration and records the run.
186
+ *
187
+ * Everything up to the point a run exists, which is everything a caller and a
188
+ * scheduled tick have in common. The dispatch that follows is typed off the
189
+ * app's RPC map, so it stays in the generated wiring.
190
+ */
191
+ export const startVirtualUserRun = async ({
192
+ store,
193
+ personas,
194
+ config,
195
+ persona: personaId,
196
+ disposition: requested,
197
+ seed: requestedSeed,
198
+ goals,
199
+ memory,
200
+ startedBy,
201
+ }: StartVirtualUserRunParams): Promise<StartedVirtualUserRun> => {
202
+ const runStore = requireVirtualUserRunStore(store)
203
+ const persona = runnablePersona(personas, personaId)
204
+
205
+ const disposition = (requested ??
206
+ persona.disposition ??
207
+ 'realistic') as VirtualUserDisposition
208
+
209
+ // Every disposition other than this one exists to find out what the product
210
+ // does wrong, which is not a thing to do to real customers' data. Checked
211
+ // against the effective disposition, so an override cannot smuggle one in.
212
+ if (
213
+ config?.nodeEnv === 'production' &&
214
+ disposition !== PRODUCTION_DISPOSITION
215
+ ) {
216
+ throw new Error(
217
+ `Only the '${PRODUCTION_DISPOSITION}' disposition may run against production; "${personaId}" is ${disposition}`
218
+ )
219
+ }
220
+
221
+ // Seeded here rather than inside the engine so the record carries the seed
222
+ // even if the run dies before returning — an unreproducible crash costs the
223
+ // most.
224
+ const seed = requestedSeed ?? Math.floor(Math.random() * 2_147_483_647)
225
+ const resolvedGoals = goals ?? []
226
+ const resolvedMemory = memory ?? {}
227
+
228
+ const runId = await runStore.start({
229
+ persona: persona.id,
230
+ disposition,
231
+ seed,
232
+ goals: resolvedGoals,
233
+ memory: resolvedMemory,
234
+ startedBy: startedBy ?? null,
235
+ })
236
+
237
+ return {
238
+ runId,
239
+ persona: persona.id,
240
+ disposition,
241
+ seed,
242
+ goals: resolvedGoals,
243
+ memory: resolvedMemory,
244
+ }
245
+ }
246
+
247
+ /**
248
+ * One run on the wire.
249
+ *
250
+ * Findings and intents are free-form by design — the engine records what it
251
+ * noticed, not a fixed row shape — so they cross as the schema's open objects
252
+ * rather than being narrowed to whatever kinds exist today.
253
+ */
254
+ export const serializeVirtualUserRun = (run: VirtualUserRunRecord) => ({
255
+ runId: run.runId,
256
+ persona: run.persona,
257
+ disposition: run.disposition,
258
+ seed: run.seed,
259
+ status: run.status,
260
+ goals: run.goals,
261
+ memory: run.memory,
262
+ findings: run.findings.map((finding) => ({
263
+ kind: finding.kind as string,
264
+ detail: finding.detail,
265
+ rpcName: finding.rpcName,
266
+ status: finding.status,
267
+ intentId: finding.intentId,
268
+ step: finding.step,
269
+ })),
270
+ intents: run.intents.map((intent) => ({
271
+ id: intent.id,
272
+ sourceId: intent.sourceId,
273
+ title: intent.title,
274
+ status: intent.status as string,
275
+ steps: intent.steps,
276
+ suspensions: intent.suspensions,
277
+ summary: intent.summary,
278
+ })),
279
+ tally: (run.tally ?? null) as Record<string, unknown> | null,
280
+ stoppedBy: run.stoppedBy,
281
+ error: run.error,
282
+ createdAt: run.createdAt.toISOString(),
283
+ finishedAt: run.finishedAt ? run.finishedAt.toISOString() : null,
284
+ })
285
+
286
+ /** One run's turns on the wire. */
287
+ export const serializeVirtualUserSteps = (steps: readonly StepRecord[]) =>
288
+ steps.map((step) => ({
289
+ index: step.index,
290
+ intentId: step.intentId,
291
+ action: step.action as unknown as Record<string, unknown>,
292
+ status: step.status,
293
+ ok: step.ok,
294
+ response: step.response,
295
+ findingKinds: step.findingKinds as string[] | undefined,
296
+ tokensIn: step.tokensIn,
297
+ tokensOut: step.tokensOut,
298
+ }))
299
+
300
+ /**
301
+ * One schedule on the wire.
302
+ *
303
+ * The budget crosses as `durationMs` because that is what every other call here
304
+ * takes; the engine's own duration also accepts `'30m'`, which nothing on this
305
+ * side ever writes.
306
+ */
307
+ export const serializeVirtualUserSchedule = (
308
+ schedule: VirtualUserScheduleRecord,
309
+ personas: ScaffoldPersonas
310
+ ) => {
311
+ const persona = personas[schedule.persona]
312
+ return {
313
+ persona: schedule.persona,
314
+ enabled: schedule.enabled,
315
+ disposition: schedule.disposition,
316
+ goals: schedule.goals,
317
+ budget: schedule.budget
318
+ ? {
319
+ steps: schedule.budget.steps,
320
+ mutations: schedule.budget.mutations,
321
+ durationMs:
322
+ typeof schedule.budget.duration === 'number'
323
+ ? schedule.budget.duration
324
+ : undefined,
325
+ }
326
+ : null,
327
+ minIntervalMs: schedule.minIntervalMs,
328
+ maxIntervalMs: schedule.maxIntervalMs,
329
+ nextRunAt: schedule.nextRunAt.toISOString(),
330
+ lastRunId: schedule.lastRunId,
331
+ lastRunAt: schedule.lastRunAt ? schedule.lastRunAt.toISOString() : null,
332
+ declared: {
333
+ disposition: (persona?.disposition ??
334
+ 'realistic') as VirtualUserDisposition,
335
+ goals: persona?.goals ?? [],
336
+ },
337
+ }
338
+ }
339
+
340
+ export interface WriteVirtualUserScheduleParams {
341
+ store: VirtualUserScheduleStore | undefined
342
+ personas: ScaffoldPersonas
343
+ persona: string
344
+ enabled?: boolean
345
+ disposition?: string
346
+ goals?: string[]
347
+ budget?: {
348
+ steps?: number
349
+ mutations?: number
350
+ durationMs?: number
351
+ } | null
352
+ minIntervalMs?: number
353
+ maxIntervalMs?: number
354
+ nextRunAt?: string
355
+ }
356
+
357
+ /**
358
+ * Writes a persona's cadence.
359
+ *
360
+ * Applies the same rule `startVirtualUserRun` enforces, at the point the row is
361
+ * written rather than every hour afterwards: an acted-upon persona has no
362
+ * session, so a cadence for one is a tick that can only ever fail to start.
363
+ */
364
+ export const writeVirtualUserSchedule = async ({
365
+ store,
366
+ personas,
367
+ persona,
368
+ enabled,
369
+ disposition,
370
+ goals,
371
+ budget,
372
+ minIntervalMs,
373
+ maxIntervalMs,
374
+ nextRunAt,
375
+ }: WriteVirtualUserScheduleParams): Promise<VirtualUserScheduleRecord> => {
376
+ const scheduleStore = requireVirtualUserScheduleStore(store)
377
+ runnablePersona(personas, persona)
378
+ return scheduleStore.set({
379
+ persona,
380
+ enabled,
381
+ disposition: disposition as VirtualUserDisposition | undefined,
382
+ goals,
383
+ budget:
384
+ budget === undefined
385
+ ? undefined
386
+ : budget === null
387
+ ? null
388
+ : {
389
+ steps: budget.steps,
390
+ mutations: budget.mutations,
391
+ duration: budget.durationMs,
392
+ },
393
+ minIntervalMs,
394
+ maxIntervalMs,
395
+ nextRunAt: nextRunAt ? new Date(nextRunAt) : undefined,
396
+ })
397
+ }
398
+
399
+ /** What a due schedule asks `runVirtualUser` for. */
400
+ export const virtualUserScheduleRunInput = (
401
+ schedule: VirtualUserScheduleRecord
402
+ ) => ({
403
+ persona: schedule.persona,
404
+ disposition: schedule.disposition as VirtualUserDisposition,
405
+ goals: schedule.goals,
406
+ budget: schedule.budget
407
+ ? {
408
+ steps: schedule.budget.steps,
409
+ mutations: schedule.budget.mutations,
410
+ durationMs:
411
+ typeof schedule.budget.duration === 'number'
412
+ ? schedule.budget.duration
413
+ : undefined,
414
+ }
415
+ : undefined,
416
+ })
417
+
418
+ /**
419
+ * What a tick did.
420
+ *
421
+ * Logged rather than returned: the caller is a cron, and a run this started is
422
+ * otherwise the only trace that a persona is still out there working.
423
+ */
424
+ export const logVirtualUserTick = (
425
+ logger: Logger,
426
+ result: VirtualUserTickResult
427
+ ): void => {
428
+ for (const { persona, runId } of result.dispatched) {
429
+ logger.info(`Virtual user ${persona} started run ${runId} on schedule`)
430
+ }
431
+ for (const runId of result.reaped) {
432
+ logger.warn(
433
+ `Virtual user run ${runId} was abandoned — marked failed so its persona can run again`
434
+ )
435
+ }
436
+ for (const { persona, reason } of result.skipped) {
437
+ logger.info(`Virtual user ${persona} skipped this tick: ${reason}`)
438
+ }
439
+ }
440
+
441
+ export interface ExecuteVirtualUserRunParams {
442
+ runStore: VirtualUserRunStore | undefined
443
+ metaService: MetaService | undefined
444
+ agentRunner: AgentRunnerService | undefined
445
+ variables: VariablesService
446
+ logger: Logger
447
+ personas: ScaffoldPersonas
448
+ /** The app's generated `createPersonas`, which knows its own persona ids. */
449
+ createPersonas: (
450
+ options: Omit<HttpPersonasConfig, 'personas'>
451
+ ) => ScenarioPersonas
452
+ runId: string
453
+ persona: string
454
+ disposition: string
455
+ goals: string[]
456
+ memory: Record<string, string>
457
+ seed: number
458
+ budget?: {
459
+ steps?: number
460
+ mutations?: number
461
+ durationMs?: number
462
+ }
463
+ operatorToken?: string
464
+ }
465
+
466
+ /**
467
+ * The run itself.
468
+ *
469
+ * Everything it needs is derived through `metaService` and the generated
470
+ * personas — the same public surface any consumer has. Nothing reaches into
471
+ * pikku's internals, because an app could not, and a feature built on what only
472
+ * the framework can see would not be this feature.
473
+ */
474
+ export const executeVirtualUserRun = async ({
475
+ runStore,
476
+ metaService,
477
+ agentRunner,
478
+ variables,
479
+ logger,
480
+ personas,
481
+ createPersonas,
482
+ runId,
483
+ persona: personaId,
484
+ disposition,
485
+ goals,
486
+ memory,
487
+ seed,
488
+ budget,
489
+ operatorToken,
490
+ }: ExecuteVirtualUserRunParams): Promise<{ findings: number }> => {
491
+ const store = requireVirtualUserRunStore(runStore)
492
+ try {
493
+ if (!metaService) {
494
+ throw new Error(
495
+ 'metaService is not wired — there is no catalogue to derive'
496
+ )
497
+ }
498
+ if (!agentRunner) {
499
+ throw new Error(
500
+ 'agentRunner is not wired — there is nothing to think with'
501
+ )
502
+ }
503
+
504
+ const apiUrl = await variables.get(VIRTUAL_USER_VARIABLES.apiUrl)
505
+ if (!apiUrl) {
506
+ throw new Error(
507
+ `${VIRTUAL_USER_VARIABLES.apiUrl} is not set — a virtual user has no address to sign in at.`
508
+ )
509
+ }
510
+
511
+ // An operator token wins wherever one is available: it is asymmetric, and
512
+ // it does not need the target to hold a shared secret at all. The actor
513
+ // secret is the local-only fallback, because only `pikku dev` serves the
514
+ // endpoint that accepts it.
515
+ const token =
516
+ operatorToken ??
517
+ (await variables.get(VIRTUAL_USER_VARIABLES.operatorToken))
518
+ const secret = token
519
+ ? undefined
520
+ : await variables.get(VIRTUAL_USER_VARIABLES.secret)
521
+ if (!token && !secret) {
522
+ throw new Error(
523
+ `Neither an operator token nor ${VIRTUAL_USER_VARIABLES.secret} is available — there is nobody for the virtual user to be. ` +
524
+ `Hand a Fabric operator token in with the run against a deployed stage, or export ${VIRTUAL_USER_VARIABLES.secret} against a local \`pikku dev\` target.`
525
+ )
526
+ }
527
+
528
+ const createMissing =
529
+ String(await variables.get(VIRTUAL_USER_VARIABLES.createMissing)) ===
530
+ 'true'
531
+ const model = await variables.get(VIRTUAL_USER_VARIABLES.model)
532
+ if (!model) {
533
+ throw new Error(
534
+ `${VIRTUAL_USER_VARIABLES.model} is not set — no model to think with.`
535
+ )
536
+ }
537
+
538
+ const functionsMeta = await metaService.getFunctionsMeta()
539
+ // Only the schemas the catalogue can actually refer to, so a large app does
540
+ // not pull every schema it has ever generated into one run.
541
+ const schemaNames = [
542
+ ...new Set(
543
+ Object.values(functionsMeta).flatMap((meta) =>
544
+ [meta.inputSchemaName, meta.outputSchemaName].filter(
545
+ (name: unknown): name is string => !!name
546
+ )
547
+ )
548
+ ),
549
+ ]
550
+ const schemas = (await metaService.getSchemas(schemaNames)) as SchemaMap
551
+
552
+ const persona = personas[personaId]
553
+ if (!persona) {
554
+ throw new Error(`Persona "${personaId}" is no longer declared`)
555
+ }
556
+
557
+ const { catalogue, intents, agents } = prepareVirtualUserRun({
558
+ persona,
559
+ functionsMeta,
560
+ schemas,
561
+ workflowsMeta: await metaService.getWorkflowMeta(),
562
+ systemRoles: await metaService.getSystemRolesMeta(),
563
+ agentsMeta: await metaService.getAgentsMeta(),
564
+ })
565
+
566
+ const configuredSignInPath =
567
+ (await variables.get(VIRTUAL_USER_VARIABLES.signInPath)) ?? undefined
568
+ const signedIn = createPersonas({
569
+ apiUrl,
570
+ ...(token
571
+ ? {
572
+ operator: {
573
+ token,
574
+ createMissing,
575
+ signInPath: signInPathFor(configuredSignInPath, 'fabric'),
576
+ },
577
+ }
578
+ : { secret }),
579
+ model,
580
+ signInPath: signInPathFor(configuredSignInPath, 'actor'),
581
+ rpcPath:
582
+ (await variables.get(VIRTUAL_USER_VARIABLES.rpcPath)) ?? undefined,
583
+ })
584
+ const target = signedIn[personaId]
585
+ if (!target) {
586
+ throw new Error(`Persona "${personaId}" cannot sign in`)
587
+ }
588
+
589
+ const result = await runVirtualUserEngine({
590
+ persona,
591
+ personaId,
592
+ disposition: disposition as VirtualUserDisposition,
593
+ catalogue,
594
+ intents,
595
+ goals,
596
+ memory,
597
+ seed,
598
+ agents,
599
+ target: personaVirtualUserTarget(target, {
600
+ model,
601
+ agents: agents.map((agent) => agent.name),
602
+ }),
603
+ // `AgentRunnerService.run` IS the engine's `ActorLLM` — same params, same
604
+ // result — so a virtual user thinks through the same runner every agent in
605
+ // the app does, provider quirks and all.
606
+ llm: (params) => agentRunner.run(params),
607
+ model,
608
+ budget: {
609
+ steps: budget?.steps,
610
+ mutations: budget?.mutations,
611
+ duration: budget?.durationMs,
612
+ },
613
+ })
614
+
615
+ await store.complete(runId, {
616
+ findings: result.findings,
617
+ tally: result.tally,
618
+ memory: result.memory,
619
+ stoppedBy: result.stoppedBy ?? null,
620
+ intents: result.intents,
621
+ steps: result.steps,
622
+ })
623
+
624
+ return { findings: result.findings.length }
625
+ } catch (error) {
626
+ // A crashed run and a run that found nothing are different states, and the
627
+ // record is the only place that distinction survives — leaving it at
628
+ // 'running' forever is what `fail` exists to prevent.
629
+ const message = error instanceof Error ? error.message : String(error)
630
+ logger.error(`Virtual user run ${runId} (${personaId}) failed: ${message}`)
631
+ await store.fail(runId, message)
632
+ throw error
633
+ }
634
+ }
@@ -14,6 +14,10 @@ export {
14
14
  WorkflowRunForbiddenError,
15
15
  } from './workflow-run-ownership.js'
16
16
  export { WorkflowApprovalForbiddenError } from './workflow-approval-policy.js'
17
+ export {
18
+ streamWorkflowRunStatus,
19
+ type WorkflowStatusStreamParams,
20
+ } from './workflow-status-stream.js'
17
21
  export type {
18
22
  WorkflowRunEngine,
19
23
  WorkflowRunExtension,