@atolis-hq/wake 0.4.62 → 0.4.64

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 (66) hide show
  1. package/dist/src/artifacts/application/artifact-context-service.d.ts +30 -0
  2. package/dist/src/artifacts/application/artifact-context-service.js +189 -0
  3. package/dist/src/artifacts/application/artifact-service.d.ts +12 -2
  4. package/dist/src/artifacts/application/artifact-service.js +44 -1
  5. package/dist/src/artifacts/contracts/context-event-factory.d.ts +6 -0
  6. package/dist/src/artifacts/contracts/context-event-factory.js +12 -0
  7. package/dist/src/artifacts/contracts/context-events.d.ts +23 -0
  8. package/dist/src/artifacts/contracts/context-events.js +64 -0
  9. package/dist/src/artifacts/contracts/context.d.ts +56 -0
  10. package/dist/src/artifacts/contracts/context.js +38 -0
  11. package/dist/src/artifacts/contracts/events.d.ts +1 -0
  12. package/dist/src/artifacts/contracts/events.js +2 -0
  13. package/dist/src/artifacts/contracts/streams.d.ts +3 -0
  14. package/dist/src/artifacts/contracts/streams.js +7 -1
  15. package/dist/src/artifacts/contracts/views.d.ts +1 -0
  16. package/dist/src/artifacts/domain/artifact-work-item.js +1 -0
  17. package/dist/src/artifacts/index.d.ts +4 -0
  18. package/dist/src/artifacts/index.js +4 -0
  19. package/dist/src/artifacts/infrastructure/mcp-server.d.ts +5 -1
  20. package/dist/src/artifacts/infrastructure/mcp-server.js +21 -6
  21. package/dist/src/artifacts/infrastructure/mcp-session-store.d.ts +4 -0
  22. package/dist/src/artifacts/infrastructure/mcp-session-store.js +15 -0
  23. package/dist/src/bootstrap/artifact-mcp.d.ts +6 -1
  24. package/dist/src/bootstrap/artifact-mcp.js +5 -7
  25. package/dist/src/bootstrap/artifact-trigger-context.d.ts +30 -0
  26. package/dist/src/bootstrap/artifact-trigger-context.js +99 -0
  27. package/dist/src/bootstrap/canonical-events.js +2 -1
  28. package/dist/src/bootstrap/composition-root.js +13 -1
  29. package/dist/src/bootstrap/config/root-schema.d.ts +3 -2
  30. package/dist/src/bootstrap/integration-runtime.d.ts +1 -0
  31. package/dist/src/bootstrap/integration-runtime.js +1 -0
  32. package/dist/src/bootstrap/surface-api-applications.js +2 -0
  33. package/dist/src/bootstrap/surface-api-trigger-applications.d.ts +3 -0
  34. package/dist/src/bootstrap/surface-api-trigger-applications.js +79 -0
  35. package/dist/src/bootstrap/surface-api-work-applications.js +8 -0
  36. package/dist/src/bootstrap/version.js +1 -1
  37. package/dist/src/control-plane/application/trigger-diagnostics.d.ts +33 -0
  38. package/dist/src/control-plane/application/trigger-diagnostics.js +38 -0
  39. package/dist/src/control-plane/application/trigger-service-ports.d.ts +21 -0
  40. package/dist/src/control-plane/application/trigger-service-ports.js +1 -0
  41. package/dist/src/control-plane/application/trigger-service.d.ts +10 -22
  42. package/dist/src/control-plane/application/trigger-service.js +25 -15
  43. package/dist/src/control-plane/contracts/config.d.ts +3 -0
  44. package/dist/src/control-plane/contracts/config.js +5 -0
  45. package/dist/src/control-plane/contracts/trigger-diagnostics.d.ts +53 -0
  46. package/dist/src/control-plane/contracts/trigger-diagnostics.js +23 -0
  47. package/dist/src/control-plane/domain/cron-trigger-policy.d.ts +1 -0
  48. package/dist/src/control-plane/domain/cron-trigger-policy.js +11 -0
  49. package/dist/src/control-plane/index.d.ts +1 -0
  50. package/dist/src/control-plane/index.js +1 -0
  51. package/dist/src/orchestration/contracts/config.d.ts +2 -2
  52. package/dist/src/surfaces/api/contracts/index.d.ts +1 -0
  53. package/dist/src/surfaces/api/contracts/index.js +1 -0
  54. package/dist/src/surfaces/api/contracts/transport-values.d.ts +8 -0
  55. package/dist/src/surfaces/api/contracts/transport-values.js +23 -0
  56. package/dist/src/surfaces/api/contracts/triggers.d.ts +22 -0
  57. package/dist/src/surfaces/api/contracts/triggers.js +8 -0
  58. package/dist/src/surfaces/api/contracts/work.d.ts +1 -0
  59. package/dist/src/surfaces/api/contracts/workflow-diagram.d.ts +4 -4
  60. package/dist/src/surfaces/api/routes/applications.d.ts +7 -1
  61. package/dist/src/surfaces/api/routes/commands.js +10 -0
  62. package/dist/src/surfaces/api/routes/read.js +16 -0
  63. package/dist/src/surfaces/web-assets/assets/index-9IfrHvBo.js +1192 -0
  64. package/dist/src/surfaces/web-assets/index.html +1 -1
  65. package/package.json +1 -1
  66. package/dist/src/surfaces/web-assets/assets/index-CCvwzTeC.js +0 -1131
