@atolis-hq/wake 0.4.59 → 0.4.61

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 (43) hide show
  1. package/dist/src/bootstrap/analytics-reports.d.ts +1 -1
  2. package/dist/src/bootstrap/analytics-reports.js +5 -2
  3. package/dist/src/bootstrap/canonical-events.d.ts +3 -0
  4. package/dist/src/bootstrap/canonical-events.js +32 -0
  5. package/dist/src/bootstrap/composition-root.d.ts +2 -2
  6. package/dist/src/bootstrap/composition-root.js +6 -3
  7. package/dist/src/bootstrap/config/root-schema.d.ts +8 -3
  8. package/dist/src/bootstrap/config/root-schema.js +29 -1
  9. package/dist/src/bootstrap/initialise.js +5 -0
  10. package/dist/src/bootstrap/integration-runtime.d.ts +6 -4
  11. package/dist/src/bootstrap/integration-runtime.js +50 -8
  12. package/dist/src/bootstrap/surface-cli-applications.js +1 -1
  13. package/dist/src/bootstrap/trigger-checkpoint-store.d.ts +9 -0
  14. package/dist/src/bootstrap/trigger-checkpoint-store.js +49 -0
  15. package/dist/src/bootstrap/version.js +1 -1
  16. package/dist/src/control-plane/application/control-plane-projection.js +2 -0
  17. package/dist/src/control-plane/application/runner-pipeline.d.ts +2 -2
  18. package/dist/src/control-plane/application/runner-pipeline.js +2 -2
  19. package/dist/src/control-plane/application/trigger-service.d.ts +35 -0
  20. package/dist/src/control-plane/application/trigger-service.js +118 -0
  21. package/dist/src/control-plane/contracts/config.d.ts +18 -8
  22. package/dist/src/control-plane/contracts/config.js +35 -6
  23. package/dist/src/control-plane/contracts/event-factory.js +2 -0
  24. package/dist/src/control-plane/contracts/events.d.ts +23 -0
  25. package/dist/src/control-plane/contracts/events.js +32 -0
  26. package/dist/src/control-plane/domain/cron-trigger-policy.d.ts +10 -0
  27. package/dist/src/control-plane/domain/{schedule-policy.js → cron-trigger-policy.js} +5 -5
  28. package/dist/src/control-plane/index.d.ts +2 -2
  29. package/dist/src/control-plane/index.js +2 -2
  30. package/dist/src/execution/application/run-reports.d.ts +13 -1
  31. package/dist/src/execution/application/run-reports.js +42 -1
  32. package/dist/src/kernel/contracts/reports.d.ts +14 -1
  33. package/dist/src/surfaces/api/contracts/observability.d.ts +1 -1
  34. package/dist/src/surfaces/api/routes/applications.d.ts +2 -2
  35. package/dist/src/surfaces/web-assets/assets/index-CCvwzTeC.js +1131 -0
  36. package/dist/src/surfaces/web-assets/index.html +1 -1
  37. package/package.json +1 -1
  38. package/dist/src/bootstrap/schedule-checkpoint-store.d.ts +0 -9
  39. package/dist/src/bootstrap/schedule-checkpoint-store.js +0 -49
  40. package/dist/src/control-plane/application/schedule-service.d.ts +0 -31
  41. package/dist/src/control-plane/application/schedule-service.js +0 -47
  42. package/dist/src/control-plane/domain/schedule-policy.d.ts +0 -8
  43. package/dist/src/surfaces/web-assets/assets/index-CC1TIxyc.js +0 -1131
@@ -6,7 +6,7 @@ export declare function createAnalyticsReports(journal: EventJournal, now: () =>
6
6
  title: string;
7
7
  }[];
8
8
  report(id: string, windowId: ReportWindowId, signal?: AbortSignal): Promise<{
9
- data: import("../kernel/index.js").TimeSeriesReport;
9
+ data: import("../kernel/index.js").AnalyticsReport;
10
10
  meta: import("../surfaces/index.js").ResponseMeta;
11
11
  }>;
