@atolis-hq/wake 0.3.117 → 0.4.0
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.
- package/README.md +13 -5
- package/dist/src/bootstrap/composition-root.js +5 -1
- package/dist/src/bootstrap/index.js +3 -3
- package/dist/src/bootstrap/initialise.js +7 -2
- package/dist/src/bootstrap/integration-runtime.js +3 -1
- package/dist/src/bootstrap/projection-runtime.js +2 -0
- package/dist/src/bootstrap/surface-api-work-applications.js +70 -0
- package/dist/src/bootstrap/surface-cli-applications.js +16 -9
- package/dist/src/bootstrap/version.js +1 -1
- package/dist/src/conversations/application/conversation-projection.js +17 -0
- package/dist/src/conversations/application/conversation-repository.js +21 -0
- package/dist/src/conversations/application/conversation-service.js +105 -0
- package/dist/src/conversations/contracts/commands.js +1 -0
- package/dist/src/conversations/contracts/events.js +100 -0
- package/dist/src/conversations/contracts/identifiers.js +8 -0
- package/dist/src/conversations/contracts/streams.js +5 -0
- package/dist/src/conversations/contracts/views.js +1 -0
- package/dist/src/conversations/contracts/vocabulary.js +6 -0
- package/dist/src/conversations/domain/conversation.js +100 -0
- package/dist/src/conversations/index.js +8 -0
- package/dist/src/integrations/application/agent-run-publication-reactor.js +31 -0
- package/dist/src/integrations/application/work-admission.js +6 -0
- package/dist/src/integrations/delivery/application/delivery-outcome-reactor.js +48 -2
- package/dist/src/integrations/delivery/application/delivery-projector.js +2 -0
- package/dist/src/integrations/delivery/contracts/intents.js +2 -0
- package/dist/src/integrations/github/application/agent-context-reader.js +49 -3
- package/dist/src/integrations/github/application/comment-history-reader.js +27 -11
- package/dist/src/integrations/github/application/delivery-marker.js +7 -0
- package/dist/src/integrations/github/application/inbound-translator.js +126 -0
- package/dist/src/integrations/github/contracts/events.js +12 -0
- package/dist/src/integrations/github/provider.js +1 -0
- package/dist/src/orchestration/domain/operator-retry-policy.js +8 -5
- package/dist/src/persistence/filesystem/file-event-journal.js +31 -5
- package/dist/src/persistence/filesystem/file-projection-store.js +25 -6
- package/dist/src/surfaces/api/http-server.js +9 -2
- package/dist/src/surfaces/api/routes/commands.js +36 -6
- package/dist/src/surfaces/api/routes/work.js +1 -0
- package/dist/src/surfaces/contracts/config.js +17 -2
- package/dist/src/surfaces/web-assets/assets/index-B0ofn_L5.css +1 -0
- package/dist/src/surfaces/web-assets/assets/index-DFBhpSSX.js +1179 -0
- package/dist/src/surfaces/web-assets/index.html +2 -2
- package/package.json +1 -1
- package/dist/src/surfaces/web-assets/assets/index-CFfq35Jj.js +0 -1179
- package/dist/src/surfaces/web-assets/assets/index-Dj-RskGs.css +0 -1
package/README.md
CHANGED
|
@@ -96,6 +96,9 @@ For more detail, see [docs/vision.md](docs/vision.md) and
|
|
|
96
96
|
- **Event-sourced and restart-safe.** The durable record is an append-only event
|
|
97
97
|
log; projections can be rebuilt, and the loop can crash and resume without
|
|
98
98
|
losing its place.
|
|
99
|
+
- **Canonical work discussion.** GitHub comments and Wake agent reports are
|
|
100
|
+
recorded in one immutable conversation per work item, preserving origin and
|
|
101
|
+
context independently of the surface where they appeared.
|
|
99
102
|
- **Local and inspectable.** Everything lives in a plain-file Wake home
|
|
100
103
|
directory: `config.yaml`, `config.workflows.yaml`, `prompts/`, `SETUP.md`, and
|
|
101
104
|
`workspaces/` at the top level for
|
|
@@ -126,11 +129,16 @@ Reviewing, approving, and merging happen exactly where they already do today -
|
|
|
126
129
|
nothing new to learn, no separate dashboard to babysit.
|
|
127
130
|
|
|
128
131
|
A local control-plane UI exists for operators who want to watch runs, inspect
|
|
129
|
-
events, or
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
132
|
+
events, or use the dedicated Conversation tab on a work item to read its
|
|
133
|
+
canonical timeline. When `surfaces.api.conversationMessages.enabled` is enabled,
|
|
134
|
+
the same tab also lets an operator add a message that Wake records and may use
|
|
135
|
+
to resume an eligible agent stage. The UI is a window into the same state - not
|
|
136
|
+
a required part of the workflow.
|
|
137
|
+
The API and UI require an operator login:
|
|
138
|
+
run `wake ui token` to print a single-use pairing link or temporary code, then
|
|
139
|
+
enter it in the UI. Successful logins persist for two years across browser and
|
|
140
|
+
Wake-container restarts. Use `wake ui token set <key>` to replace the durable
|
|
141
|
+
access key; replacement signs out existing sessions.
|
|
134
142
|
|
|
135
143
|
## Supported Agent CLIs
|
|
136
144
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createPullRequestService } from '../activities/index.js';
|
|
2
2
|
import { ControlStreamKind, DispatchPolicy, createAdvanceOnce, createControlPlaneService, createRunnerControlService, ineligibleRunners, } from '../control-plane/index.js';
|
|
3
|
+
import { createConversationService } from '../conversations/index.js';
|
|
3
4
|
import { ExecutionCancellationReason, ExternalExecutionState, GitWorkspaceProvider, RecoveryService, TranscriptStore, createExecutionService, createRunnerMemoryProfileDecorator, } from '../execution/index.js';
|
|
4
5
|
import { createGitHubAgentContextReader, gitHubProviderDefinition, resolveGitHubResourceUrl, } from '../integrations/github/index.js';
|
|
5
6
|
import { SystemClock, UlidIdGenerator, } from '../kernel/index.js';
|
|
@@ -34,6 +35,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
|
|
|
34
35
|
const ids = new UlidIdGenerator();
|
|
35
36
|
const { journal, projections, checkpoints } = composePersistence(paths, clock, options);
|
|
36
37
|
const work = createWorkService(journal);
|
|
38
|
+
const conversations = createConversationService(journal);
|
|
37
39
|
const lookup = createResourceLookup({ journal, projections });
|
|
38
40
|
const resources = createResourceService(journal, lookup);
|
|
39
41
|
const pullRequests = createPullRequestService(journal, work, resources);
|
|
@@ -41,7 +43,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
|
|
|
41
43
|
createBuiltInActivityRegistry(journal, pullRequests, resources, wakeRoot, createGitHubAgentContextReader(journal, resources, {
|
|
42
44
|
publicUiUrl: config.surfaces.web.publicUrl,
|
|
43
45
|
githubAdapters: githubAdapters(config),
|
|
44
|
-
}));
|
|
46
|
+
}, conversations));
|
|
45
47
|
const definitions = Object.fromEntries(Object.entries(config.orchestration.workflows).map(([name, definition]) => [
|
|
46
48
|
name,
|
|
47
49
|
compileWorkflow(name, definition, activities, Object.keys(config.orchestration.workflows)),
|
|
@@ -143,6 +145,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
|
|
|
143
145
|
isPaused: isRuntimePaused,
|
|
144
146
|
clock,
|
|
145
147
|
work,
|
|
148
|
+
conversations,
|
|
146
149
|
ids,
|
|
147
150
|
wakeRoot,
|
|
148
151
|
projectionRunSerialiser: createFileProjectionRunSerialiser(paths.dataRoot),
|
|
@@ -165,6 +168,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
|
|
|
165
168
|
checkpoints,
|
|
166
169
|
activities,
|
|
167
170
|
work,
|
|
171
|
+
conversations,
|
|
168
172
|
resources,
|
|
169
173
|
lookup,
|
|
170
174
|
orchestration,
|
|
@@ -4,8 +4,8 @@ import { createRuntimeProjectionRunner } from './projection-runtime.js';
|
|
|
4
4
|
export function composeDeliveryService(dependencies) {
|
|
5
5
|
return new DeliveryService(dependencies);
|
|
6
6
|
}
|
|
7
|
-
export function composeDeliveryOutcomeReactor(journal, checkpoints, orchestration, projections) {
|
|
8
|
-
return new DeliveryOutcomeReactor(journal, checkpoints, orchestration, projections);
|
|
7
|
+
export function composeDeliveryOutcomeReactor(journal, checkpoints, orchestration, projections, conversations) {
|
|
8
|
+
return new DeliveryOutcomeReactor(journal, checkpoints, orchestration, projections, conversations);
|
|
9
9
|
}
|
|
10
10
|
export function composeDeliveryRuntime(dependencies) {
|
|
11
11
|
const projectionRunner = createRuntimeProjectionRunner(dependencies.journal, dependencies.projections, dependencies.checkpoints);
|
|
@@ -16,7 +16,7 @@ export function composeDeliveryRuntime(dependencies) {
|
|
|
16
16
|
adapter: dependencies.adapter,
|
|
17
17
|
now: dependencies.now,
|
|
18
18
|
});
|
|
19
|
-
const reactor = composeDeliveryOutcomeReactor(dependencies.journal, dependencies.checkpoints, dependencies.orchestration, dependencies.projections);
|
|
19
|
+
const reactor = composeDeliveryOutcomeReactor(dependencies.journal, dependencies.checkpoints, dependencies.orchestration, dependencies.projections, dependencies.conversations);
|
|
20
20
|
return {
|
|
21
21
|
async runOnce(signal) {
|
|
22
22
|
await projectionRunner.runRegisteredOnce();
|
|
@@ -48,8 +48,13 @@ orchestration:
|
|
|
48
48
|
# configure one — see SETUP.md.
|
|
49
49
|
integrations: {}
|
|
50
50
|
|
|
51
|
-
# Operator-facing HTTP API / web UI. Disabled by default.
|
|
52
|
-
|
|
51
|
+
# Operator-facing HTTP API / web UI. Disabled by default. Control-plane
|
|
52
|
+
# conversation messages stay disabled until Wake can attribute them to the
|
|
53
|
+
# authenticated operator.
|
|
54
|
+
surfaces:
|
|
55
|
+
api:
|
|
56
|
+
conversationMessages:
|
|
57
|
+
enabled: false
|
|
53
58
|
|
|
54
59
|
# Transcript capture is opt-in. Captured transcripts expire after one day.
|
|
55
60
|
transcripts:
|
|
@@ -34,6 +34,7 @@ export async function composeIntegrationRuntime(input) {
|
|
|
34
34
|
const { instances, failures: providerFailures } = registry.compose(await hydrateFakeProviderEvidence(input.wakeRoot, input.config.integrations), {
|
|
35
35
|
publicUiUrl: input.config.surfaces.web.publicUrl,
|
|
36
36
|
work: input.work,
|
|
37
|
+
conversations: input.conversations,
|
|
37
38
|
resources: input.resources,
|
|
38
39
|
resourceLookup: input.lookup,
|
|
39
40
|
pullRequests: input.pullRequests,
|
|
@@ -103,6 +104,7 @@ export async function composeIntegrationRuntime(input) {
|
|
|
103
104
|
runs,
|
|
104
105
|
resources: input.resources,
|
|
105
106
|
orchestration: input.orchestration,
|
|
107
|
+
conversations: input.conversations,
|
|
106
108
|
...(replies === undefined ? {} : { replies }),
|
|
107
109
|
});
|
|
108
110
|
const watch = createWatchReactor(input.orchestration, input.journal, input.checkpoints, runs);
|
|
@@ -124,7 +126,7 @@ export async function composeIntegrationRuntime(input) {
|
|
|
124
126
|
await resourceTransitions.drain();
|
|
125
127
|
return operation();
|
|
126
128
|
});
|
|
127
|
-
const outcomes = new DeliveryOutcomeReactor(input.journal, input.checkpoints, input.orchestration, input.projections);
|
|
129
|
+
const outcomes = new DeliveryOutcomeReactor(input.journal, input.checkpoints, input.orchestration, input.projections, input.conversations);
|
|
128
130
|
const catchUpProjections = async () => {
|
|
129
131
|
await projectionRunner.runRegisteredOnce();
|
|
130
132
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { activityProjectionDefinitions } from '../activities/index.js';
|
|
3
3
|
import { controlPlaneProjectionDefinitions } from '../control-plane/index.js';
|
|
4
|
+
import { conversationProjection } from '../conversations/index.js';
|
|
4
5
|
import { executionProjection, runsByWorkflowInstanceProjection } from '../execution/index.js';
|
|
5
6
|
import { deliveryProjectionDefinitions } from '../integrations/index.js';
|
|
6
7
|
import { orchestrationProjection, workflowDefinitionsProjection, workflowsByWorkItemProjection, } from '../orchestration/index.js';
|
|
@@ -10,6 +11,7 @@ import { workProjection } from '../work/index.js';
|
|
|
10
11
|
import { analyticsProjection } from './analytics-projection.js';
|
|
11
12
|
import { boardProjection } from './board-projection.js';
|
|
12
13
|
export const runtimeProjectionDefinitions = [
|
|
14
|
+
conversationProjection,
|
|
13
15
|
workProjection,
|
|
14
16
|
resourceProjection,
|
|
15
17
|
resourceCorrelationProjection,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { pullRequestProjection } from '../activities/index.js';
|
|
2
|
+
import { conversationIdForWorkItem, ConversationOriginKind, } from '../conversations/index.js';
|
|
2
3
|
import { executionProjection, runsByWorkflowInstanceProjection, } from '../execution/index.js';
|
|
3
4
|
import { correlationId, EventActorKind } from '../kernel/index.js';
|
|
4
5
|
import { ApprovalAuthorityKind, GroupBudgetExtensionIneligibleError, isGroupBudgetExtensionEligible, OperatorRetryIneligibleError, orchestrationProjection, selectOperatorRetryTarget, workflowsByWorkItemProjection, } from '../orchestration/index.js';
|
|
@@ -11,6 +12,8 @@ import { projectionPage } from './surface-api-projection-pages.js';
|
|
|
11
12
|
import { enrichRun } from './surface-api-run-context.js';
|
|
12
13
|
import { readWorkTranscript, transcriptGroups } from './surface-api-transcripts.js';
|
|
13
14
|
export function createSurfaceWorkApplications(root, now) {
|
|
15
|
+
const conversationMessagesEnabled = root.config?.surfaces?.api?.conversationMessages?.enabled ===
|
|
16
|
+
true;
|
|
14
17
|
return {
|
|
15
18
|
async list(query) {
|
|
16
19
|
const stored = (await root.projections.list('work')).flatMap((entry) => entry.value === null ? [] : [{ ...entry, value: entry.value }]);
|
|
@@ -112,8 +115,42 @@ export function createSurfaceWorkApplications(root, now) {
|
|
|
112
115
|
}
|
|
113
116
|
return accepted(command.idempotencyKey, now());
|
|
114
117
|
},
|
|
118
|
+
...(conversationMessagesEnabled
|
|
119
|
+
? {
|
|
120
|
+
async message(key, command) {
|
|
121
|
+
const id = decodeWorkItemId(key);
|
|
122
|
+
if (id === undefined)
|
|
123
|
+
throw new Error('Work item not found');
|
|
124
|
+
const work = await root.work.get(id);
|
|
125
|
+
if (work === null)
|
|
126
|
+
throw new Error('Work item not found');
|
|
127
|
+
if (work.deleted === true)
|
|
128
|
+
throw new Error('Work item is deleted');
|
|
129
|
+
const context = commandContext(command.idempotencyKey, now);
|
|
130
|
+
await root.conversations.createForWorkItem(id, context);
|
|
131
|
+
await root.conversations.record({
|
|
132
|
+
conversationId: conversationIdForWorkItem(id),
|
|
133
|
+
entryId: `control-plane:${command.idempotencyKey}`,
|
|
134
|
+
body: command.body,
|
|
135
|
+
origin: { kind: ConversationOriginKind.ControlPlane, actorId: context.actor.id },
|
|
136
|
+
}, context);
|
|
137
|
+
await resumeAgentStages(root, id, context);
|
|
138
|
+
return accepted(command.idempotencyKey, now());
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
: {}),
|
|
115
142
|
};
|
|
116
143
|
}
|
|
144
|
+
async function resumeAgentStages(root, itemId, context) {
|
|
145
|
+
const workflows = await root.orchestration.listForWorkItem(itemId);
|
|
146
|
+
for (const workflow of workflows)
|
|
147
|
+
try {
|
|
148
|
+
await root.orchestration.resumeBlockedStageForChanges(workflow.workflowInstanceId, context);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
console.error(`Conversation message resume failed for workflow ${workflow.workflowInstanceId}`, error);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
117
154
|
async function workDetail(root, key, now) {
|
|
118
155
|
const id = decodeWorkItemId(key);
|
|
119
156
|
if (id === undefined)
|
|
@@ -131,6 +168,9 @@ async function workDetail(root, key, now) {
|
|
|
131
168
|
const pullRequest = (await Promise.all(resources.map((resource) => root.projections.read(pullRequestProjection.name, resource.resourceId)))).find((entry) => entry !== null && entry.value !== null);
|
|
132
169
|
const primary = workflows.find((value) => value.parentWorkflowInstanceId === undefined) ?? null;
|
|
133
170
|
const externalRef = await primaryExternalRef(root, work.workItemId, correlations, resources);
|
|
171
|
+
// Narrow test/application seams may provide a partial composition root while
|
|
172
|
+
// the production root always composes Conversations.
|
|
173
|
+
const conversation = await conversationForWorkItem(root, id);
|
|
134
174
|
const data = {
|
|
135
175
|
work: presentDetailWork(work, externalRef, runs),
|
|
136
176
|
resources: resources.map(presentResource(root.resolveResourceLink)),
|
|
@@ -146,6 +186,7 @@ async function workDetail(root, key, now) {
|
|
|
146
186
|
transcriptGroups: await transcriptGroups(root.transcriptStore, id, runs),
|
|
147
187
|
},
|
|
148
188
|
activities: presentPullRequest(pullRequest?.value),
|
|
189
|
+
conversation: presentConversation(conversation, root.config?.surfaces.api.conversationMessages.enabled === true),
|
|
149
190
|
};
|
|
150
191
|
const [projections, correlationFacts] = await Promise.all([
|
|
151
192
|
contributingProjections(root, id, resources, workflows, runs),
|
|
@@ -156,6 +197,35 @@ async function workDetail(root, key, now) {
|
|
|
156
197
|
meta: await projectionMeta(root.journal, [...projections, ...correlationFacts, ...(pullRequest == null ? [] : [pullRequest])], now()),
|
|
157
198
|
};
|
|
158
199
|
}
|
|
200
|
+
async function conversationForWorkItem(root, id) {
|
|
201
|
+
// Narrow test/application seams may provide a partial composition root while
|
|
202
|
+
// the production root always composes Conversations.
|
|
203
|
+
return (await root.conversations?.forWorkItem(id)) ?? null;
|
|
204
|
+
}
|
|
205
|
+
function presentConversation(conversation, canCreateEntries) {
|
|
206
|
+
return {
|
|
207
|
+
canCreateEntries,
|
|
208
|
+
entries: (conversation?.entries ?? []).map((entry) => ({
|
|
209
|
+
entryId: entry.entryId,
|
|
210
|
+
body: entry.deleted ? '' : entry.body,
|
|
211
|
+
occurredAt: entry.occurredAt,
|
|
212
|
+
origin: entry.origin.kind,
|
|
213
|
+
actorId: entry.origin.actorId,
|
|
214
|
+
deleted: entry.deleted,
|
|
215
|
+
representations: entry.representations,
|
|
216
|
+
...(entry.origin.kind === ConversationOriginKind.Agent
|
|
217
|
+
? { runId: entry.origin.runId, stage: entry.origin.stage }
|
|
218
|
+
: {}),
|
|
219
|
+
...(entry.origin.kind === ConversationOriginKind.External
|
|
220
|
+
? {
|
|
221
|
+
sourceAdapter: entry.origin.adapter,
|
|
222
|
+
sourceResourceId: entry.origin.resourceId,
|
|
223
|
+
sourceThreadId: entry.origin.threadId,
|
|
224
|
+
}
|
|
225
|
+
: {}),
|
|
226
|
+
})),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
159
229
|
function presentDetailWork(work, externalRef, runs) {
|
|
160
230
|
const latestAgentOutcome = runs[0]?.agent?.outcome;
|
|
161
231
|
return {
|
|
@@ -22,6 +22,7 @@ const execFile = promisify(nodeExecFile);
|
|
|
22
22
|
export function createSurfaceCliApplications(root, api, now) {
|
|
23
23
|
const runnerTick = new TickHost((options) => root.runnerPipeline.run(options));
|
|
24
24
|
const intakeHost = new IntakeHost((signal) => root.intakePipeline.run(signal));
|
|
25
|
+
const runnerIdleWait = createRunnerIdleWait(root, root.config.controlPlane?.resident);
|
|
25
26
|
const reportResidentError = (label) => async (error) => {
|
|
26
27
|
process.stderr.write(`Wake ${label} tick failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
27
28
|
};
|
|
@@ -36,15 +37,8 @@ export function createSurfaceCliApplications(root, api, now) {
|
|
|
36
37
|
// run of consecutive *errors* — as opposed to ordinary "no local work"
|
|
37
38
|
// idling — still backs off exponentially, or a live rate-limit window gets
|
|
38
39
|
// hammered every cycle instead of given a chance to recover.
|
|
39
|
-
const runnerResident = new ResidentHost(runnerTick,
|
|
40
|
-
|
|
41
|
-
return sleepUntilAbort(signal, nextPollBackoffMs(root.config.controlPlane.resident, consecutiveErrorTicks));
|
|
42
|
-
// Genuine idle (no errors): wait for the journal to actually change.
|
|
43
|
-
return consecutiveIdleTicks === 0
|
|
44
|
-
? Promise.resolve()
|
|
45
|
-
: root.journal.changeSignal.waitForChange(signal, JOURNAL_CHANGE_FALLBACK_MS);
|
|
46
|
-
}, reportResidentError('runner'));
|
|
47
|
-
const intakeResident = new ResidentHost(intakeHost, (signal, { consecutiveIdleTicks }) => sleepUntilAbort(signal, nextPollBackoffMs(root.config.controlPlane.resident, consecutiveIdleTicks)), reportResidentError('intake'));
|
|
40
|
+
const runnerResident = new ResidentHost(runnerTick, runnerIdleWait, reportResidentError('runner'));
|
|
41
|
+
const intakeResident = new ResidentHost(intakeHost, (signal, { consecutiveIdleTicks }) => sleepUntilAbort(signal, nextPollBackoffMs(root.config.controlPlane?.resident, consecutiveIdleTicks)), reportResidentError('intake'));
|
|
48
42
|
const servers = new Set();
|
|
49
43
|
const startHttp = createHttpStarter(root, api, servers);
|
|
50
44
|
return {
|
|
@@ -158,6 +152,19 @@ export function createSurfaceCliApplications(root, api, now) {
|
|
|
158
152
|
operational: createOperationalApplications(root),
|
|
159
153
|
};
|
|
160
154
|
}
|
|
155
|
+
export function createRunnerIdleWait(root, resident) {
|
|
156
|
+
let priorRevision = root.journal.changeSignal.revision();
|
|
157
|
+
return (signal, { consecutiveIdleTicks, consecutiveErrorTicks, }) => {
|
|
158
|
+
if (consecutiveErrorTicks > 0)
|
|
159
|
+
return sleepUntilAbort(signal, nextPollBackoffMs(resident, consecutiveErrorTicks));
|
|
160
|
+
const revision = root.journal.changeSignal.revision();
|
|
161
|
+
const journalChanged = revision !== priorRevision;
|
|
162
|
+
priorRevision = revision;
|
|
163
|
+
return consecutiveIdleTicks === 0 && journalChanged
|
|
164
|
+
? Promise.resolve()
|
|
165
|
+
: root.journal.changeSignal.waitForChange(signal, JOURNAL_CHANGE_FALLBACK_MS);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
161
168
|
export async function runProjectionPump(root, signal) {
|
|
162
169
|
while (!signal.aborted) {
|
|
163
170
|
try {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { selectConversationEvent } from '../contracts/events.js';
|
|
2
|
+
import { ConversationStreamKind } from '../contracts/streams.js';
|
|
3
|
+
import { applyConversationEvent } from '../domain/conversation.js';
|
|
4
|
+
export const conversationProjection = {
|
|
5
|
+
name: ConversationStreamKind.Conversation,
|
|
6
|
+
select(event) {
|
|
7
|
+
const owned = selectConversationEvent(event);
|
|
8
|
+
return owned === null ? null : { key: owned.stream.id };
|
|
9
|
+
},
|
|
10
|
+
initial: () => null,
|
|
11
|
+
project(previous, event) {
|
|
12
|
+
const owned = selectConversationEvent(event);
|
|
13
|
+
if (owned === null)
|
|
14
|
+
return previous;
|
|
15
|
+
return applyConversationEvent(previous, owned);
|
|
16
|
+
},
|
|
17
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { decodeConversationEvent, selectConversationEvent, } from '../contracts/events.js';
|
|
2
|
+
import { conversationStream } from '../contracts/streams.js';
|
|
3
|
+
import { foldConversation } from '../domain/conversation.js';
|
|
4
|
+
export class ConversationRepository {
|
|
5
|
+
journal;
|
|
6
|
+
constructor(journal) {
|
|
7
|
+
this.journal = journal;
|
|
8
|
+
}
|
|
9
|
+
async load(id) {
|
|
10
|
+
const events = await this.journal.readStream(conversationStream(id));
|
|
11
|
+
return {
|
|
12
|
+
sequence: events.length,
|
|
13
|
+
view: foldConversation(events
|
|
14
|
+
.map(selectConversationEvent)
|
|
15
|
+
.filter((event) => event !== null)),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
async append(id, expected, drafts) {
|
|
19
|
+
return (await this.journal.append(conversationStream(id), expected, drafts)).map(decodeConversationEvent);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createEventDraft, EventSourceKind, } from '../../kernel/index.js';
|
|
2
|
+
import { ConversationEventType, } from '../contracts/events.js';
|
|
3
|
+
import { conversationIdForWorkItem } from '../contracts/identifiers.js';
|
|
4
|
+
import { conversationStream } from '../contracts/streams.js';
|
|
5
|
+
import { applyConversationEvent } from '../domain/conversation.js';
|
|
6
|
+
import { ConversationRepository } from './conversation-repository.js';
|
|
7
|
+
// The public service surface deliberately keeps all command handlers adjacent.
|
|
8
|
+
// eslint-disable-next-line max-lines-per-function
|
|
9
|
+
export function createConversationService(journal) {
|
|
10
|
+
const repository = new ConversationRepository(journal);
|
|
11
|
+
const change = changeConversation(repository);
|
|
12
|
+
const create = createConversation(repository, change);
|
|
13
|
+
return {
|
|
14
|
+
create,
|
|
15
|
+
createForWorkItem: (workItemId, context) => create({ conversationId: conversationIdForWorkItem(workItemId), workItemId }, context),
|
|
16
|
+
async record(command, context) {
|
|
17
|
+
const existing = await repository.load(command.conversationId);
|
|
18
|
+
if (existing.view === null)
|
|
19
|
+
throw new Error(`Conversation ${command.conversationId} does not exist`);
|
|
20
|
+
if (existing.view.entries.some((entry) => entry.entryId === command.entryId))
|
|
21
|
+
return existing.view;
|
|
22
|
+
return change(command.conversationId, context, ConversationEventType.EntryRecorded, {
|
|
23
|
+
entryId: command.entryId,
|
|
24
|
+
body: command.body,
|
|
25
|
+
origin: command.origin,
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
async associateResource(command, context) {
|
|
29
|
+
const existing = await repository.load(command.conversationId);
|
|
30
|
+
if (existing.view === null)
|
|
31
|
+
throw new Error(`Conversation ${command.conversationId} does not exist`);
|
|
32
|
+
if (existing.view.resources.some((resource) => resource.resourceId === command.resourceId && resource.threadId === command.threadId))
|
|
33
|
+
return existing.view;
|
|
34
|
+
return change(command.conversationId, context, ConversationEventType.ResourceAssociated, {
|
|
35
|
+
resourceId: command.resourceId,
|
|
36
|
+
...(command.threadId === undefined ? {} : { threadId: command.threadId }),
|
|
37
|
+
});
|
|
38
|
+
},
|
|
39
|
+
async revise(command, context) {
|
|
40
|
+
const existing = await repository.load(command.conversationId);
|
|
41
|
+
if (existing.view === null ||
|
|
42
|
+
!existing.view.entries.some((entry) => entry.entryId === command.entryId))
|
|
43
|
+
throw new Error(`Conversation entry ${command.entryId} does not exist`);
|
|
44
|
+
return change(command.conversationId, context, ConversationEventType.EntryRevised, {
|
|
45
|
+
entryId: command.entryId,
|
|
46
|
+
body: command.body,
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
async tombstone(command, context) {
|
|
50
|
+
const existing = await repository.load(command.conversationId);
|
|
51
|
+
if (existing.view === null ||
|
|
52
|
+
!existing.view.entries.some((entry) => entry.entryId === command.entryId))
|
|
53
|
+
throw new Error(`Conversation entry ${command.entryId} does not exist`);
|
|
54
|
+
return change(command.conversationId, context, ConversationEventType.EntryTombstoned, {
|
|
55
|
+
entryId: command.entryId,
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
async recordRepresentation(command, context) {
|
|
59
|
+
const existing = await repository.load(command.conversationId);
|
|
60
|
+
const entry = existing.view?.entries.find((candidate) => candidate.entryId === command.entryId);
|
|
61
|
+
if (entry === undefined)
|
|
62
|
+
throw new Error(`Conversation entry ${command.entryId} does not exist`);
|
|
63
|
+
if (entry.representations.some((representation) => representation.resourceId === command.resourceId &&
|
|
64
|
+
representation.externalId === command.externalId))
|
|
65
|
+
return existing.view;
|
|
66
|
+
return change(command.conversationId, context, ConversationEventType.EntryRepresentationRecorded, {
|
|
67
|
+
entryId: command.entryId,
|
|
68
|
+
resourceId: command.resourceId,
|
|
69
|
+
externalId: command.externalId,
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
get: async (id) => (await repository.load(id)).view,
|
|
73
|
+
forWorkItem: async (workItemId) => (await repository.load(conversationIdForWorkItem(workItemId))).view,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function changeConversation(repository) {
|
|
77
|
+
return async (id, context, eventType, payload) => {
|
|
78
|
+
const loaded = await repository.load(id);
|
|
79
|
+
const draft = createEventDraft({
|
|
80
|
+
eventId: `${context.commandId}:${eventType}`,
|
|
81
|
+
eventType,
|
|
82
|
+
occurredAt: context.occurredAt,
|
|
83
|
+
correlationId: context.correlationId,
|
|
84
|
+
causationId: context.commandId,
|
|
85
|
+
actor: context.actor,
|
|
86
|
+
source: { kind: EventSourceKind.Internal, id: 'conversation-service' },
|
|
87
|
+
stream: conversationStream(id),
|
|
88
|
+
payload,
|
|
89
|
+
});
|
|
90
|
+
const [recorded] = await repository.append(id, loaded.sequence, [draft]);
|
|
91
|
+
const next = recorded === undefined ? null : applyConversationEvent(loaded.view, recorded);
|
|
92
|
+
if (next === null)
|
|
93
|
+
throw new Error(`Conversation ${id} was not created`);
|
|
94
|
+
return next;
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function createConversation(repository, change) {
|
|
98
|
+
return async (command, context) => {
|
|
99
|
+
const existing = await repository.load(command.conversationId);
|
|
100
|
+
return (existing.view ??
|
|
101
|
+
change(command.conversationId, context, ConversationEventType.Created, {
|
|
102
|
+
workItemId: command.workItemId,
|
|
103
|
+
}));
|
|
104
|
+
};
|
|
105
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { brandedStringSchema, eventEnvelopeSchema, } from '../../kernel/index.js';
|
|
3
|
+
import { workItemId } from '../../work/index.js';
|
|
4
|
+
import { conversationId } from './identifiers.js';
|
|
5
|
+
import { ConversationStreamKind } from './streams.js';
|
|
6
|
+
import { ConversationOriginKind } from './vocabulary.js';
|
|
7
|
+
export const ConversationEventType = {
|
|
8
|
+
Created: 'conversation.created',
|
|
9
|
+
ResourceAssociated: 'conversation.resource-associated',
|
|
10
|
+
EntryRecorded: 'conversation.entry-recorded',
|
|
11
|
+
EntryRevised: 'conversation.entry-revised',
|
|
12
|
+
EntryTombstoned: 'conversation.entry-tombstoned',
|
|
13
|
+
EntryRepresentationRecorded: 'conversation.entry-representation-recorded',
|
|
14
|
+
};
|
|
15
|
+
const stream = z
|
|
16
|
+
.object({
|
|
17
|
+
kind: z.literal(ConversationStreamKind.Conversation),
|
|
18
|
+
id: brandedStringSchema(conversationId),
|
|
19
|
+
})
|
|
20
|
+
.strict();
|
|
21
|
+
const origin = z.discriminatedUnion('kind', [
|
|
22
|
+
z
|
|
23
|
+
.object({ kind: z.literal(ConversationOriginKind.ControlPlane), actorId: z.string().min(1) })
|
|
24
|
+
.strict(),
|
|
25
|
+
z
|
|
26
|
+
.object({
|
|
27
|
+
kind: z.literal(ConversationOriginKind.Agent),
|
|
28
|
+
actorId: z.string().min(1),
|
|
29
|
+
runId: z.string().min(1),
|
|
30
|
+
stage: z.string().min(1).optional(),
|
|
31
|
+
})
|
|
32
|
+
.strict(),
|
|
33
|
+
z
|
|
34
|
+
.object({
|
|
35
|
+
kind: z.literal(ConversationOriginKind.External),
|
|
36
|
+
adapter: z.string().min(1),
|
|
37
|
+
actorId: z.string().min(1),
|
|
38
|
+
resourceId: z.string().min(1),
|
|
39
|
+
threadId: z.string().min(1),
|
|
40
|
+
messageId: z.string().min(1),
|
|
41
|
+
location: z
|
|
42
|
+
.object({
|
|
43
|
+
path: z.string().min(1),
|
|
44
|
+
line: z.number().int(),
|
|
45
|
+
side: z.enum(['LEFT', 'RIGHT']),
|
|
46
|
+
})
|
|
47
|
+
.strict()
|
|
48
|
+
.optional(),
|
|
49
|
+
})
|
|
50
|
+
.strict(),
|
|
51
|
+
]);
|
|
52
|
+
const schema = z.discriminatedUnion('eventType', [
|
|
53
|
+
eventEnvelopeSchema.extend({
|
|
54
|
+
eventType: z.literal(ConversationEventType.Created),
|
|
55
|
+
stream,
|
|
56
|
+
payload: z.object({ workItemId: brandedStringSchema(workItemId) }).strict(),
|
|
57
|
+
}),
|
|
58
|
+
eventEnvelopeSchema.extend({
|
|
59
|
+
eventType: z.literal(ConversationEventType.EntryRepresentationRecorded),
|
|
60
|
+
stream,
|
|
61
|
+
payload: z
|
|
62
|
+
.object({
|
|
63
|
+
entryId: z.string().min(1),
|
|
64
|
+
resourceId: z.string().min(1),
|
|
65
|
+
externalId: z.string().min(1),
|
|
66
|
+
})
|
|
67
|
+
.strict(),
|
|
68
|
+
}),
|
|
69
|
+
eventEnvelopeSchema.extend({
|
|
70
|
+
eventType: z.literal(ConversationEventType.ResourceAssociated),
|
|
71
|
+
stream,
|
|
72
|
+
payload: z
|
|
73
|
+
.object({ resourceId: z.string().min(1), threadId: z.string().min(1).optional() })
|
|
74
|
+
.strict(),
|
|
75
|
+
}),
|
|
76
|
+
eventEnvelopeSchema.extend({
|
|
77
|
+
eventType: z.literal(ConversationEventType.EntryRecorded),
|
|
78
|
+
stream,
|
|
79
|
+
payload: z.object({ entryId: z.string().min(1), body: z.string(), origin }).strict(),
|
|
80
|
+
}),
|
|
81
|
+
eventEnvelopeSchema.extend({
|
|
82
|
+
eventType: z.literal(ConversationEventType.EntryRevised),
|
|
83
|
+
stream,
|
|
84
|
+
payload: z.object({ entryId: z.string().min(1), body: z.string() }).strict(),
|
|
85
|
+
}),
|
|
86
|
+
eventEnvelopeSchema.extend({
|
|
87
|
+
eventType: z.literal(ConversationEventType.EntryTombstoned),
|
|
88
|
+
stream,
|
|
89
|
+
payload: z.object({ entryId: z.string().min(1) }).strict(),
|
|
90
|
+
}),
|
|
91
|
+
]);
|
|
92
|
+
export function decodeConversationEvent(event) {
|
|
93
|
+
const result = schema.safeParse(event);
|
|
94
|
+
if (!result.success)
|
|
95
|
+
throw new Error(`Invalid Conversation event ${event.eventId}: ${result.error.message}`);
|
|
96
|
+
return result.data;
|
|
97
|
+
}
|
|
98
|
+
export function selectConversationEvent(event) {
|
|
99
|
+
return event.eventType.startsWith('conversation.') ? decodeConversationEvent(event) : null;
|
|
100
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function conversationId(value) {
|
|
2
|
+
if (!/^conversation-[0-9a-hjkmnp-tv-z]{26}$/.test(value))
|
|
3
|
+
throw new Error('Invalid ConversationId');
|
|
4
|
+
return value;
|
|
5
|
+
}
|
|
6
|
+
export function conversationIdForWorkItem(workItemId) {
|
|
7
|
+
return conversationId(`conversation-${String(workItemId).slice('work-'.length)}`);
|
|
8
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|