@@ -2,6 +2,7 @@ import type { CommandContext } from '@atolis-hq/eventing';
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import type { WorkItemId } from '../../work/index.js';
4
4
  import type { ArtifactService } from '../application/artifact-service.js';
5
+ import type { ArtifactRevisionReference } from '../contracts/context.js';
5
6
  /** A capability token is resolved into this server-side scope by Execution. */
6
7
  export interface ArtifactMcpSession {
7
8
  readonly workItemId: WorkItemId;
@@ -9,9 +10,12 @@ export interface ArtifactMcpSession {
9
10
  readonly runId: string;
10
11
  readonly activationId: string;
11
12
  readonly readableProducers: ReadonlySet<string>;
13
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
14
+ readonly currentMemory?: ArtifactRevisionReference | null;
15
+ readonly contextScope?: string;
12
16
  readonly nextRevisionId: () => string;
13
17
  readonly commandContext: () => CommandContext;
14
- readonly acceptedActivation: (activationId: string) => Promise<boolean>;
18
+ readonly acceptedActivation: (activationId: string, workItemId?: string) => Promise<boolean>;
15
19
  /** Revalidates the run-bound credential for every tool request. */
16
20
  readonly assertActive: () => Promise<void>;
17
21
  }
@@ -9,13 +9,14 @@ export function createArtifactMcpServer(artifacts, session) {
9
9
  description: 'Read a visible artifact revision as UTF-8 text or base64 bytes.',
10
10
  inputSchema: {
11
11
  revisionId: z.string().min(1),
12
+ workItemId: z.string().min(1).optional(),
12
13
  encoding: z.enum(['utf8', 'base64']).default('utf8'),
13
14
  offset: z.number().int().nonnegative().default(0),
14
15
  length: z.number().int().positive().optional(),
15
16
  },
16
- }, async ({ revisionId, encoding, offset, length }) => {
17
+ }, async ({ revisionId, workItemId, encoding, offset, length }) => {
17
18
  await session.assertActive();
18
- const artifact = await visibleArtifact(artifacts, session, revisionId);
19
+ const artifact = await visibleArtifact(artifacts, session, revisionId, workItemId);
19
20
  if (artifact.location === undefined)
20
21
  throw new Error('Artifact revision has no content');
21
22
  const bytes = (await artifacts.read(artifact.location)).slice(offset, length === undefined ? undefined : offset + length);
@@ -51,7 +52,7 @@ export function createArtifactMcpServer(artifacts, session) {
51
52
  }, async ({ revisionId, find, replace }) => {
52
53
  await session.assertActive();
53
54
  const artifact = await visibleArtifact(artifacts, session, revisionId);
54
- if (artifact.producer !== session.producer)
55
+ if (artifact.producer !== session.producer || artifact.workItemId !== session.workItemId)
55
56
  throw new Error('Only the owning producer may patch an artifact');
56
57
  if (artifact.location === undefined)
57
58
  throw new Error('Artifact revision has no content');
@@ -76,14 +77,19 @@ export function createArtifactMcpServer(artifacts, session) {
76
77
  content: z.string(),
77
78
  encoding: z.enum(['utf8', 'base64']).default('utf8'),
78
79
  mediaType: z.string().min(1).optional(),
80
+ share: z
81
+ .boolean()
82
+ .optional()
83
+ .describe("Select this revision for export to the run's trusted context after successful acceptance."),
79
84
  },
80
- }, async ({ path, content, encoding, mediaType }) => {
85
+ }, async ({ path, content, encoding, mediaType, share }) => {
81
86
  await session.assertActive();
82
87
  const revisionId = session.nextRevisionId();
83
88
  await artifacts.stageRevision({
84
89
  revisionId,
85
90
  path: artifactPath(path),
86
91
  bytes: decodeContent(content, encoding),
92
+ ...(share === undefined ? {} : { share }),
87
93
  ...(mediaType === undefined ? {} : { mediaType }),
88
94
  }, writeScope(session), session.commandContext());
89
95
  return { content: [{ type: 'text', text: JSON.stringify({ revisionId }) }] };
@@ -102,8 +108,12 @@ export function createArtifactMcpServer(artifacts, session) {
102
108
  });
103
109
  return server;
104
110
  }
105
- async function visibleArtifact(artifacts, session, revisionId) {
106
- const artifact = (await visibleArtifacts(artifacts, session)).find((candidate) => candidate.revisionId === revisionId && session.readableProducers.has(candidate.producer));
111
+ async function visibleArtifact(artifacts, session, revisionId, workItemId) {
112
+ const matches = (await visibleArtifacts(artifacts, session)).filter((candidate) => candidate.revisionId === revisionId &&
113
+ (workItemId === undefined || candidate.workItemId === workItemId));
114
+ if (matches.length > 1)
115
+ throw new Error('Artifact revision is ambiguous; specify workItemId');
116
+ const artifact = matches[0];
107
117
  if (artifact === undefined)
108
118
  throw new Error('Artifact revision is not visible to this activation');
109
119
  return artifact;
@@ -115,6 +125,10 @@ function visibleArtifacts(artifacts, session) {
115
125
  runId: session.runId,
116
126
  activationId: session.activationId,
117
127
  readableProducers: session.readableProducers,
128
+ ...(session.sharedReferences === undefined
129
+ ? {}
130
+ : { sharedReferences: session.sharedReferences }),
131
+ ...(session.currentMemory === undefined ? {} : { currentMemory: session.currentMemory }),
118
132
  }, session.acceptedActivation);
119
133
  }
120
134
  function writeScope(session) {
@@ -123,6 +137,7 @@ function writeScope(session) {
123
137
  producer: session.producer,
124
138
  runId: session.runId,
125
139
  activationId: session.activationId,
140
+ ...(session.contextScope === undefined ? {} : { contextScope: session.contextScope }),
126
141
  };
127
142
  }
128
143
  function decodeContent(content, encoding) {
@@ -1,4 +1,5 @@
1
1
  import type { WorkItemId } from '../../work/index.js';
2
+ import { type ArtifactRevisionReference } from '../contracts/context.js';
2
3
  export interface ArtifactMcpSessionDescriptor {
3
4
  readonly workItemId: WorkItemId;
4
5
  readonly producer: string;
@@ -6,6 +7,9 @@ export interface ArtifactMcpSessionDescriptor {
6
7
  readonly activationId: string;
7
8
  readonly readableProducers: readonly string[];
8
9
  readonly expiresAt: string;
10
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
11
+ readonly currentMemory?: ArtifactRevisionReference | null;
12
+ readonly contextScope?: string;
9
13
  }
10
14
  /**
11
15
  * Ephemeral run-scoped descriptors are intentionally outside a Git workspace.
@@ -1,6 +1,8 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { artifactRevisionReferenceSchema, artifactSharedContextNameSchema, } from '../contracts/context.js';
4
6
  /**
5
7
  * Ephemeral run-scoped descriptors are intentionally outside a Git workspace.
6
8
  * The unpredictable filename is the capability presented by the configured MCP
@@ -35,6 +37,7 @@ export class FileArtifactMcpSessionStore {
35
37
  typeof descriptor.activationId !== 'string' ||
36
38
  !Array.isArray(descriptor.readableProducers) ||
37
39
  typeof descriptor.expiresAt !== 'string' ||
40
+ !validSharedContext(descriptor) ||
38
41
  !Number.isFinite(Date.parse(descriptor.expiresAt)) ||
39
42
  Date.parse(descriptor.expiresAt) <= Date.parse(this.now()))
40
43
  throw new Error('Invalid artifact MCP session');
@@ -51,6 +54,18 @@ export class FileArtifactMcpSessionStore {
51
54
  }
52
55
  }
53
56
  }
57
+ const sharedContextSchema = z.object({
58
+ contextScope: artifactSharedContextNameSchema.optional(),
59
+ sharedReferences: z.array(artifactRevisionReferenceSchema).optional(),
60
+ currentMemory: artifactRevisionReferenceSchema.nullable().optional(),
61
+ });
62
+ function validSharedContext(descriptor) {
63
+ return sharedContextSchema.safeParse({
64
+ contextScope: descriptor.contextScope,
65
+ sharedReferences: descriptor.sharedReferences,
66
+ currentMemory: descriptor.currentMemory,
67
+ }).success;
68
+ }
54
69
  function digest(value) {
55
70
  return createHash('sha256').update(value).digest('hex');
56
71
  }
@@ -1,5 +1,5 @@
1
1
  import type { FileArtifactMcpSessionStore } from '../artifacts/index.js';
2
- import { type ArtifactService } from '../artifacts/index.js';
2
+ import { type ArtifactRevisionReference, type ArtifactService } from '../artifacts/index.js';
3
3
  import { type ExecutionDependencies } from '../execution/index.js';
4
4
  import type { OrchestrationService } from '../orchestration/index.js';
5
5
  /** Bootstrap binds Artifact's generic policy to verified Execution and Orchestration facts. */
@@ -10,6 +10,11 @@ export declare function createArtifactMcpProvisioner(input: {
10
10
  readonly wakeRoot: string;
11
11
  readonly now: () => string;
12
12
  readonly nextId: () => string;
13
+ readonly sharedContext?: (workItemId: string) => Promise<{
14
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
15
+ readonly currentMemory?: ArtifactRevisionReference | null;
16
+ readonly contextScope?: string;
17
+ }>;
13
18
  }): NonNullable<ExecutionDependencies['mcp']>;
14
19
  /** Creates the transport-neutral Wake MCP server for the run-bound CLI command. */
15
20
  export declare function createArtifactMcpServerForSession(root: ArtifactMcpRoot, sessions: FileArtifactMcpSessionStore, path: string, token: string, options: {
@@ -20,6 +20,7 @@ export function createArtifactMcpProvisioner(input) {
20
20
  activationId: activation.activationId,
21
21
  readableProducers: [...readableProducers],
22
22
  expiresAt,
23
+ ...(await input.sharedContext?.(context.workItemId)),
23
24
  };
24
25
  const issued = await input.sessions.issue(descriptor);
25
26
  try {
@@ -68,13 +69,10 @@ function commandContext(occurredAt, descriptor) {
68
69
  }
69
70
  function acceptedActivation(orchestration, workItemId) {
70
71
  let accepted;
71
- return async (activationId) => {
72
- accepted ??= orchestration
73
- .listAll()
74
- .then((workflows) => new Set(workflows
75
- .filter((workflow) => workflow.workItemId === workItemId)
76
- .flatMap((workflow) => workflow.acceptedOutcomes)));
77
- return (await accepted).has(activationId);
72
+ return async (activationId, sourceWorkItemId = workItemId) => {
73
+ accepted ??= orchestration.listAll();
74
+ return (await accepted).some((workflow) => workflow.workItemId === sourceWorkItemId &&
75
+ workflow.acceptedOutcomes.includes(activationId));
78
76
  };
79
77
  }
80
78
  function producerFor(workflowInstanceId, stage, activity) {
@@ -0,0 +1,30 @@
1
+ import { type EventJournal } from '@atolis-hq/eventing';
2
+ import { type ArtifactContextService, type ArtifactService } from '../artifacts/index.js';
3
+ import { type TriggerConfig } from '../control-plane/index.js';
4
+ import { type OrchestrationService } from '../orchestration/index.js';
5
+ /** Only durable claims matching the operator binding authorize named enrollment. */
6
+ export declare function createArtifactTriggerContext(input: {
7
+ readonly journal: EventJournal;
8
+ readonly contexts: ArtifactContextService;
9
+ readonly artifacts: ArtifactService;
10
+ readonly orchestration: OrchestrationService;
11
+ readonly triggers: readonly TriggerConfig[];
12
+ readonly now: () => string;
13
+ }): {
14
+ provision(item: string): Promise<{
15
+ contextScope?: never;
16
+ sharedReferences?: never;
17
+ currentMemory?: never;
18
+ } | {
19
+ contextScope: string;
20
+ sharedReferences: readonly {
21
+ workItemId: import("../work/index.js").WorkItemId;
22
+ revisionId: string;
23
+ }[];
24
+ currentMemory: {
25
+ workItemId: import("../work/index.js").WorkItemId;
26
+ revisionId: string;
27
+ } | null;
28
+ }>;
29
+ reconcile(): Promise<void>;
30
+ };
@@ -0,0 +1,99 @@
1
+ import { EventActorKind, correlationId } from '@atolis-hq/eventing';
2
+ import { ActivityOutcomeKind } from '../activities/index.js';
3
+ import { ArtifactContextProvenanceKind, } from '../artifacts/index.js';
4
+ import { ControlEventType, artifactContextCoordinationKey, selectControlEvent, triggerInvocationStream, } from '../control-plane/index.js';
5
+ import { WorkflowStatus } from '../orchestration/index.js';
6
+ import { workItemId } from '../work/index.js';
7
+ /** Only durable claims matching the operator binding authorize named enrollment. */
8
+ export function createArtifactTriggerContext(input) {
9
+ // Completed receipts and immutable claim bindings need no repeated stream reads in a resident host.
10
+ const reconciled = new Set();
11
+ const bindings = new Map();
12
+ async function binding(item) {
13
+ if (bindings.has(item))
14
+ return bindings.get(item) ?? null;
15
+ for (const envelope of await input.journal.readStream(triggerInvocationStream(item))) {
16
+ const event = selectControlEvent(envelope);
17
+ if (event?.event.eventType !== ControlEventType.TriggerInvocationClaimed)
18
+ continue;
19
+ const claimed = event.event.payload;
20
+ const config = input.triggers.find((trigger) => trigger.id === claimed.triggerId);
21
+ if (config?.contextScope === undefined ||
22
+ claimed.coordinationKey !== artifactContextCoordinationKey(config.contextScope))
23
+ break;
24
+ const result = {
25
+ contextScope: config.contextScope,
26
+ workflowInstanceId: claimed.workflowInstanceId,
27
+ };
28
+ await input.contexts.enroll(config.contextScope, workItemId(item), {
29
+ kind: ArtifactContextProvenanceKind.Trigger,
30
+ triggerId: config.id,
31
+ invocationId: claimed.workflowInstanceId,
32
+ }, context(item));
33
+ bindings.set(item, result);
34
+ return result;
35
+ }
36
+ bindings.set(item, null);
37
+ return null;
38
+ }
39
+ function context(item) {
40
+ return {
41
+ commandId: `artifact-trigger:${item}`,
42
+ correlationId: correlationId(item),
43
+ occurredAt: input.now(),
44
+ actor: { kind: EventActorKind.System, id: 'artifact-trigger-context' },
45
+ };
46
+ }
47
+ return {
48
+ async provision(item) {
49
+ const bound = await binding(item);
50
+ if (bound === null)
51
+ return {};
52
+ const view = await input.contexts.get(bound.contextScope);
53
+ return {
54
+ contextScope: bound.contextScope,
55
+ sharedReferences: await input.contexts.references(bound.contextScope, workItemId(item)),
56
+ currentMemory: view.memory,
57
+ };
58
+ },
59
+ async reconcile() {
60
+ for (const workflow of await input.orchestration.listAll()) {
61
+ if (reconciled.has(workflow.workflowInstanceId) ||
62
+ (workflow.status !== WorkflowStatus.Completed &&
63
+ workflow.status !== WorkflowStatus.Superseded))
64
+ continue;
65
+ try {
66
+ const bound = await binding(workflow.workItemId);
67
+ // A trigger claim authorizes its invocation, not every workflow on its WorkItem.
68
+ if (bound !== null && bound.workflowInstanceId === workflow.workflowInstanceId) {
69
+ const view = await input.contexts.get(bound.contextScope);
70
+ const member = view.members.find((candidate) => candidate.workItemId === workflow.workItemId);
71
+ const accepted = async (id, item) => item === workflow.workItemId &&
72
+ workflow.acceptedOutcomes.some((acceptedId) => acceptedId === id);
73
+ const revisions = await input.artifacts.latestPublished(workflow.workItemId, (id) => accepted(id, workflow.workItemId));
74
+ const successful = workflow.status === WorkflowStatus.Completed &&
75
+ workflow.lastOutcome?.kind !== ActivityOutcomeKind.Failed;
76
+ await input.contexts.publish({
77
+ contextScope: bound.contextScope,
78
+ workItemId: workflow.workItemId,
79
+ publicationId: workflow.workflowInstanceId,
80
+ successful,
81
+ exports: revisions
82
+ .filter((revision) => successful && revision.contextExport === bound.contextScope)
83
+ .map((revision) => ({
84
+ workItemId: workflow.workItemId,
85
+ revisionId: revision.revisionId,
86
+ })),
87
+ expectedMemory: member.expectedMemory,
88
+ }, accepted, context(workflow.workItemId));
89
+ }
90
+ reconciled.add(workflow.workflowInstanceId);
91
+ }
92
+ catch (error) {
93
+ // Retry this invocation next pass without starving other scopes or trigger admission.
94
+ console.error(`Artifact context publication failed for ${workflow.workflowInstanceId}`, error);
95
+ }
96
+ }
97
+ },
98
+ };
99
+ }
@@ -1,5 +1,5 @@
1
1
  import { ActivityEventType, selectActivityEvent } from '../activities/index.js';
2
- import { ArtifactEventType, selectArtifactEvent } from '../artifacts/index.js';
2
+ import { ArtifactContextEventType, ArtifactEventType, selectArtifactContextEvent, selectArtifactEvent, } from '../artifacts/index.js';
3
3
  import { ControlEventType, selectControlEvent } from '../control-plane/index.js';
4
4
  import { ConversationEventType, selectConversationEvent } from '../conversations/index.js';
5
5
  import { ExecutionEventType, selectExecutionEvent } from '../execution/index.js';
@@ -12,6 +12,7 @@ import { WorkEventType, selectWorkEvent } from '../work/index.js';
12
12
  const registrations = [
13
13
  { types: Object.values(ActivityEventType), decode: selectActivityEvent },
14
14
  { types: Object.values(ArtifactEventType), decode: selectArtifactEvent },
15
+ { types: Object.values(ArtifactContextEventType), decode: selectArtifactContextEvent },
15
16
  { types: Object.values(ControlEventType), decode: selectControlEvent },
16
17
  { types: Object.values(ConversationEventType), decode: selectConversationEvent },
17
18
  { types: Object.values(ExecutionEventType), decode: selectExecutionEvent },
@@ -1,6 +1,6 @@
1
1
  import { acquireFileLock } from '@atolis-hq/eventing-filesystem';
2
2
  import { createPullRequestService } from '../activities/index.js';
3
- import { FileArtifactMcpSessionStore, FileArtifactStore, createArtifactService, } from '../artifacts/index.js';
3
+ import { ArtifactContextService, FileArtifactMcpSessionStore, FileArtifactStore, createArtifactService, } from '../artifacts/index.js';
4
4
  import { DispatchPolicy, createActivationScheduler, createActivationSchedulerSubscriber, createControlPlaneService, createDurableRunnerIneligibility, createRunnerControlService, } from '../control-plane/index.js';
5
5
  import { createConversationService } from '../conversations/index.js';
6
6
  import { ExecutionCancellationReason, ExternalExecutionState, GitWorkspaceProvider, RecoveryService, TranscriptStore, createExecutionService, createRunnerMemoryProfileDecorator, } from '../execution/index.js';
@@ -12,6 +12,7 @@ import { createWorkService } from '../work/index.js';
12
12
  import { createFileActivationSchedulerSerialiser } from './activation-scheduler-serialiser.js';
13
13
  import { createBuiltInActivityRegistry } from './activity-registry.js';
14
14
  import { createArtifactMcpProvisioner } from './artifact-mcp.js';
15
+ import { createArtifactTriggerContext } from './artifact-trigger-context.js';
15
16
  import { loadConfig } from './config/load-config.js';
16
17
  import { EventProcessorRuntime } from './event-processor-runtime.js';
17
18
  import { loadFakeScenarios } from './fake-scenarios.js';
@@ -41,6 +42,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
41
42
  const processorRuntime = new EventProcessorRuntime(journal, checkpoints, subscriptionRunSerialiser, clock);
42
43
  const work = createWorkService(journal);
43
44
  const artifacts = createArtifactService(journal, new FileArtifactStore(paths.artifactsRoot), config.artifacts);
45
+ const artifactContexts = new ArtifactContextService(journal, artifacts);
44
46
  const artifactMcpSessions = new FileArtifactMcpSessionStore(paths.artifactsRoot, () => clock.now().toISOString());
45
47
  const conversations = createConversationService(journal);
46
48
  const lookup = createResourceLookup({ journal, projections });
@@ -86,6 +88,14 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
86
88
  ? profileDecorator
87
89
  : (runner, name) => profileDecorator(options.decorateRunner(runner, name), name);
88
90
  const runners = createRunnerRegistry(config.execution, fakeScenarios, decorateRunner);
91
+ const artifactTriggerContext = createArtifactTriggerContext({
92
+ journal,
93
+ contexts: artifactContexts,
94
+ artifacts,
95
+ orchestration,
96
+ triggers: config.controlPlane.triggers,
97
+ now: () => clock.now().toISOString(),
98
+ });
89
99
  const execution = createExecutionService(journal, activities, config.execution, {
90
100
  clock,
91
101
  ids,
@@ -97,6 +107,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
97
107
  wakeRoot: paths.wakeRoot,
98
108
  now: () => clock.now().toISOString(),
99
109
  nextId: () => ids.next('artifact'),
110
+ sharedContext: artifactTriggerContext.provision,
100
111
  }),
101
112
  reportRunnerQuota: createRunnerQuotaReporter(journal, clock, ids),
102
113
  ...(transcriptStore !== undefined
@@ -174,6 +185,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
174
185
  processorRuntime,
175
186
  activities,
176
187
  runners,
188
+ reconcileArtifactContext: artifactTriggerContext.reconcile,
177
189
  triggerCheckpoints: options.triggerCheckpoints ?? new ProcessorTriggerCheckpointStore(processorState),
178
190
  ...(options.triggerCoordinationKey === undefined
179
191
  ? {}
@@ -15,8 +15,8 @@ declare const orchestrationConfigSchema: z.ZodDefault<z.ZodObject<{
15
15
  with: z.ZodOptional<z.ZodUnknown>;
16
16
  allowedActors: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
17
17
  human: "human";
18
- watch: "watch";
19
18
  auto: "auto";
19
+ watch: "watch";
20
20
  }>>>;
21
21
  }, z.core.$strict>>>;
22
22
  watches: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodObject<{
@@ -162,8 +162,8 @@ export declare const rootConfigSchema: z.ZodObject<{
162
162
  with: z.ZodOptional<z.ZodUnknown>;
163
163
  allowedActors: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
164
164
  human: "human";
165
- watch: "watch";
166
165
  auto: "auto";
166
+ watch: "watch";
167
167
  }>>>;
168
168
  }, z.core.$strict>>>;
169
169
  watches: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodObject<{
@@ -341,6 +341,7 @@ export declare const rootConfigSchema: z.ZodObject<{
341
341
  triggers: z.ZodDefault<z.ZodArray<z.ZodObject<{
342
342
  id: z.ZodString;
343
343
  workflow: z.ZodString;
344
+ contextScope: z.ZodOptional<z.ZodString>;
344
345
  on: z.ZodObject<{
345
346
  events: z.ZodOptional<z.ZodArray<z.ZodString>>;
346
347
  cron: z.ZodOptional<z.ZodString>;
@@ -45,6 +45,7 @@ export interface IntegrationRuntimeInput {
45
45
  readonly subscriptionRunSerialiser: ProcessorRunSerialiser;
46
46
  readonly processorRuntime: EventProcessorRuntime;
47
47
  readonly triggerCheckpoints: TriggerCheckpointStore;
48
+ readonly reconcileArtifactContext?: () => Promise<void>;
48
49
  readonly triggerCoordinationKey?: (config: TriggerConfig) => string;
49
50
  readonly decorateDeliveryAdapter?: (adapter: ExternalDeliveryAdapter, provider: ProviderInstance) => ExternalDeliveryAdapter;
50
51
  readonly fakeDeliveryProvider?: DurableFakeDeliveryProvider;
@@ -232,6 +232,7 @@ export async function composeIntegrationRuntime(input) {
232
232
  const runnerPipeline = createRunnerPipeline({
233
233
  isPaused: input.isPaused,
234
234
  runTriggers: () => observeMemory(memoryProfile, 'runner.triggers', async () => {
235
+ await input.reconcileArtifactContext?.();
235
236
  await triggers.reconcile({
236
237
  commandId: input.ids.next('command'),
237
238
  correlationId: correlationId('trigger-recovery'),
@@ -8,6 +8,7 @@ import { createSelfUpdateFailureLog, describeSelfUpdateFailure, } from './self-u
8
8
  import { createExecutionApplications } from './surface-api-execution-applications.js';
9
9
  import { projectionMeta, sampledMeta } from './surface-api-metadata.js';
10
10
  import { projectionPage } from './surface-api-projection-pages.js';
11
+ import { createTriggerApplications } from './surface-api-trigger-applications.js';
11
12
  import { createSurfaceWorkApplications } from './surface-api-work-applications.js';
12
13
  import { createWorkflowDiagramApplications } from './surface-api-workflow-diagrams.js';
13
14
  import { UpdateMaintenancePhase } from './update-maintenance-lease.js';
@@ -18,6 +19,7 @@ export function createSurfaceApiApplications(root, now) {
18
19
  board: createBoardApplications(root, now),
19
20
  status: createStatusApplications(root, now),
20
21
  controlPlane: createControlPlaneApplications(root, now),
22
+ triggers: createTriggerApplications(root, now),
21
23
  work: createSurfaceWorkApplications(root, now),
22
24
  resources: createResourceApplications(root, now),
23
25
  orchestration: createOrchestrationApplications(root, now),
@@ -0,0 +1,3 @@
1
+ import { type ApiApplications } from '../surfaces/index.js';
2
+ import type { CompositionRoot } from './composition-root.js';
3
+ export declare function createTriggerApplications(root: CompositionRoot, now: () => string): NonNullable<ApiApplications['triggers']>;
@@ -0,0 +1,79 @@
1
+ import { correlationId, EventActorKind } from '@atolis-hq/eventing';
2
+ import { CronTriggerPolicy } from '../control-plane/index.js';
3
+ import { ApiCommandStatus, toWorkItemKey, TriggerStatus, } from '../surfaces/index.js';
4
+ export function createTriggerApplications(root, now) {
5
+ async function list() {
6
+ const view = await root.triggers.get();
7
+ const ids = new Set([
8
+ ...root.config.controlPlane.triggers.map((config) => config.id),
9
+ ...Object.keys(view.pauses),
10
+ ...view.requests.map((request) => request.triggerId),
11
+ ...view.invocations.map((entry) => entry.claim.triggerId),
12
+ ...(view.diagnostics ?? []).map((entry) => entry.triggerId),
13
+ ]);
14
+ const asOf = now();
15
+ return { data: [...ids].sort().map((id) => present(id, view, asOf)), meta: { asOf } };
16
+ }
17
+ function present(id, view, asOf) {
18
+ const definition = root.config.controlPlane.triggers.find((config) => config.id === id) ?? null;
19
+ const invocations = view.invocations
20
+ .filter((entry) => entry.claim.triggerId === id)
21
+ .sort((a, b) => b.claimedAt.localeCompare(a.claimedAt))
22
+ .map((entry) => ({ ...entry, workItemKey: toWorkItemKey(entry.claim.workItemId) }));
23
+ const pauseReason = view.pauses[id] ?? null;
24
+ const running = invocations.some((entry) => entry.result === undefined);
25
+ return {
26
+ triggerId: id,
27
+ definition,
28
+ paused: pauseReason !== null,
29
+ pauseReason,
30
+ status: definition === null
31
+ ? TriggerStatus.Removed
32
+ : pauseReason !== null
33
+ ? TriggerStatus.Paused
34
+ : running
35
+ ? TriggerStatus.Running
36
+ : TriggerStatus.Enabled,
37
+ nextOccurrence: definition?.on.cron === undefined
38
+ ? null
39
+ : new CronTriggerPolicy().nextOccurrence(definition.on.cron, asOf),
40
+ pending: Object.values(view.coalesced).filter((entry) => entry.triggerId === id),
41
+ latestSkip: view.diagnostics?.find((entry) => entry.triggerId === id) ?? null,
42
+ invocations,
43
+ };
44
+ }
45
+ async function command(id, request, pause) {
46
+ if (!(await list()).data.some((entry) => entry.triggerId === id))
47
+ return {
48
+ conflict: true,
49
+ code: 'trigger-not-found',
50
+ detail: 'Trigger definition and history are unavailable',
51
+ };
52
+ const context = {
53
+ commandId: 'trigger:' + request.idempotencyKey,
54
+ correlationId: correlationId('trigger:' + request.idempotencyKey),
55
+ occurredAt: now(),
56
+ actor: { kind: EventActorKind.Operator, id: 'web' },
57
+ };
58
+ if (pause)
59
+ await root.triggers.pause(id, 'Operator pause', context);
60
+ else
61
+ await root.triggers.resume(id, context);
62
+ return {
63
+ commandId: context.commandId,
64
+ idempotencyKey: request.idempotencyKey,
65
+ acceptedAt: now(),
66
+ status: ApiCommandStatus.Completed,
67
+ };
68
+ }
69
+ return {
70
+ list,
71
+ async detail(id) {
72
+ const result = await list();
73
+ const data = result.data.find((entry) => entry.triggerId === id);
74
+ return data === undefined ? undefined : { data, meta: result.meta };
75
+ },
76
+ pause: (id, request) => command(id, request, true),
77
+ resume: (id, request) => command(id, request, false),
78
+ };
79
+ }
@@ -1,5 +1,6 @@
1
1
  import { correlationId, EventActorKind } from '@atolis-hq/eventing';
2
2
  import { pullRequestProjection } from '../activities/index.js';
3
+ import { triggerInvocationProjection } from '../control-plane/index.js';
3
4
  import { conversationIdForWorkItem, ConversationOriginKind, } from '../conversations/index.js';
4
5
  import { executionProjection, runsByWorkflowInstanceProjection, } from '../execution/index.js';
5
6
  import { ApprovalAuthorityKind, ConversationSurfaceCapability, GroupBudgetExtensionIneligibleError, isGroupBudgetExtensionEligible, OperatorRetryIneligibleError, orchestrationProjection, selectOperatorRetryTarget, workflowsByWorkItemProjection, } from '../orchestration/index.js';
@@ -198,6 +199,7 @@ async function workDetail(root, key, now) {
198
199
  // the production root always composes Conversations.
199
200
  const conversation = await conversationForWorkItem(root, id);
200
201
  const data = {
202
+ ...(await triggerOriginForWork(root, id)),
201
203
  work: presentDetailWork(work, externalRef, runs),
202
204
  resources: resources.map(presentResource(root.resolveResourceLink)),
203
205
  orchestration: {
@@ -320,6 +322,7 @@ function presentPullRequest(value) {
320
322
  async function contributingProjections(root, id, resources, workflows, runs) {
321
323
  const records = await Promise.all([
322
324
  root.projections.read('work', id),
325
+ root.projections.read(triggerInvocationProjection.name, id),
323
326
  ...resources.map((value) => root.projections.read('resources', value.resourceId)),
324
327
  ...workflows.map((value) => root.projections.read(orchestrationProjection.name, value.workflowInstanceId)),
325
328
  ...runs.map((value) => root.projections.read(executionProjection.name, value.runId)),
@@ -352,3 +355,8 @@ function retryIneligible(detail) {
352
355
  function extendIneligible(detail) {
353
356
  return { conflict: true, code: 'extend-ineligible', detail };
354
357
  }
358
+ async function triggerOriginForWork(root, id) {
359
+ await root.projectionSubscriptions?.catchUp(triggerInvocationProjection);
360
+ const origin = await root.projections.read(triggerInvocationProjection.name, id);
361
+ return origin?.value == null ? {} : { triggerOrigin: origin.value.claim.triggerId };
362
+ }
@@ -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.62";
127
+ export const wakeVersion = "v0.4.64";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -0,0 +1,33 @@
1
+ import type { ProcessorStateStore } from '@atolis-hq/eventing';
2
+ import type { TriggerConfig } from '../contracts/config.js';
3
+ import type { TriggerSource } from '../contracts/events.js';
4
+ import { type TriggerSkipReason as SkipReason } from '../contracts/trigger-diagnostics.js';
5
+ import type { TriggerView } from './trigger-projection.js';
6
+ interface Dependencies {
7
+ readonly state: ProcessorStateStore;
8
+ readonly now: () => string;
9
+ readonly isDispatchPaused: () => Promise<boolean>;
10
+ readonly capacityAvailable: (config: TriggerConfig) => Promise<boolean>;
11
+ }
12
+ /** Diagnostic writes never emit trigger sources or retain an unbounded occurrence history. */
13
+ export declare class TriggerDiagnostics {
14
+ private readonly dependencies;
15
+ private readonly consumer;
16
+ constructor(dependencies: Dependencies, consumer: string);
17
+ get(): Promise<{
18
+ triggerId: string;
19
+ source: {
20
+ kind: "event";
21
+ eventId: string;
22
+ eventType: string;
23
+ } | {
24
+ kind: "cron";
25
+ slot: string;
26
+ };
27
+ occurredAt: string;
28
+ reason: "paused" | "own-scope" | "removed" | "dispatch-paused" | "capacity-unavailable" | "pending-source-limit";
29
+ }[]>;
30
+ record(triggerId: string, source: TriggerSource, reason: SkipReason): Promise<void>;
31
+ ineligibleReason(view: TriggerView, id: string, config: TriggerConfig | undefined, configured: boolean, active?: boolean): Promise<SkipReason | undefined>;
32
+ }
33
+ export {};