Open History to see the last commit
1# Orchestration Interface Spec (Required State)
2
3Status: Required target architecture (not a description of current behavior).
4
5## 1. Identifier Schema (Branded)
6
7All identifiers are branded and never plain `string` in schema definitions.
8
9```ts
10const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
11const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
12const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
13const EventId = Schema.String.pipe(Schema.brand("EventId"));
14const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
15const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
16
17const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
18const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
19const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
20const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
21const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
22
23const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
24```
25
26Rules:
27
28- `ThreadId` is app/orchestration thread identity.
29- `ProviderThreadId` is provider runtime thread identity.
30- They are never assigned to each other.
31- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
32- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
33
34## 2. Client Commands (Domain Commands)
35
36All commands are sent through one RPC: `orchestration.dispatchCommand`.
37
38Output for every command: `DispatchResultSchema = { sequence: number }`.
39
40### 2.1 Client-Dispatchable Commands
41
421. `project.create`
43
44- Input:
45 - `commandId: CommandId`
46 - `projectId: ProjectId`
47 - `title: string`
48 - `workspaceRoot: string`
49 - `defaultModel?: string`
50 - `createdAt: IsoDateTime`
51- Output: `DispatchResult`
52
532. `project.meta.update`
54
55- Input:
56 - `commandId: CommandId`
57 - `projectId: ProjectId`
58 - optional `{ title, workspaceRoot, defaultModel, scripts }`
59- Output: `DispatchResult`
60
613. `project.delete`
62
63- Input: `commandId`, `projectId`
64- Output: `DispatchResult`
65
664. `thread.create`
67
68- Input:
69 - `commandId: CommandId`
70 - `threadId: ThreadId`
71 - `projectId: ProjectId`
72 - `title: string`
73 - `model: string`
74 - `branch: string | null`
75 - `worktreePath: string | null`
76 - `createdAt: IsoDateTime`
77- Output: `DispatchResult`
78
795. `thread.delete`
80
81- Input: `commandId`, `threadId`
82- Output: `DispatchResult`
83
846. `thread.meta.update`
85
86- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
87- Output: `DispatchResult`
88
897. `thread.turn.start`
90
91- Input:
92 - `commandId`
93 - `threadId`
94 - `message`:
95 - `messageId: MessageId`
96 - `role: "user"`
97 - `text: string`
98 - `attachments: ChatAttachment[]` (schema-shared)
99 - `model?: string`
100 - `effort?: string`
101 - `createdAt`
102- Output: `DispatchResult`
103
1048. `thread.turn.interrupt`
105
106- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
107- Output: `DispatchResult`
108
1099. `thread.approval.respond`
110
111- Input:
112 - `commandId`
113 - `threadId`
114 - `requestId: ApprovalRequestId`
115 - `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
116 - `createdAt`
117- Output: `DispatchResult`
118
11910. `thread.checkpoint.revert`
120
121- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
122- Output: `DispatchResult`
123
12411. `thread.session.stop`
125
126- Input: `commandId`, `threadId`, `createdAt`
127- Output: `DispatchResult`
128
129### 2.2 Internal-Only Commands (Not Client Dispatchable)
130
1311. `thread.session.set`
132
133- Server-owned projection update for session lifecycle.
134
1352. `thread.message.assistant.delta`
136
137- Server-owned incremental assistant content append.
138
1393. `thread.message.assistant.complete`
140
141- Server-owned assistant message completion marker.
142
1434. `thread.turn.diff.complete`
144
145- Server-owned checkpoint diff summary write.
146
1475. `thread.activity.append`
148
149- Server-owned activity feed append.
150
151## 3. Client RPC (Required)
152
153These are the required client-facing RPC methods.
154
1551. `orchestration.getSnapshot`
156
157- Input: `{}`
158- Output: `OrchestrationReadModel`
159
1602. `orchestration.dispatchCommand`
161
162- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
163- Output: `DispatchResult`
164
1653. `orchestration.getTurnDiff`
166
167- Input:
168 - `threadId: ThreadId`
169 - `fromTurnCount: number`
170 - `toTurnCount: number`
171- Output:
172 - `threadId: ThreadId`
173 - `fromTurnCount: number`
174 - `toTurnCount: number`
175 - `diff: string`
176
1774. `orchestration.replayEvents` (optional operational/debug API)
178
179- Input: `{ fromSequenceExclusive: number }`
180- Output: `OrchestrationEvent[]`
181
182### 3.1 RPC To Remove
183
184Remove from client boundary:
185
186- `providers.startSession`
187- `providers.sendTurn`
188- `providers.interruptTurn`
189- `providers.respondToRequest`
190- `providers.stopSession`
191- `providers.listCheckpoints`
192- `providers.getCheckpointDiff`
193- `providers.revertToCheckpoint`
194
195Rationale:
196
197- Session/turn/checkpoint control belongs to orchestrator command path.
198- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
199
200## 4. Server Orchestrator Command <-> Event Schemas
201
202Each command deterministically yields one or more domain events that are persisted to the event store.
203
2041. `project.create` -> `project.created`
2052. `project.meta.update` -> `project.meta-updated`
2063. `project.delete` -> `project.deleted`
2074. `thread.create` -> `thread.created`
2085. `thread.delete` -> `thread.deleted`
2096. `thread.meta.update` -> `thread.meta-updated`
2107. `thread.turn.start` ->
211
212- `thread.message-sent` (user message append)
213- `thread.turn-start-requested`
214- then (async side effect success) `thread.session-set` + provider-driven message/turn events
215
2168. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
2179. `thread.approval.respond` -> `thread.approval-response-requested`
21810. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
21911. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
220
221Internal command/event path:
222
223- `thread.session.set` -> `thread.session-set`
224- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
225- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
226- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
227- `thread.activity.append` -> `thread.activity-appended`
228
229## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
230
231Required mapping pipeline:
232
233`Raw Provider Event (adapter-specific)`
234-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
235-> `Internal Orchestration Command`
236-> `Orchestration Domain Event`
237
238### 5.1 Mapping Table for Codex Adapter
239
2401. Raw `thread/started`
241
242- Generic: `thread.started`
243- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
244- Domain event: `thread.session-set`
245
2462. Raw `turn/started`
247
248- Generic: `turn.started`
249- Internal command: `thread.session.set` (status `running`, active turn)
250- Domain event: `thread.session-set`
251
2523. Raw `item/agentMessage/delta`
253
254- Generic: `message.delta`
255- Internal command: `thread.message.assistant.delta`
256- Domain event: `thread.message-sent` (assistant, streaming)
257
2584. Raw `item/completed` (agent message)
259
260- Generic: `message.completed`
261- Internal command: `thread.message.assistant.complete`
262- Domain event: `thread.message-sent` (assistant, completed)
263
2645. Raw `turn/completed`
265
266- Generic: `turn.completed`
267- Internal commands:
268 - `thread.session.set` (ready/error)
269 - `thread.activity.append` (optional summary)
270- Domain events: `thread.session-set`, `thread.activity-appended`
271
2726. Raw approval request
273
274- Generic: `approval.requested`
275- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
276- Domain event: `thread.activity-appended`
277
2787. Raw approval decision ack
279
280- Generic: `approval.resolved`
281- Internal command: `thread.activity.append`
282- Domain event: `thread.activity-appended`
283
2848. Raw tool start/complete
285
286- Generic: `tool.started` / `tool.completed`
287- Internal command: `thread.activity.append`
288- Domain event: `thread.activity-appended`
289
2909. Checkpoint capture (server-produced)
291
292- Generic: `checkpoint.captured`
293- Internal command: `thread.turn.diff.complete`
294- Domain event: `thread.turn-diff-completed`
295
29610. Raw/runtime error
297
298- Generic: `runtime.error`
299- Internal commands:
300 - `thread.session.set` (status `error`)
301 - `thread.activity.append` (`tone=error`)
302- Domain events: `thread.session-set`, `thread.activity-appended`
303
304## 6. Schema Section (Boundary + Reuse)
305
306### 6.1 Shared Schemas (contracts package)
307
308Expose to both web and server:
309
310- `OrchestrationReadModelSchema`
311- `ClientOrchestrationCommandSchema`
312- `OrchestrationEventSchema`
313- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
314- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
315- Shared message/activity/checkpoint summary schemas used in snapshot
316
317### 6.2 Server-Internal Schemas
318
319Not exposed to web:
320
321- `InternalOrchestrationCommandSchema`
322- Adapter raw-event schemas and provider-specific payload schemas
323- Provider session directory records and persistence-only row schemas
324- Git service cache/query schemas (non-orchestration read model)
325
326### 6.3 Reuse Requirements
327
328- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
329- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
330- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
331- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
332
333## 7. Persistence Model (Required)
334
335This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
336
337### 7.1 Write-Side Persisted Tables
338
3391. `orchestration_events` (append-only event store)
340
341- `sequence: number` (global monotonic sequence, primary key)
342- `eventId: EventId` (unique)
343- `aggregateKind: "project" | "thread"`
344- `streamId: ProjectId | ThreadId` (aggregate stream id)
345- `streamVersion: number` (per-aggregate monotonic version)
346- `eventType: OrchestrationEventType`
347- `occurredAt: IsoDateTime`
348- `commandId: CommandId | null`
349- `causationEventId: EventId | null`
350- `correlationId: CommandId | null`
351- `actorKind: "client" | "server" | "provider"`
352- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
353- `metadata: OrchestrationEventMetadata`
354
3552. `orchestration_command_receipts` (idempotency + ack replay)
356
357- `commandId: CommandId` (primary key)
358- `aggregateKind: "project" | "thread"`
359- `aggregateId: ProjectId | ThreadId`
360- `acceptedAt: IsoDateTime`
361- `resultSequence: number`
362- `status: "accepted" | "rejected"`
363- `error: string | null`
364
3653. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
366
367- `threadId: ThreadId`
368- `fromTurnCount: number`
369- `toTurnCount: number`
370- `diff: string`
371- `createdAt: IsoDateTime`
372- unique key: `(threadId, fromTurnCount, toTurnCount)`
373
3744. `provider_session_runtime` (server-internal adapter resume state)
375
376- `providerSessionId: ProviderSessionId` (primary key)
377- `threadId: ThreadId`
378- `providerName: string`
379- `adapterKey: string`
380- `providerThreadId: ProviderThreadId | null`
381- `status: "starting" | "running" | "stopped" | "error"`
382- `lastSeenAt: IsoDateTime`
383- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
384- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
385
386### 7.2 Canonical Persisted Event Schema
387
388`OrchestrationPersistedEventSchema` (full envelope):
389
390```ts
391type OrchestrationPersistedEvent = {
392 sequence: number;
393 eventId: EventId;
394 aggregateKind: "project" | "thread";
395 streamId: ProjectId | ThreadId;
396 streamVersion: number;
397 eventType: OrchestrationEventType;
398 occurredAt: IsoDateTime;
399 commandId: CommandId | null;
400 causationEventId: EventId | null;
401 correlationId: CommandId | null;
402 actorKind: "client" | "server" | "provider";
403 payload: OrchestrationEventPayload;
404 metadata: {
405 providerSessionId?: ProviderSessionId;
406 providerThreadId?: ProviderThreadId;
407 providerTurnId?: ProviderTurnId;
408 providerItemId?: ProviderItemId;
409 adapterKey?: string;
410 requestId?: ApprovalRequestId;
411 ingestedAt?: IsoDateTime;
412 };
413};
414```
415
416Rules:
417
418- `payload` must be schema-discriminated by `eventType`.
419- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
420- `streamVersion` is concurrency guard for aggregate writes.
421
422### 7.3 Required Projected Tables (Read Models)
423
4241. `projection_projects`
425
426- `projectId: ProjectId` (primary key)
427- `title: string`
428- `workspaceRoot: string`
429- `defaultModel: string | null`
430- `scripts: ProjectScript[]`
431- `createdAt: IsoDateTime`
432- `updatedAt: IsoDateTime`
433- `deletedAt: IsoDateTime | null`
434
4352. `projection_threads`
436
437- `threadId: ThreadId` (primary key)
438- `projectId: ProjectId`
439- `title: string`
440- `model: string`
441- `branch: string | null`
442- `worktreePath: string | null`
443- `latestTurnId: TurnId | null`
444- `createdAt: IsoDateTime`
445- `updatedAt: IsoDateTime`
446- `deletedAt: IsoDateTime | null`
447
4483. `projection_thread_messages`
449
450- `messageId: MessageId` (primary key)
451- `threadId: ThreadId`
452- `turnId: TurnId | null`
453- `role: "user" | "assistant" | "system"`
454- `text: string`
455- `isStreaming: boolean`
456- `createdAt: IsoDateTime`
457- `updatedAt: IsoDateTime`
458
4594. `projection_thread_activities`
460
461- `activityId: EventId` (primary key; derived from source event)
462- `threadId: ThreadId`
463- `turnId: TurnId | null`
464- `tone: "info" | "tool" | "approval" | "error"`
465- `kind: string`
466- `summary: string`
467- `payload: JsonValue`
468- `createdAt: IsoDateTime`
469
4705. `projection_thread_sessions`
471
472- `threadId: ThreadId` (primary key)
473- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
474- `providerName: string | null`
475- `providerSessionId: ProviderSessionId | null`
476- `providerThreadId: ProviderThreadId | null`
477- `activeTurnId: TurnId | null`
478- `lastError: string | null`
479- `updatedAt: IsoDateTime`
480
4816. `projection_thread_turns`
482
483- `turnId: TurnId` (primary key)
484- `threadId: ThreadId`
485- `turnCount: number`
486- `status: "running" | "completed" | "interrupted" | "error"`
487- `userMessageId: MessageId | null`
488- `assistantMessageId: MessageId | null`
489- `startedAt: IsoDateTime`
490- `completedAt: IsoDateTime | null`
491
4927. `projection_checkpoints`
493
494- `threadId: ThreadId`
495- `turnId: TurnId`
496- `checkpointTurnCount: number`
497- `checkpointRef: CheckpointRef`
498- `status: "ready" | "missing" | "error"`
499- `files: JsonArray` (typed as file diff summary schema)
500- `assistantMessageId: MessageId | null`
501- `completedAt: IsoDateTime`
502- unique key: `(threadId, checkpointTurnCount)`
503
5048. `projection_pending_approvals`
505
506- `requestId: ApprovalRequestId` (primary key)
507- `threadId: ThreadId`
508- `turnId: TurnId | null`
509- `status: "pending" | "resolved"`
510- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
511- `createdAt: IsoDateTime`
512- `resolvedAt: IsoDateTime | null`
513
5149. `projection_state`
515
516- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
517- `lastAppliedSequence: number`
518- `updatedAt: IsoDateTime`
519
520Projection consistency rules:
521
522- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
523- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
524
525### 7.4 Snapshot and RPC Requirements
526
5271. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
5282. Snapshot must include `projects[]` from `projection_projects`.
5293. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
530
531- `turnId: TurnId`
532- `completedAt: IsoDateTime`
533- `status`
534- `files[]` (`path`, `kind`, `additions`, `deletions`)
535- `checkpointRef: CheckpointRef`
536- `assistantMessageId?: MessageId`
537- `checkpointTurnCount: number`
538
5394. Client does not require `listCheckpoints` RPC:
540
541- checkpoint list comes from snapshot projections
542- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
543
5445. Provider session identity is not a client routing key:
545
546- client acts on `ThreadId`
547- server resolves provider session internally via `projection_thread_sessions`
548
5496. `snapshotSequence` is derived from `projection_state`:
550
551- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
552
5537. Event subscription handoff contract:
554
555- client performs `getSnapshot` and reads `snapshotSequence`
556- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
557- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
558
559### 7.5 External Derived State (Non-Orchestration)
560
5611. Current git/worktree state is not projected from orchestration events.
5622. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
5633. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
5644. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
565
566### 7.6 Existing Repository Placement
567
5681. `ProjectsRepository`
569
570- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
571- Must not bypass command->event append path for mutations.
572
5732. `CheckpointsRepository`
574
575- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
576- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
577- Must not be an independent source of truth outside orchestration events.
578
5793. `ProviderSessionsRepository`
580
581- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
582- Not part of client RPC/domain aggregate boundary.