12
12
  summary(windowId: ReportWindowId, signal?: AbortSignal): Promise<{
@@ -1,9 +1,12 @@
1
- import { createRunOutcomesReport, queryRunAnalytics } from '../execution/index.js';
1
+ import { createRunBreakdownReport, createRunOutcomesReport, queryRunAnalytics, } from '../execution/index.js';
2
2
  import { reportWindow } from '../kernel/index.js';
3
3
  import { queryWorkCompletionSummary } from '../orchestration/index.js';
4
4
  import { sampledMeta } from './surface-api-metadata.js';
5
5
  export function createAnalyticsReports(journal, now) {
6
- const definitions = [createRunOutcomesReport(journal)];
6
+ const definitions = [
7
+ createRunOutcomesReport(journal),
8
+ createRunBreakdownReport(journal),
9
+ ];
7
10
  return {
8
11
  catalogue: () => definitions.map(({ id, title }) => ({ id, title })),
9
12
  async report(id, windowId, signal) {
@@ -0,0 +1,3 @@
1
+ import type { EventEnvelope } from '@atolis-hq/eventing';
2
+ export declare const canonicalEventTypes: ReadonlySet<string>;
3
+ export declare function decodeCanonicalEvent(event: EventEnvelope): void;
@@ -0,0 +1,32 @@
1
+ import { ActivityEventType, selectActivityEvent } from '../activities/index.js';
2
+ import { ArtifactEventType, selectArtifactEvent } from '../artifacts/index.js';
3
+ import { ControlEventType, selectControlEvent } from '../control-plane/index.js';
4
+ import { ConversationEventType, selectConversationEvent } from '../conversations/index.js';
5
+ import { ExecutionEventType, selectExecutionEvent } from '../execution/index.js';
6
+ import { GitHubEventType, selectGitHubAdapterEvent } from '../integrations/github/index.js';
7
+ import { DeliveryEventType, DeliveryIntentEventType, ArtifactEventType as IntegrationArtifactEventType, decodeArtifactEvent, selectDeliveryEvent, selectDeliveryIntentEvent, } from '../integrations/index.js';
8
+ import { OrchestrationEventType, selectOrchestrationEvent } from '../orchestration/index.js';
9
+ import { ResourceEventType, selectResourceEvent } from '../resources/index.js';
10
+ import { WorkEventType, selectWorkEvent } from '../work/index.js';
11
+ // Bootstrap registers the owning modules' public vocabularies and decoders together.
12
+ const registrations = [
13
+ { types: Object.values(ActivityEventType), decode: selectActivityEvent },
14
+ { types: Object.values(ArtifactEventType), decode: selectArtifactEvent },
15
+ { types: Object.values(ControlEventType), decode: selectControlEvent },
16
+ { types: Object.values(ConversationEventType), decode: selectConversationEvent },
17
+ { types: Object.values(ExecutionEventType), decode: selectExecutionEvent },
18
+ { types: Object.values(GitHubEventType), decode: selectGitHubAdapterEvent },
19
+ { types: Object.values(IntegrationArtifactEventType), decode: decodeArtifactEvent },
20
+ { types: Object.values(DeliveryEventType), decode: selectDeliveryEvent },
21
+ { types: Object.values(DeliveryIntentEventType), decode: selectDeliveryIntentEvent },
22
+ { types: Object.values(OrchestrationEventType), decode: selectOrchestrationEvent },
23
+ { types: Object.values(ResourceEventType), decode: selectResourceEvent },
24
+ { types: Object.values(WorkEventType), decode: selectWorkEvent },
25
+ ];
26
+ export const canonicalEventTypes = new Set(registrations.flatMap(({ types }) => types));
27
+ export function decodeCanonicalEvent(event) {
28
+ const registration = registrations.find(({ types }) => types.includes(event.event.eventType));
29
+ if (registration === undefined)
30
+ throw new Error(`Unknown canonical event ${event.event.eventType}`);
31
+ registration.decode(event);
32
+ }
@@ -1,7 +1,7 @@
1
1
  import { type CheckpointStore, type EventJournal, type ProcessorRunSerialiser, type ProcessorStateStore, type ProjectionStore } from '@atolis-hq/eventing';
2
2
  import { createPullRequestService, type ActivityRegistry } from '../activities/index.js';
3
3
  import { createArtifactService } from '../artifacts/index.js';
4
- import { createControlPlaneService, createRunnerControlService, type ActivationScheduler, type ActivationSchedulerSubscriber, type IntakePipeline, type RunnerPipeline, type ScheduleCheckpointStore } from '../control-plane/index.js';
4
+ import { createControlPlaneService, createRunnerControlService, type ActivationScheduler, type ActivationSchedulerSubscriber, type IntakePipeline, type RunnerPipeline, type TriggerCheckpointStore } from '../control-plane/index.js';
5
5
  import { createConversationService } from '../conversations/index.js';
6
6
  import { RecoveryService, TranscriptStore, createExecutionService, type FakeScenarioResolver, type Runner } from '../execution/index.js';
7
7
  import type { DeliveryService, DurableFakeDeliveryProvider, ExternalDeliveryAdapter, ProviderCompositionFailure, ProviderInstance } from '../integrations/index.js';
@@ -32,7 +32,7 @@ export interface CompositionRootOptions {
32
32
  readonly decorateProjections?: (projections: ProjectionStore) => ProjectionStore;
33
33
  readonly decorateCheckpoints?: (checkpoints: CheckpointStore) => CheckpointStore;
34
34
  readonly subscriptionRunSerialiser?: ProcessorRunSerialiser;
35
- readonly scheduleCheckpoints?: ScheduleCheckpointStore;
35
+ readonly triggerCheckpoints?: TriggerCheckpointStore;
36
36
  readonly decorateDeliveryAdapter?: (adapter: ExternalDeliveryAdapter, provider: ProviderInstance) => ExternalDeliveryAdapter;
37
37
  readonly decorateRunner?: (runner: Runner, name: string) => Runner;
38
38
  /** A real fake-provider adapter for deterministic composed integration evidence. */
@@ -20,8 +20,8 @@ import { resolveWakePaths } from './paths.js';
20
20
  import { composePersistence } from './persistence-composition.js';
21
21
  import { createRunnerQuotaReporter } from './runner-quota-reporter.js';
22
22
  import { createRunnerRegistry } from './runner-registry.js';
23
- import { FileScheduleCheckpointStore } from './schedule-checkpoint-store.js';
24
23
  import { createTranscriptRetention } from './transcript-retention.js';
24
+ import { FileTriggerCheckpointStore } from './trigger-checkpoint-store.js';
25
25
  import { createUpdateMaintenanceLease, } from './update-maintenance-lease.js';
26
26
  const resourceLinkResolvers = {
27
27
  github: resolveGitHubResourceUrl,
@@ -85,10 +85,11 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
85
85
  : options.decorateRunner === undefined
86
86
  ? profileDecorator
87
87
  : (runner, name) => profileDecorator(options.decorateRunner(runner, name), name);
88
+ const runners = createRunnerRegistry(config.execution, fakeScenarios, decorateRunner);
88
89
  const execution = createExecutionService(journal, activities, config.execution, {
89
90
  clock,
90
91
  ids,
91
- runners: createRunnerRegistry(config.execution, fakeScenarios, decorateRunner),
92
+ runners,
92
93
  mcp: createArtifactMcpProvisioner({
93
94
  artifacts,
94
95
  orchestration,
@@ -171,7 +172,9 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
171
172
  wakeRoot,
172
173
  subscriptionRunSerialiser,
173
174
  processorRuntime,
174
- scheduleCheckpoints: options.scheduleCheckpoints ?? new FileScheduleCheckpointStore(paths.dataRoot),
175
+ activities,
176
+ runners,
177
+ triggerCheckpoints: options.triggerCheckpoints ?? new FileTriggerCheckpointStore(paths.dataRoot),
175
178
  ...(options.decorateDeliveryAdapter === undefined
176
179
  ? {}
177
180
  : { decorateDeliveryAdapter: options.decorateDeliveryAdapter }),
@@ -338,11 +338,16 @@ export declare const rootConfigSchema: z.ZodObject<{
338
338
  controlPlane: z.ZodDefault<z.ZodObject<{
339
339
  maxDispatches: z.ZodDefault<z.ZodNumber>;
340
340
  maxConcurrentRuns: z.ZodDefault<z.ZodNumber>;
341
- schedules: z.ZodDefault<z.ZodArray<z.ZodObject<{
341
+ triggers: z.ZodDefault<z.ZodArray<z.ZodObject<{
342
342
  id: z.ZodString;
343
343
  workflow: z.ZodString;
344
- cron: z.ZodString;
345
- objective: z.ZodString;
344
+ on: z.ZodObject<{
345
+ events: z.ZodOptional<z.ZodArray<z.ZodString>>;
346
+ cron: z.ZodOptional<z.ZodString>;
347
+ }, z.core.$strict>;
348
+ when: z.ZodOptional<z.ZodObject<{
349
+ capacityAvailable: z.ZodLiteral<true>;
350
+ }, z.core.$strict>>;
346
351
  }, z.core.$strict>>>;
347
352
  resident: z.ZodDefault<z.ZodObject<{
348
353
  pollBackoffMs: z.ZodDefault<z.ZodNumber>;
@@ -8,6 +8,7 @@ import { workflowDefinitionConfigSchema, workflowSelectorConfigSchema, } from '.
8
8
  import { resourcesConfigSchema } from '../../resources/index.js';
9
9
  import { surfacesConfigSchema } from '../../surfaces/index.js';
10
10
  import { workConfigSchema } from '../../work/index.js';
11
+ import { canonicalEventTypes } from '../canonical-events.js';
11
12
  const orchestrationConfigSchema = z
12
13
  .object({
13
14
  workflows: z.record(z.string().trim().min(1), workflowDefinitionConfigSchema).default({}),
@@ -151,7 +152,34 @@ export const rootConfigSchema = z
151
152
  surfaces: surfacesConfigSchema,
152
153
  host: hostConfigSchema,
153
154
  })
154
- .strict();
155
+ .strict()
156
+ .superRefine((value, context) => {
157
+ const ids = new Set();
158
+ for (const [index, trigger] of value.controlPlane.triggers.entries()) {
159
+ const path = ['controlPlane', 'triggers', index];
160
+ if (ids.has(trigger.id))
161
+ context.addIssue({
162
+ code: 'custom',
163
+ path: [...path, 'id'],
164
+ message: 'Trigger ids must be unique',
165
+ });
166
+ ids.add(trigger.id);
167
+ if (value.orchestration.workflows[trigger.workflow] === undefined)
168
+ context.addIssue({
169
+ code: 'custom',
170
+ path: [...path, 'workflow'],
171
+ message: 'Trigger workflow is not configured',
172
+ });
173
+ for (const [eventIndex, event] of (trigger.on.events ?? []).entries()) {
174
+ if (!canonicalEventTypes.has(event))
175
+ context.addIssue({
176
+ code: 'custom',
177
+ path: [...path, 'on', 'events', eventIndex],
178
+ message: 'Unknown canonical event',
179
+ });
180
+ }
181
+ }
182
+ });
155
183
  export function parseRootConfig(input) {
156
184
  return rootConfigSchema.parse(input);
157
185
  }
@@ -40,6 +40,11 @@ orchestration:
40
40
  matchMode: all
41
41
  workflow: approval
42
42
 
43
+ # Independent workflow invocations need an explicit event and/or UTC cron source.
44
+ # Activity prompts define their tasks. No triggers are enabled by default.
45
+ controlPlane:
46
+ triggers: []
47
+
43
48
  # External providers Wake correlates inbound work with. Empty until you
44
49
  # configure one — see SETUP.md.
45
50
  integrations: {}
@@ -1,8 +1,8 @@
1
1
  import { type CheckpointStore, type EventJournal, type EventProcessor, type ProcessorRunSerialiser, type ProcessorStateStore, type ProjectionStore } from '@atolis-hq/eventing';
2
- import type { createPullRequestService } from '../activities/index.js';
3
- import { type IntakePipeline, type RunnerPipeline, type ScheduleCheckpointStore, type createControlPlaneService } from '../control-plane/index.js';
2
+ import { type ActivityRegistry, type createPullRequestService } from '../activities/index.js';
3
+ import { type IntakePipeline, type RunnerPipeline, type TriggerCheckpointStore, type createControlPlaneService } from '../control-plane/index.js';
4
4
  import type { createConversationService } from '../conversations/index.js';
5
- import { type createExecutionService } from '../execution/index.js';
5
+ import { type RunnerRegistry, type createExecutionService } from '../execution/index.js';
6
6
  import { DeliveryService, type DurableFakeDeliveryProvider, type ExternalDeliveryAdapter, type ProviderCompositionFailure, type ProviderDefinition, type ProviderInstance } from '../integrations/index.js';
7
7
  import { type Clock, type UlidIdGenerator } from '../kernel/index.js';
8
8
  import { type createOrchestrationService } from '../orchestration/index.js';
@@ -22,6 +22,8 @@ export interface IntegrationRuntime {
22
22
  readonly requestImmediatePoll: (adapter: string) => void;
23
23
  }
24
24
  export interface IntegrationRuntimeInput {
25
+ readonly activities: ActivityRegistry;
26
+ readonly runners: RunnerRegistry;
25
27
  readonly config: ResolvedWakeModulesConfig;
26
28
  readonly journal: EventJournal;
27
29
  readonly projections: ProjectionStore;
@@ -41,7 +43,7 @@ export interface IntegrationRuntimeInput {
41
43
  readonly wakeRoot: string;
42
44
  readonly subscriptionRunSerialiser: ProcessorRunSerialiser;
43
45
  readonly processorRuntime: EventProcessorRuntime;
44
- readonly scheduleCheckpoints: ScheduleCheckpointStore;
46
+ readonly triggerCheckpoints: TriggerCheckpointStore;
45
47
  readonly decorateDeliveryAdapter?: (adapter: ExternalDeliveryAdapter, provider: ProviderInstance) => ExternalDeliveryAdapter;
46
48
  readonly fakeDeliveryProvider?: DurableFakeDeliveryProvider;
47
49
  readonly providerDefinitions: readonly ProviderDefinition[];
@@ -1,11 +1,13 @@
1
1
  import { EventActorKind, } from '@atolis-hq/eventing';
2
2
  import { withFileLock } from '@atolis-hq/eventing-filesystem';
3
3
  import { join } from 'node:path';
4
- import { ControlStreamKind, ScheduleService, createIntakePipeline, createRunnerPipeline, createWorkCancellationPolicy, } from '../control-plane/index.js';
5
- import { RunRepository, createRuntimeMemoryProfile, } from '../execution/index.js';
4
+ import { ActivityExecutionKind, activityName, } from '../activities/index.js';
5
+ import { ControlStreamKind, TriggerService, createDurableRunnerIneligibility, createIntakePipeline, createRunnerPipeline, createTriggerReactor, createWorkCancellationPolicy, } from '../control-plane/index.js';
6
+ import { NoEligibleRunnerError, RunRepository, createRuntimeMemoryProfile, isActiveRunStatus, } from '../execution/index.js';
6
7
  import { AgentRunPublicationReactor, ArtifactRegistrationReactor, DeliveryOutcomeReactor, DeliveryService, IntegrationStreamKind, PollService, ProviderRegistry, deliveryProjectionDefinitions, fakeProviderDefinition, } from '../integrations/index.js';
7
8
  import { compileWorkflowSelectors, createConversationCommandReactor, createPullRequestTransitionEvidence, createResourceTransitionReactor, createWatchReactor, createWatchReconciler, selectWorkflow, workflowName, } from '../orchestration/index.js';
8
9
  import { BuiltInResourceCapability, resourceId, } from '../resources/index.js';
10
+ import { decodeCanonicalEvent } from './canonical-events.js';
9
11
  import { hydrateFakeProviderEvidence } from './fake-provider-files.js';
10
12
  import { createRuntimeProjectionSubscriptions, } from './projection-runtime.js';
11
13
  import { createCapabilityResourceTransitionEvidence } from './resource-transition-evidence.js';
@@ -65,13 +67,52 @@ export async function composeIntegrationRuntime(input) {
65
67
  },
66
68
  now: () => input.clock.now().toISOString(),
67
69
  });
68
- const schedules = new ScheduleService({
69
- checkpoint: input.scheduleCheckpoints,
70
+ const runnerIneligibility = createDurableRunnerIneligibility(input.journal, () => input.clock.now().toISOString());
71
+ const triggers = new TriggerService({
72
+ journal: input.journal,
73
+ capacityAvailable: async (trigger) => {
74
+ if (await input.isPaused())
75
+ return false;
76
+ const active = (await input.execution.list()).filter((run) => isActiveRunStatus(run.status));
77
+ if (active.length >= input.config.controlPlane.maxConcurrentRuns)
78
+ return false;
79
+ const workflow = input.config.orchestration.workflows[trigger.workflow];
80
+ const stage = workflow.stages[workflow.entry ?? Object.keys(workflow.stages)[0]];
81
+ const pool = stage.execution?.runnerPool ?? input.config.execution.defaultRunnerPool;
82
+ if (input.config.execution.runnerPools[pool] === undefined)
83
+ return false;
84
+ if (input.activities.describe(activityName(stage.activity)).executionKind !==
85
+ ActivityExecutionKind.Agent)
86
+ return true;
87
+ try {
88
+ input.runners.resolve(pool, await runnerIneligibility(), { ephemeralMcp: true });
89
+ return true;
90
+ }
91
+ catch (error) {
92
+ if (error instanceof NoEligibleRunnerError)
93
+ return false;
94
+ throw error;
95
+ }
96
+ },
97
+ checkpoint: input.triggerCheckpoints,
70
98
  ids: input.ids,
71
99
  work: input.work,
72
100
  orchestration: input.orchestration,
73
101
  now: () => input.clock.now().toISOString(),
74
102
  });
103
+ const triggerReactors = input.config.controlPlane.triggers.map((config) => createTriggerReactor(triggers, config, decodeCanonicalEvent));
104
+ // Registration starts at the current journal boundary; historical facts are not sources.
105
+ for (const reactor of triggerReactors) {
106
+ if ((await input.processorState.read(reactor.consumer, 'registration')) !== null)
107
+ continue;
108
+ const position = await input.journal.latestGlobalPosition();
109
+ await input.checkpoints.save(reactor.consumer, position);
110
+ await input.processorState.write({
111
+ consumer: reactor.consumer,
112
+ key: 'registration',
113
+ value: { position },
114
+ });
115
+ }
75
116
  const artifacts = new ArtifactRegistrationReactor({
76
117
  journal: input.journal,
77
118
  resources: input.resources,
@@ -136,11 +177,11 @@ export async function composeIntegrationRuntime(input) {
136
177
  });
137
178
  const runnerPipeline = createRunnerPipeline({
138
179
  isPaused: input.isPaused,
139
- runSchedules: () => observeMemory(memoryProfile, 'runner.schedules', async () => {
140
- for (const schedule of input.config.controlPlane.schedules)
141
- await schedules.run(schedule, {
180
+ runTriggers: () => observeMemory(memoryProfile, 'runner.triggers', async () => {
181
+ for (const trigger of input.config.controlPlane.triggers)
182
+ await triggers.run(trigger, {
142
183
  commandId: input.ids.next('command'),
143
- correlationId: 'schedule-tick',
184
+ correlationId: 'trigger-tick',
144
185
  occurredAt: input.clock.now().toISOString(),
145
186
  actor: { kind: EventActorKind.System, id: ControlStreamKind.Global },
146
187
  });
@@ -169,6 +210,7 @@ export async function composeIntegrationRuntime(input) {
169
210
  projectionSubscriptions,
170
211
  processors: [
171
212
  ...projectionSubscriptions.processors,
213
+ ...triggerReactors,
172
214
  watch.processor,
173
215
  resourceTransitions.processor,
174
216
  artifacts.processor,
@@ -37,7 +37,7 @@ export function createSurfaceCliApplications(root, api, now) {
37
37
  process.stderr.write(`Wake ${label} tick failed: ${error instanceof Error ? error.message : String(error)}\n`);
38
38
  };
39
39
  // Intake owns provider polling, so only its resident loop backs off
40
- // exponentially when idle. The runner loop owns schedules, reconciliation,
40
+ // exponentially when idle. The runner loop owns triggers, reconciliation,
41
41
  // and delivery; it stays on a fast cadence when there is no local work.
42
42
  // The independent durable subscriber owns activation scheduling. Delivery
43
43
  // can still hit an external API, so consecutive errors back off
@@ -0,0 +1,9 @@
1
+ import type { TriggerCheckpointStore } from '../control-plane/index.js';
2
+ /** Durable timestamp cursor for TriggerService; journal checkpoints only store numeric offsets. */
3
+ export declare class FileTriggerCheckpointStore implements TriggerCheckpointStore {
4
+ private readonly dataRoot;
5
+ constructor(dataRoot: string);
6
+ load(triggerId: string): Promise<string | null>;
7
+ save(triggerId: string, slot: string): Promise<void>;
8
+ private path;
9
+ }
@@ -0,0 +1,49 @@
1
+ import { mkdir, open, readFile, rename, rm } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ /** Durable timestamp cursor for TriggerService; journal checkpoints only store numeric offsets. */
4
+ export class FileTriggerCheckpointStore {
5
+ dataRoot;
6
+ constructor(dataRoot) {
7
+ this.dataRoot = dataRoot;
8
+ }
9
+ async load(triggerId) {
10
+ try {
11
+ const parsed = JSON.parse(await readFile(this.path(triggerId), 'utf8'));
12
+ if (parsed.triggerId !== triggerId || Number.isNaN(Date.parse(parsed.slot)))
13
+ throw new Error(`Invalid trigger checkpoint: ${triggerId}`);
14
+ return parsed.slot;
15
+ }
16
+ catch (error) {
17
+ if (error.code === 'ENOENT')
18
+ return null;
19
+ throw error;
20
+ }
21
+ }
22
+ async save(triggerId, slot) {
23
+ const existing = await this.load(triggerId);
24
+ if (existing !== null && Date.parse(slot) < Date.parse(existing))
25
+ throw new Error(`Trigger checkpoint regression: ${triggerId}`);
26
+ const path = this.path(triggerId);
27
+ await mkdir(dirname(path), { recursive: true });
28
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
29
+ try {
30
+ const handle = await open(temporary, 'wx');
31
+ try {
32
+ await handle.writeFile(`${JSON.stringify({ triggerId, slot })}\n`, 'utf8');
33
+ await handle.sync();
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ await rename(temporary, path);
39
+ }
40
+ finally {
41
+ await rm(temporary, { force: true });
42
+ }
43
+ }
44
+ path(triggerId) {
45
+ if (triggerId.length === 0 || /[\\/]/.test(triggerId))
46
+ throw new Error('Trigger id must not contain path separators');
47
+ return join(this.dataRoot, 'trigger-checkpoints', `${encodeURIComponent(triggerId)}.json`);
48
+ }
49
+ }
@@ -124,6 +124,6 @@ export function resolveWakeVersion(options = {}) {
124
124
  return `g${headHash.slice(0, 7)}`;
125
125
  return '0.1.0-dev';
126
126
  }
127
- export const wakeVersion = "v0.4.59";
127
+ export const wakeVersion = "v0.4.61";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -32,6 +32,8 @@ export const controlPlaneProjection = {
32
32
  if (event === null)
33
33
  return previous;
34
34
  switch (event.event.eventType) {
35
+ case ControlEventType.TriggerInvocationStarted:
36
+ return previous;
35
37
  case ControlEventType.DispatchPaused:
36
38
  return {
37
39
  ...previous,
@@ -4,7 +4,7 @@ export type RunnerPipelineResult = Extract<AdvanceResult, {
4
4
  }>;
5
5
  export interface RunnerPipelineStages {
6
6
  readonly isPaused?: () => Promise<boolean>;
7
- readonly runSchedules: () => Promise<void>;
7
+ readonly runTriggers: () => Promise<void>;
8
8
  readonly maintain?: () => Promise<void>;
9
9
  readonly deliver: (signal: AbortSignal) => Promise<void>;
10
10
  }
@@ -16,7 +16,7 @@ export interface RunnerPipeline {
16
16
  run(options: AdvanceOptions, signal?: AbortSignal, beforeDelivery?: () => Promise<void>): Promise<RunnerPipelineResult>;
17
17
  }
18
18
  /**
19
- * Runs the non-reactive internal half of a Wake tick: schedules, maintenance,
19
+ * Runs the non-reactive internal half of a Wake tick: triggers, maintenance,
20
20
  * and delivery. Processors are owned by the Eventing runtime. None of this touches a rate-limited external poll, so its
21
21
  * host runs on a fast, un-backed-off cadence — see IntakePipeline for the
22
22
  * half that does need backoff.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Runs the non-reactive internal half of a Wake tick: schedules, maintenance,
2
+ * Runs the non-reactive internal half of a Wake tick: triggers, maintenance,
3
3
  * and delivery. Processors are owned by the Eventing runtime. None of this touches a rate-limited external poll, so its
4
4
  * host runs on a fast, un-backed-off cadence — see IntakePipeline for the
5
5
  * half that does need backoff.
@@ -9,7 +9,7 @@ export function createRunnerPipeline(stages) {
9
9
  const runOnce = async (options, signal, beforeDelivery) => {
10
10
  if (await isPaused())
11
11
  return { kind: 'paused' };
12
- await stages.runSchedules();
12
+ await stages.runTriggers();
13
13
  if (await isPaused())
14
14
  return { kind: 'paused' };
15
15
  await stages.maintain?.();
@@ -0,0 +1,35 @@
1
+ import { type CommandContext, type EventEnvelope, type EventJournal } from '@atolis-hq/eventing';
2
+ import type { IdGenerator } from '../../kernel/index.js';
3
+ import { workflowInstanceId, type StartWorkflowInstance } from '../../orchestration/index.js';
4
+ import { workItemId, type CreateWorkItem } from '../../work/index.js';
5
+ import type { TriggerConfig } from '../contracts/config.js';
6
+ import { type TriggerSource } from '../contracts/events.js';
7
+ export interface TriggerCheckpointStore {
8
+ load(triggerId: string): Promise<string | null>;
9
+ save(triggerId: string, slot: string): Promise<void>;
10
+ }
11
+ export interface TriggerServiceDependencies {
12
+ readonly checkpoint: TriggerCheckpointStore;
13
+ readonly journal: EventJournal;
14
+ readonly ids: IdGenerator;
15
+ readonly work: {
16
+ create(command: CreateWorkItem, context: CommandContext): Promise<unknown>;
17
+ };
18
+ readonly orchestration: {
19
+ start(command: StartWorkflowInstance, context: CommandContext): Promise<unknown>;
20
+ get(id: ReturnType<typeof workflowInstanceId>): Promise<{
21
+ readonly workItemId: ReturnType<typeof workItemId>;
22
+ } | null>;
23
+ };
24
+ readonly capacityAvailable: (config: TriggerConfig) => Promise<boolean>;
25
+ readonly now: () => string;
26
+ }
27
+ export declare class TriggerService {
28
+ private readonly dependencies;
29
+ private readonly policy;
30
+ constructor(dependencies: TriggerServiceDependencies);
31
+ run(config: TriggerConfig, context: CommandContext): Promise<readonly string[]>;
32
+ start(config: TriggerConfig, source: TriggerSource, context: CommandContext): Promise<boolean>;
33
+ private recordInvocation;
34
+ }
35
+ export declare function createTriggerReactor(service: TriggerService, config: TriggerConfig, decode: (event: EventEnvelope) => void): import("@atolis-hq/eventing").EventProcessor;
@@ -0,0 +1,118 @@
1
+ import { correlationId, defineEventProcessor, EventActorKind, EventProcessorCategory, EventProcessorReplayPolicy, EventSourceKind, WrongExpectedSequenceError, } from '@atolis-hq/eventing';
2
+ import { orchestrationGroupId, workflowInstanceId, workflowName, } from '../../orchestration/index.js';
3
+ import { workItemId } from '../../work/index.js';
4
+ import { createControlPlaneEventData } from '../contracts/event-factory.js';
5
+ import { ControlEventType, selectControlEvent, TriggerSourceKind, } from '../contracts/events.js';
6
+ import { controlPlaneStream, ControlStreamKind } from '../contracts/streams.js';
7
+ import { CronTriggerPolicy } from '../domain/cron-trigger-policy.js';
8
+ export class TriggerService {
9
+ dependencies;
10
+ policy = new CronTriggerPolicy();
11
+ constructor(dependencies) {
12
+ this.dependencies = dependencies;
13
+ }
14
+ async run(config, context) {
15
+ if (config.on.cron === undefined)
16
+ return [];
17
+ const checkpoint = await this.dependencies.checkpoint.load(config.id);
18
+ const slots = this.policy.elapsedSlots({ id: config.id, cron: config.on.cron }, this.dependencies.now(), checkpoint);
19
+ const accepted = [];
20
+ for (const slot of slots) {
21
+ if (await this.start(config, { kind: TriggerSourceKind.Cron, slot: slot.at }, context))
22
+ accepted.push(slot.identity);
23
+ // A failed gate consumes the occurrence; becoming eligible is not a source.
24
+ await this.dependencies.checkpoint.save(config.id, slot.at);
25
+ }
26
+ return accepted;
27
+ }
28
+ async start(config, source, context) {
29
+ const identity = `trigger:${config.id}:${source.kind}:${source.kind === TriggerSourceKind.Cron ? source.slot : source.eventId}`;
30
+ const workflow = workflowInstanceId(`workflow-${encodeURIComponent(identity)}`);
31
+ const invocationContext = {
32
+ ...context,
33
+ commandId: `${context.commandId}:${identity}`,
34
+ correlationId: correlationId(identity),
35
+ };
36
+ const existing = await this.dependencies.orchestration.get(workflow);
37
+ if (existing === null &&
38
+ config.when?.capacityAvailable === true &&
39
+ !(await this.dependencies.capacityAvailable(config)))
40
+ return false;
41
+ const item = existing?.workItemId ?? workItemId(this.dependencies.ids.next('work'));
42
+ if (existing === null) {
43
+ await this.dependencies.work.create({ workItemId: item, objective: `Trigger ${config.id}: workflow ${config.workflow}` }, invocationContext);
44
+ await this.dependencies.orchestration.start({
45
+ workflowInstanceId: workflow,
46
+ workItemId: item,
47
+ workflowName: workflowName(config.workflow),
48
+ orchestrationGroupId: orchestrationGroupId(`primary:${item}`),
49
+ }, invocationContext);
50
+ }
51
+ await this.recordInvocation(config, source, invocationContext, item, workflow);
52
+ return true;
53
+ }
54
+ async recordInvocation(config, source, context, item, workflow) {
55
+ const stream = controlPlaneStream();
56
+ const draft = createControlPlaneEventData({
57
+ eventId: `${workflow}:${ControlEventType.TriggerInvocationStarted}`,
58
+ eventType: ControlEventType.TriggerInvocationStarted,
59
+ occurredAt: this.dependencies.now(),
60
+ correlationId: context.correlationId,
61
+ causationId: source.kind === TriggerSourceKind.Event ? source.eventId : context.commandId,
62
+ actor: context.actor,
63
+ source: { kind: EventSourceKind.Internal, id: config.id },
64
+ payload: {
65
+ triggerId: config.id,
66
+ source,
67
+ workItemId: item,
68
+ workflowInstanceId: workflow,
69
+ workflowName: config.workflow,
70
+ },
71
+ });
72
+ for (let attempt = 0; attempt < 8; attempt += 1) {
73
+ const events = await this.dependencies.journal.readStream(stream);
74
+ if (events.some((envelope) => {
75
+ const event = selectControlEvent(envelope);
76
+ return (event?.event.eventType === ControlEventType.TriggerInvocationStarted &&
77
+ event.event.payload.workflowInstanceId === workflow);
78
+ }))
79
+ return;
80
+ try {
81
+ await this.dependencies.journal.appendToStream(stream, events.length, [draft]);
82
+ return;
83
+ }
84
+ catch (error) {
85
+ // Other triggers and runner controls share this stream. Re-read on contention.
86
+ if (!(error instanceof WrongExpectedSequenceError) || attempt === 7)
87
+ throw error;
88
+ }
89
+ }
90
+ }
91
+ }
92
+ export function createTriggerReactor(service, config, decode) {
93
+ return defineEventProcessor({
94
+ consumer: `reactor:control-plane.trigger:${config.id}`,
95
+ name: 'workflow-triggers',
96
+ owner: ControlStreamKind.Global,
97
+ category: EventProcessorCategory.Reactor,
98
+ replayPolicy: EventProcessorReplayPolicy.Idempotent,
99
+ select(event) {
100
+ if (!config.on.events?.includes(event.event.eventType))
101
+ return null;
102
+ decode(event);
103
+ return event;
104
+ },
105
+ async handle(event) {
106
+ await service.start(config, {
107
+ kind: TriggerSourceKind.Event,
108
+ eventId: event.event.eventId,
109
+ eventType: event.event.eventType,
110
+ }, {
111
+ commandId: `trigger:${config.id}:${event.event.eventId}`,
112
+ correlationId: correlationId(`trigger:${config.id}:${event.event.eventId}`),
113
+ occurredAt: event.event.occurredAt,
114
+ actor: { kind: EventActorKind.System, id: config.id },
115
+ });
116
+ },
117
+ });
118
+ }