Integrate orchestration v2 with the application runtime
Retain the existing event-sourced application data plane for projects and shell state while making orchestration v2 the sole agent runtime. Adapt v2 events and receipts to the shared infrastructure and remove the v1 provider reactors.
This commit is contained in:
1 parent
8616a426b2
commit
f38dbfd84c
120 files changed
+3396
-33976
No files matched your search
@@ -4,6 +4,8 @@
|
||||
|
||||
Make Orchestration V2 the only orchestration system used by the server, web app, and mobile app. Preserve reusable platform infrastructure, remove V1 orchestration as each replacement becomes authoritative, and leave legacy persistence untouched until a separate state-migration plan is chosen.
|
||||
|
||||
In this plan, "Orchestration V2" means the agent orchestrator: provider sessions, runs, attempts, runtime requests, and external agent effects. It does not replace the application event-sourcing data plane. Projects and threads remain first-class application aggregates in one durable, globally ordered event source, and the shell remains a projection of that source.
|
||||
|
||||
The work is split into four sequential architectural shapes. Finish and validate one shape before beginning the next. These shapes are implementation checkpoints only: they exist to keep the work reviewable and easier to reason about, not to define rollout stages or supported compatibility windows.
|
||||
|
||||
There will be no users until after Shape 4 is complete. No intermediate shape is released, deployed for users, or expected to provide a usable mixed-version application. The first user-facing build uses the completed V2-only server and V2-native clients.
|
||||
@@ -12,6 +14,8 @@ Execution rules:
|
||||
|
||||
- Do not dual-write V1 and V2 state.
|
||||
- Do not mirror production commands into both runtimes.
|
||||
- Do not write core entity projection tables directly. Project and thread mutations commit application events first; projections are derived transactionally and remain replayable.
|
||||
- Preserve one application event cursor across project and thread shell changes.
|
||||
- Shapes 1 and 2 may keep V1 runnable as a development reference while V2 is completed through direct and replay-backed tests; this is not a supported user path or rollout strategy.
|
||||
- Shape 3 performs the backend hard cut and intentionally breaks the old client protocol.
|
||||
- Shape 4 updates web and mobile to the final protocol. No intermediate backend/client compatibility adapter is required because no users consume the intermediate shapes.
|
||||
@@ -299,20 +303,20 @@ Implementation status: complete. The production WebSocket/client cutover remains
|
||||
|
||||
Recreate the application behavior currently hidden in V1 reactors and WebSocket handlers using explicit V2 services and durable workflows.
|
||||
|
||||
### 1. Standalone project domain
|
||||
### 1. Project domain service
|
||||
|
||||
Create a `ProjectService` outside orchestration that owns:
|
||||
Create a `ProjectService` outside the agent orchestrator that owns project validation and application commands for:
|
||||
|
||||
- create, update, and delete
|
||||
- lookup by ID and workspace root
|
||||
- project list and snapshot
|
||||
- project lookup and snapshot queries over the event-derived projection
|
||||
- repository identity
|
||||
- setup-script configuration
|
||||
- favicon metadata
|
||||
- startup auto-bootstrap
|
||||
- project change subscriptions
|
||||
- project event planning
|
||||
|
||||
Reuse `projection_projects` initially instead of migrating project data. Stop treating project commands as orchestration commands.
|
||||
Reuse `projection_projects` initially instead of migrating project data. Project commands are application-domain commands, not agent-orchestrator commands, but they still commit to the shared application event source. `ProjectService` must not mutate `projection_projects` directly or own a standalone in-memory change stream.
|
||||
|
||||
Reuse existing project infrastructure:
|
||||
|
||||
@@ -519,9 +523,11 @@ Direct service-level integration tests must cover:
|
||||
|
||||
## Shape 3: V2-Only Backend Ownership
|
||||
|
||||
Implementation status: complete. The revision removes the V1 agent runtime, restores the existing application event-sourcing data plane, and installs V2 behind it instead of replacing it.
|
||||
|
||||
### Goal
|
||||
|
||||
Make V2 the only live orchestration runtime and remove V1 from the server.
|
||||
Make V2 the only live agent orchestration runtime while preserving the event-sourced application backend.
|
||||
|
||||
This shape intentionally breaks the old client protocol. That is acceptable because the shapes are implementation chunks and there are no users or releases between them.
|
||||
|
||||
@@ -529,8 +535,7 @@ This shape intentionally breaks the old client protocol. That is acceptable beca
|
||||
|
||||
Replace V1 and debug V2 endpoints with one production API containing:
|
||||
|
||||
- project snapshot and subscription
|
||||
- thread shell snapshot and subscription
|
||||
- one shell snapshot and subscription containing projects, active threads, and archived threads
|
||||
- archived-thread query and subscription
|
||||
- full thread projection snapshot and subscription
|
||||
- thread launch
|
||||
@@ -547,14 +552,21 @@ Replace V1 and debug V2 endpoints with one production API containing:
|
||||
|
||||
Use final unversioned method names. Do not retain compatibility aliases.
|
||||
|
||||
The shell stream uses one durable application-event cursor. Project and thread deltas cannot be split into independently ordered streams.
|
||||
|
||||
The project HTTP API may remain as a CLI command/query transport, but it must call the same event-sourced `ProjectService`. It is not a second project state source, and the WebSocket protocol must not expose a separate project snapshot or subscription.
|
||||
|
||||
Move the debug route's projection reducer into a shared pure client-runtime module. Backend behavior must not depend on debugger state.
|
||||
|
||||
### 2. Replace server runtime composition
|
||||
|
||||
In `apps/server/src/server.ts`:
|
||||
|
||||
- remove `OrchestrationLayerLive`
|
||||
- remove V1 reactor composition
|
||||
- remove the V1 agent reactors and provider runtime from the composition, but retain the existing `OrchestrationLayerLive` application event/projection infrastructure
|
||||
- retain `orchestration_events` and `orchestration_command_receipts` as the generic application event log and receipt store; their historical names do not make them V1-only tables
|
||||
- migrate the isolated `orchestration_v2_events` and `orchestration_v2_command_receipts` rows into that shared log, then treat the V2-specific tables as read-only legacy storage
|
||||
- preserve or rename the generic projection, replay, and shell-query infrastructure
|
||||
- remove only V1 agent/provider reactor composition
|
||||
- remove the V1 provider runtime layer
|
||||
- install V2 application services
|
||||
- install the durable effect worker
|
||||
@@ -573,6 +585,29 @@ In `apps/server/src/serverRuntimeStartup.ts`, establish this startup order:
|
||||
|
||||
No V1 reactor or provider-session reaper starts.
|
||||
|
||||
The resulting ownership boundary is:
|
||||
|
||||
```text
|
||||
application commands
|
||||
-> application event transaction
|
||||
-> project/shell/thread projections
|
||||
-> Agent Orchestrator V2 durable effects
|
||||
-> provider execution
|
||||
-> additional application events
|
||||
```
|
||||
|
||||
The event transaction remains responsible for ordered append, command idempotency, projection updates, effect-outbox enqueue, and the committed sequence.
|
||||
|
||||
This is an integration, not a replacement data plane. Restore and adapt the existing components:
|
||||
|
||||
- `OrchestrationEventStore` remains the one durable event source and gains V2 thread-event codecs; V2 `EventStore` is an adapter over it, not a second SQL implementation.
|
||||
- `OrchestrationCommandReceiptRepository` remains the command-idempotency store; the V2 receipt service adapts to it.
|
||||
- `OrchestrationEngine` retains its serialized project-command transaction, decider, and projector path. Its production command surface is narrowed to project commands instead of restoring V1 agent execution.
|
||||
- `OrchestrationProjectionPipeline` remains responsible for project projection replay and cursor advancement.
|
||||
- `ProjectionSnapshotQuery` remains the source of project shell rows and is composed with V2 thread projections for the unified shell.
|
||||
|
||||
Do not introduce parallel `ApplicationEventStore`, `ProjectProjection`, or `ApplicationShellService` replacements for these components.
|
||||
|
||||
### 3. Update backend consumers
|
||||
|
||||
Rewrite or redirect:
|
||||
@@ -589,7 +624,7 @@ Rewrite or redirect:
|
||||
|
||||
Delete:
|
||||
|
||||
- `apps/server/src/orchestration/**`
|
||||
- V1-only files under `apps/server/src/orchestration/**`, while keeping the existing event transaction, project decider/projector, projection pipeline, and snapshot query
|
||||
- V1 orchestration HTTP routes
|
||||
- V1 WebSocket handlers
|
||||
- V1 reactor and startup wiring
|
||||
@@ -599,9 +634,11 @@ Delete:
|
||||
- V1 high-level provider adapters and services after import analysis confirms no remaining consumers
|
||||
- corresponding tests and duplicate service interfaces
|
||||
|
||||
Do not delete infrastructure merely because it lived under the old `orchestration` namespace. Retain or relocate code whose responsibility is generic application event append/replay, command receipts, project/shell projection, cursor catch-up, or projection rebuild.
|
||||
|
||||
Retain low-level provider infrastructure imported by V2, including provider instance configuration, SDK and ACP transports, environment setup, logging, and runtime utilities.
|
||||
|
||||
Add an import-boundary test preventing production code from importing the deleted V1 namespace.
|
||||
Add an import-boundary test preventing production code from importing the deleted V1 agent reactors and provider services. Imports of the retained application event/projection services are expected.
|
||||
|
||||
### 5. Preserve legacy storage
|
||||
|
||||
@@ -621,6 +658,9 @@ Add backend integration coverage for:
|
||||
- startup ordering and command readiness
|
||||
- V2-only provider session creation
|
||||
- shell and thread snapshot reconnects
|
||||
- project and thread changes sharing one ordered shell cursor
|
||||
- project command idempotency and projection replay
|
||||
- proof that project commands cannot bypass the application event store
|
||||
- CLI project operations
|
||||
- MCP send, wait, interrupt, fork, and merge flows
|
||||
- agent-awareness output
|
||||
@@ -633,9 +673,11 @@ Add backend integration coverage for:
|
||||
|
||||
- Server startup does not construct any V1 orchestration or provider runtime.
|
||||
- Every production orchestration endpoint targets V2.
|
||||
- Projects and threads are committed through one application event source and exposed through one shell stream.
|
||||
- `projection_projects` and core thread projections are only changed by event projection/rebuild code.
|
||||
- CLI, MCP, checkpoints, awareness, startup, and telemetry use V2.
|
||||
- No production import references `apps/server/src/orchestration`.
|
||||
- No writes occur to legacy orchestration tables.
|
||||
- No production import references the deleted V1 agent reactors, provider runtime ingestion, provider command handling, or session-reaper services.
|
||||
- New writes go only to the retained application event/receipt tables and event-derived projections; the retired V1-only projection/runtime tables and isolated `orchestration_v2_*` event/receipt tables remain untouched.
|
||||
- Backend integration and restart tests pass.
|
||||
- Old clients are expected to be incompatible at this boundary.
|
||||
- `vp check`, `vp run typecheck`, and `vp test` pass.
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.make(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const codexTurnTextFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "request.opened",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "request.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,602 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
|
||||
import * as NodeHttp from "node:http";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentOrchestrationHttpApi,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as HttpApi from "effect/unstable/httpapi/HttpApi";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli, makeCli } from "./bin.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
|
||||
import {
|
||||
makePersistedServerRuntimeState,
|
||||
persistServerRuntimeState,
|
||||
} from "./serverRuntimeState.ts";
|
||||
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
|
||||
|
||||
const connectCli = makeCli({ cloudEnabled: true });
|
||||
const noConnectCli = makeCli({ cloudEnabled: false });
|
||||
const runCli = (args: ReadonlyArray<string>, command = cli) =>
|
||||
Command.runWith(command, { version: "0.0.0" })(args);
|
||||
const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
|
||||
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
||||
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
|
||||
|
||||
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* effect;
|
||||
const output =
|
||||
(yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
|
||||
"";
|
||||
return { result, output };
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
|
||||
|
||||
const makeCliTestServerConfig = (baseDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
|
||||
return {
|
||||
logLevel: "Info",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: "127.0.0.1",
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
devAllowedOrigins: [],
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
});
|
||||
|
||||
const makeProjectPersistenceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
|
||||
Layer.mergeAll(
|
||||
OrchestrationLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
),
|
||||
WorkspacePaths.layer,
|
||||
).pipe(Layer.provideMerge(NodeServices.layer), Layer.provide(ServerConfig.layer(config)));
|
||||
|
||||
const readPersistedSnapshot = (baseDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeCliTestServerConfig(baseDir);
|
||||
return yield* Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
|
||||
});
|
||||
|
||||
const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeCliTestServerConfig(baseDir);
|
||||
const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
|
||||
Layer.provide(orchestrationHttpApiLayer),
|
||||
Layer.provide(environmentAuthenticatedAuthLayer),
|
||||
);
|
||||
const appLayer = HttpRouter.serve(routesLayer, {
|
||||
disableListenLog: true,
|
||||
disableLogger: true,
|
||||
}).pipe(
|
||||
Layer.provideMerge(
|
||||
EnvironmentAuth.layer.pipe(
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provide(ServerSecretStore.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(makeProjectPersistenceLayer(config)),
|
||||
Layer.provideMerge(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(ServerConfig.layer(config)),
|
||||
);
|
||||
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* HttpServer.HttpServer;
|
||||
const address = server.address;
|
||||
if (typeof address === "string" || !("port" in address)) {
|
||||
assert.fail(`Expected TCP address, got ${address}`);
|
||||
}
|
||||
yield* persistServerRuntimeState({
|
||||
path: config.serverRuntimeStatePath,
|
||||
state: yield* makePersistedServerRuntimeState({
|
||||
config,
|
||||
port: address.port,
|
||||
}),
|
||||
});
|
||||
return yield* run();
|
||||
}).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("accepts canonical --no-<flag> boolean negation", () =>
|
||||
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "InvalidValue") {
|
||||
assert.fail(`Expected InvalidValue, got ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.option, "log-level");
|
||||
assert.equal(error.value, "Debug");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects connect commands when public configuration is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "ShowHelp") {
|
||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(error.commandPath, ["t3", "connect"]);
|
||||
assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
|
||||
|
||||
const output = (yield* TestConsole.errorLines).join("\n");
|
||||
assert.include(output, "ERROR");
|
||||
assert.include(output, "missing T3 Connect public configuration");
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
|
||||
);
|
||||
|
||||
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
|
||||
|
||||
assert.include(output, "Manage the T3 Code background service.");
|
||||
assert.include(output, "install");
|
||||
assert.include(output, "uninstall");
|
||||
assert.include(output, "update");
|
||||
assert.include(output, "status");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports fresh headless connect state without requiring local configuration", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-test-"),
|
||||
);
|
||||
const { output } = yield* captureStdout(
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
|
||||
const status = JSON.parse(output) as {
|
||||
readonly desired: boolean;
|
||||
readonly authenticated: boolean;
|
||||
readonly linked: boolean;
|
||||
readonly cloudUserId: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
};
|
||||
|
||||
assert.equal(status.desired, false);
|
||||
assert.equal(status.authenticated, false);
|
||||
assert.equal(status.linked, false);
|
||||
assert.equal(status.cloudUserId, null);
|
||||
assert.equal(status.relayUrl, null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports actionable human-readable headless connect state", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-human-test-"),
|
||||
);
|
||||
const { output } = yield* captureStdout(
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.include(output, "T3 Connect\n Exposure: disabled");
|
||||
assert.include(output, " Authorization: missing");
|
||||
assert.include(output, " Environment link: not provisioned");
|
||||
assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts the --headless login override without enabling access", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),
|
||||
);
|
||||
const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
|
||||
NodeFS.mkdirSync(secretsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"),
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
|
||||
JSON.stringify({
|
||||
accessToken: "access-token",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
);
|
||||
|
||||
const login = yield* captureStdout(
|
||||
runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]),
|
||||
);
|
||||
const status = yield* captureStdout(
|
||||
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
|
||||
const decoded = JSON.parse(status.output) as {
|
||||
readonly desired: boolean;
|
||||
readonly authenticated: boolean;
|
||||
};
|
||||
|
||||
assert.equal(login.output, "✓ Signed in");
|
||||
assert.isFalse(decoded.desired);
|
||||
assert.isTrue(decoded.authenticated);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("disables headless connect without a running server", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-unlink-test-"),
|
||||
);
|
||||
const { output } = yield* captureStdout(
|
||||
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(output, "T3 Connect is disabled locally.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-logout-test-"),
|
||||
);
|
||||
const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
|
||||
const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin");
|
||||
NodeFS.mkdirSync(secretsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(tokenPath, "invalid persisted token");
|
||||
|
||||
const { output } = yield* captureStdout(
|
||||
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
output,
|
||||
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
|
||||
);
|
||||
assert.isFalse(NodeFS.existsSync(tokenPath));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-pairing-test-"),
|
||||
);
|
||||
|
||||
const createdOutput = yield* captureStdout(
|
||||
runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
const created = JSON.parse(createdOutput.output) as {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
};
|
||||
const listedOutput = yield* captureStdout(
|
||||
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
|
||||
readonly id: string;
|
||||
readonly credential?: string;
|
||||
}>;
|
||||
|
||||
assert.equal(typeof created.id, "string");
|
||||
assert.equal(typeof created.credential, "string");
|
||||
assert.equal(created.credential.length > 0, true);
|
||||
assert.equal(listed.length, 1);
|
||||
assert.equal(listed[0]?.id, created.id);
|
||||
assert.equal("credential" in (listed[0] ?? {}), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("executes auth session subcommands and redacts secrets from list output", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-session-test-"),
|
||||
);
|
||||
|
||||
const issuedOutput = yield* captureStdout(
|
||||
runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
const issued = JSON.parse(issuedOutput.output) as {
|
||||
readonly sessionId: string;
|
||||
readonly token: string;
|
||||
readonly scopes: ReadonlyArray<string>;
|
||||
};
|
||||
const listedOutput = yield* captureStdout(
|
||||
runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
|
||||
readonly sessionId: string;
|
||||
readonly token?: string;
|
||||
readonly scopes: ReadonlyArray<string>;
|
||||
}>;
|
||||
|
||||
assert.equal(typeof issued.sessionId, "string");
|
||||
assert.equal(typeof issued.token, "string");
|
||||
assert.deepEqual(issued.scopes, [
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
"relay:read",
|
||||
"access:read",
|
||||
"access:write",
|
||||
"relay:write",
|
||||
]);
|
||||
assert.equal(listed.length, 1);
|
||||
assert.equal(listed[0]?.sessionId, issued.sessionId);
|
||||
assert.deepEqual(listed[0]?.scopes, [
|
||||
"orchestration:read",
|
||||
"orchestration:operate",
|
||||
"terminal:operate",
|
||||
"review:write",
|
||||
"relay:read",
|
||||
"access:read",
|
||||
"access:write",
|
||||
"relay:write",
|
||||
]);
|
||||
assert.equal("token" in (listed[0] ?? {}), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid ttl values before running auth commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "ShowHelp") {
|
||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
|
||||
const ttlError = error.errors[0] as CliError.CliError | undefined;
|
||||
if (!ttlError || ttlError._tag !== "InvalidValue") {
|
||||
assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
|
||||
}
|
||||
assert.equal(ttlError.option, "ttl");
|
||||
assert.equal(ttlError.value, "soon");
|
||||
assert.isTrue(ttlError.message.includes("Invalid duration"));
|
||||
assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-offline-test-"),
|
||||
);
|
||||
const workspaceRoot = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-workspace-"),
|
||||
);
|
||||
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"add",
|
||||
workspaceRoot,
|
||||
"--title",
|
||||
"Alpha",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const afterAdd = yield* readPersistedSnapshot(baseDir);
|
||||
const addedProject = afterAdd.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
assert.isTrue(addedProject !== undefined);
|
||||
assert.equal(addedProject?.title, "Alpha");
|
||||
|
||||
yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
|
||||
const afterRename = yield* readPersistedSnapshot(baseDir);
|
||||
const renamedProject = afterRename.projects.find(
|
||||
(project) => project.id === addedProject?.id,
|
||||
);
|
||||
assert.equal(renamedProject?.title, "Beta");
|
||||
assert.equal(renamedProject?.deletedAt, null);
|
||||
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"remove",
|
||||
addedProject?.id ?? "",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const afterRemove = yield* readPersistedSnapshot(baseDir);
|
||||
const removedProject = afterRemove.projects.find(
|
||||
(project) => project.id === addedProject?.id,
|
||||
);
|
||||
assert.isTrue((removedProject?.deletedAt ?? null) !== null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("force removes projects that still contain threads", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-test-"),
|
||||
);
|
||||
const workspaceRoot = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-workspace-"),
|
||||
);
|
||||
|
||||
yield* runCliWithRuntime(["project", "add", workspaceRoot, "--base-dir", baseDir]);
|
||||
const afterAdd = yield* readPersistedSnapshot(baseDir);
|
||||
const project = afterAdd.projects.find(
|
||||
(candidate) => candidate.workspaceRoot === workspaceRoot && candidate.deletedAt === null,
|
||||
);
|
||||
assert.isTrue(project !== undefined);
|
||||
|
||||
const config = yield* makeCliTestServerConfig(baseDir);
|
||||
yield* Effect.gen(function* () {
|
||||
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
yield* engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-cli-force-remove-thread"),
|
||||
threadId: ThreadId.make("thread-cli-force-remove"),
|
||||
projectId: project!.id,
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: DateTime.formatIso(yield* DateTime.now),
|
||||
});
|
||||
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
|
||||
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"remove",
|
||||
project!.id,
|
||||
"--force",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const afterRemove = yield* readPersistedSnapshot(baseDir);
|
||||
assert.isTrue(
|
||||
(afterRemove.projects.find((candidate) => candidate.id === project!.id)?.deletedAt ??
|
||||
null) !== null,
|
||||
);
|
||||
assert.isTrue(
|
||||
(afterRemove.threads.find((thread) => thread.id === "thread-cli-force-remove")?.deletedAt ??
|
||||
null) !== null,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes project commands through a running server when runtime state is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-test-"),
|
||||
);
|
||||
const workspaceRoot = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-workspace-"),
|
||||
);
|
||||
|
||||
yield* withLiveProjectCliServer(baseDir, () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"add",
|
||||
workspaceRoot,
|
||||
"--title",
|
||||
"Live Project",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const addedProject = readModel.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
assert.isTrue(addedProject !== undefined);
|
||||
assert.equal(addedProject?.title, "Live Project");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects dev-url on project commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceRoot = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
|
||||
);
|
||||
const error = yield* runCliWithRuntime([
|
||||
"project",
|
||||
"add",
|
||||
workspaceRoot,
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
]).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "ShowHelp") {
|
||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
|
||||
const optionError = error.errors[0] as CliError.CliError | undefined;
|
||||
if (!optionError || optionError._tag !== "UnrecognizedOption") {
|
||||
assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
|
||||
}
|
||||
assert.equal(optionError.option, "--dev-url");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,436 +1,158 @@
|
||||
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { it } from "@effect/vitest";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
CheckpointRef,
|
||||
CheckpointScopeId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
|
||||
import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
|
||||
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
import { CheckpointThreadNotFoundError } from "./Errors.ts";
|
||||
import {
|
||||
CheckpointRefUnavailableError,
|
||||
CheckpointThreadNotFoundError,
|
||||
CheckpointTurnRangeUnavailableError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
function makeThreadCheckpointContext(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): ProjectionSnapshotQuery.ProjectionThreadCheckpointContext {
|
||||
const threadId = ThreadId.make("thread:checkpoint-diff-v2");
|
||||
const firstRunId = RunId.make("run:checkpoint-diff-v2:1");
|
||||
const secondRunId = RunId.make("run:checkpoint-diff-v2:2");
|
||||
const firstScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:1");
|
||||
const secondScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:2");
|
||||
const secondRef = CheckpointRef.make("refs/t3/test/second");
|
||||
|
||||
function makeProjection(): OrchestrationV2ThreadProjection {
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
worktreePath: input.worktreePath,
|
||||
runs: [
|
||||
{ id: firstRunId, ordinal: 1 },
|
||||
{ id: secondRunId, ordinal: 2 },
|
||||
],
|
||||
checkpointScopes: [
|
||||
{ id: firstScopeId, runId: firstRunId, kind: "root_run", cwd: "/repo" },
|
||||
{ id: secondScopeId, runId: secondRunId, kind: "root_run", cwd: "/repo" },
|
||||
],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.make("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
scopeId: secondScopeId,
|
||||
appRunOrdinal: 2,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
ref: secondRef,
|
||||
},
|
||||
],
|
||||
};
|
||||
} as unknown as OrchestrationV2ThreadProjection;
|
||||
}
|
||||
|
||||
describe("CheckpointDiffQuery.layer", () => {
|
||||
it.effect("uses the narrow full-thread context lookup for all-turns diffs", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-full-thread");
|
||||
const threadId = ThreadId.make("thread-full-thread");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
|
||||
let getThreadCheckpointContextCalls = 0;
|
||||
let getFullThreadDiffContextCalls = 0;
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "full thread diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () =>
|
||||
Effect.sync(() => {
|
||||
getThreadCheckpointContextCalls += 1;
|
||||
return Option.none();
|
||||
}),
|
||||
getFullThreadDiffContext: () =>
|
||||
Effect.sync(() => {
|
||||
getFullThreadDiffContextCalls += 1;
|
||||
return Option.some({
|
||||
threadId,
|
||||
projectId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: "/tmp/worktree",
|
||||
latestCheckpointTurnCount: 4,
|
||||
toCheckpointRef,
|
||||
});
|
||||
}),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getFullThreadDiff({
|
||||
threadId,
|
||||
toTurnCount: 4,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(getThreadCheckpointContextCalls).toBe(0);
|
||||
expect(getFullThreadDiffContextCalls).toBe(1);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/worktree",
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 4,
|
||||
diff: "full thread diff patch",
|
||||
});
|
||||
}),
|
||||
function makeLayer(input: {
|
||||
readonly projection: Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorProjectionError>;
|
||||
readonly diffCheckpoints?: CheckpointStore.CheckpointStore["Service"]["diffCheckpoints"];
|
||||
}) {
|
||||
return CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(ThreadManagement.ThreadManagementService)({
|
||||
getThreadProjection: () => input.projection,
|
||||
}),
|
||||
Layer.mock(CheckpointStore.CheckpointStore)({
|
||||
diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("computes diffs using canonical turn-0 checkpoint refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
diff: "diff patch",
|
||||
});
|
||||
}),
|
||||
it.effect("computes V2 run diffs from projected checkpoint scopes", () => {
|
||||
const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) =>
|
||||
Effect.succeed("diff --git a/file b/file"),
|
||||
);
|
||||
const layer = makeLayer({ projection: Effect.succeed(makeProjection()), diffCheckpoints });
|
||||
|
||||
it.effect("defaults to hide whitespace changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-default-whitespace");
|
||||
const threadId = ThreadId.make("thread-default-whitespace");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const result = yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 });
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not preflight checkpoint refs before diffing", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectId = ProjectId.make("project-no-preflight");
|
||||
const threadId = ThreadId.make("thread-no-preflight");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
let hasCheckpointRefCallCount = 0;
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () =>
|
||||
Effect.sync(() => {
|
||||
hasCheckpointRefCallCount += 1;
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed("diff patch"),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(hasCheckpointRefCallCount).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails when the thread is missing from the snapshot", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQuery.layer.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getArchivedShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer), Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(CheckpointThreadNotFoundError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "CheckpointDiffQuery.getTurnDiff",
|
||||
threadId,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
"Checkpoint invariant violation in CheckpointDiffQuery.getTurnDiff: Thread 'thread-missing' not found.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
assert.deepEqual(result, {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 2,
|
||||
diff: "diff --git a/file b/file",
|
||||
});
|
||||
assert.deepEqual(diffCheckpoints.mock.calls[0]?.[0], {
|
||||
cwd: "/repo",
|
||||
fromCheckpointRef: checkpointRefForScopeOrdinal({
|
||||
scopeId: firstScopeId,
|
||||
ordinalWithinScope: 0,
|
||||
}),
|
||||
toCheckpointRef: secondRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("preserves the typed missing-thread error contract", () => {
|
||||
const layer = makeLayer({
|
||||
projection: Effect.fail(new OrchestratorProjectionError({ threadId })),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const error = yield* query
|
||||
.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CheckpointThreadNotFoundError);
|
||||
assert.deepEqual(
|
||||
{ operation: error.operation, threadId: error.threadId },
|
||||
{ operation: "CheckpointDiffQuery.getTurnDiff", threadId },
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("preserves the typed unavailable-range error contract", () => {
|
||||
const layer = makeLayer({ projection: Effect.succeed(makeProjection()) });
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const error = yield* query
|
||||
.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 3 })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CheckpointTurnRangeUnavailableError);
|
||||
assert.deepEqual(
|
||||
{
|
||||
requestedTurnCount: error.requestedTurnCount,
|
||||
availableTurnCount: error.availableTurnCount,
|
||||
},
|
||||
{ requestedTurnCount: 3, availableTurnCount: 2 },
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("preserves the typed missing-baseline-ref error contract", () => {
|
||||
const projection = makeProjection();
|
||||
const layer = makeLayer({
|
||||
projection: Effect.succeed({
|
||||
...projection,
|
||||
checkpointScopes: projection.checkpointScopes.filter((scope) => scope.id !== firstScopeId),
|
||||
}),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
|
||||
const error = yield* query
|
||||
.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, CheckpointRefUnavailableError);
|
||||
assert.deepEqual(
|
||||
{ checkpoint: error.checkpoint, turnCount: error.turnCount },
|
||||
{ checkpoint: "from", turnCount: 0 },
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -7,7 +7,6 @@
|
||||
* @module CheckpointDiffQuery
|
||||
*/
|
||||
import {
|
||||
type CheckpointRef,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
type OrchestrationGetFullThreadDiffInput,
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
@@ -18,19 +17,18 @@ import {
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
|
||||
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import {
|
||||
CheckpointDiffResultInvalidError,
|
||||
CheckpointRefUnavailableError,
|
||||
CheckpointThreadNotFoundError,
|
||||
CheckpointTurnRangeUnavailableError,
|
||||
CheckpointWorkspacePathMissingError,
|
||||
type CheckpointServiceError,
|
||||
} from "./Errors.ts";
|
||||
import type { CheckpointServiceError } from "./Errors.ts";
|
||||
import { checkpointRefForThreadTurn } from "./Utils.ts";
|
||||
import * as CheckpointStore from "./CheckpointStore.ts";
|
||||
|
||||
/** Service tag for checkpoint diff queries. */
|
||||
@@ -76,7 +74,7 @@ function buildTurnDiffResult(
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const threads = yield* ThreadManagement.ThreadManagementService;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
|
||||
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
@@ -91,12 +89,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff: "",
|
||||
};
|
||||
const emptyDiff = buildTurnDiffResult(input, "");
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
operation,
|
||||
@@ -106,18 +99,21 @@ export const make = Effect.gen(function* () {
|
||||
return emptyDiff;
|
||||
}
|
||||
|
||||
const threadContext = yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(input.threadId)
|
||||
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointThreadNotFoundError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const maxTurnCount = threadContext.value.checkpoints.reduce(
|
||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||
const projection = yield* threads.getThreadProjection(input.threadId).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new CheckpointThreadNotFoundError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("checkpoint.turnDiff.lookupProjection"),
|
||||
);
|
||||
const readyCheckpoints = projection.checkpoints.filter(
|
||||
(checkpoint) => checkpoint.status === "ready" && checkpoint.appRunOrdinal !== null,
|
||||
);
|
||||
const maxTurnCount = readyCheckpoints.reduce(
|
||||
(max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0),
|
||||
0,
|
||||
);
|
||||
if (input.toTurnCount > maxTurnCount) {
|
||||
@@ -129,33 +125,10 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const fromCheckpointRef =
|
||||
input.fromTurnCount === 0
|
||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||
: threadContext.value.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
checkpoint: "from",
|
||||
});
|
||||
}
|
||||
|
||||
const toCheckpointRef = threadContext.value.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
const toCheckpoint = readyCheckpoints.find(
|
||||
(checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount,
|
||||
);
|
||||
if (toCheckpoint === undefined) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
@@ -164,11 +137,46 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const toScope = projection.checkpointScopes.find(
|
||||
(scope) => scope.id === toCheckpoint.scopeId,
|
||||
);
|
||||
if (toScope === undefined) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
const fromCheckpointRef =
|
||||
input.fromTurnCount === 0
|
||||
? (() => {
|
||||
const firstRun = projection.runs.find((run) => run.ordinal === 1);
|
||||
const firstScope = projection.checkpointScopes.find(
|
||||
(scope) => scope.runId === firstRun?.id && scope.kind === "root_run",
|
||||
);
|
||||
return firstScope === undefined
|
||||
? undefined
|
||||
: checkpointRefForScopeOrdinal({
|
||||
scopeId: firstScope.id,
|
||||
ordinalWithinScope: 0,
|
||||
});
|
||||
})()
|
||||
: readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
|
||||
?.ref;
|
||||
if (fromCheckpointRef === undefined) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
checkpoint: "from",
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
cwd: toScope.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
toCheckpointRef: toCheckpoint.ref,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
@@ -217,61 +225,12 @@ export const make = Effect.gen(function* () {
|
||||
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
|
||||
}
|
||||
|
||||
const threadContext = yield* projectionSnapshotQuery
|
||||
.getFullThreadDiffContext(input.threadId, input.toTurnCount)
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
|
||||
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* new CheckpointThreadNotFoundError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
|
||||
return yield* new CheckpointTurnRangeUnavailableError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
requestedTurnCount: input.toTurnCount,
|
||||
availableTurnCount: threadContext.value.latestCheckpointTurnCount,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointWorkspacePathMissingError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
|
||||
if (!threadContext.value.toCheckpointRef) {
|
||||
return yield* new CheckpointRefUnavailableError({
|
||||
operation,
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
checkpoint: "to",
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
|
||||
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
})
|
||||
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
|
||||
|
||||
const turnDiff = buildTurnDiffResult(
|
||||
{
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
},
|
||||
diff,
|
||||
);
|
||||
const turnDiff = yield* getTurnDiff({
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointDiffResultInvalidError({
|
||||
operation,
|
||||
|
||||
@@ -1,17 +1,89 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - CLI integration uses temporary Node paths.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as References from "effect/References";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "../bin.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import {
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerRequestError,
|
||||
projectCommandErrorFromLiveServerRequest,
|
||||
} from "./project.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
const runCli = (args: ReadonlyArray<string>) =>
|
||||
Command.runWith(cli, { version: "0.0.0" })(args).pipe(Effect.provide(CliRuntimeLayer));
|
||||
|
||||
const makeConfig = (baseDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
|
||||
return {
|
||||
logLevel: "Info",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: "127.0.0.1",
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
} satisfies ServerConfig.ServerConfig["Service"];
|
||||
});
|
||||
|
||||
const readProjects = (baseDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeConfig(baseDir);
|
||||
const layer = ProjectServiceLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(ProjectFaviconResolver.layer),
|
||||
Layer.provideMerge(WorkspacePaths.layer),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(ServerConfig.layer(config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
|
||||
);
|
||||
return yield* ProjectService.ProjectService.pipe(
|
||||
Effect.flatMap((projects) => projects.snapshot),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
});
|
||||
|
||||
it("maps declared server failures into structural project command errors", () => {
|
||||
const cause = new EnvironmentInternalError({
|
||||
code: "internal_error",
|
||||
reason: "orchestration_snapshot_failed",
|
||||
reason: "access_token_issuance_failed",
|
||||
traceId: "trace-123",
|
||||
});
|
||||
|
||||
@@ -35,3 +107,23 @@ it("preserves unexpected server failures without deriving the message from them"
|
||||
assert.strictEqual(error.message, "Failed to call the running server.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
});
|
||||
|
||||
it.effect("adds, renames, and removes projects through the V2 project CLI domain", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-cli-"));
|
||||
const workspaceRoot = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3-v2-project-workspace-"),
|
||||
);
|
||||
|
||||
yield* runCli(["project", "add", workspaceRoot, "--title", "Alpha", "--base-dir", baseDir]);
|
||||
const added = (yield* readProjects(baseDir)).projects[0];
|
||||
assert.equal(added?.title, "Alpha");
|
||||
assert.equal(added?.workspaceRoot, workspaceRoot);
|
||||
|
||||
yield* runCli(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
|
||||
assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Beta");
|
||||
|
||||
yield* runCli(["project", "remove", added?.id ?? "", "--base-dir", baseDir]);
|
||||
assert.deepEqual((yield* readProjects(baseDir)).projects, []);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -1,15 +1,14 @@
|
||||
import {
|
||||
CommandId,
|
||||
AuthAdministrativeScopes,
|
||||
CommandId,
|
||||
EnvironmentHttpApi,
|
||||
EnvironmentHttpCommonError,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectMutation,
|
||||
type ProjectSnapshot,
|
||||
ProjectId,
|
||||
type ClientOrchestrationCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -25,11 +24,11 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
|
||||
import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
|
||||
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
|
||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
@@ -45,10 +44,7 @@ type ProjectMutationTarget = {
|
||||
};
|
||||
|
||||
type ProjectCommandExecutionMode = "live" | "offline";
|
||||
type ProjectCliDispatchCommand = Extract<
|
||||
ClientOrchestrationCommand,
|
||||
{ type: "project.create" | "project.meta.update" | "project.delete" }
|
||||
>;
|
||||
type ProjectCliDispatchCommand = ProjectMutation;
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
|
||||
@@ -198,12 +194,11 @@ const projectCommandUuid = Crypto.Crypto.pipe(
|
||||
),
|
||||
);
|
||||
|
||||
const ProjectCliRuntimeLive = Layer.mergeAll(
|
||||
WorkspacePaths.layer,
|
||||
OrchestrationLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
),
|
||||
const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(ProjectFaviconResolver.layer.pipe(Layer.provide(WorkspacePaths.layer))),
|
||||
Layer.provideMerge(WorkspacePaths.layer),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
);
|
||||
|
||||
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
|
||||
@@ -256,7 +251,7 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
});
|
||||
|
||||
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly snapshot: ProjectSnapshot;
|
||||
readonly identifier: string;
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
@@ -311,7 +306,7 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* makeLiveServerClient(origin);
|
||||
return yield* client.orchestration.snapshot({
|
||||
return yield* client.projects.snapshot({
|
||||
headers: { authorization: `Bearer ${bearerToken}` },
|
||||
});
|
||||
}).pipe(
|
||||
@@ -326,20 +321,18 @@ const dispatchLiveOrchestrationCommand = (
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* makeLiveServerClient(origin);
|
||||
yield* client.orchestration.dispatch({
|
||||
yield* client.projects.mutate({
|
||||
headers: { authorization: `Bearer ${bearerToken}` },
|
||||
payload: command,
|
||||
} as Parameters<typeof client.orchestration.dispatch>[0]);
|
||||
} as Parameters<typeof client.projects.mutate>[0]);
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
// Project commands only read the project list, so use the lightweight
|
||||
// command read model instead of hydrating every thread body in the database.
|
||||
return yield* projectionSnapshotQuery.getCommandReadModel();
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
return yield* projects.snapshot;
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
@@ -377,7 +370,7 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
|
||||
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly snapshot: ProjectSnapshot;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
@@ -422,10 +415,41 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const snapshot = yield* getOfflineSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) => orchestrationEngine.dispatch(command),
|
||||
dispatch: (command) =>
|
||||
command.type === "project.create"
|
||||
? projects
|
||||
.create({
|
||||
commandId: command.commandId,
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
...(command.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: command.defaultModelSelection }),
|
||||
...(command.scripts === undefined ? {} : { scripts: command.scripts }),
|
||||
})
|
||||
.pipe(Effect.asVoid)
|
||||
: command.type === "project.update"
|
||||
? projects
|
||||
.update({
|
||||
commandId: command.commandId,
|
||||
projectId: command.projectId,
|
||||
...(command.title === undefined ? {} : { title: command.title }),
|
||||
...(command.workspaceRoot === undefined
|
||||
? {}
|
||||
: { workspaceRoot: command.workspaceRoot }),
|
||||
...(command.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: command.defaultModelSelection }),
|
||||
...(command.scripts === undefined ? {} : { scripts: command.scripts }),
|
||||
})
|
||||
.pipe(Effect.asVoid)
|
||||
: projects
|
||||
.delete({ commandId: command.commandId, projectId: command.projectId })
|
||||
.pipe(Effect.asVoid),
|
||||
mode: "offline",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
@@ -456,7 +480,7 @@ const projectAddCommand = Command.make("add", {
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly snapshot: ProjectSnapshot;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
@@ -482,7 +506,6 @@ const projectAddCommand = Command.make("add", {
|
||||
title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),
|
||||
createdAt: DateTime.formatIso(yield* DateTime.now),
|
||||
});
|
||||
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
|
||||
}),
|
||||
@@ -508,7 +531,7 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly snapshot: ProjectSnapshot;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
@@ -544,7 +567,7 @@ const projectRenameCommand = Command.make("rename", {
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly snapshot: ProjectSnapshot;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
@@ -559,7 +582,7 @@ const projectRenameCommand = Command.make("rename", {
|
||||
}
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
type: "project.update",
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
projectId: project.id,
|
||||
title: nextTitle,
|
||||
|
||||
@@ -24,7 +24,7 @@ export class McpInvocationContext extends Context.Service<
|
||||
>()("t3/mcp/McpInvocationContext") {}
|
||||
|
||||
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
|
||||
capability: McpCapability,
|
||||
capability: "preview",
|
||||
) {
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
|
||||
@@ -21,6 +21,6 @@ export const layer = Layer.succeed(
|
||||
resolve: () => Effect.succeed(undefined),
|
||||
revokeProviderSession: () => Effect.void,
|
||||
revokeThread: () => Effect.void,
|
||||
revokeAll: Effect.succeed(undefined),
|
||||
revokeAll: Effect.void,
|
||||
}),
|
||||
);
|
||||
@@ -154,7 +154,7 @@ export class CheckpointServiceV2 extends Context.Service<
|
||||
CheckpointServiceV2Shape
|
||||
>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
|
||||
|
||||
function checkpointRefForScopeOrdinal(input: {
|
||||
export function checkpointRefForScopeOrdinal(input: {
|
||||
readonly scopeId: CheckpointScopeId;
|
||||
readonly ordinalWithinScope: number;
|
||||
}): CheckpointRef {
|
||||
|
||||
@@ -5,7 +5,12 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import {
|
||||
OrchestrationCommandReceiptRepository,
|
||||
type OrchestrationCommandReceipt,
|
||||
} from "../persistence/Services/OrchestrationCommandReceipts.ts";
|
||||
|
||||
/**
|
||||
* ERRORS
|
||||
@@ -75,16 +80,6 @@ export class CommandReceiptStoreV2 extends Context.Service<
|
||||
/**
|
||||
* IMPLEMENTATIONS
|
||||
*/
|
||||
type CommandReceiptRow = {
|
||||
readonly command_id: string;
|
||||
readonly thread_id: string;
|
||||
readonly command_type: string;
|
||||
readonly accepted_at: string;
|
||||
readonly result_sequence: number;
|
||||
readonly status: string;
|
||||
readonly error: string | null;
|
||||
};
|
||||
|
||||
const decodeReceipt = Schema.decodeUnknownEffect(
|
||||
CommandReceiptV2.mapFields((fields) => ({
|
||||
...fields,
|
||||
@@ -92,121 +87,81 @@ const decodeReceipt = Schema.decodeUnknownEffect(
|
||||
})),
|
||||
);
|
||||
|
||||
function rowToReceipt(row: CommandReceiptRow) {
|
||||
function fromApplicationReceipt(receipt: OrchestrationCommandReceipt) {
|
||||
return decodeReceipt({
|
||||
commandId: row.command_id,
|
||||
threadId: row.thread_id,
|
||||
commandType: row.command_type,
|
||||
acceptedAt: row.accepted_at,
|
||||
resultSequence: row.result_sequence,
|
||||
status: row.status,
|
||||
error: row.error,
|
||||
commandId: receipt.commandId,
|
||||
threadId: receipt.aggregateId,
|
||||
commandType: receipt.commandType,
|
||||
acceptedAt: receipt.acceptedAt,
|
||||
resultSequence: receipt.resultSequence,
|
||||
status: receipt.status,
|
||||
error: receipt.error,
|
||||
});
|
||||
}
|
||||
|
||||
export const layer: Layer.Layer<CommandReceiptStoreV2, never, SqlClient.SqlClient> = Layer.effect(
|
||||
CommandReceiptStoreV2,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
function toApplicationReceipt(receipt: CommandReceiptV2): OrchestrationCommandReceipt {
|
||||
return {
|
||||
commandId: receipt.commandId,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: receipt.threadId,
|
||||
commandType: receipt.commandType,
|
||||
acceptedAt: DateTime.formatIso(receipt.acceptedAt),
|
||||
resultSequence: receipt.resultSequence,
|
||||
status: receipt.status,
|
||||
error: receipt.error,
|
||||
};
|
||||
}
|
||||
|
||||
return CommandReceiptStoreV2.of({
|
||||
insertIfAbsent: (receipt) =>
|
||||
sql<{ readonly command_id: string }>`
|
||||
INSERT INTO orchestration_v2_command_receipts (
|
||||
command_id,
|
||||
thread_id,
|
||||
command_type,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
error
|
||||
)
|
||||
VALUES (
|
||||
${receipt.commandId},
|
||||
${receipt.threadId},
|
||||
${receipt.commandType},
|
||||
${DateTime.formatIso(receipt.acceptedAt)},
|
||||
${receipt.resultSequence},
|
||||
${receipt.status},
|
||||
${receipt.error}
|
||||
)
|
||||
ON CONFLICT(command_id) DO NOTHING
|
||||
RETURNING command_id
|
||||
`.pipe(
|
||||
Effect.map((rows) => rows.length === 1),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CommandReceiptStoreWriteError({
|
||||
commandId: receipt.commandId,
|
||||
cause,
|
||||
}),
|
||||
const baseLayer: Layer.Layer<CommandReceiptStoreV2, never, OrchestrationCommandReceiptRepository> =
|
||||
Layer.effect(
|
||||
CommandReceiptStoreV2,
|
||||
Effect.gen(function* () {
|
||||
const receipts = yield* OrchestrationCommandReceiptRepository;
|
||||
|
||||
return CommandReceiptStoreV2.of({
|
||||
insertIfAbsent: (receipt) =>
|
||||
receipts.insertIfAbsent(toApplicationReceipt(receipt)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CommandReceiptStoreWriteError({
|
||||
commandId: receipt.commandId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
upsert: (receipt) =>
|
||||
sql`
|
||||
INSERT INTO orchestration_v2_command_receipts (
|
||||
command_id,
|
||||
thread_id,
|
||||
command_type,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
error
|
||||
)
|
||||
VALUES (
|
||||
${receipt.commandId},
|
||||
${receipt.threadId},
|
||||
${receipt.commandType},
|
||||
${DateTime.formatIso(receipt.acceptedAt)},
|
||||
${receipt.resultSequence},
|
||||
${receipt.status},
|
||||
${receipt.error}
|
||||
)
|
||||
ON CONFLICT(command_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
command_type = excluded.command_type,
|
||||
accepted_at = excluded.accepted_at,
|
||||
result_sequence = excluded.result_sequence,
|
||||
status = excluded.status,
|
||||
error = excluded.error
|
||||
`.pipe(
|
||||
Effect.asVoid,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CommandReceiptStoreWriteError({
|
||||
commandId: receipt.commandId,
|
||||
cause,
|
||||
}),
|
||||
upsert: (receipt) =>
|
||||
receipts.upsert(toApplicationReceipt(receipt)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CommandReceiptStoreWriteError({
|
||||
commandId: receipt.commandId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getByCommandId: (commandId) =>
|
||||
sql<CommandReceiptRow>`
|
||||
SELECT
|
||||
command_id,
|
||||
thread_id,
|
||||
command_type,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
error
|
||||
FROM orchestration_v2_command_receipts
|
||||
WHERE command_id = ${commandId}
|
||||
`.pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const row = rows[0];
|
||||
return row === undefined
|
||||
? Effect.succeed(Option.none())
|
||||
: rowToReceipt(row).pipe(Effect.map(Option.some));
|
||||
}),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CommandReceiptStoreReadError({
|
||||
commandId,
|
||||
cause,
|
||||
getByCommandId: (commandId) =>
|
||||
receipts.getByCommandId({ commandId }).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (receipt) =>
|
||||
receipt.aggregateKind !== "thread"
|
||||
? Effect.succeed(Option.none())
|
||||
: fromApplicationReceipt(receipt).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new CommandReceiptStoreReadError({
|
||||
commandId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
} satisfies CommandReceiptStoreV2Shape);
|
||||
}),
|
||||
);
|
||||
} satisfies CommandReceiptStoreV2Shape);
|
||||
}),
|
||||
);
|
||||
|
||||
export const layer = baseLayer.pipe(Layer.provide(OrchestrationCommandReceiptRepositoryLive));
|
||||
|
||||
export const layerFromApplicationReceipts = baseLayer;
|
||||
@@ -346,21 +346,21 @@ export const layerWithOptions = (
|
||||
|
||||
export const layer = layerWithOptions();
|
||||
|
||||
export const daemonLayer: Layer.Layer<never, never, OrchestrationEffectWorkerV2> =
|
||||
Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const worker = yield* OrchestrationEffectWorkerV2;
|
||||
yield* Effect.forever(
|
||||
worker.runOnce.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)),
|
||||
),
|
||||
Effect.flatMap((worked) =>
|
||||
worked
|
||||
? Effect.yieldNow
|
||||
: Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
}),
|
||||
export const runDaemon = Effect.gen(function* () {
|
||||
const worker = yield* OrchestrationEffectWorkerV2;
|
||||
return yield* Effect.forever(
|
||||
worker.runOnce.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)),
|
||||
),
|
||||
Effect.flatMap((worked) =>
|
||||
worked
|
||||
? Effect.yieldNow
|
||||
: Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export const daemonLayer: Layer.Layer<never, never, OrchestrationEffectWorkerV2> =
|
||||
Layer.effectDiscard(runDaemon.pipe(Effect.forkScoped));
|
||||
@@ -219,6 +219,7 @@ const baseLayer: Layer.Layer<
|
||||
if (input.effects.length > 0) {
|
||||
yield* effectOutbox.notifyAvailable;
|
||||
}
|
||||
yield* eventStore.publishCommitted(storedEvents);
|
||||
yield* PubSub.publishAll(liveEvents, storedEvents);
|
||||
return storedEvents;
|
||||
});
|
||||
@@ -287,6 +288,7 @@ const baseLayer: Layer.Layer<
|
||||
yield* effectOutbox.notifyAvailable;
|
||||
}
|
||||
if (result.committed) {
|
||||
yield* eventStore.publishCommitted(result.storedEvents);
|
||||
yield* PubSub.publishAll(liveEvents, result.storedEvents);
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
CommandId,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2DomainEventJson,
|
||||
OrchestrationV2StoredEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -10,11 +9,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import type * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts";
|
||||
|
||||
/**
|
||||
* ERRORS
|
||||
*/
|
||||
export class EventStoreAppendEventsError extends Schema.TaggedErrorClass<EventStoreAppendEventsError>()(
|
||||
"EventStoreAppendEventsError",
|
||||
{
|
||||
@@ -23,7 +22,7 @@ export class EventStoreAppendEventsError extends Schema.TaggedErrorClass<EventSt
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to append ${this.eventCount} orchestration V2 event(s).`;
|
||||
return `Failed to append ${this.eventCount} agent orchestration event(s).`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +36,8 @@ export class EventStoreReadEventsError extends Schema.TaggedErrorClass<EventStor
|
||||
) {
|
||||
override get message(): string {
|
||||
return this.threadId === undefined
|
||||
? "Failed to read orchestration V2 events."
|
||||
: `Failed to read orchestration V2 events for thread ${this.threadId}.`;
|
||||
? "Failed to read agent orchestration events."
|
||||
: `Failed to read agent orchestration events for thread ${this.threadId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,9 +47,6 @@ export const EventStoreV2Error = Schema.Union([
|
||||
]);
|
||||
export type EventStoreV2Error = typeof EventStoreV2Error.Type;
|
||||
|
||||
/**
|
||||
* SERVICE DEFINITION
|
||||
*/
|
||||
export interface EventStoreV2Shape {
|
||||
readonly append: (input: {
|
||||
readonly commandId?: CommandId;
|
||||
@@ -68,188 +64,32 @@ export interface EventStoreV2Shape {
|
||||
readonly latestSequence: (input?: {
|
||||
readonly threadId?: ThreadId;
|
||||
}) => Effect.Effect<number, EventStoreV2Error>;
|
||||
readonly publishCommitted: (
|
||||
events: ReadonlyArray<OrchestrationV2StoredEvent>,
|
||||
) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class EventStoreV2 extends Context.Service<EventStoreV2, EventStoreV2Shape>()(
|
||||
"t3/orchestration-v2/EventStore/EventStoreV2",
|
||||
) {}
|
||||
|
||||
/**
|
||||
* IMPLEMENTATIONS
|
||||
*/
|
||||
type EventRow = {
|
||||
readonly sequence: number;
|
||||
readonly event_id: string;
|
||||
readonly command_id: string | null;
|
||||
readonly thread_id: string;
|
||||
readonly run_id: string | null;
|
||||
readonly node_id: string | null;
|
||||
readonly driver: string | null;
|
||||
readonly provider_instance_id: string | null;
|
||||
readonly raw_event_id: string | null;
|
||||
readonly event_type: string;
|
||||
readonly occurred_at: string;
|
||||
readonly payload_json: string;
|
||||
};
|
||||
|
||||
const encodeEventJson = Schema.encodeEffect(Schema.fromJsonString(OrchestrationV2DomainEventJson));
|
||||
const decodeEventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson);
|
||||
const decodeStoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent);
|
||||
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
const decodeUnknownJsonString = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
function parseJson(json: string): unknown {
|
||||
return decodeUnknownJsonString(json);
|
||||
}
|
||||
|
||||
function compactUndefined(record: Record<string, unknown>): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
|
||||
}
|
||||
|
||||
export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Layer.effect(
|
||||
const baseLayer: Layer.Layer<EventStoreV2, never, OrchestrationEventStore> = Layer.effect(
|
||||
EventStoreV2,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const rowToStoredEvent = (
|
||||
row: EventRow,
|
||||
input?: { readonly afterSequence?: number; readonly threadId?: ThreadId },
|
||||
) =>
|
||||
decodeEventJson(
|
||||
compactUndefined({
|
||||
id: row.event_id,
|
||||
threadId: row.thread_id,
|
||||
runId: row.run_id ?? undefined,
|
||||
nodeId: row.node_id ?? undefined,
|
||||
driver: row.driver ?? undefined,
|
||||
providerInstanceId: row.provider_instance_id ?? undefined,
|
||||
rawEventId: row.raw_event_id ?? undefined,
|
||||
type: row.event_type,
|
||||
occurredAt: row.occurred_at,
|
||||
payload: parseJson(row.payload_json),
|
||||
}),
|
||||
).pipe(
|
||||
Effect.flatMap((event) =>
|
||||
decodeStoredEvent({
|
||||
sequence: row.sequence,
|
||||
commandId: row.command_id,
|
||||
event,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EventStoreReadEventsError({
|
||||
...(input?.afterSequence === undefined ? {} : { afterSequence: input.afterSequence }),
|
||||
...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const append: EventStoreV2Shape["append"] = (input) =>
|
||||
Effect.forEach(
|
||||
input.events,
|
||||
(event) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeEventJson(event);
|
||||
const normalized = parseJson(encoded) as {
|
||||
readonly payload: unknown;
|
||||
readonly occurredAt: string;
|
||||
};
|
||||
|
||||
const rows = yield* sql<EventRow>`
|
||||
INSERT INTO orchestration_v2_events (
|
||||
event_id,
|
||||
command_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
driver,
|
||||
provider_instance_id,
|
||||
raw_event_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json
|
||||
)
|
||||
VALUES (
|
||||
${event.id},
|
||||
${input.commandId ?? null},
|
||||
${event.threadId},
|
||||
${event.runId ?? null},
|
||||
${event.nodeId ?? null},
|
||||
${event.driver ?? null},
|
||||
${event.providerInstanceId ?? null},
|
||||
${event.rawEventId ?? null},
|
||||
${event.type},
|
||||
${normalized.occurredAt},
|
||||
${encodeUnknownJsonString(normalized.payload)}
|
||||
)
|
||||
RETURNING
|
||||
sequence,
|
||||
event_id,
|
||||
command_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
driver,
|
||||
provider_instance_id,
|
||||
raw_event_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json
|
||||
`;
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return yield* new EventStoreAppendEventsError({
|
||||
eventCount: input.events.length,
|
||||
cause: "Insert did not return a stored event row.",
|
||||
});
|
||||
}
|
||||
return yield* rowToStoredEvent(row).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EventStoreAppendEventsError({
|
||||
eventCount: input.events.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EventStoreAppendEventsError({
|
||||
eventCount: input.events.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const applicationEvents = yield* OrchestrationEventStore;
|
||||
|
||||
const read: EventStoreV2Shape["read"] = (input) =>
|
||||
Stream.fromEffect(
|
||||
sql<EventRow>`
|
||||
SELECT
|
||||
sequence,
|
||||
event_id,
|
||||
command_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
driver,
|
||||
provider_instance_id,
|
||||
raw_event_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json
|
||||
FROM orchestration_v2_events
|
||||
WHERE sequence > ${input?.afterSequence ?? 0}
|
||||
AND sequence <= ${input?.throughSequence ?? Number.MAX_SAFE_INTEGER}
|
||||
AND (${input?.threadId ?? null} IS NULL OR thread_id = ${input?.threadId ?? null})
|
||||
ORDER BY sequence ASC
|
||||
LIMIT ${input?.limit ?? 1000}
|
||||
`.pipe(
|
||||
Effect.mapError(
|
||||
applicationEvents
|
||||
.readAgentEvents({
|
||||
...(input?.afterSequence === undefined ? {} : { afterSequence: input.afterSequence }),
|
||||
...(input?.throughSequence === undefined
|
||||
? {}
|
||||
: { throughSequence: input.throughSequence }),
|
||||
...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
...(input?.limit === undefined ? {} : { limit: input.limit }),
|
||||
})
|
||||
.pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new EventStoreReadEventsError({
|
||||
...(input?.afterSequence === undefined
|
||||
@@ -259,65 +99,41 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Stream.flatMap(Stream.fromIterable),
|
||||
Stream.mapEffect((row) => rowToStoredEvent(row, input)),
|
||||
);
|
||||
);
|
||||
|
||||
const readByCommandId: EventStoreV2Shape["readByCommandId"] = (input) =>
|
||||
Stream.fromEffect(
|
||||
sql<EventRow>`
|
||||
SELECT
|
||||
sequence,
|
||||
event_id,
|
||||
command_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
driver,
|
||||
provider_instance_id,
|
||||
raw_event_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json
|
||||
FROM orchestration_v2_events
|
||||
WHERE command_id = ${input.commandId}
|
||||
ORDER BY sequence ASC
|
||||
`.pipe(
|
||||
return EventStoreV2.of({
|
||||
append: (input) =>
|
||||
applicationEvents.appendAgentEvents(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EventStoreReadEventsError({
|
||||
new EventStoreAppendEventsError({
|
||||
eventCount: input.events.length,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Stream.flatMap(Stream.fromIterable),
|
||||
Stream.mapEffect((row) => rowToStoredEvent(row)),
|
||||
);
|
||||
|
||||
const latestSequence: EventStoreV2Shape["latestSequence"] = (input) =>
|
||||
sql<{ readonly sequence: number | null }>`
|
||||
SELECT MAX(sequence) AS sequence
|
||||
FROM orchestration_v2_events
|
||||
WHERE ${input?.threadId ?? null} IS NULL OR thread_id = ${input?.threadId ?? null}
|
||||
`.pipe(
|
||||
Effect.map((rows) => rows[0]?.sequence ?? 0),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EventStoreReadEventsError({
|
||||
...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
append,
|
||||
read,
|
||||
readByCommandId,
|
||||
latestSequence,
|
||||
} satisfies EventStoreV2Shape;
|
||||
readByCommandId: ({ commandId }) =>
|
||||
applicationEvents
|
||||
.readAgentEvents({ commandId })
|
||||
.pipe(Stream.mapError((cause) => new EventStoreReadEventsError({ cause }))),
|
||||
latestSequence: (input) =>
|
||||
applicationEvents.latestAgentSequence(input?.threadId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EventStoreReadEventsError({
|
||||
...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
publishCommitted: applicationEvents.publishCommitted,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = baseLayer.pipe(
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
);
|
||||
|
||||
export const layerFromOrchestrationEventStore = baseLayer;
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
type OrchestrationV2ProviderTurn,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2RunAttempt,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadShellSnapshot,
|
||||
type OrchestrationV2StoredEvent,
|
||||
type OrchestrationV2Subagent,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
@@ -145,7 +145,10 @@ export interface OrchestratorV2Shape {
|
||||
},
|
||||
OrchestratorV2Error
|
||||
>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<OrchestrationV2ShellSnapshot, OrchestratorV2Error>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestratorV2Error
|
||||
>;
|
||||
readonly getThreadEventSequence: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<number, OrchestratorV2Error>;
|
||||
|
||||
@@ -2,7 +2,7 @@ import type {
|
||||
OrchestrationV2ConversationMessage,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2ProjectedTurnItem,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestrationV2ShellThreadStatus,
|
||||
OrchestrationV2ThreadShell,
|
||||
OrchestrationV2ThreadProjection,
|
||||
@@ -100,7 +100,7 @@ export interface ProjectionStoreV2Shape {
|
||||
event: OrchestrationV2DomainEvent,
|
||||
) => Effect.Effect<void, ProjectionStoreV2Error>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
ProjectionStoreV2Error
|
||||
>;
|
||||
readonly getThreadProjection: (
|
||||
@@ -1882,8 +1882,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
const projection = yield* getThreadProjection(threadId);
|
||||
const rows = yield* sql<{ readonly snapshot_sequence: number | null }>`
|
||||
SELECT MAX(sequence) AS snapshot_sequence
|
||||
FROM orchestration_v2_events
|
||||
WHERE thread_id = ${threadId}
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
AND stream_id = ${threadId}
|
||||
`;
|
||||
return {
|
||||
schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
|
||||
@@ -1971,7 +1973,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
`,
|
||||
sql<{ readonly snapshot_sequence: number | null }>`
|
||||
SELECT MAX(sequence) AS snapshot_sequence
|
||||
FROM orchestration_v2_events
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
`,
|
||||
]);
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ const makeInstance = (
|
||||
displayName: String(instanceId),
|
||||
enabled: true,
|
||||
snapshot: {} as ProviderInstance["snapshot"],
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
orchestrationAdapter,
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
});
|
||||
|
||||
@@ -194,9 +194,10 @@ it.effect("drains durable effects before reporting recovery complete", () =>
|
||||
),
|
||||
),
|
||||
);
|
||||
const summary = yield* Effect.gen(function* () {
|
||||
return yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).recover;
|
||||
}).pipe(Effect.provide(layer));
|
||||
const summary = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService.pipe(
|
||||
Effect.flatMap((service) => service.recover),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
assert.deepEqual(summary, { resumedSessions: 0, terminalizedRuns: 0, executedEffects: 2 });
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ArchivedShellStreamItem,
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestrationV2ShellStreamItem,
|
||||
OrchestrationV2StoredEvent,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -7,7 +8,7 @@ import type {
|
||||
/** Converts a committed event and its resulting shell snapshot into one delta. */
|
||||
export function shellStreamItemFromSnapshot(input: {
|
||||
readonly stored: OrchestrationV2StoredEvent;
|
||||
readonly snapshot: OrchestrationV2ShellSnapshot;
|
||||
readonly snapshot: OrchestrationV2ThreadShellSnapshot;
|
||||
}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
|
||||
const active = input.snapshot.threads.find((thread) => thread.id === input.stored.event.threadId);
|
||||
if (active !== undefined) {
|
||||
@@ -41,3 +42,31 @@ export function shellStreamItemFromSnapshot(input: {
|
||||
threadId: input.stored.event.threadId,
|
||||
};
|
||||
}
|
||||
|
||||
/** Converts a committed event into an archive-only delta when it changes archive membership. */
|
||||
export function archivedShellStreamItemFromSnapshot(input: {
|
||||
readonly stored: OrchestrationV2StoredEvent;
|
||||
readonly snapshot: OrchestrationV2ThreadShellSnapshot;
|
||||
}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
|
||||
const archived = input.snapshot.archivedThreads.find(
|
||||
(thread) => thread.id === input.stored.event.threadId,
|
||||
);
|
||||
if (archived !== undefined) {
|
||||
return {
|
||||
kind: "thread.updated",
|
||||
sequence: input.stored.sequence,
|
||||
thread: archived,
|
||||
};
|
||||
}
|
||||
if (
|
||||
input.stored.event.type === "thread.unarchived" ||
|
||||
(input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
|
||||
) {
|
||||
return {
|
||||
kind: "thread.removed",
|
||||
sequence: input.stored.sequence,
|
||||
threadId: input.stored.event.threadId,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
@@ -126,7 +125,6 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
getById: (id) => Effect.succeed(id === projectId ? Option.some(project) : Option.none()),
|
||||
getByWorkspaceRoot: () => Effect.succeed(Option.some(project)),
|
||||
snapshot: Effect.die("unused"),
|
||||
changes: Stream.empty,
|
||||
}),
|
||||
Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, removeWorktree }),
|
||||
Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type OrchestrationV2ConversationMessage,
|
||||
type OrchestrationV2CreationSource,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadShellSnapshot,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2ThreadShell,
|
||||
type OrchestrationV2TurnItem,
|
||||
@@ -143,7 +143,10 @@ export interface ThreadManagementServiceShape {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
}) => Effect.Effect<OrchestrationV2ThreadProjection, ThreadManagementError>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<OrchestrationV2ShellSnapshot, OrchestratorV2Error>;
|
||||
readonly getShellSnapshot: () => Effect.Effect<
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestratorV2Error
|
||||
>;
|
||||
readonly listProjectThreads: (input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly includeSubagents: boolean;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Static architecture test scans source files.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
const sourceRoot = NodePath.resolve(import.meta.dirname, "..");
|
||||
const forbiddenImport =
|
||||
/from\s+["'][^"']*(?:ProviderService|ProviderSessionDirectory|ProviderSessionReaper|ProviderCommandReactor|ProviderRuntimeIngestion)[^"']*["']/;
|
||||
const retiredAgentRuntimePaths = [
|
||||
"orchestration/Layers/ProviderCommandReactor.ts",
|
||||
"orchestration/Layers/ProviderRuntimeIngestion.ts",
|
||||
"orchestration/Services/ProviderCommandReactor.ts",
|
||||
"orchestration/Services/ProviderRuntimeIngestion.ts",
|
||||
] as const;
|
||||
|
||||
function productionTypeScriptFiles(directory: string): ReadonlyArray<string> {
|
||||
return NodeFS.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||
const path = NodePath.join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
return entry.name === "legacy" ? [] : productionTypeScriptFiles(path);
|
||||
}
|
||||
return entry.isFile() && entry.name.endsWith(".ts") && !entry.name.includes(".test.")
|
||||
? [path]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
it("retains the application data plane without restoring the V1 agent runtime", () => {
|
||||
for (const relativePath of retiredAgentRuntimePaths) {
|
||||
assert.isFalse(NodeFS.existsSync(NodePath.join(sourceRoot, relativePath)));
|
||||
}
|
||||
const violations = productionTypeScriptFiles(sourceRoot).flatMap((path) => {
|
||||
const source = NodeFS.readFileSync(path, "utf8");
|
||||
return forbiddenImport.test(source) ? [NodePath.relative(sourceRoot, path)] : [];
|
||||
});
|
||||
assert.deepEqual(violations, []);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
type ApplicationStoredEvent,
|
||||
CommandId,
|
||||
type ModelSelection,
|
||||
ProjectId,
|
||||
@@ -10,12 +11,18 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { GitCoreLive } from "../git/Layers/GitCore.ts";
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts";
|
||||
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts";
|
||||
import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
@@ -58,7 +65,6 @@ const providerInstance = {
|
||||
displayName: "Codex test",
|
||||
enabled: true,
|
||||
snapshot: {} as ProviderInstance["snapshot"],
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
orchestrationAdapter,
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
@@ -82,6 +88,24 @@ const TestLayer = OrchestrationV2LayerLive.pipe(
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
const SharedApplicationDataPlaneTestLayer = Layer.merge(
|
||||
OrchestrationLayerLive,
|
||||
OrchestrationV2LayerLive,
|
||||
).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
|
||||
resolve: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
Layer.provide(mcpSessionRegistryTestLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provide(CheckpointStoreTestLayer),
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(ServerSettingsService.layerTest()),
|
||||
Layer.provide(TestProviderInstanceRegistry),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
|
||||
it.effect("creates and reads a thread through the production V2 composition", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -248,3 +272,83 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(SharedApplicationDataPlaneTestLayer)("shared application data plane", (it) => {
|
||||
it.effect("orders retained project transactions and V2 thread transactions in one source", () =>
|
||||
Effect.gen(function* () {
|
||||
const applicationEngine = yield* OrchestrationEngineService;
|
||||
const applicationEvents = yield* OrchestrationEventStore;
|
||||
const orchestrator = yield* OrchestratorV2;
|
||||
const projectionSnapshot = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const projectId = ProjectId.make("runtime-layer-shared-project");
|
||||
const threadId = ThreadId.make("runtime-layer-shared-thread");
|
||||
const projectCommand = {
|
||||
type: "project.create" as const,
|
||||
commandId: CommandId.make("runtime-layer-shared-project-create"),
|
||||
projectId,
|
||||
title: "Shared application source",
|
||||
workspaceRoot: "/tmp/runtime-layer-shared-project",
|
||||
defaultModelSelection: modelSelection,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
};
|
||||
|
||||
const projectResult = yield* applicationEngine.dispatch(projectCommand);
|
||||
const projectRetry = yield* applicationEngine.dispatch(projectCommand);
|
||||
assert.equal(projectRetry.sequence, projectResult.sequence);
|
||||
|
||||
const delivered = yield* Queue.unbounded<ApplicationStoredEvent>();
|
||||
yield* applicationEvents.streamApplicationEvents().pipe(
|
||||
Stream.take(2),
|
||||
Stream.runForEach((event) => Queue.offer(delivered, event)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const projectEvent = yield* Queue.take(delivered);
|
||||
assert.equal(projectEvent.sequence, projectResult.sequence);
|
||||
|
||||
const threadResult = yield* orchestrator.dispatch({
|
||||
type: "thread.create",
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
commandId: CommandId.make("runtime-layer-shared-thread-create"),
|
||||
threadId,
|
||||
projectId,
|
||||
title: "Shared thread",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
});
|
||||
const threadEvent = yield* Queue.take(delivered);
|
||||
|
||||
assert.equal(threadEvent.sequence, threadResult.sequence);
|
||||
assert.isAbove(threadEvent.sequence, projectEvent.sequence);
|
||||
assert.isTrue("aggregateKind" in projectEvent);
|
||||
assert.isTrue("event" in threadEvent);
|
||||
assert.equal((yield* projectionSnapshot.getProjectShellById(projectId))._tag, "Some");
|
||||
|
||||
const retainedReceipts = yield* sql<{
|
||||
readonly aggregate_kind: string;
|
||||
readonly aggregate_id: string;
|
||||
}>`
|
||||
SELECT aggregate_kind, aggregate_id
|
||||
FROM orchestration_command_receipts
|
||||
ORDER BY result_sequence ASC
|
||||
`;
|
||||
assert.deepEqual(retainedReceipts, [
|
||||
{ aggregate_kind: "project", aggregate_id: projectId },
|
||||
{ aggregate_kind: "thread", aggregate_id: threadId },
|
||||
]);
|
||||
|
||||
const retiredWrites = yield* sql<{ readonly count: number }>`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM orchestration_v2_events) +
|
||||
(SELECT COUNT(*) FROM orchestration_v2_command_receipts) AS count
|
||||
`;
|
||||
assert.equal(retiredWrites[0]?.count, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,19 +1,24 @@
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
import {
|
||||
OrchestrationEventInfrastructureLayerLive,
|
||||
OrchestrationLayerLive,
|
||||
} from "../orchestration/runtimeLayer.ts";
|
||||
import { ProjectionProjectRepositoryLive } from "../persistence/Layers/ProjectionProjects.ts";
|
||||
import { layer as projectServiceLayer } from "../project/ProjectService.ts";
|
||||
import { layer as projectSetupScriptRunnerLayer } from "../project/ProjectSetupScriptRunner.ts";
|
||||
import { layer as checkpointCaptureServiceLayer } from "./CheckpointCaptureService.ts";
|
||||
import { layer as checkpointServiceLayer } from "./CheckpointService.ts";
|
||||
import { layer as checkpointRollbackServiceLayer } from "./CheckpointRollbackService.ts";
|
||||
import { layer as commandPolicyLayer } from "./CommandPolicy.ts";
|
||||
import { layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
|
||||
import { layerFromApplicationReceipts as commandReceiptStoreLayer } from "./CommandReceiptStore.ts";
|
||||
import { layer as contextHandoffServiceLayer } from "./ContextHandoffService.ts";
|
||||
import { layer as effectOutboxLayer } from "./EffectOutbox.ts";
|
||||
import {
|
||||
daemonLayer as effectWorkerDaemonLayer,
|
||||
executorLayer as effectExecutorLayer,
|
||||
layer as effectWorkerLayer,
|
||||
} from "./EffectWorker.ts";
|
||||
import { layerFromStores as eventSinkLayer } from "./EventSink.ts";
|
||||
import { layer as eventStoreLayer } from "./EventStore.ts";
|
||||
import { layerFromOrchestrationEventStore as eventStoreLayer } from "./EventStore.ts";
|
||||
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
|
||||
import { layer as orchestratorLayer } from "./Orchestrator.ts";
|
||||
import { layer as projectionStoreLayer } from "./ProjectionStore.ts";
|
||||
@@ -21,10 +26,7 @@ import { layer as projectionMaintenanceLayer } from "./ProjectionMaintenance.ts"
|
||||
import { layerFromProviderInstanceRegistry as providerAdapterRegistryLayerFromProviderInstances } from "./ProviderAdapterRegistry.ts";
|
||||
import { layer as providerEventIngestorLayer } from "./ProviderEventIngestor.ts";
|
||||
import { layer as providerSessionManagerLayer } from "./ProviderSessionManager.ts";
|
||||
import {
|
||||
layer as providerRuntimeRecoveryLayer,
|
||||
ProviderRuntimeRecoveryService,
|
||||
} from "./ProviderRuntimeRecoveryService.ts";
|
||||
import { layer as providerRuntimeRecoveryLayer } from "./ProviderRuntimeRecoveryService.ts";
|
||||
import { layer as providerSwitchServiceLayer } from "./ProviderSwitchService.ts";
|
||||
import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlService.ts";
|
||||
import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts";
|
||||
@@ -33,13 +35,23 @@ import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.t
|
||||
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
|
||||
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.ts";
|
||||
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
|
||||
import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";
|
||||
|
||||
const eventStoreProvided = eventStoreLayer.pipe(
|
||||
Layer.provide(OrchestrationEventInfrastructureLayerLive),
|
||||
);
|
||||
const commandReceiptStoreProvided = commandReceiptStoreLayer.pipe(
|
||||
Layer.provide(OrchestrationEventInfrastructureLayerLive),
|
||||
);
|
||||
|
||||
const storesLayer = Layer.mergeAll(
|
||||
eventStoreLayer,
|
||||
OrchestrationEventInfrastructureLayerLive,
|
||||
eventStoreProvided,
|
||||
projectionStoreLayer,
|
||||
commandReceiptStoreLayer,
|
||||
commandReceiptStoreProvided,
|
||||
effectOutboxLayer,
|
||||
turnItemPositionStoreLayer,
|
||||
);
|
||||
@@ -47,8 +59,6 @@ const storesLayer = Layer.mergeAll(
|
||||
const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesLayer));
|
||||
const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesLayer));
|
||||
|
||||
const commandReceiptStoreProvided = commandReceiptStoreLayer;
|
||||
|
||||
const providerEventIngestorProvided = providerEventIngestorLayer.pipe(
|
||||
Layer.provide(Layer.mergeAll(eventSinkProvided, idAllocatorLayer)),
|
||||
);
|
||||
@@ -153,10 +163,6 @@ const effectExecutorProvided = effectExecutorLayer.pipe(
|
||||
const effectWorkerProvided = effectWorkerLayer.pipe(
|
||||
Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)),
|
||||
);
|
||||
const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe(
|
||||
Layer.provide(effectWorkerProvided),
|
||||
);
|
||||
|
||||
const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
@@ -169,9 +175,6 @@ const providerRuntimeRecoveryProvided = providerRuntimeRecoveryLayer.pipe(
|
||||
),
|
||||
),
|
||||
);
|
||||
const providerRuntimeRecoveryStartupProvided = Layer.effectDiscard(
|
||||
Effect.flatMap(ProviderRuntimeRecoveryService, (recovery) => recovery.recover),
|
||||
).pipe(Layer.provide(providerRuntimeRecoveryProvided));
|
||||
|
||||
const orchestratorProvided = orchestratorLayer.pipe(
|
||||
Layer.provide(
|
||||
@@ -194,11 +197,42 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const threadManagementProvided = threadManagementServiceLayer.pipe(
|
||||
Layer.provide(orchestratorProvided),
|
||||
);
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe(
|
||||
Layer.provide(ProjectServiceLayerLive),
|
||||
);
|
||||
const threadLaunchProvided = threadLaunchServiceLayer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
ProjectServiceLayerLive,
|
||||
ProjectSetupScriptRunnerLayerLive,
|
||||
threadManagementProvided,
|
||||
idAllocatorLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
const threadLifecycleProvided = threadLifecycleServiceLayer.pipe(
|
||||
Layer.provide(threadManagementProvided),
|
||||
);
|
||||
|
||||
export const OrchestrationV2LayerLive = Layer.mergeAll(
|
||||
orchestratorProvided,
|
||||
threadManagementServiceLayer.pipe(Layer.provide(orchestratorProvided)),
|
||||
effectWorkerDaemonProvided,
|
||||
providerRuntimeRecoveryStartupProvided,
|
||||
threadManagementProvided,
|
||||
effectWorkerProvided,
|
||||
providerRuntimeRecoveryProvided,
|
||||
projectionMaintenanceProvided,
|
||||
);
|
||||
|
||||
export const OrchestrationV2ProductionLayerLive = Layer.mergeAll(
|
||||
OrchestrationLayerLive,
|
||||
OrchestrationV2LayerLive,
|
||||
ProjectServiceLayerLive,
|
||||
threadLaunchProvided,
|
||||
threadLifecycleProvided,
|
||||
);
|
||||
@@ -3,7 +3,7 @@ import type {
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2RuntimeRequest,
|
||||
OrchestrationV2Run,
|
||||
OrchestrationV2ShellSnapshot,
|
||||
OrchestrationV2ThreadShellSnapshot,
|
||||
OrchestrationV2StoredEvent,
|
||||
OrchestrationV2ThreadProjection,
|
||||
OrchestrationV2TurnItem,
|
||||
@@ -74,7 +74,7 @@ export interface OrchestratorV2ScenarioResult {
|
||||
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
|
||||
readonly domainEvents: ReadonlyArray<OrchestrationV2DomainEvent>;
|
||||
readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
|
||||
readonly shellSnapshot: OrchestrationV2ShellSnapshot;
|
||||
readonly shellSnapshot: OrchestrationV2ThreadShellSnapshot;
|
||||
}
|
||||
|
||||
export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass<OrchestratorV2ScenarioStepError>()(
|
||||
|
||||
@@ -1,946 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
type CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
type ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type VcsStatusLocalResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as PlatformError from "effect/PlatformError";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
|
||||
import {
|
||||
checkpointRefForThreadTurn,
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { forkParked } from "../../serverActivation.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
readonly source: "runtime";
|
||||
readonly event: ProviderRuntimeEvent;
|
||||
}
|
||||
| {
|
||||
readonly source: "domain";
|
||||
readonly event: OrchestrationEvent;
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.make(String(value));
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
if (left === null || left === undefined || right === null || right === undefined) {
|
||||
return false;
|
||||
}
|
||||
return left === right;
|
||||
}
|
||||
|
||||
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
||||
switch (status) {
|
||||
case "failed":
|
||||
return "error";
|
||||
case "cancelled":
|
||||
case "interrupted":
|
||||
return "missing";
|
||||
case "completed":
|
||||
default:
|
||||
return "ready";
|
||||
}
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const randomUUID = crypto.randomUUIDv4;
|
||||
const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
|
||||
const serverCommandId = (tag: string) =>
|
||||
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
|
||||
const appendRevertFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnCount: number;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.all({
|
||||
commandId: serverCommandId("checkpoint-revert-failure"),
|
||||
activityId: serverEventId,
|
||||
}).pipe(
|
||||
Effect.flatMap(({ commandId, activityId }) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: activityId,
|
||||
tone: "error",
|
||||
kind: "checkpoint.revert.failed",
|
||||
summary: "Checkpoint revert failed",
|
||||
payload: {
|
||||
turnCount: input.turnCount,
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const appendCaptureFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.all({
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
activityId: serverEventId,
|
||||
}).pipe(
|
||||
Effect.flatMap(({ commandId, activityId }) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: activityId,
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
|
||||
const sessions = yield* providerService.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
return session?.cwd
|
||||
? Option.some({ threadId: session.threadId, cwd: session.cwd })
|
||||
: Option.none();
|
||||
});
|
||||
|
||||
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
|
||||
return yield* projectionSnapshotQuery
|
||||
.getThreadDetailById(threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
});
|
||||
|
||||
const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
|
||||
projectId: ProjectId,
|
||||
) {
|
||||
const project = yield* projectionSnapshotQuery
|
||||
.getProjectShellById(projectId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
return project ? [project] : [];
|
||||
});
|
||||
|
||||
const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
|
||||
|
||||
// Resolves the workspace CWD for checkpoint operations, preferring the
|
||||
// active provider session CWD and falling back to the thread/project config.
|
||||
// Returns undefined when no CWD can be determined or the workspace is not
|
||||
// a git repository.
|
||||
const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
|
||||
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
|
||||
readonly preferSessionRuntime: boolean;
|
||||
}): Effect.fn.Return<string | undefined> {
|
||||
const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);
|
||||
const fromThread = resolveThreadWorkspaceCwd({
|
||||
thread: input.thread,
|
||||
projects: input.projects,
|
||||
});
|
||||
|
||||
const cwd = input.preferSessionRuntime
|
||||
? (Option.match(fromSession, {
|
||||
onNone: () => undefined,
|
||||
onSome: (runtime) => runtime.cwd,
|
||||
}) ?? fromThread)
|
||||
: (fromThread ??
|
||||
Option.match(fromSession, {
|
||||
onNone: () => undefined,
|
||||
onSome: (runtime) => runtime.cwd,
|
||||
}));
|
||||
|
||||
if (!cwd) {
|
||||
return undefined;
|
||||
}
|
||||
if (!isGitWorkspace(cwd)) {
|
||||
return undefined;
|
||||
}
|
||||
return cwd;
|
||||
});
|
||||
|
||||
// Shared tail for both capture paths: creates the git checkpoint ref, diffs
|
||||
// it against the previous turn, then dispatches the domain events to update
|
||||
// the orchestration read model.
|
||||
const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId;
|
||||
readonly thread: {
|
||||
readonly messages: ReadonlyArray<{
|
||||
readonly id: MessageId;
|
||||
readonly role: string;
|
||||
readonly turnId: TurnId | null;
|
||||
}>;
|
||||
};
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
readonly status: "ready" | "missing" | "error";
|
||||
readonly assistantMessageId: MessageId | undefined;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const fromTurnCount = Math.max(0, input.turnCount - 1);
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount);
|
||||
const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount);
|
||||
|
||||
const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: input.cwd,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
});
|
||||
if (!fromCheckpointExists) {
|
||||
yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", {
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
fromTurnCount,
|
||||
});
|
||||
}
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: input.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
|
||||
// Refresh the workspace entry index so the @-mention file picker
|
||||
// reflects files created or deleted during this turn.
|
||||
yield* workspaceEntries.refresh(input.cwd);
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: input.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
|
||||
path: file.path,
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
})),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to derive checkpoint file summary", {
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
turnCount: input.turnCount,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as([])),
|
||||
),
|
||||
);
|
||||
|
||||
const assistantMessageId =
|
||||
input.assistantMessageId ??
|
||||
input.thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
|
||||
MessageId.make(`assistant:${input.turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: yield* serverCommandId("checkpoint-turn-diff-complete"),
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
completedAt: input.createdAt,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: input.status,
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: input.turnCount,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
yield* receiptBus.publish({
|
||||
type: "checkpoint.diff.finalized",
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
checkpointTurnCount: input.turnCount,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: input.status,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
yield* receiptBus.publish({
|
||||
type: "turn.processing.quiesced",
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
checkpointTurnCount: input.turnCount,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: yield* serverCommandId("checkpoint-captured-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(yield* randomUUID),
|
||||
tone: "info",
|
||||
kind: "checkpoint.captured",
|
||||
summary: "Checkpoint captured",
|
||||
payload: {
|
||||
turnCount: input.turnCount,
|
||||
status: input.status,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
// Captures a real git checkpoint when a turn completes via a runtime event.
|
||||
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
|
||||
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
|
||||
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
|
||||
// before this reactor runs; those must not prevent real git capture.
|
||||
if (
|
||||
thread.checkpoints.some(
|
||||
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If a placeholder checkpoint exists for this turn, reuse its turn count
|
||||
// instead of incrementing past it.
|
||||
const existingPlaceholder = thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
|
||||
);
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
const nextTurnCount = existingPlaceholder
|
||||
? existingPlaceholder.checkpointTurnCount
|
||||
: currentTurnCount + 1;
|
||||
|
||||
yield* captureAndDispatchCheckpoint({
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
thread,
|
||||
cwd: checkpointCwd,
|
||||
turnCount: nextTurnCount,
|
||||
status: checkpointStatusFromRuntime(event.payload.state),
|
||||
assistantMessageId: undefined,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Captures a real git checkpoint when a placeholder checkpoint (status "missing")
|
||||
// is detected via a domain event. This replaces the placeholder with a real
|
||||
// git-ref-based checkpoint.
|
||||
//
|
||||
// ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated
|
||||
// events from the Codex runtime. This handler fires when the corresponding
|
||||
// domain event arrives, allowing the reactor to capture the actual filesystem
|
||||
// state into a git ref and dispatch a replacement checkpoint.
|
||||
const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
|
||||
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
|
||||
) {
|
||||
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
|
||||
|
||||
// Only replace placeholders; skip events from our own real captures.
|
||||
if (status !== "missing") {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
if (!thread) {
|
||||
yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// If a real checkpoint already exists for this turn, skip.
|
||||
if (
|
||||
thread.checkpoints.some(
|
||||
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
|
||||
)
|
||||
) {
|
||||
yield* Effect.logDebug(
|
||||
"checkpoint capture from placeholder skipped: real checkpoint already exists",
|
||||
{ threadId, turnId },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects,
|
||||
preferSessionRuntime: true,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* captureAndDispatchCheckpoint({
|
||||
threadId,
|
||||
turnId,
|
||||
thread,
|
||||
cwd: checkpointCwd,
|
||||
turnCount: checkpointTurnCount,
|
||||
status: "ready",
|
||||
assistantMessageId: event.payload.assistantMessageId ?? undefined,
|
||||
createdAt: event.payload.completedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
|
||||
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
|
||||
const baselineExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
if (baselineExists) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
yield* receiptBus.publish({
|
||||
type: "checkpoint.baseline.captured",
|
||||
threadId: thread.id,
|
||||
checkpointTurnCount: currentTurnCount,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshLocalGitStatusFromTurnCompletion = Effect.fn(
|
||||
"refreshLocalGitStatusFromTurnCompletion",
|
||||
)(function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const local = yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to refresh local git status after turn completion", {
|
||||
threadId: event.threadId,
|
||||
turnId: event.turnId ?? null,
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
if (local !== null) {
|
||||
yield* followWorktreeBranchDrift({
|
||||
threadId: event.threadId,
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
local,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// A `git checkout` run inside a thread's dedicated worktree (by an agent or
|
||||
// the user) bypasses T3's commands, so the thread's recorded branch goes
|
||||
// stale. Since #4460 the client only attributes PR state to a thread when
|
||||
// the checked-out branch equals the recorded one, so stale metadata silently
|
||||
// orphans the thread's PR. Follow the drift here: adopt the checked-out
|
||||
// branch as the thread's branch, but only when the worktree belongs to
|
||||
// exactly this thread — for shared cwds the strict matching is the point.
|
||||
const followWorktreeBranchDrift = Effect.fn("followWorktreeBranchDrift")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly cwd: string;
|
||||
readonly local: VcsStatusLocalResult;
|
||||
}) {
|
||||
// Detached HEAD has no branch to adopt; a temporary placeholder checkout
|
||||
// means the first-turn auto-rename is still in flight — don't race it.
|
||||
const checkedOutBranch = input.local.refName;
|
||||
if (checkedOutBranch === null || isTemporaryWorktreeBranch(checkedOutBranch)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(input.threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
if (
|
||||
!thread ||
|
||||
thread.branch === null ||
|
||||
thread.branch === checkedOutBranch ||
|
||||
thread.worktreePath === null ||
|
||||
thread.worktreePath !== input.cwd ||
|
||||
isTemporaryWorktreeBranch(thread.branch)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const shell = yield* projectionSnapshotQuery.getShellSnapshot();
|
||||
const worktreeIsShared = shell.threads.some(
|
||||
(other) => other.id !== thread.id && other.worktreePath === thread.worktreePath,
|
||||
);
|
||||
if (worktreeIsShared) {
|
||||
return;
|
||||
}
|
||||
|
||||
// expectedBranch makes this a compare-and-swap in the decider: if the
|
||||
// recorded branch moved between our read and the dispatch (rename,
|
||||
// concurrent drift-follow), the stale update is dropped.
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* serverCommandId("worktree-branch-drift"),
|
||||
threadId: thread.id,
|
||||
branch: checkedOutBranch,
|
||||
expectedBranch: thread.branch,
|
||||
});
|
||||
yield* Effect.logInfo("thread branch followed worktree checkout", {
|
||||
threadId: thread.id,
|
||||
previousBranch: thread.branch,
|
||||
branch: checkedOutBranch,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("failed to follow worktree branch drift", {
|
||||
threadId: input.threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
|
||||
"ensurePreTurnBaselineFromDomainTurnStart",
|
||||
)(function* (
|
||||
event: Extract<
|
||||
OrchestrationEvent,
|
||||
{ type: "thread.turn-start-requested" | "thread.message-sent" }
|
||||
>,
|
||||
) {
|
||||
if (event.type === "thread.message-sent") {
|
||||
if (
|
||||
event.payload.role !== "user" ||
|
||||
event.payload.streaming ||
|
||||
event.payload.turnId !== null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const threadId = event.payload.threadId;
|
||||
const thread = yield* resolveThreadDetail(threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projects = yield* resolveThreadProjects(thread.projectId);
|
||||
const checkpointCwd = yield* resolveCheckpointCwd({
|
||||
threadId,
|
||||
thread,
|
||||
projects,
|
||||
preferSessionRuntime: false,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);
|
||||
const baselineExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
if (baselineExists) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
yield* receiptBus.publish({
|
||||
type: "checkpoint.baseline.captured",
|
||||
threadId,
|
||||
checkpointTurnCount: currentTurnCount,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
createdAt: event.occurredAt,
|
||||
});
|
||||
});
|
||||
|
||||
const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
|
||||
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
|
||||
) {
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
|
||||
const thread = yield* resolveThreadDetail(event.payload.threadId);
|
||||
if (!thread) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "Thread was not found in read model.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "No active provider session with workspace cwd is bound to this thread.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "Checkpoints are unavailable because this project is not a git repository.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
|
||||
if (event.payload.turnCount > currentTurnCount) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const targetCheckpointRef =
|
||||
event.payload.turnCount === 0
|
||||
? checkpointRefForThreadTurn(event.payload.threadId, 0)
|
||||
: thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,
|
||||
)?.checkpointRef;
|
||||
|
||||
if (!targetCheckpointRef) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const restored = yield* checkpointStore.restoreCheckpoint({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
fallbackToHead: event.payload.turnCount === 0,
|
||||
});
|
||||
if (!restored) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
// Refresh the workspace entry index so the @-mention file picker
|
||||
// reflects the reverted filesystem state.
|
||||
yield* workspaceEntries.refresh(sessionRuntime.value.cwd);
|
||||
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
yield* providerService.rollbackConversation({
|
||||
threadId: sessionRuntime.value.threadId,
|
||||
numTurns: rolledBackTurns,
|
||||
});
|
||||
}
|
||||
|
||||
const staleCheckpointRefs: Array<CheckpointRef> = [];
|
||||
for (const checkpoint of thread.checkpoints) {
|
||||
if (checkpoint.checkpointTurnCount > event.payload.turnCount) {
|
||||
staleCheckpointRefs.push(checkpoint.checkpointRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (staleCheckpointRefs.length > 0) {
|
||||
yield* checkpointStore.deleteCheckpointRefs({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRefs: staleCheckpointRefs,
|
||||
});
|
||||
}
|
||||
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.revert.complete",
|
||||
commandId: yield* serverCommandId("checkpoint-revert-complete"),
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: error.message,
|
||||
createdAt: now,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
|
||||
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
|
||||
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "thread.checkpoint-revert-requested") {
|
||||
yield* handleRevertRequested(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.flatMap(nowIso, (createdAt) =>
|
||||
appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: error.message,
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing")
|
||||
// from a turn.diff.updated runtime event, capture the real git checkpoint to
|
||||
// replace it. The providerService.streamEvents PubSub does not reliably deliver
|
||||
// turn.completed runtime events to this reactor (shared subscription), so
|
||||
// reacting to the domain event is the reliable path.
|
||||
if (event.type === "thread.turn-diff-completed") {
|
||||
yield* captureCheckpointFromPlaceholder(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.flatMap(nowIso, (createdAt) =>
|
||||
appendCaptureFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
detail: error.message,
|
||||
createdAt,
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
|
||||
event: ProviderRuntimeEvent,
|
||||
) {
|
||||
if (event.type === "turn.started") {
|
||||
yield* ensurePreTurnBaselineFromTurnStart(event);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
yield* refreshLocalGitStatusFromTurnCompletion(event);
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.flatMap(nowIso, (createdAt) =>
|
||||
appendCaptureFailureActivity({
|
||||
threadId: event.threadId,
|
||||
turnId,
|
||||
detail: error.message,
|
||||
createdAt,
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const processInput = (
|
||||
input: ReactorInput,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,
|
||||
never
|
||||
> =>
|
||||
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: ReactorInput) =>
|
||||
processInput(input).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("checkpoint reactor failed to process input", {
|
||||
source: input.source,
|
||||
eventType: input.event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const worker = yield* makeDrainableWorker(processInputSafely);
|
||||
|
||||
const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* forkParked(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.message-sent" &&
|
||||
event.type !== "thread.checkpoint-revert-requested" &&
|
||||
event.type !== "thread.turn-diff-completed"
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return worker.enqueue({ source: "domain", event });
|
||||
}),
|
||||
);
|
||||
|
||||
yield* forkParked(
|
||||
Stream.runForEach(providerService.streamEvents, (event) => {
|
||||
if (event.type !== "turn.started" && event.type !== "turn.completed") {
|
||||
return Effect.void;
|
||||
}
|
||||
return worker.enqueue({ source: "runtime", event });
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
drain: worker.drain,
|
||||
} satisfies CheckpointReactorShape;
|
||||
});
|
||||
|
||||
export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);
|
||||
@@ -2,9 +2,8 @@ import type {
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
ProjectOrchestrationCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import { OrchestrationCommand } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -51,29 +50,16 @@ const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
|
||||
const isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError);
|
||||
|
||||
interface CommandEnvelope {
|
||||
command: OrchestrationCommand;
|
||||
command: ProjectOrchestrationCommand;
|
||||
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
|
||||
startedAtMs: number;
|
||||
}
|
||||
|
||||
function commandToAggregateRef(command: OrchestrationCommand): {
|
||||
readonly aggregateKind: "project" | "thread";
|
||||
readonly aggregateId: ProjectId | ThreadId;
|
||||
function commandToAggregateRef(command: ProjectOrchestrationCommand): {
|
||||
readonly aggregateKind: "project";
|
||||
readonly aggregateId: ProjectId;
|
||||
} {
|
||||
switch (command.type) {
|
||||
case "project.create":
|
||||
case "project.meta.update":
|
||||
case "project.delete":
|
||||
return {
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
};
|
||||
}
|
||||
return { aggregateKind: "project", aggregateId: command.projectId };
|
||||
}
|
||||
|
||||
const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
@@ -120,6 +106,15 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
|
||||
commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);
|
||||
|
||||
yield* eventStore.publishCommitted(
|
||||
persistedEvents.filter(
|
||||
(event) =>
|
||||
event.type === "project.created" ||
|
||||
event.type === "project.meta-updated" ||
|
||||
event.type === "project.deleted",
|
||||
),
|
||||
);
|
||||
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
yield* PubSub.publish(eventPubSub, persistedEvent);
|
||||
}
|
||||
@@ -191,6 +186,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
commandId: envelope.command.commandId,
|
||||
aggregateKind: lastSavedEvent.aggregateKind,
|
||||
aggregateId: lastSavedEvent.aggregateId,
|
||||
commandType: envelope.command.type,
|
||||
acceptedAt: lastSavedEvent.occurredAt,
|
||||
resultSequence: lastSavedEvent.sequence,
|
||||
status: "accepted",
|
||||
@@ -213,6 +209,14 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
commandReadModel = committedCommand.nextCommandReadModel;
|
||||
yield* eventStore.publishCommitted(
|
||||
committedCommand.committedEvents.filter(
|
||||
(event) =>
|
||||
event.type === "project.created" ||
|
||||
event.type === "project.meta-updated" ||
|
||||
event.type === "project.deleted",
|
||||
),
|
||||
);
|
||||
for (const [index, event] of committedCommand.committedEvents.entries()) {
|
||||
yield* PubSub.publish(eventPubSub, event);
|
||||
if (index === 0) {
|
||||
@@ -282,6 +286,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
commandId: envelope.command.commandId,
|
||||
aggregateKind: aggregateRef.aggregateKind,
|
||||
aggregateId: aggregateRef.aggregateId,
|
||||
commandType: envelope.command.type,
|
||||
acceptedAt: yield* nowIso,
|
||||
resultSequence: commandReadModel.snapshotSequence,
|
||||
status: "rejected",
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
|
||||
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
|
||||
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
|
||||
|
||||
describe("OrchestrationReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<OrchestrationReactor, never> | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => {
|
||||
const started: string[] = [];
|
||||
|
||||
runtime = ManagedRuntime.make(
|
||||
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderRuntimeIngestionService, {
|
||||
start: () => {
|
||||
started.push("provider-runtime-ingestion");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderCommandReactor, {
|
||||
start: () => {
|
||||
started.push("provider-command-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(CheckpointReactor, {
|
||||
start: () => {
|
||||
started.push("checkpoint-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => {
|
||||
started.push("thread-deletion-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {
|
||||
publishThread: () => Effect.void,
|
||||
start: () => {
|
||||
started.push("agent-awareness-relay");
|
||||
return Effect.void;
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor));
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
|
||||
expect(started).toEqual([
|
||||
"provider-runtime-ingestion",
|
||||
"provider-command-reactor",
|
||||
"checkpoint-reactor",
|
||||
"thread-deletion-reactor",
|
||||
"agent-awareness-relay",
|
||||
]);
|
||||
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import {
|
||||
OrchestrationReactor,
|
||||
type OrchestrationReactorShape,
|
||||
} from "../Services/OrchestrationReactor.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
|
||||
|
||||
export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
|
||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
const threadDeletionReactor = yield* ThreadDeletionReactor;
|
||||
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* providerRuntimeIngestion.start();
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
yield* threadDeletionReactor.start();
|
||||
yield* agentAwarenessRelay.start();
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies OrchestrationReactorShape;
|
||||
});
|
||||
|
||||
export const OrchestrationReactorLive = Layer.effect(
|
||||
OrchestrationReactor,
|
||||
makeOrchestrationReactor,
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,39 +0,0 @@
|
||||
/**
|
||||
* RuntimeReceiptBus layers.
|
||||
*
|
||||
* `RuntimeReceiptBusLive` is the production default and intentionally does not
|
||||
* retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory
|
||||
* PubSub-backed implementation used by integration tests that need to await
|
||||
* checkpoint-reactor milestones precisely.
|
||||
*
|
||||
* @module RuntimeReceiptBus
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import {
|
||||
RuntimeReceiptBus,
|
||||
type RuntimeReceiptBusShape,
|
||||
type OrchestrationRuntimeReceipt,
|
||||
} from "../Services/RuntimeReceiptBus.ts";
|
||||
|
||||
const makeRuntimeReceiptBus = Effect.succeed({
|
||||
publish: () => Effect.void,
|
||||
streamEventsForTest: Stream.empty,
|
||||
} satisfies RuntimeReceiptBusShape);
|
||||
|
||||
const makeRuntimeReceiptBusTest = Effect.gen(function* () {
|
||||
const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();
|
||||
|
||||
return {
|
||||
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
|
||||
get streamEventsForTest() {
|
||||
return Stream.fromPubSub(pubSub);
|
||||
},
|
||||
} satisfies RuntimeReceiptBusShape;
|
||||
});
|
||||
|
||||
export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);
|
||||
export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest);
|
||||
@@ -1,38 +0,0 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
|
||||
|
||||
describe("logCleanupCauseUnlessInterrupted", () => {
|
||||
const threadId = ThreadId.make("thread-deletion-reactor-test");
|
||||
|
||||
it("swallows ordinary cleanup failures", async () => {
|
||||
const exit = await Effect.runPromiseExit(
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.fail("cleanup failed"),
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isSuccess(exit)).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves interrupt causes", async () => {
|
||||
const exit = await Effect.runPromiseExit(
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.interrupt,
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
import type { OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ThreadDeletionReactor,
|
||||
type ThreadDeletionReactorShape,
|
||||
} from "../Services/ThreadDeletionReactor.ts";
|
||||
import { forkParked } from "../../serverActivation.ts";
|
||||
|
||||
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
|
||||
|
||||
export const logCleanupCauseUnlessInterrupted = <R, E>({
|
||||
effect,
|
||||
message,
|
||||
threadId,
|
||||
}: {
|
||||
readonly effect: Effect.Effect<void, E, R>;
|
||||
readonly message: string;
|
||||
readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
|
||||
}): Effect.Effect<void, E, R> =>
|
||||
effect.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logDebug(message, {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: providerService.stopSession({ threadId }),
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: terminalManager.close({ threadId, deleteHistory: true }),
|
||||
message: "thread deletion cleanup skipped terminal close",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
|
||||
event: ThreadDeletedEvent,
|
||||
) {
|
||||
const { threadId } = event.payload;
|
||||
yield* stopProviderSession(threadId);
|
||||
yield* closeThreadTerminals(threadId);
|
||||
});
|
||||
|
||||
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
|
||||
processThreadDeleted(event).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("thread deletion reactor failed to process event", {
|
||||
eventType: event.type,
|
||||
threadId: event.payload.threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
|
||||
|
||||
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* forkParked(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (event.type !== "thread.deleted") {
|
||||
return Effect.void;
|
||||
}
|
||||
return worker.enqueue(event);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
drain: worker.drain,
|
||||
} satisfies ThreadDeletionReactorShape;
|
||||
});
|
||||
|
||||
export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);
|
||||
@@ -1,179 +0,0 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
type IsoDateTime,
|
||||
type OrchestrationCommand,
|
||||
OrchestrationDispatchCommandError,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { parseBase64DataUrl } from "../imageMime.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
|
||||
export const canonicalizeClientCommandTimestamps = (
|
||||
command: ClientOrchestrationCommand,
|
||||
receivedAt: IsoDateTime,
|
||||
): ClientOrchestrationCommand => {
|
||||
const canonicalCommand =
|
||||
"createdAt" in command
|
||||
? {
|
||||
...command,
|
||||
createdAt: receivedAt,
|
||||
}
|
||||
: command;
|
||||
|
||||
if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) {
|
||||
return canonicalCommand;
|
||||
}
|
||||
|
||||
return {
|
||||
...canonicalCommand,
|
||||
bootstrap: {
|
||||
...canonicalCommand.bootstrap,
|
||||
createThread: {
|
||||
...canonicalCommand.bootstrap.createThread,
|
||||
createdAt: receivedAt,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
Effect.gen(function* () {
|
||||
const receivedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
|
||||
const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
|
||||
workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: cause.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const normalizeProjectWorkspaceRootForCreate = (
|
||||
workspaceRoot: string,
|
||||
createIfMissing: boolean | undefined,
|
||||
) =>
|
||||
workspacePaths
|
||||
.normalizeWorkspaceRoot(workspaceRoot, {
|
||||
createIfMissing: createIfMissing === true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: cause.message,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (canonicalCommand.type === "project.create") {
|
||||
return {
|
||||
...canonicalCommand,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
|
||||
canonicalCommand.workspaceRoot,
|
||||
canonicalCommand.createWorkspaceRootIfMissing,
|
||||
),
|
||||
createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (
|
||||
canonicalCommand.type === "project.meta.update" &&
|
||||
canonicalCommand.workspaceRoot !== undefined
|
||||
) {
|
||||
return {
|
||||
...canonicalCommand,
|
||||
workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),
|
||||
} satisfies OrchestrationCommand;
|
||||
}
|
||||
|
||||
if (canonicalCommand.type !== "thread.turn.start") {
|
||||
return canonicalCommand as OrchestrationCommand;
|
||||
}
|
||||
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
canonicalCommand.message.attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentId = createAttachmentId(canonicalCommand.threadId);
|
||||
if (!attachmentId) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: "Failed to create a safe attachment id.",
|
||||
});
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
sizeBytes: bytes.byteLength,
|
||||
};
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment: persistedAttachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return persistedAttachment;
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
...canonicalCommand,
|
||||
message: {
|
||||
...canonicalCommand.message,
|
||||
attachments: normalizedAttachments,
|
||||
},
|
||||
} satisfies OrchestrationCommand;
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
/**
|
||||
* CheckpointReactor - Checkpoint reaction service interface.
|
||||
*
|
||||
* Owns background workers that react to orchestration checkpoint lifecycle
|
||||
* events and apply checkpoint side effects.
|
||||
*
|
||||
* @module CheckpointReactor
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* CheckpointReactorShape - Service API for checkpoint reactor lifecycle.
|
||||
*/
|
||||
export interface CheckpointReactorShape {
|
||||
/**
|
||||
* Start the checkpoint reactor.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*
|
||||
* Consumes both orchestration-domain and provider-runtime events via an
|
||||
* internal queue.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
* Intended for test use to replace timing-sensitive sleeps.
|
||||
*/
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointReactor - Service tag for checkpoint reactor workers.
|
||||
*/
|
||||
export class CheckpointReactor extends Context.Service<CheckpointReactor, CheckpointReactorShape>()(
|
||||
"t3/orchestration/Services/CheckpointReactor",
|
||||
) {}
|
||||
@@ -1,16 +1,16 @@
|
||||
/**
|
||||
* OrchestrationEngineService - Service interface for orchestration command handling.
|
||||
* Historical name for the application event-sourcing engine.
|
||||
*
|
||||
* Owns command validation/dispatch and in-memory read-model updates backed by
|
||||
* `OrchestrationEventStore` persistence. It does not own provider process
|
||||
* management or transport concerns (e.g. websocket request parsing).
|
||||
* This is not the agent orchestrator. It retains serialized project-command
|
||||
* validation, append, receipt, and projection transactions. Agent execution is
|
||||
* owned by orchestration V2, whose thread events use the same event store.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection. Command dispatch,
|
||||
* replay, and unknown-input decoding all return typed domain errors.
|
||||
*
|
||||
* @module OrchestrationEngineService
|
||||
*/
|
||||
import type { OrchestrationCommand, OrchestrationEvent } from "@t3tools/contracts";
|
||||
import type { OrchestrationEvent, ProjectOrchestrationCommand } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
@@ -47,7 +47,7 @@ export interface OrchestrationEngineShape {
|
||||
* command receipts.
|
||||
*/
|
||||
readonly dispatch: (
|
||||
command: OrchestrationCommand,
|
||||
command: ProjectOrchestrationCommand,
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
/**
|
||||
* OrchestrationReactor - Composite orchestration reactor service interface.
|
||||
*
|
||||
* Coordinates startup of orchestration runtime reactors that translate domain
|
||||
* events into downstream side effects.
|
||||
*
|
||||
* @module OrchestrationReactor
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* OrchestrationReactorShape - Service API for orchestration reactor lifecycle.
|
||||
*/
|
||||
export interface OrchestrationReactorShape {
|
||||
/**
|
||||
* Start orchestration-side reactors for provider/runtime/checkpoint flows.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
* OrchestrationReactor - Service tag for orchestration reactor coordination.
|
||||
*/
|
||||
export class OrchestrationReactor extends Context.Service<
|
||||
OrchestrationReactor,
|
||||
OrchestrationReactorShape
|
||||
>()("t3/orchestration/Services/OrchestrationReactor") {}
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* ProviderCommandReactor - Provider command reaction service interface.
|
||||
*
|
||||
* Owns background workers that react to orchestration intent events and
|
||||
* dispatch provider-side command execution.
|
||||
*
|
||||
* @module ProviderCommandReactor
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* ProviderCommandReactorShape - Service API for provider command reactors.
|
||||
*/
|
||||
export interface ProviderCommandReactorShape {
|
||||
/**
|
||||
* Start reacting to provider-intent orchestration domain events.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*
|
||||
* Filters orchestration domain events to provider-intent types before
|
||||
* processing.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
* Intended for test use to replace timing-sensitive sleeps.
|
||||
*/
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderCommandReactor - Service tag for provider command reaction workers.
|
||||
*/
|
||||
export class ProviderCommandReactor extends Context.Service<
|
||||
ProviderCommandReactor,
|
||||
ProviderCommandReactorShape
|
||||
>()("t3/orchestration/Services/ProviderCommandReactor") {}
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* ProviderRuntimeIngestionService - Provider runtime ingestion service interface.
|
||||
*
|
||||
* Owns background workers that consume provider runtime streams and emit
|
||||
* orchestration commands/events.
|
||||
*
|
||||
* @module ProviderRuntimeIngestionService
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* ProviderRuntimeIngestionShape - Service API for runtime ingestion lifecycle.
|
||||
*/
|
||||
export interface ProviderRuntimeIngestionShape {
|
||||
/**
|
||||
* Start ingesting provider runtime events into orchestration commands.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*
|
||||
* Uses an internal queue and continues after non-interrupt failures by
|
||||
* logging warnings.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
* Intended for test use to replace timing-sensitive sleeps.
|
||||
*/
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderRuntimeIngestionService - Service tag for runtime ingestion workers.
|
||||
*/
|
||||
export class ProviderRuntimeIngestionService extends Context.Service<
|
||||
ProviderRuntimeIngestionService,
|
||||
ProviderRuntimeIngestionShape
|
||||
>()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {}
|
||||
@@ -1,66 +0,0 @@
|
||||
/**
|
||||
* RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts.
|
||||
*
|
||||
* This service exists to expose short-lived orchestration milestones that are
|
||||
* useful in tests and harnesses but are not part of the production runtime
|
||||
* event model. `CheckpointReactor` publishes receipts such as baseline capture,
|
||||
* diff finalization, and turn-processing quiescence so integration tests can
|
||||
* wait for those exact points without inferring them indirectly from persisted
|
||||
* state.
|
||||
*
|
||||
* Production code should only call `publish`. Test code may subscribe via
|
||||
* `streamEventsForTest`, which is intentionally named to make the intended
|
||||
* usage explicit.
|
||||
*
|
||||
* @module RuntimeReceiptBus
|
||||
*/
|
||||
import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
export const CheckpointBaselineCapturedReceipt = Schema.Struct({
|
||||
type: Schema.Literal("checkpoint.baseline.captured"),
|
||||
threadId: ThreadId,
|
||||
checkpointTurnCount: NonNegativeInt,
|
||||
checkpointRef: CheckpointRef,
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type CheckpointBaselineCapturedReceipt = typeof CheckpointBaselineCapturedReceipt.Type;
|
||||
|
||||
export const CheckpointDiffFinalizedReceipt = Schema.Struct({
|
||||
type: Schema.Literal("checkpoint.diff.finalized"),
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
checkpointTurnCount: NonNegativeInt,
|
||||
checkpointRef: CheckpointRef,
|
||||
status: Schema.Literals(["ready", "missing", "error"]),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type CheckpointDiffFinalizedReceipt = typeof CheckpointDiffFinalizedReceipt.Type;
|
||||
|
||||
export const TurnProcessingQuiescedReceipt = Schema.Struct({
|
||||
type: Schema.Literal("turn.processing.quiesced"),
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
checkpointTurnCount: NonNegativeInt,
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type TurnProcessingQuiescedReceipt = typeof TurnProcessingQuiescedReceipt.Type;
|
||||
|
||||
export const OrchestrationRuntimeReceipt = Schema.Union([
|
||||
CheckpointBaselineCapturedReceipt,
|
||||
CheckpointDiffFinalizedReceipt,
|
||||
TurnProcessingQuiescedReceipt,
|
||||
]);
|
||||
export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Type;
|
||||
|
||||
export interface RuntimeReceiptBusShape {
|
||||
readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;
|
||||
readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;
|
||||
}
|
||||
|
||||
export class RuntimeReceiptBus extends Context.Service<RuntimeReceiptBus, RuntimeReceiptBusShape>()(
|
||||
"t3/orchestration/Services/RuntimeReceiptBus",
|
||||
) {}
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* ThreadDeletionReactor - Thread deletion cleanup reactor service interface.
|
||||
*
|
||||
* Owns background workers that react to thread deletion domain events and
|
||||
* perform best-effort runtime cleanup for provider sessions and terminals.
|
||||
*
|
||||
* @module ThreadDeletionReactor
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* ThreadDeletionReactorShape - Service API for thread deletion cleanup.
|
||||
*/
|
||||
export interface ThreadDeletionReactorShape {
|
||||
/**
|
||||
* Start reacting to thread.deleted orchestration domain events.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
* Intended for test use to replace timing-sensitive sleeps.
|
||||
*/
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ThreadDeletionReactor - Service tag for thread deletion cleanup workers.
|
||||
*/
|
||||
export class ThreadDeletionReactor extends Context.Service<
|
||||
ThreadDeletionReactor,
|
||||
ThreadDeletionReactorShape
|
||||
>()("t3/orchestration/Services/ThreadDeletionReactor") {}
|
||||
@@ -1,223 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import {
|
||||
MessageId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationReadModel,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import {
|
||||
findThreadById,
|
||||
listThreadsByProjectId,
|
||||
requireNonNegativeInteger,
|
||||
requireThread,
|
||||
requireThreadAbsent,
|
||||
} from "./commandInvariants.ts";
|
||||
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
const readModel: OrchestrationReadModel = {
|
||||
snapshotSequence: 2,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.make("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: ProjectId.make("project-b"),
|
||||
title: "Project B",
|
||||
workspaceRoot: "/tmp/project-b",
|
||||
defaultModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-a"),
|
||||
title: "Thread A",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
{
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-b"),
|
||||
title: "Thread B",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messageSendCommand: OrchestrationCommand = {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("msg-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
};
|
||||
|
||||
describe("commandInvariants", () => {
|
||||
it("finds threads by id and project", () => {
|
||||
expect(findThreadById(readModel, ThreadId.make("thread-1"))?.projectId).toBe("project-a");
|
||||
expect(findThreadById(readModel, ThreadId.make("missing"))).toBeUndefined();
|
||||
expect(
|
||||
listThreadsByProjectId(readModel, ProjectId.make("project-b")).map((thread) => thread.id),
|
||||
).toEqual([ThreadId.make("thread-2")]);
|
||||
});
|
||||
|
||||
it("requires existing thread", async () => {
|
||||
const thread = await Effect.runPromise(
|
||||
requireThread({
|
||||
readModel,
|
||||
command: messageSendCommand,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}),
|
||||
);
|
||||
expect(thread.id).toBe(ThreadId.make("thread-1"));
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
requireThread({
|
||||
readModel,
|
||||
command: messageSendCommand,
|
||||
threadId: ThreadId.make("missing"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("does not exist");
|
||||
});
|
||||
|
||||
it("requires missing thread for create flows", async () => {
|
||||
await Effect.runPromise(
|
||||
requireThreadAbsent({
|
||||
readModel,
|
||||
command: {
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-2"),
|
||||
threadId: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-a"),
|
||||
title: "new",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
},
|
||||
threadId: ThreadId.make("thread-3"),
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
requireThreadAbsent({
|
||||
readModel,
|
||||
command: {
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-3"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-a"),
|
||||
title: "dup",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
},
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("already exists");
|
||||
});
|
||||
|
||||
it("requires non-negative integers", async () => {
|
||||
await Effect.runPromise(
|
||||
requireNonNegativeInteger({
|
||||
commandType: "thread.checkpoint.revert",
|
||||
field: "turnCount",
|
||||
value: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
requireNonNegativeInteger({
|
||||
commandType: "thread.checkpoint.revert",
|
||||
field: "turnCount",
|
||||
value: -1,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("greater than or equal to 0");
|
||||
});
|
||||
});
|
||||
@@ -1,217 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const asCommandId = (value: string): CommandId => CommandId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
const seedReadModel = Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-delete"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Project Delete",
|
||||
workspaceRoot: "/tmp/project-delete",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const withFirstThread = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-create-1"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Thread Delete 1",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
return yield* projectEvent(withFirstThread, {
|
||||
sequence: 3,
|
||||
eventId: asEventId("evt-thread-create-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-2"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-create-2"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Thread Delete 2",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>) {
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
return events.map((entry) => {
|
||||
switch (entry.type) {
|
||||
case "thread.deleted":
|
||||
return {
|
||||
type: entry.type,
|
||||
aggregateKind: entry.aggregateKind,
|
||||
aggregateId: entry.aggregateId,
|
||||
commandId: entry.commandId,
|
||||
correlationId: entry.correlationId,
|
||||
payload: {
|
||||
threadId: entry.payload.threadId,
|
||||
},
|
||||
};
|
||||
case "project.deleted":
|
||||
return {
|
||||
type: entry.type,
|
||||
aggregateKind: entry.aggregateKind,
|
||||
aggregateId: entry.aggregateId,
|
||||
commandId: entry.commandId,
|
||||
correlationId: entry.correlationId,
|
||||
payload: {
|
||||
projectId: entry.payload.projectId,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return entry;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(NodeServices.layer)("decider deletion flows", (it) => {
|
||||
it.effect("rejects deleting a non-empty project without force", () =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* seedReadModel;
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.delete",
|
||||
commandId: asCommandId("cmd-project-delete-no-force"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
expect(error.message).toContain("cannot be deleted without force=true");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses thread.delete semantics when force-deleting a non-empty project", () =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* seedReadModel;
|
||||
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
|
||||
type: "project.delete",
|
||||
commandId: asCommandId("cmd-project-delete-force"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
force: true,
|
||||
};
|
||||
|
||||
const forcedResult = yield* decideOrchestrationCommand({
|
||||
command: projectDeleteCommand,
|
||||
readModel,
|
||||
});
|
||||
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
|
||||
|
||||
expect(forcedEvents.map((event) => event.type)).toEqual([
|
||||
"thread.deleted",
|
||||
"thread.deleted",
|
||||
"project.deleted",
|
||||
]);
|
||||
|
||||
let sequentialReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const sequentialEvents: PlannedEvent[] = [];
|
||||
for (const nextCommand of [
|
||||
{
|
||||
type: "thread.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
},
|
||||
{
|
||||
type: "thread.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
},
|
||||
{
|
||||
type: "project.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
projectId: asProjectId("project-delete"),
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationCommand>) {
|
||||
const decided = yield* decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: sequentialReadModel,
|
||||
});
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = yield* projectEvent(sequentialReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,460 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
it.layer(NodeServices.layer)("decider project scripts", (it) => {
|
||||
it.effect("emits empty scripts on project.create", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const readModel = createEmptyReadModel(now);
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-scripts"),
|
||||
projectId: asProjectId("project-scripts"),
|
||||
title: "Scripts",
|
||||
workspaceRoot: "/tmp/scripts",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const event = Array.isArray(result) ? result[0] : result;
|
||||
expect(event.type).toBe("project.created");
|
||||
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("propagates scripts in project.meta.update payload", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const readModel = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-scripts"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-scripts"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-scripts"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-scripts"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-scripts"),
|
||||
title: "Scripts",
|
||||
workspaceRoot: "/tmp/scripts",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const scripts = [
|
||||
{
|
||||
id: "lint",
|
||||
name: "Lint",
|
||||
command: "bun run lint",
|
||||
icon: "lint",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
] as const;
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-scripts"),
|
||||
projectId: asProjectId("project-scripts"),
|
||||
scripts: Array.from(scripts),
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const event = Array.isArray(result) ? result[0] : result;
|
||||
expect(event.type).toBe("project.meta-updated");
|
||||
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects project.create for an active workspace root that already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const readModel = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-existing"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-existing"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-duplicate-root"),
|
||||
projectId: asProjectId("project-duplicate-root"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project/",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(failure.message).toContain(
|
||||
"Active project 'project-existing' already exists for workspace root '/tmp/project'.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects project.meta.update when moving onto another active workspace root", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withFirstProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-first"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-first"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-first"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-first"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-first"),
|
||||
title: "First",
|
||||
workspaceRoot: "/tmp/project-first",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withFirstProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-project-create-second"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-second"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create-second"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create-second"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-second"),
|
||||
title: "Second",
|
||||
workspaceRoot: "/tmp/project-second",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const failure = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-duplicate-root"),
|
||||
projectId: asProjectId("project-second"),
|
||||
workspaceRoot: "/tmp/project-first",
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(failure.message).toContain(
|
||||
"Active project 'project-first' already exists for workspace root '/tmp/project-first'.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("message-user-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
const events = Array.isArray(result) ? result : [result];
|
||||
expect(events).toHaveLength(2);
|
||||
expect(events[0]?.type).toBe("thread.message-sent");
|
||||
const turnStartEvent = events[1];
|
||||
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
|
||||
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
|
||||
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
||||
return;
|
||||
}
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits thread.runtime-mode-set from thread.runtime-mode.set", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const singleResult = Array.isArray(result) ? null : result;
|
||||
if (singleResult === null) {
|
||||
throw new Error("Expected a single runtime-mode-set event.");
|
||||
}
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits thread.interaction-mode-set from thread.interaction-mode.set", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = yield* projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.make("cmd-interaction-mode-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
const singleResult = Array.isArray(result) ? null : result;
|
||||
if (singleResult === null) {
|
||||
throw new Error("Expected a single interaction-mode-set event.");
|
||||
}
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
interactionMode: "plan",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -250,7 +250,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
||||
scripts: [],
|
||||
scripts: command.scripts ?? [],
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
|
||||
@@ -1,959 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
function makeEvent(input: {
|
||||
sequence: number;
|
||||
type: OrchestrationEvent["type"];
|
||||
occurredAt: string;
|
||||
aggregateKind: OrchestrationEvent["aggregateKind"];
|
||||
aggregateId: string;
|
||||
commandId: string | null;
|
||||
payload: unknown;
|
||||
}): OrchestrationEvent {
|
||||
return {
|
||||
sequence: input.sequence,
|
||||
eventId: EventId.make(`event-${input.sequence}`),
|
||||
type: input.type,
|
||||
aggregateKind: input.aggregateKind,
|
||||
aggregateId:
|
||||
input.aggregateKind === "project"
|
||||
? ProjectId.make(input.aggregateId)
|
||||
: ThreadId.make(input.aggregateId),
|
||||
occurredAt: input.occurredAt,
|
||||
commandId: input.commandId === null ? null : CommandId.make(input.commandId),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload: input.payload as never,
|
||||
} as OrchestrationEvent;
|
||||
}
|
||||
|
||||
describe("orchestration projector", () => {
|
||||
it("applies thread.created events", async () => {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
const next = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-thread-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.snapshotSequence).toBe(1);
|
||||
expect(next.threads).toEqual([
|
||||
{
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when event payload cannot be decoded by runtime schema", async () => {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-invalid",
|
||||
payload: {
|
||||
// missing required threadId
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("applies thread.archived and thread.unarchived events", async () => {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const later = "2026-01-01T00:00:01.000Z";
|
||||
const created = await Effect.runPromise(
|
||||
projectEvent(
|
||||
createEmptyReadModel(now),
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-thread-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const archived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
created,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.archived",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: later,
|
||||
commandId: "cmd-thread-archive",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
archivedAt: later,
|
||||
updatedAt: later,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(archived.threads[0]?.archivedAt).toBe(later);
|
||||
|
||||
const unarchived = await Effect.runPromise(
|
||||
projectEvent(
|
||||
archived,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.unarchived",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: later,
|
||||
commandId: "cmd-thread-unarchive",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
updatedAt: later,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(unarchived.threads[0]?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
const next = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 7,
|
||||
type: "thread.turn-start-requested",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-01-01T00:00:00.000Z",
|
||||
commandId: "cmd-unhandled",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "message-1",
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.snapshotSequence).toBe(7);
|
||||
expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
|
||||
expect(next.threads).toEqual([]);
|
||||
});
|
||||
|
||||
it("tracks latest turn id from session lifecycle events", async () => {
|
||||
const createdAt = "2026-02-23T08:00:00.000Z";
|
||||
const startedAt = "2026-02-23T08:00:05.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const settledAt = "2026-02-23T08:01:00.000Z";
|
||||
const [afterRunning, afterReady] = await Effect.runPromise(
|
||||
Effect.flatMap(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: startedAt,
|
||||
commandId: "cmd-running",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
session: {
|
||||
threadId: "thread-1",
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
(running) =>
|
||||
Effect.map(
|
||||
projectEvent(
|
||||
running,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: settledAt,
|
||||
commandId: "cmd-ready",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
session: {
|
||||
threadId: "thread-1",
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: settledAt,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
(ready) => [running, ready] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const thread = afterRunning.threads[0];
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
|
||||
// Leaving the "running" session status settles the running turn with the
|
||||
// session timestamp as the turn end.
|
||||
const settledThread = afterReady.threads[0];
|
||||
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(settledThread?.latestTurn?.state).toBe("completed");
|
||||
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
|
||||
});
|
||||
|
||||
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
|
||||
const createdAt = "2026-02-23T08:00:00.000Z";
|
||||
const updatedAt = "2026-02-23T08:00:05.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const afterUpdate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.runtime-mode-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: updatedAt,
|
||||
commandId: "cmd-runtime-mode-set",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
updatedAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required");
|
||||
expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt);
|
||||
});
|
||||
|
||||
it("marks assistant messages completed with non-streaming updates", async () => {
|
||||
const createdAt = "2026-02-23T09:00:00.000Z";
|
||||
const deltaAt = "2026-02-23T09:00:01.000Z";
|
||||
const completeAt = "2026-02-23T09:00:03.500Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const afterDelta = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: deltaAt,
|
||||
commandId: "cmd-delta",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "assistant:msg-1",
|
||||
role: "assistant",
|
||||
text: "hello",
|
||||
turnId: "turn-1",
|
||||
streaming: true,
|
||||
createdAt: deltaAt,
|
||||
updatedAt: deltaAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const afterComplete = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterDelta,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: completeAt,
|
||||
commandId: "cmd-complete",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "assistant:msg-1",
|
||||
role: "assistant",
|
||||
text: "",
|
||||
turnId: "turn-1",
|
||||
streaming: false,
|
||||
createdAt: completeAt,
|
||||
updatedAt: completeAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const message = afterComplete.threads[0]?.messages[0];
|
||||
expect(message?.id).toBe("assistant:msg-1");
|
||||
expect(message?.text).toBe("hello");
|
||||
expect(message?.streaming).toBe(false);
|
||||
expect(message?.updatedAt).toBe(completeAt);
|
||||
});
|
||||
|
||||
it("prunes reverted turn messages from in-memory thread snapshot", async () => {
|
||||
const createdAt = "2026-02-23T10:00:00.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const events: ReadonlyArray<OrchestrationEvent> = [
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:01.000Z",
|
||||
commandId: "cmd-user-1",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "user-msg-1",
|
||||
role: "user",
|
||||
text: "First edit",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-02-23T10:00:01.000Z",
|
||||
updatedAt: "2026-02-23T10:00:01.000Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:02.000Z",
|
||||
commandId: "cmd-assistant-1",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "assistant-msg-1",
|
||||
role: "assistant",
|
||||
text: "Updated README to v2.\n",
|
||||
turnId: "turn-1",
|
||||
streaming: false,
|
||||
createdAt: "2026-02-23T10:00:02.000Z",
|
||||
updatedAt: "2026-02-23T10:00:02.000Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 4,
|
||||
type: "thread.turn-diff-completed",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:02.500Z",
|
||||
commandId: "cmd-turn-1-complete",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: "refs/t3/checkpoints/thread-1/turn/1",
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: "assistant-msg-1",
|
||||
completedAt: "2026-02-23T10:00:02.500Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 5,
|
||||
type: "thread.activity-appended",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:02.750Z",
|
||||
commandId: "cmd-activity-1",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
activity: {
|
||||
id: "activity-1",
|
||||
tone: "tool",
|
||||
kind: "tool.started",
|
||||
summary: "Edit file started",
|
||||
payload: { toolKind: "command" },
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-23T10:00:02.750Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 6,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:03.000Z",
|
||||
commandId: "cmd-user-2",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "user-msg-2",
|
||||
role: "user",
|
||||
text: "Second edit",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-02-23T10:00:03.000Z",
|
||||
updatedAt: "2026-02-23T10:00:03.000Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 7,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:04.000Z",
|
||||
commandId: "cmd-assistant-2",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "assistant-msg-2",
|
||||
role: "assistant",
|
||||
text: "Updated README to v3.\n",
|
||||
turnId: "turn-2",
|
||||
streaming: false,
|
||||
createdAt: "2026-02-23T10:00:04.000Z",
|
||||
updatedAt: "2026-02-23T10:00:04.000Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 8,
|
||||
type: "thread.turn-diff-completed",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:04.500Z",
|
||||
commandId: "cmd-turn-2-complete",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-2",
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: "refs/t3/checkpoints/thread-1/turn/2",
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: "assistant-msg-2",
|
||||
completedAt: "2026-02-23T10:00:04.500Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 9,
|
||||
type: "thread.activity-appended",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:04.750Z",
|
||||
commandId: "cmd-activity-2",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
activity: {
|
||||
id: "activity-2",
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Edit file complete",
|
||||
payload: { toolKind: "command" },
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-23T10:00:04.750Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 10,
|
||||
type: "thread.reverted",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: "2026-02-23T10:00:05.000Z",
|
||||
commandId: "cmd-revert",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnCount: 1,
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const afterRevert = await events.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
|
||||
(statePromise, event) =>
|
||||
statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const thread = afterRevert.threads[0];
|
||||
expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual(
|
||||
[
|
||||
{ role: "user", text: "First edit" },
|
||||
{ role: "assistant", text: "Updated README to v2.\n" },
|
||||
],
|
||||
);
|
||||
expect(
|
||||
thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
|
||||
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
|
||||
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
});
|
||||
|
||||
it("does not fallback-retain messages tied to removed turn IDs", async () => {
|
||||
const createdAt = "2026-02-26T12:00:00.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create-revert",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const events: ReadonlyArray<OrchestrationEvent> = [
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.turn-diff-completed",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: "2026-02-26T12:00:01.000Z",
|
||||
commandId: "cmd-turn-1",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
turnId: "turn-1",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: "refs/t3/checkpoints/thread-revert/turn/1",
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: "assistant-keep",
|
||||
completedAt: "2026-02-26T12:00:01.000Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: "2026-02-26T12:00:01.100Z",
|
||||
commandId: "cmd-assistant-keep",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
messageId: "assistant-keep",
|
||||
role: "assistant",
|
||||
text: "kept",
|
||||
turnId: "turn-1",
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T12:00:01.100Z",
|
||||
updatedAt: "2026-02-26T12:00:01.100Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 4,
|
||||
type: "thread.turn-diff-completed",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: "2026-02-26T12:00:02.000Z",
|
||||
commandId: "cmd-turn-2",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
turnId: "turn-2",
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: "refs/t3/checkpoints/thread-revert/turn/2",
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: "assistant-remove",
|
||||
completedAt: "2026-02-26T12:00:02.000Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 5,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: "2026-02-26T12:00:02.050Z",
|
||||
commandId: "cmd-user-remove",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
messageId: "user-remove",
|
||||
role: "user",
|
||||
text: "removed",
|
||||
turnId: "turn-2",
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T12:00:02.050Z",
|
||||
updatedAt: "2026-02-26T12:00:02.050Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 6,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: "2026-02-26T12:00:02.100Z",
|
||||
commandId: "cmd-assistant-remove",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
messageId: "assistant-remove",
|
||||
role: "assistant",
|
||||
text: "removed",
|
||||
turnId: "turn-2",
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T12:00:02.100Z",
|
||||
updatedAt: "2026-02-26T12:00:02.100Z",
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
sequence: 7,
|
||||
type: "thread.reverted",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-revert",
|
||||
occurredAt: "2026-02-26T12:00:03.000Z",
|
||||
commandId: "cmd-revert",
|
||||
payload: {
|
||||
threadId: "thread-revert",
|
||||
turnCount: 1,
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const afterRevert = await events.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
|
||||
(statePromise, event) =>
|
||||
statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const thread = afterRevert.threads[0];
|
||||
expect(
|
||||
thread?.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
turnId: message.turnId,
|
||||
})),
|
||||
).toEqual([{ id: "assistant-keep", role: "assistant", turnId: "turn-1" }]);
|
||||
});
|
||||
|
||||
it("caps message and checkpoint retention for long-lived threads", async () => {
|
||||
const createdAt = "2026-03-01T10:00:00.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-capped",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create-capped",
|
||||
payload: {
|
||||
threadId: "thread-capped",
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
modelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const messageEvents: ReadonlyArray<OrchestrationEvent> = Array.from(
|
||||
{ length: 2_100 },
|
||||
(_, index) =>
|
||||
makeEvent({
|
||||
sequence: index + 2,
|
||||
type: "thread.message-sent",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-capped",
|
||||
occurredAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
|
||||
commandId: `cmd-message-${index}`,
|
||||
payload: {
|
||||
threadId: "thread-capped",
|
||||
messageId: `msg-${index}`,
|
||||
role: "assistant",
|
||||
text: `message-${index}`,
|
||||
turnId: `turn-${index}`,
|
||||
streaming: false,
|
||||
createdAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
|
||||
updatedAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const afterMessages = await messageEvents.reduce<
|
||||
Promise<ReturnType<typeof createEmptyReadModel>>
|
||||
>(
|
||||
(statePromise, event) =>
|
||||
statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
|
||||
Promise.resolve(afterCreate),
|
||||
);
|
||||
|
||||
const checkpointEvents: ReadonlyArray<OrchestrationEvent> = Array.from(
|
||||
{ length: 600 },
|
||||
(_, index) =>
|
||||
makeEvent({
|
||||
sequence: index + 2_102,
|
||||
type: "thread.turn-diff-completed",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-capped",
|
||||
occurredAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`,
|
||||
commandId: `cmd-checkpoint-${index}`,
|
||||
payload: {
|
||||
threadId: "thread-capped",
|
||||
turnId: `turn-${index}`,
|
||||
checkpointTurnCount: index + 1,
|
||||
checkpointRef: `refs/t3/checkpoints/thread-capped/turn/${index + 1}`,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: `msg-${index}`,
|
||||
completedAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const finalState = await checkpointEvents.reduce<
|
||||
Promise<ReturnType<typeof createEmptyReadModel>>
|
||||
>(
|
||||
(statePromise, event) =>
|
||||
statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
|
||||
Promise.resolve(afterMessages),
|
||||
);
|
||||
|
||||
const thread = finalState.threads[0];
|
||||
expect(thread?.messages).toHaveLength(2_000);
|
||||
expect(thread?.messages[0]?.id).toBe("msg-100");
|
||||
expect(thread?.messages.at(-1)?.id).toBe("msg-2099");
|
||||
expect(thread?.checkpoints).toHaveLength(500);
|
||||
expect(thread?.checkpoints[0]?.turnId).toBe("turn-100");
|
||||
expect(thread?.checkpoints.at(-1)?.turnId).toBe("turn-599");
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
|
||||
command_id,
|
||||
aggregate_kind,
|
||||
aggregate_id,
|
||||
command_type,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
@@ -32,6 +33,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
|
||||
${receipt.commandId},
|
||||
${receipt.aggregateKind},
|
||||
${receipt.aggregateId},
|
||||
${receipt.commandType},
|
||||
${receipt.acceptedAt},
|
||||
${receipt.resultSequence},
|
||||
${receipt.status},
|
||||
@@ -40,7 +42,8 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
|
||||
ON CONFLICT (command_id)
|
||||
DO UPDATE SET
|
||||
aggregate_kind = excluded.aggregate_kind,
|
||||
aggregate_id = excluded.aggregate_id,
|
||||
aggregate_id = excluded.aggregate_id,
|
||||
command_type = excluded.command_type,
|
||||
accepted_at = excluded.accepted_at,
|
||||
result_sequence = excluded.result_sequence,
|
||||
status = excluded.status,
|
||||
@@ -57,6 +60,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
|
||||
command_id AS "commandId",
|
||||
aggregate_kind AS "aggregateKind",
|
||||
aggregate_id AS "aggregateId",
|
||||
command_type AS "commandType",
|
||||
accepted_at AS "acceptedAt",
|
||||
result_sequence AS "resultSequence",
|
||||
status,
|
||||
@@ -71,6 +75,37 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
|
||||
Effect.mapError(toPersistenceSqlError("OrchestrationCommandReceiptRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const insertIfAbsent: OrchestrationCommandReceiptRepositoryShape["insertIfAbsent"] = (receipt) =>
|
||||
sql<{ readonly command_id: string }>`
|
||||
INSERT INTO orchestration_command_receipts (
|
||||
command_id,
|
||||
aggregate_kind,
|
||||
aggregate_id,
|
||||
command_type,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
error
|
||||
)
|
||||
VALUES (
|
||||
${receipt.commandId},
|
||||
${receipt.aggregateKind},
|
||||
${receipt.aggregateId},
|
||||
${receipt.commandType},
|
||||
${receipt.acceptedAt},
|
||||
${receipt.resultSequence},
|
||||
${receipt.status},
|
||||
${receipt.error}
|
||||
)
|
||||
ON CONFLICT(command_id) DO NOTHING
|
||||
RETURNING command_id
|
||||
`.pipe(
|
||||
Effect.map((rows) => rows.length === 1),
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("OrchestrationCommandReceiptRepository.insertIfAbsent:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const getByCommandId: OrchestrationCommandReceiptRepositoryShape["getByCommandId"] = (input) =>
|
||||
findReceiptByCommandId(input).pipe(
|
||||
Effect.mapError(
|
||||
@@ -79,6 +114,7 @@ const makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
return {
|
||||
insertIfAbsent,
|
||||
upsert,
|
||||
getByCommandId,
|
||||
} satisfies OrchestrationCommandReceiptRepositoryShape;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { CommandId, EventId, ProjectId } from "@t3tools/contracts";
|
||||
import { CommandId, EventId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -120,4 +121,96 @@ layer("OrchestrationEventStore", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("orders project and V2 agent events in the retained application event source", () =>
|
||||
Effect.gen(function* () {
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectId = ProjectId.make("project-shared-stream");
|
||||
const threadId = ThreadId.make("thread-shared-stream");
|
||||
const providerInstanceId = ProviderInstanceId.make("codex");
|
||||
const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
|
||||
const now = DateTime.formatIso(occurredAt);
|
||||
const baselineSequence = yield* eventStore.latestApplicationSequence;
|
||||
|
||||
const projectEvent = yield* eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("event-project-shared-stream"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: projectId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("command-project-shared-stream"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-project-shared-stream"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId,
|
||||
title: "Shared stream",
|
||||
workspaceRoot: "/tmp/shared-stream",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
const [threadEvent] = yield* eventStore.appendAgentEvents({
|
||||
commandId: CommandId.make("command-thread-shared-stream"),
|
||||
events: [
|
||||
{
|
||||
id: EventId.make("event-thread-shared-stream"),
|
||||
type: "thread.created",
|
||||
threadId,
|
||||
providerInstanceId,
|
||||
occurredAt,
|
||||
payload: {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
rootThreadId: threadId,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt: occurredAt,
|
||||
updatedAt: occurredAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const applicationEvents = yield* eventStore
|
||||
.streamApplicationEvents({ afterSequence: baselineSequence })
|
||||
.pipe(
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.map((chunk) => Array.from(chunk)),
|
||||
);
|
||||
assert.deepEqual(
|
||||
applicationEvents.map((event) => event.sequence),
|
||||
[projectEvent.sequence, threadEvent!.sequence],
|
||||
);
|
||||
assert.isTrue("aggregateKind" in applicationEvents[0]!);
|
||||
assert.isTrue("event" in applicationEvents[1]!);
|
||||
|
||||
const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.map((chunk) => Array.from(chunk)),
|
||||
);
|
||||
assert.deepEqual(
|
||||
legacyReplay.map((event) => event.type),
|
||||
["project.created"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
type ApplicationStoredEvent,
|
||||
CommandId,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
@@ -8,13 +9,17 @@ import {
|
||||
OrchestrationEvent,
|
||||
OrchestrationEventMetadata,
|
||||
OrchestrationEventType,
|
||||
OrchestrationV2DomainEventJson,
|
||||
OrchestrationV2StoredEvent,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationV2DomainEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
@@ -44,6 +49,7 @@ const AppendEventRequestSchema = Schema.Struct({
|
||||
commandId: Schema.NullOr(CommandId),
|
||||
payloadJson: UnknownFromJsonString,
|
||||
metadataJson: EventMetadataFromJsonString,
|
||||
applicationEventVersion: Schema.Number,
|
||||
});
|
||||
|
||||
const OrchestrationEventPersistedRowSchema = Schema.Struct({
|
||||
@@ -67,6 +73,99 @@ const ReadFromSequenceRequestSchema = Schema.Struct({
|
||||
const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;
|
||||
const READ_PAGE_SIZE = 500;
|
||||
|
||||
interface ApplicationEventRow {
|
||||
readonly sequence: number;
|
||||
readonly event_id: string;
|
||||
readonly command_id: string | null;
|
||||
readonly aggregate_kind: "project" | "thread";
|
||||
readonly stream_id: string;
|
||||
readonly event_type: string;
|
||||
readonly occurred_at: string;
|
||||
readonly payload_json: string;
|
||||
readonly metadata_json: string;
|
||||
readonly application_event_version: number;
|
||||
readonly causation_event_id: string | null;
|
||||
readonly correlation_id: string | null;
|
||||
}
|
||||
|
||||
const decodeV2EventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson);
|
||||
const encodeV2EventJson = Schema.encodeEffect(OrchestrationV2DomainEventJson);
|
||||
const decodeV2StoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent);
|
||||
const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeJson = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
function metadataForV2Event(event: OrchestrationV2DomainEvent): Record<string, unknown> {
|
||||
return {
|
||||
...(event.runId === undefined ? {} : { runId: event.runId }),
|
||||
...(event.nodeId === undefined ? {} : { nodeId: event.nodeId }),
|
||||
...(event.driver === undefined ? {} : { driver: event.driver }),
|
||||
...(event.providerInstanceId === undefined
|
||||
? {}
|
||||
: { providerInstanceId: event.providerInstanceId }),
|
||||
...(event.rawEventId === undefined ? {} : { rawEventId: event.rawEventId }),
|
||||
};
|
||||
}
|
||||
|
||||
const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent")(function* (
|
||||
row: ApplicationEventRow,
|
||||
) {
|
||||
const payload = yield* decodeJson(row.payload_json);
|
||||
const metadata = yield* decodeJson(row.metadata_json);
|
||||
const values =
|
||||
typeof metadata === "object" && metadata !== null ? (metadata as Record<string, unknown>) : {};
|
||||
const event = yield* decodeV2EventJson({
|
||||
id: row.event_id,
|
||||
threadId: row.stream_id,
|
||||
type: row.event_type,
|
||||
occurredAt: row.occurred_at,
|
||||
payload,
|
||||
...(values.runId === undefined ? {} : { runId: values.runId }),
|
||||
...(values.nodeId === undefined ? {} : { nodeId: values.nodeId }),
|
||||
...(values.driver === undefined ? {} : { driver: values.driver }),
|
||||
...(values.providerInstanceId === undefined
|
||||
? {}
|
||||
: { providerInstanceId: values.providerInstanceId }),
|
||||
...(values.rawEventId === undefined ? {} : { rawEventId: values.rawEventId }),
|
||||
});
|
||||
return yield* decodeV2StoredEvent({
|
||||
sequence: row.sequence,
|
||||
commandId: row.command_id,
|
||||
event,
|
||||
});
|
||||
});
|
||||
|
||||
const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* (
|
||||
row: ApplicationEventRow,
|
||||
) {
|
||||
const event = yield* decodeEvent({
|
||||
sequence: row.sequence,
|
||||
eventId: row.event_id,
|
||||
type: row.event_type,
|
||||
aggregateKind: row.aggregate_kind,
|
||||
aggregateId: row.stream_id,
|
||||
occurredAt: row.occurred_at,
|
||||
commandId: row.command_id,
|
||||
causationEventId: row.causation_event_id,
|
||||
correlationId: row.correlation_id,
|
||||
payload: yield* decodeJson(row.payload_json),
|
||||
metadata: yield* decodeJson(row.metadata_json),
|
||||
});
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
case "project.meta-updated":
|
||||
case "project.deleted":
|
||||
return event;
|
||||
default:
|
||||
return yield* Effect.die(`Expected a project event, received '${event.type}'.`);
|
||||
}
|
||||
});
|
||||
|
||||
function rowToApplicationStoredEvent(
|
||||
row: ApplicationEventRow,
|
||||
): Effect.Effect<ApplicationStoredEvent, Schema.SchemaError> {
|
||||
return row.aggregate_kind === "project" ? rowToProjectEvent(row) : rowToV2StoredEvent(row);
|
||||
}
|
||||
|
||||
function inferActorKind(
|
||||
event: Omit<OrchestrationEvent, "sequence">,
|
||||
): Schema.Schema.Type<typeof OrchestrationActorKind> {
|
||||
@@ -98,6 +197,7 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
|
||||
const makeEventStore = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const committedEvents = yield* PubSub.unbounded<ApplicationStoredEvent>();
|
||||
|
||||
const appendEventRow = SqlSchema.findOne({
|
||||
Request: AppendEventRequestSchema,
|
||||
@@ -117,6 +217,7 @@ const makeEventStore = Effect.gen(function* () {
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json
|
||||
, application_event_version
|
||||
)
|
||||
VALUES (
|
||||
${request.eventId},
|
||||
@@ -141,6 +242,7 @@ const makeEventStore = Effect.gen(function* () {
|
||||
${request.actorKind},
|
||||
${request.payloadJson},
|
||||
${request.metadataJson}
|
||||
, ${request.applicationEventVersion}
|
||||
)
|
||||
RETURNING
|
||||
sequence,
|
||||
@@ -176,6 +278,7 @@ const makeEventStore = Effect.gen(function* () {
|
||||
metadata_json AS "metadata"
|
||||
FROM orchestration_events
|
||||
WHERE sequence > ${request.sequenceExclusive}
|
||||
AND (application_event_version = 1 OR aggregate_kind = 'project')
|
||||
ORDER BY sequence ASC
|
||||
LIMIT ${request.limit}
|
||||
`,
|
||||
@@ -194,6 +297,7 @@ const makeEventStore = Effect.gen(function* () {
|
||||
commandId: event.commandId,
|
||||
payloadJson: event.payload,
|
||||
metadataJson: event.metadata,
|
||||
applicationEventVersion: event.aggregateKind === "project" ? 2 : 1,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -260,10 +364,229 @@ const makeEventStore = Effect.gen(function* () {
|
||||
return readPage(sequenceExclusive, normalizedLimit);
|
||||
};
|
||||
|
||||
const readApplicationRows = (input: {
|
||||
readonly afterSequence: number;
|
||||
readonly throughSequence?: number;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly commandId?: CommandId;
|
||||
readonly onlyAgentEvents?: boolean;
|
||||
readonly limit: number;
|
||||
}) =>
|
||||
sql<ApplicationEventRow>`
|
||||
SELECT
|
||||
sequence,
|
||||
event_id,
|
||||
command_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json,
|
||||
metadata_json,
|
||||
application_event_version,
|
||||
causation_event_id,
|
||||
correlation_id
|
||||
FROM orchestration_events
|
||||
WHERE sequence > ${input.afterSequence}
|
||||
AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
|
||||
AND (
|
||||
(${input.onlyAgentEvents === true ? 1 : 0} = 0 AND aggregate_kind = 'project')
|
||||
OR (application_event_version = 2 AND aggregate_kind = 'thread')
|
||||
)
|
||||
AND (${input.threadId ?? null} IS NULL OR stream_id = ${input.threadId ?? null})
|
||||
AND (${input.commandId ?? null} IS NULL OR command_id = ${input.commandId ?? null})
|
||||
ORDER BY sequence ASC
|
||||
LIMIT ${input.limit}
|
||||
`;
|
||||
|
||||
const appendAgentEvents: OrchestrationEventStoreShape["appendAgentEvents"] = (input) =>
|
||||
Effect.forEach(
|
||||
input.events,
|
||||
(event) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeV2EventJson(event);
|
||||
const rows = yield* sql<{ readonly sequence: number }>`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json,
|
||||
application_event_version
|
||||
)
|
||||
VALUES (
|
||||
${event.id},
|
||||
'thread',
|
||||
${event.threadId},
|
||||
COALESCE(
|
||||
(
|
||||
SELECT MAX(stream_version) + 1
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId}
|
||||
),
|
||||
0
|
||||
),
|
||||
${event.type},
|
||||
${encoded.occurredAt},
|
||||
${input.commandId ?? null},
|
||||
NULL,
|
||||
${input.commandId ?? null},
|
||||
${event.rawEventId === undefined ? "server" : "provider"},
|
||||
${yield* encodeJson(encoded.payload)},
|
||||
${yield* encodeJson(metadataForV2Event(event))},
|
||||
2
|
||||
)
|
||||
RETURNING sequence
|
||||
`;
|
||||
return yield* decodeV2StoredEvent({
|
||||
sequence: rows[0]?.sequence,
|
||||
commandId: input.commandId ?? null,
|
||||
event,
|
||||
});
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"OrchestrationEventStore.appendAgentEvents:insert",
|
||||
"OrchestrationEventStore.appendAgentEvents:decode",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const readAgentEvents: OrchestrationEventStoreShape["readAgentEvents"] = (input) =>
|
||||
Stream.fromEffect(
|
||||
readApplicationRows({
|
||||
afterSequence: input?.afterSequence ?? 0,
|
||||
...(input?.throughSequence === undefined ? {} : { throughSequence: input.throughSequence }),
|
||||
...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
...(input?.commandId === undefined ? {} : { commandId: input.commandId }),
|
||||
onlyAgentEvents: true,
|
||||
limit: input?.limit ?? DEFAULT_READ_FROM_SEQUENCE_LIMIT,
|
||||
}).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")),
|
||||
),
|
||||
).pipe(
|
||||
Stream.flatMap(Stream.fromIterable),
|
||||
Stream.mapEffect((row) =>
|
||||
rowToV2StoredEvent(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const latestAgentSequence: OrchestrationEventStoreShape["latestAgentSequence"] = (threadId) =>
|
||||
sql<{ readonly sequence: number | null }>`
|
||||
SELECT MAX(sequence) AS sequence
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
AND aggregate_kind = 'thread'
|
||||
AND (${threadId ?? null} IS NULL OR stream_id = ${threadId ?? null})
|
||||
`.pipe(
|
||||
Effect.map((rows) => rows[0]?.sequence ?? 0),
|
||||
Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
|
||||
);
|
||||
|
||||
const latestApplicationSequence = sql<{ readonly sequence: number | null }>`
|
||||
SELECT MAX(sequence) AS sequence
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = 'project'
|
||||
OR (application_event_version = 2 AND aggregate_kind = 'thread')
|
||||
`.pipe(
|
||||
Effect.map((rows) => rows[0]?.sequence ?? 0),
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const readApplicationEvents = (input: {
|
||||
readonly afterSequence: number;
|
||||
readonly throughSequence: number;
|
||||
readonly limit: number;
|
||||
}): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
|
||||
Stream.fromEffect(
|
||||
readApplicationRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"),
|
||||
),
|
||||
),
|
||||
).pipe(
|
||||
Stream.flatMap(Stream.fromIterable),
|
||||
Stream.mapEffect((row) =>
|
||||
rowToApplicationStoredEvent(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const catchUpApplicationEvents = (input: {
|
||||
readonly afterSequence: number;
|
||||
readonly throughSequence: number;
|
||||
}): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> => {
|
||||
const loop = (
|
||||
afterSequence: number,
|
||||
): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
|
||||
Stream.unwrap(
|
||||
readApplicationEvents({
|
||||
afterSequence,
|
||||
throughSequence: input.throughSequence,
|
||||
limit: READ_PAGE_SIZE,
|
||||
}).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.map((chunk) => Array.from(chunk)),
|
||||
Effect.map((events) => {
|
||||
if (events.length === 0) return Stream.empty;
|
||||
const current = Stream.fromIterable(events);
|
||||
const last = events.at(-1)?.sequence ?? input.throughSequence;
|
||||
return events.length < READ_PAGE_SIZE || last >= input.throughSequence
|
||||
? current
|
||||
: Stream.concat(current, loop(last));
|
||||
}),
|
||||
),
|
||||
);
|
||||
return loop(input.afterSequence);
|
||||
};
|
||||
|
||||
const streamApplicationEvents: OrchestrationEventStoreShape["streamApplicationEvents"] = (
|
||||
input,
|
||||
) =>
|
||||
Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(committedEvents);
|
||||
const highWater = yield* latestApplicationSequence;
|
||||
const afterSequence = input?.afterSequence ?? 0;
|
||||
const replay = catchUpApplicationEvents({
|
||||
afterSequence,
|
||||
throughSequence: highWater,
|
||||
});
|
||||
const live = Stream.fromSubscription(subscription).pipe(
|
||||
Stream.filter((event) => event.sequence > Math.max(highWater, afterSequence)),
|
||||
);
|
||||
return Stream.concat(replay, live);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
append,
|
||||
readFromSequence,
|
||||
readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),
|
||||
appendAgentEvents,
|
||||
readAgentEvents,
|
||||
latestAgentSequence,
|
||||
latestApplicationSequence,
|
||||
publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
|
||||
streamApplicationEvents,
|
||||
} satisfies OrchestrationEventStoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ import Migration034V2 from "./Migrations/034_OrchestrationV2Subagents.ts";
|
||||
import Migration035V2 from "./Migrations/035_OrchestrationV2Foundation.ts";
|
||||
import Migration036V2 from "./Migrations/036_OrchestrationV2ProviderSessionBindings.ts";
|
||||
import Migration037V2 from "./Migrations/037_OrchestrationV2ThreadLaunchWorkflows.ts";
|
||||
import Migration038V2 from "./Migrations/038_ApplicationEventSource.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -103,12 +104,21 @@ export const migrationEntries = [
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
[35, "ProjectionThreadTitleRegeneration", Migration0035],
|
||||
[36, "ProjectionThreadsPinned", Migration0036],
|
||||
<<<<<<< HEAD
|
||||
[37, "ProjectionTurnsKeysetIndex", Migration0037],
|
||||
[38, "OrchestrationV2", Migration033V2],
|
||||
[39, "OrchestrationV2Subagents", Migration034V2],
|
||||
[40, "OrchestrationV2Foundation", Migration035V2],
|
||||
[41, "OrchestrationV2ProviderSessionBindings", Migration036V2],
|
||||
[42, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
|
||||
=======
|
||||
[37, "OrchestrationV2", Migration0026V2],
|
||||
[38, "OrchestrationV2Subagents", Migration0034V2],
|
||||
[39, "OrchestrationV2Foundation", Migration0035V2],
|
||||
[40, "OrchestrationV2ProviderSessionBindings", Migration036V2],
|
||||
[41, "OrchestrationV2ThreadLaunchWorkflows", Migration037V2],
|
||||
[42, "ApplicationEventSource", Migration038V2],
|
||||
>>>>>>> 56f9a4b262 (Integrate orchestration v2 with the application runtime)
|
||||
] as const;
|
||||
|
||||
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../Migrations.ts";
|
||||
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
|
||||
|
||||
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
|
||||
|
||||
layer("038_ApplicationEventSource", (it) => {
|
||||
it.effect("moves V2 events and current project state behind one global sequence", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* runMigrations({ toMigrationInclusive: 37 });
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_v2_events (
|
||||
event_id,
|
||||
command_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
provider,
|
||||
driver,
|
||||
provider_instance_id,
|
||||
raw_event_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json
|
||||
) VALUES (
|
||||
'event:v2:existing',
|
||||
'command:v2:existing',
|
||||
'thread:v2:existing',
|
||||
NULL,
|
||||
NULL,
|
||||
'codex',
|
||||
'codex',
|
||||
'codex',
|
||||
NULL,
|
||||
'thread.created',
|
||||
'2026-06-20T00:00:00.000Z',
|
||||
'{}'
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_v2_command_receipts (
|
||||
command_id,
|
||||
thread_id,
|
||||
command_type,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
error
|
||||
) VALUES (
|
||||
'command:v2:existing',
|
||||
'thread:v2:existing',
|
||||
'thread.create',
|
||||
'2026-06-20T00:00:00.000Z',
|
||||
1,
|
||||
'accepted',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
) VALUES (
|
||||
'project:existing',
|
||||
'Existing project',
|
||||
'/work/existing',
|
||||
'{"instanceId":"codex","model":"gpt-5.4"}',
|
||||
'[]',
|
||||
'2026-06-19T00:00:00.000Z',
|
||||
'2026-06-20T00:00:00.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* runMigrations({ toMigrationInclusive: 38 });
|
||||
|
||||
const events = yield* sql<{
|
||||
readonly sequence: number;
|
||||
readonly aggregate_kind: string;
|
||||
readonly stream_id: string;
|
||||
readonly event_type: string;
|
||||
readonly application_event_version: number;
|
||||
}>`
|
||||
SELECT
|
||||
sequence,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
event_type,
|
||||
application_event_version
|
||||
FROM orchestration_events
|
||||
WHERE application_event_version = 2
|
||||
ORDER BY sequence ASC
|
||||
`;
|
||||
assert.deepStrictEqual(
|
||||
events.map((event) => [event.aggregate_kind, event.stream_id, event.event_type]),
|
||||
[
|
||||
["thread", "thread:v2:existing", "thread.created"],
|
||||
["project", "project:existing", "project.created"],
|
||||
],
|
||||
);
|
||||
assert.ok(events[0]!.sequence < events[1]!.sequence);
|
||||
|
||||
const receipts = yield* sql<{
|
||||
readonly aggregate_kind: string;
|
||||
readonly aggregate_id: string;
|
||||
readonly command_type: string;
|
||||
readonly result_sequence: number;
|
||||
}>`
|
||||
SELECT aggregate_kind, aggregate_id, command_type, result_sequence
|
||||
FROM orchestration_command_receipts
|
||||
WHERE command_id = 'command:v2:existing'
|
||||
`;
|
||||
assert.deepStrictEqual(receipts, [
|
||||
{
|
||||
aggregate_kind: "thread",
|
||||
aggregate_id: "thread:v2:existing",
|
||||
command_type: "thread.create",
|
||||
result_sequence: events[0]!.sequence,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
interface LegacyV2EventRow {
|
||||
readonly event_id: string;
|
||||
readonly command_id: string | null;
|
||||
readonly thread_id: string;
|
||||
readonly run_id: string | null;
|
||||
readonly node_id: string | null;
|
||||
readonly driver: string | null;
|
||||
readonly provider_instance_id: string | null;
|
||||
readonly raw_event_id: string | null;
|
||||
readonly event_type: string;
|
||||
readonly occurred_at: string;
|
||||
readonly payload_json: string;
|
||||
}
|
||||
|
||||
interface ProjectProjectionRow {
|
||||
readonly project_id: string;
|
||||
readonly title: string;
|
||||
readonly workspace_root: string;
|
||||
readonly default_model_selection_json: string | null;
|
||||
readonly scripts_json: string;
|
||||
readonly created_at: string;
|
||||
readonly updated_at: string;
|
||||
readonly deleted_at: string | null;
|
||||
}
|
||||
|
||||
const decodeJson = Schema.decodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeJson = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE orchestration_events
|
||||
ADD COLUMN application_event_version INTEGER NOT NULL DEFAULT 1
|
||||
`;
|
||||
yield* sql`
|
||||
CREATE INDEX idx_orchestration_events_application_sequence
|
||||
ON orchestration_events(application_event_version, sequence)
|
||||
`;
|
||||
yield* sql`
|
||||
ALTER TABLE orchestration_command_receipts
|
||||
ADD COLUMN command_type TEXT NOT NULL DEFAULT 'legacy'
|
||||
`;
|
||||
|
||||
const legacyV2Events = yield* sql<LegacyV2EventRow>`
|
||||
SELECT
|
||||
event_id,
|
||||
command_id,
|
||||
thread_id,
|
||||
run_id,
|
||||
node_id,
|
||||
driver,
|
||||
provider_instance_id,
|
||||
raw_event_id,
|
||||
event_type,
|
||||
occurred_at,
|
||||
payload_json
|
||||
FROM orchestration_v2_events
|
||||
ORDER BY sequence ASC
|
||||
`;
|
||||
|
||||
yield* Effect.forEach(
|
||||
legacyV2Events,
|
||||
(event) =>
|
||||
Effect.gen(function* () {
|
||||
const metadata = yield* encodeJson({
|
||||
applicationEventVersion: 2,
|
||||
...(event.run_id === null ? {} : { runId: event.run_id }),
|
||||
...(event.node_id === null ? {} : { nodeId: event.node_id }),
|
||||
...(event.driver === null ? {} : { driver: event.driver }),
|
||||
...(event.provider_instance_id === null
|
||||
? {}
|
||||
: { providerInstanceId: event.provider_instance_id }),
|
||||
...(event.raw_event_id === null ? {} : { rawEventId: event.raw_event_id }),
|
||||
});
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json,
|
||||
application_event_version
|
||||
)
|
||||
SELECT
|
||||
${event.event_id},
|
||||
'thread',
|
||||
${event.thread_id},
|
||||
COALESCE(
|
||||
(
|
||||
SELECT MAX(stream_version) + 1
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = 'thread' AND stream_id = ${event.thread_id}
|
||||
),
|
||||
0
|
||||
),
|
||||
${event.event_type},
|
||||
${event.occurred_at},
|
||||
${event.command_id},
|
||||
NULL,
|
||||
${event.command_id},
|
||||
${event.raw_event_id === null ? "server" : "provider"},
|
||||
${event.payload_json},
|
||||
${metadata},
|
||||
2
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM orchestration_events WHERE event_id = ${event.event_id}
|
||||
)
|
||||
`;
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
|
||||
// ProjectService wrote this projection directly before the application event
|
||||
// boundary was restored. Re-baseline every current row into the shared log so
|
||||
// projection rebuilds preserve the exact pre-migration project state.
|
||||
const projectRows = yield* sql<ProjectProjectionRow>`
|
||||
SELECT
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
FROM projection_projects
|
||||
ORDER BY created_at ASC, project_id ASC
|
||||
`;
|
||||
yield* Effect.forEach(
|
||||
projectRows,
|
||||
(project) =>
|
||||
Effect.gen(function* () {
|
||||
const createdEventId = `migration:38:project:${project.project_id}:baseline`;
|
||||
const createdPayload = {
|
||||
projectId: project.project_id,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspace_root,
|
||||
defaultModelSelection:
|
||||
project.default_model_selection_json === null
|
||||
? null
|
||||
: yield* decodeJson(project.default_model_selection_json),
|
||||
scripts: yield* decodeJson(project.scripts_json),
|
||||
createdAt: project.created_at,
|
||||
updatedAt: project.updated_at,
|
||||
};
|
||||
const createdPayloadJson = yield* encodeJson(createdPayload);
|
||||
const migrationMetadataJson = yield* encodeJson({
|
||||
applicationEventVersion: 2,
|
||||
migration: 38,
|
||||
});
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json,
|
||||
application_event_version
|
||||
)
|
||||
VALUES (
|
||||
${createdEventId},
|
||||
'project',
|
||||
${project.project_id},
|
||||
COALESCE(
|
||||
(
|
||||
SELECT MAX(stream_version) + 1
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = 'project' AND stream_id = ${project.project_id}
|
||||
),
|
||||
0
|
||||
),
|
||||
'project.created',
|
||||
${project.updated_at},
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
'server',
|
||||
${createdPayloadJson},
|
||||
${migrationMetadataJson},
|
||||
2
|
||||
)
|
||||
`;
|
||||
|
||||
if (project.deleted_at !== null) {
|
||||
const deletedPayloadJson = yield* encodeJson({
|
||||
projectId: project.project_id,
|
||||
deletedAt: project.deleted_at,
|
||||
});
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_events (
|
||||
event_id,
|
||||
aggregate_kind,
|
||||
stream_id,
|
||||
stream_version,
|
||||
event_type,
|
||||
occurred_at,
|
||||
command_id,
|
||||
causation_event_id,
|
||||
correlation_id,
|
||||
actor_kind,
|
||||
payload_json,
|
||||
metadata_json,
|
||||
application_event_version
|
||||
)
|
||||
VALUES (
|
||||
${`migration:38:project:${project.project_id}:deleted`},
|
||||
'project',
|
||||
${project.project_id},
|
||||
(
|
||||
SELECT MAX(stream_version) + 1
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = 'project' AND stream_id = ${project.project_id}
|
||||
),
|
||||
'project.deleted',
|
||||
${project.deleted_at},
|
||||
NULL,
|
||||
${createdEventId},
|
||||
NULL,
|
||||
'server',
|
||||
${deletedPayloadJson},
|
||||
${migrationMetadataJson},
|
||||
2
|
||||
)
|
||||
`;
|
||||
}
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO orchestration_command_receipts (
|
||||
command_id,
|
||||
aggregate_kind,
|
||||
aggregate_id,
|
||||
accepted_at,
|
||||
result_sequence,
|
||||
status,
|
||||
error,
|
||||
command_type
|
||||
)
|
||||
SELECT
|
||||
command_id,
|
||||
'thread',
|
||||
thread_id,
|
||||
accepted_at,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT MAX(events.sequence)
|
||||
FROM orchestration_events events
|
||||
WHERE events.application_event_version = 2
|
||||
AND events.command_id = receipts.command_id
|
||||
),
|
||||
0
|
||||
),
|
||||
status,
|
||||
error,
|
||||
command_type
|
||||
FROM orchestration_v2_command_receipts receipts
|
||||
WHERE TRUE
|
||||
ON CONFLICT(command_id) DO NOTHING
|
||||
`;
|
||||
});
|
||||
@@ -26,6 +26,7 @@ export const OrchestrationCommandReceipt = Schema.Struct({
|
||||
commandId: CommandId,
|
||||
aggregateKind: OrchestrationAggregateKind,
|
||||
aggregateId: Schema.Union([ProjectId, ThreadId]),
|
||||
commandType: Schema.String,
|
||||
acceptedAt: IsoDateTime,
|
||||
resultSequence: NonNegativeInt,
|
||||
status: OrchestrationCommandReceiptStatus,
|
||||
@@ -42,6 +43,10 @@ export type GetByCommandIdInput = typeof GetByCommandIdInput.Type;
|
||||
* OrchestrationCommandReceiptRepositoryShape - Service API for command receipts.
|
||||
*/
|
||||
export interface OrchestrationCommandReceiptRepositoryShape {
|
||||
readonly insertIfAbsent: (
|
||||
receipt: OrchestrationCommandReceipt,
|
||||
) => Effect.Effect<boolean, OrchestrationCommandReceiptRepositoryError>;
|
||||
|
||||
/**
|
||||
* Insert or replace a command receipt row.
|
||||
*
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
/**
|
||||
* OrchestrationEventStore - Event store interface for orchestration events.
|
||||
* Historical name for the shared application event store.
|
||||
*
|
||||
* Owns durable append/replay access to the orchestration event stream. It does
|
||||
* not reduce events into read models or apply command validation rules.
|
||||
* Owns durable append/replay access for project events and V2 agent-thread
|
||||
* events under one global sequence. It does not reduce events into read models
|
||||
* or apply command validation rules.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* persistence/decode errors for event append and replay operations.
|
||||
*
|
||||
* @module OrchestrationEventStore
|
||||
*/
|
||||
import { OrchestrationEvent } from "@t3tools/contracts";
|
||||
import type {
|
||||
ApplicationStoredEvent,
|
||||
CommandId,
|
||||
OrchestrationEvent,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2StoredEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
@@ -52,6 +60,35 @@ export interface OrchestrationEventStoreShape {
|
||||
* @returns Stream containing all stored events.
|
||||
*/
|
||||
readonly readAll: () => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
|
||||
|
||||
/** Append V2 agent events to the same globally ordered application log. */
|
||||
readonly appendAgentEvents: (input: {
|
||||
readonly commandId?: CommandId;
|
||||
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
|
||||
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, OrchestrationEventStoreError>;
|
||||
|
||||
/** Read only V2 thread events from the application log. */
|
||||
readonly readAgentEvents: (input?: {
|
||||
readonly afterSequence?: number;
|
||||
readonly throughSequence?: number;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly commandId?: CommandId;
|
||||
readonly limit?: number;
|
||||
}) => Stream.Stream<OrchestrationV2StoredEvent, OrchestrationEventStoreError>;
|
||||
|
||||
readonly latestAgentSequence: (
|
||||
threadId?: ThreadId,
|
||||
) => Effect.Effect<number, OrchestrationEventStoreError>;
|
||||
|
||||
readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
|
||||
|
||||
/** Publish only after the surrounding event/projection transaction commits. */
|
||||
readonly publishCommitted: (events: ReadonlyArray<ApplicationStoredEvent>) => Effect.Effect<void>;
|
||||
|
||||
/** Race-free replay-to-live stream for project and V2 thread events. */
|
||||
readonly streamApplicationEvents: (input?: {
|
||||
readonly afterSequence?: number;
|
||||
}) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { ProjectId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { CommandId, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import * as ProjectionProjects from "../persistence/Layers/ProjectionProjects.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
|
||||
@@ -38,11 +39,12 @@ const metadataLayer = Layer.merge(
|
||||
}),
|
||||
);
|
||||
|
||||
const TestLayer = ProjectService.layer.pipe(
|
||||
Layer.provideMerge(ProjectionProjects.ProjectionProjectRepositoryLive),
|
||||
const TestLayer = ProjectServiceLayerLive.pipe(
|
||||
Layer.provideMerge(workspacePathsLayer),
|
||||
Layer.provideMerge(metadataLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.layer(TestLayer)("ProjectService", (it) => {
|
||||
@@ -56,14 +58,8 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
} as const;
|
||||
yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z"));
|
||||
|
||||
const changesFiber = yield* service.changes.pipe(
|
||||
Stream.take(3),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const created = yield* service.create({
|
||||
commandId: CommandId.make("command:project:create"),
|
||||
projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/work/project/",
|
||||
@@ -82,7 +78,11 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
assert.equal(created.repositoryIdentity?.canonicalKey, "github.com/t3tools/project");
|
||||
assert.equal(created.faviconPath, "/work/project/favicon.svg");
|
||||
|
||||
const updated = yield* service.update({ projectId, title: "Renamed" });
|
||||
const updated = yield* service.update({
|
||||
commandId: CommandId.make("command:project:update"),
|
||||
projectId,
|
||||
title: "Renamed",
|
||||
});
|
||||
assert.equal(updated.title, "Renamed");
|
||||
assert.equal(updated.createdAt, created.createdAt);
|
||||
|
||||
@@ -96,16 +96,25 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
[projectId],
|
||||
);
|
||||
|
||||
const deleted = yield* service.delete(projectId);
|
||||
const deleted = yield* service.delete({
|
||||
commandId: CommandId.make("command:project:delete"),
|
||||
projectId,
|
||||
});
|
||||
assert.isNotNull(deleted.deletedAt);
|
||||
assert.isTrue(Option.isNone(yield* service.getById(projectId)));
|
||||
assert.isTrue(Option.isSome(yield* service.getById(projectId, { includeDeleted: true })));
|
||||
assert.deepEqual((yield* service.snapshot).projects, []);
|
||||
|
||||
const changes = Array.from(yield* Fiber.join(changesFiber));
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const changes = yield* sql<{ readonly event_type: string }>`
|
||||
SELECT event_type
|
||||
FROM orchestration_events
|
||||
WHERE aggregate_kind = 'project' AND stream_id = ${projectId}
|
||||
ORDER BY sequence ASC
|
||||
`;
|
||||
assert.deepEqual(
|
||||
changes.map((change) => change.type),
|
||||
["project.upserted", "project.upserted", "project.deleted"],
|
||||
changes.map((change) => change.event_type),
|
||||
["project.created", "project.meta-updated", "project.deleted"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -115,12 +124,14 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
const service = yield* ProjectService.ProjectService;
|
||||
yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z"));
|
||||
yield* service.create({
|
||||
commandId: CommandId.make("command:collision:first"),
|
||||
projectId: ProjectId.make("project:collision:first"),
|
||||
title: "First",
|
||||
workspaceRoot: "/work/shared",
|
||||
});
|
||||
const error = yield* service
|
||||
.create({
|
||||
commandId: CommandId.make("command:collision:second"),
|
||||
projectId: ProjectId.make("project:collision:second"),
|
||||
title: "Second",
|
||||
workspaceRoot: "/work/shared",
|
||||
@@ -135,6 +146,7 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
const service = yield* ProjectService.ProjectService;
|
||||
yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z"));
|
||||
const input = {
|
||||
commandId: CommandId.make("command:bootstrap:first"),
|
||||
projectId: ProjectId.make("project:bootstrap"),
|
||||
title: "Bootstrap",
|
||||
workspaceRoot: "/work/bootstrap/",
|
||||
@@ -142,6 +154,7 @@ it.layer(TestLayer)("ProjectService", (it) => {
|
||||
const first = yield* service.bootstrap(input);
|
||||
const second = yield* service.bootstrap({
|
||||
...input,
|
||||
commandId: CommandId.make("command:bootstrap:second"),
|
||||
projectId: ProjectId.make("project:bootstrap:unused"),
|
||||
});
|
||||
assert.isTrue(first.created);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
type CommandId,
|
||||
ModelSelection,
|
||||
ProjectChange,
|
||||
ProjectId,
|
||||
type Project,
|
||||
type ProjectScript,
|
||||
@@ -11,16 +11,16 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts";
|
||||
import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts";
|
||||
import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
|
||||
export interface ProjectCreateInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
@@ -30,6 +30,7 @@ export interface ProjectCreateInput {
|
||||
}
|
||||
|
||||
export interface ProjectUpdateInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly title?: string;
|
||||
readonly workspaceRoot?: string;
|
||||
@@ -39,6 +40,11 @@ export interface ProjectUpdateInput {
|
||||
|
||||
export interface ProjectBootstrapInput extends ProjectCreateInput {}
|
||||
|
||||
export interface ProjectDeleteInput {
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
}
|
||||
|
||||
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
|
||||
"ProjectNotFoundError",
|
||||
{ projectId: ProjectId },
|
||||
@@ -68,7 +74,7 @@ export class ProjectOperationError extends Schema.TaggedErrorClass<ProjectOperat
|
||||
"normalize-workspace",
|
||||
"read-project",
|
||||
"list-projects",
|
||||
"persist-project",
|
||||
"dispatch-project-command",
|
||||
"resolve-favicon",
|
||||
]),
|
||||
projectId: Schema.optional(ProjectId),
|
||||
@@ -97,7 +103,7 @@ export class ProjectService extends Context.Service<
|
||||
ProjectServiceError
|
||||
>;
|
||||
readonly update: (input: ProjectUpdateInput) => Effect.Effect<Project, ProjectServiceError>;
|
||||
readonly delete: (projectId: ProjectId) => Effect.Effect<Project, ProjectServiceError>;
|
||||
readonly delete: (input: ProjectDeleteInput) => Effect.Effect<Project, ProjectServiceError>;
|
||||
readonly getById: (
|
||||
projectId: ProjectId,
|
||||
options?: { readonly includeDeleted?: boolean },
|
||||
@@ -107,16 +113,15 @@ export class ProjectService extends Context.Service<
|
||||
options?: { readonly includeDeleted?: boolean },
|
||||
) => Effect.Effect<Option.Option<Project>, ProjectOperationError>;
|
||||
readonly snapshot: Effect.Effect<ProjectSnapshot, ProjectOperationError>;
|
||||
readonly changes: Stream.Stream<ProjectChange>;
|
||||
}
|
||||
>()("t3/project/ProjectService") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const engine = yield* OrchestrationEngineService;
|
||||
const projects = yield* ProjectionProjects.ProjectionProjectRepository;
|
||||
const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
|
||||
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const changesPubSub = yield* PubSub.unbounded<ProjectChange>();
|
||||
|
||||
const hydrate = Effect.fn("ProjectService.hydrate")(function* (
|
||||
row: ProjectionProjects.ProjectionProject,
|
||||
@@ -194,24 +199,40 @@ export const make = Effect.gen(function* () {
|
||||
return row === undefined ? Option.none() : Option.some(yield* hydrate(row));
|
||||
});
|
||||
|
||||
const persist = Effect.fn("ProjectService.persist")(function* (
|
||||
row: ProjectionProjects.ProjectionProject,
|
||||
) {
|
||||
yield* projects.upsert(row).pipe(
|
||||
const readCommitted = Effect.fn("ProjectService.readCommitted")(function* (projectId: ProjectId) {
|
||||
const row = yield* projects
|
||||
.getById({ projectId })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ProjectOperationError({ operation: "read-project", projectId, cause }),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new ProjectOperationError({
|
||||
operation: "read-project",
|
||||
projectId,
|
||||
cause: "The accepted project command did not produce a project projection.",
|
||||
});
|
||||
}
|
||||
return yield* hydrate(row.value);
|
||||
});
|
||||
|
||||
const dispatch = <A>(
|
||||
projectId: ProjectId,
|
||||
command: Parameters<OrchestrationEngineService["Service"]["dispatch"]>[0],
|
||||
onCommitted: Effect.Effect<A, ProjectOperationError>,
|
||||
) =>
|
||||
engine.dispatch(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectOperationError({
|
||||
operation: "persist-project",
|
||||
projectId: row.projectId,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
operation: "dispatch-project-command",
|
||||
projectId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(onCommitted),
|
||||
);
|
||||
const project = yield* hydrate(row);
|
||||
yield* PubSub.publish(changesPubSub, { type: "project.upserted", project });
|
||||
return project;
|
||||
});
|
||||
|
||||
const assertWorkspaceAvailable = Effect.fn("ProjectService.assertWorkspaceAvailable")(function* (
|
||||
projectId: ProjectId,
|
||||
@@ -250,27 +271,21 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
yield* assertWorkspaceAvailable(input.projectId, workspaceRoot);
|
||||
const existing = yield* projects.getById({ projectId: input.projectId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectOperationError({
|
||||
operation: "read-project",
|
||||
projectId: input.projectId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
return yield* persist({
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: input.defaultModelSelection ?? null,
|
||||
scripts: [...(input.scripts ?? [])],
|
||||
createdAt: Option.isSome(existing) ? existing.value.createdAt : now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
});
|
||||
return yield* dispatch(
|
||||
input.projectId,
|
||||
{
|
||||
type: "project.create",
|
||||
commandId: input.commandId,
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: input.defaultModelSelection ?? null,
|
||||
scripts: [...(input.scripts ?? [])],
|
||||
createdAt: now,
|
||||
},
|
||||
readCommitted(input.projectId),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -304,16 +319,21 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
yield* assertWorkspaceAvailable(input.projectId, workspaceRoot);
|
||||
return yield* persist({
|
||||
...existing.value,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
workspaceRoot,
|
||||
...(input.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: input.defaultModelSelection }),
|
||||
...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }),
|
||||
updatedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
});
|
||||
return yield* dispatch(
|
||||
input.projectId,
|
||||
{
|
||||
type: "project.meta.update",
|
||||
commandId: input.commandId,
|
||||
projectId: input.projectId,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(workspaceRoot === existing.value.workspaceRoot ? {} : { workspaceRoot }),
|
||||
...(input.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: input.defaultModelSelection }),
|
||||
...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }),
|
||||
},
|
||||
readCommitted(input.projectId),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -326,7 +346,8 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")(
|
||||
function* (projectId) {
|
||||
function* (input) {
|
||||
const { projectId } = input;
|
||||
const existing = yield* projects
|
||||
.getById({ projectId })
|
||||
.pipe(
|
||||
@@ -337,22 +358,15 @@ export const make = Effect.gen(function* () {
|
||||
if (Option.isNone(existing) || existing.value.deletedAt !== null) {
|
||||
return yield* new ProjectNotFoundError({ projectId });
|
||||
}
|
||||
const deletedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const row = { ...existing.value, updatedAt: deletedAt, deletedAt };
|
||||
yield* projects.upsert(row).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectOperationError({
|
||||
operation: "persist-project",
|
||||
projectId,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
return yield* dispatch(
|
||||
projectId,
|
||||
{
|
||||
type: "project.delete",
|
||||
commandId: input.commandId,
|
||||
projectId,
|
||||
},
|
||||
readCommitted(projectId),
|
||||
);
|
||||
const project = yield* hydrate(row);
|
||||
yield* PubSub.publish(changesPubSub, { type: "project.deleted", projectId, deletedAt });
|
||||
return project;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -373,7 +387,6 @@ export const make = Effect.gen(function* () {
|
||||
getById,
|
||||
getByWorkspaceRoot,
|
||||
snapshot,
|
||||
changes: Stream.fromPubSub(changesPubSub),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,200 +1,79 @@
|
||||
import { describe, expect, it, vi } from "@effect/vitest";
|
||||
import { type OrchestrationProject, ProjectId } from "@t3tools/contracts";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import { ProjectId } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as TerminalManager from "../terminal/Manager.ts";
|
||||
import * as ProjectService from "./ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
|
||||
|
||||
const isProjectSetupScriptOperationError = Schema.is(
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptOperationError,
|
||||
);
|
||||
|
||||
const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModelSelection: null,
|
||||
scripts,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
});
|
||||
|
||||
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
|
||||
Effect.succeed(
|
||||
workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
|
||||
),
|
||||
getProjectShellById: (projectId) =>
|
||||
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
});
|
||||
|
||||
const makeTerminalManagerLayer = (
|
||||
overrides: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
|
||||
) =>
|
||||
Layer.succeed(TerminalManager.TerminalManager, {
|
||||
...overrides,
|
||||
attachStream: () => Effect.die(new Error("unused")),
|
||||
resize: () => Effect.void,
|
||||
clear: () => Effect.void,
|
||||
restart: () => Effect.die(new Error("unused")),
|
||||
close: () => Effect.void,
|
||||
subscribe: () => Effect.succeed(() => undefined),
|
||||
subscribeMetadata: () => Effect.succeed(() => undefined),
|
||||
});
|
||||
|
||||
const testLayer = (
|
||||
project: OrchestrationProject,
|
||||
terminal: Pick<TerminalManager.TerminalManager["Service"], "open" | "write">,
|
||||
) =>
|
||||
ProjectSetupScriptRunner.layer.pipe(
|
||||
Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
|
||||
Layer.provideMerge(makeTerminalManagerLayer(terminal)),
|
||||
it.effect("resolves setup scripts through the standalone project service", () => {
|
||||
const open = vi.fn((input: Parameters<TerminalManager.TerminalManager["Service"]["open"]>[0]) =>
|
||||
Effect.succeed({
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: input.worktreePath ?? null,
|
||||
status: "running" as const,
|
||||
pid: 123,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "Shell",
|
||||
updatedAt: "2026-06-20T00:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
describe("ProjectSetupScriptRunner", () => {
|
||||
it.effect("returns no-script when no setup script exists", () => {
|
||||
const open = vi.fn(() => Effect.die("unexpected open"));
|
||||
const write = vi.fn(() => Effect.die("unexpected write"));
|
||||
const project = makeProject([]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const result = yield* runner.runForThread({
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
worktreePath: "/repo/worktrees/a",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ status: "no-script" });
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(testLayer(project, { open, write })));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"opens the deterministic setup terminal with worktree env and writes the command",
|
||||
() => {
|
||||
const open = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
threadId: "thread-1",
|
||||
terminalId: "setup-setup",
|
||||
cwd: "/repo/worktrees/a",
|
||||
worktreePath: "/repo/worktrees/a",
|
||||
status: "running" as const,
|
||||
pid: 123,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
label: "setup-setup",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
const write = vi.fn(() => Effect.void);
|
||||
const project = makeProject([
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const result = yield* runner.runForThread({
|
||||
threadId: "thread-1",
|
||||
projectCwd: "/repo/project",
|
||||
worktreePath: "/repo/worktrees/a",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "started",
|
||||
scriptId: "setup",
|
||||
scriptName: "Setup",
|
||||
terminalId: "setup-setup",
|
||||
cwd: "/repo/worktrees/a",
|
||||
});
|
||||
expect(open).toHaveBeenCalledWith({
|
||||
threadId: "thread-1",
|
||||
terminalId: "setup-setup",
|
||||
cwd: "/repo/worktrees/a",
|
||||
worktreePath: "/repo/worktrees/a",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
|
||||
},
|
||||
});
|
||||
expect(write).toHaveBeenCalledWith({
|
||||
threadId: "thread-1",
|
||||
terminalId: "setup-setup",
|
||||
data: "bun install\r",
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer(project, { open, write })));
|
||||
},
|
||||
const write = vi.fn(
|
||||
(_input: Parameters<TerminalManager.TerminalManager["Service"]["write"]>[0]) => Effect.void,
|
||||
);
|
||||
|
||||
it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
|
||||
const rootCause = new Error("stat failed");
|
||||
const terminalError = new TerminalManager.TerminalCwdStatError({
|
||||
cwd: "/repo/worktrees/a",
|
||||
cause: rootCause,
|
||||
});
|
||||
const project = makeProject([
|
||||
const projectId = ProjectId.make("project:setup-runner-v2");
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
command: "vp install",
|
||||
icon: "configure" as const,
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const error = yield* runner
|
||||
.runForThread({
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
worktreePath: "/repo/worktrees/a",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(isProjectSetupScriptOperationError(error)).toBe(true);
|
||||
if (isProjectSetupScriptOperationError(error)) {
|
||||
expect(error.operation).toBe("openTerminal");
|
||||
expect(error.threadId).toBe("thread-1");
|
||||
expect(error.projectId).toBe("project-1");
|
||||
expect(error.worktreePath).toBe("/repo/worktrees/a");
|
||||
expect(error.cause).toBe(terminalError);
|
||||
expect(terminalError.cause).toBe(rootCause);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
testLayer(project, {
|
||||
open: () => Effect.fail(terminalError),
|
||||
write: () => Effect.die("unexpected write"),
|
||||
],
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
updatedAt: "2026-06-20T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
};
|
||||
const layer = ProjectSetupScriptRunner.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(ProjectService.ProjectService)({
|
||||
getById: () => Effect.succeed(Option.some(project)),
|
||||
}),
|
||||
Layer.mock(TerminalManager.TerminalManager)({ open, write }),
|
||||
),
|
||||
);
|
||||
});
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const result = yield* runner.runForThread({
|
||||
threadId: "thread-1",
|
||||
projectId,
|
||||
worktreePath: "/repo-worktree",
|
||||
});
|
||||
assert.deepEqual(result, {
|
||||
status: "started",
|
||||
scriptId: "setup",
|
||||
scriptName: "Setup",
|
||||
terminalId: "setup-setup",
|
||||
cwd: "/repo-worktree",
|
||||
});
|
||||
assert.equal(open.mock.calls[0]?.[0].cwd, "/repo-worktree");
|
||||
assert.equal(write.mock.calls[0]?.[0].data, "vp install\r");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
@@ -6,8 +6,8 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as TerminalManager from "../terminal/Manager.ts";
|
||||
import * as ProjectService from "./ProjectService.ts";
|
||||
|
||||
export interface ProjectSetupScriptRunnerResultNoScript {
|
||||
readonly status: "no-script";
|
||||
@@ -83,7 +83,7 @@ export class ProjectSetupScriptRunner extends Context.Service<
|
||||
>()("t3/project/ProjectSetupScriptRunner") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
|
||||
const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn(
|
||||
@@ -99,7 +99,7 @@ export const make = Effect.gen(function* () {
|
||||
const projectById =
|
||||
suppliedProject ??
|
||||
(input.projectId
|
||||
? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(
|
||||
? yield* projects.getById(ProjectId.make(input.projectId)).pipe(
|
||||
Effect.map(Option.getOrUndefined),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -115,7 +115,7 @@ export const make = Effect.gen(function* () {
|
||||
suppliedProject ??
|
||||
projectById ??
|
||||
(input.projectCwd
|
||||
? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(
|
||||
? yield* projects.getByWorkspaceRoot(input.projectCwd).pipe(
|
||||
Effect.map(Option.getOrUndefined),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
AuthOrchestrationOperateScope,
|
||||
AuthOrchestrationReadScope,
|
||||
EnvironmentHttpApi,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import {
|
||||
annotateEnvironmentRequest,
|
||||
failEnvironmentInternal,
|
||||
requireEnvironmentScope,
|
||||
} from "../auth/http.ts";
|
||||
import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
|
||||
import { ProjectService } from "./ProjectService.ts";
|
||||
|
||||
export const projectHttpApiLayer = HttpApiBuilder.group(
|
||||
EnvironmentHttpApi,
|
||||
"projects",
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const projects = yield* ProjectService;
|
||||
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
|
||||
|
||||
return handlers
|
||||
.handle(
|
||||
"snapshot",
|
||||
Effect.fn("environment.projects.snapshot")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
|
||||
return yield* projects.snapshot.pipe(
|
||||
Effect.catch((cause) => failEnvironmentInternal("project_snapshot_failed", cause)),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"mutate",
|
||||
Effect.fn("environment.projects.mutate")(function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthOrchestrationOperateScope);
|
||||
const mutation = args.payload;
|
||||
const operation =
|
||||
mutation.type === "project.create"
|
||||
? projects.create({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
title: mutation.title,
|
||||
workspaceRoot: mutation.workspaceRoot,
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
})
|
||||
: mutation.type === "project.update"
|
||||
? projects.update({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
...(mutation.title === undefined ? {} : { title: mutation.title }),
|
||||
...(mutation.workspaceRoot === undefined
|
||||
? {}
|
||||
: { workspaceRoot: mutation.workspaceRoot }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
})
|
||||
: projects.delete({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
});
|
||||
return yield* startup
|
||||
.enqueueCommand(operation)
|
||||
.pipe(
|
||||
Effect.catch((cause) => failEnvironmentInternal("project_mutation_failed", cause)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
type AcpRegistryAdapterV2DriverEnv,
|
||||
} from "../../orchestration-v2/Adapters/AcpRegistryAdapterV2.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderAdapterRequestError, ProviderDriverError } from "../Errors.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -25,32 +25,6 @@ import {
|
||||
const DRIVER_KIND = ProviderDriverKind.make("acpRegistry");
|
||||
const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
|
||||
|
||||
const unsupportedLegacyCall = (operation: string) =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: DRIVER_KIND,
|
||||
method: operation,
|
||||
detail: "ACP Registry instances are available through orchestration V2 only.",
|
||||
}),
|
||||
);
|
||||
|
||||
const makeLegacyAdapter = (): ProviderInstance["adapter"] => ({
|
||||
provider: DRIVER_KIND,
|
||||
capabilities: { sessionModelSwitch: "unsupported" },
|
||||
startSession: () => unsupportedLegacyCall("startSession"),
|
||||
sendTurn: () => unsupportedLegacyCall("sendTurn"),
|
||||
interruptTurn: () => unsupportedLegacyCall("interruptTurn"),
|
||||
respondToRequest: () => unsupportedLegacyCall("respondToRequest"),
|
||||
respondToUserInput: () => unsupportedLegacyCall("respondToUserInput"),
|
||||
stopSession: () => Effect.void,
|
||||
listSessions: () => Effect.succeed([]),
|
||||
hasSession: () => Effect.succeed(false),
|
||||
readThread: () => unsupportedLegacyCall("readThread"),
|
||||
rollbackThread: () => unsupportedLegacyCall("rollbackThread"),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.empty,
|
||||
});
|
||||
|
||||
const makeUnsupportedTextGeneration = (): TextGenerationShape => {
|
||||
const unsupported = (operation: string) =>
|
||||
Effect.fail(
|
||||
@@ -163,7 +137,6 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
|
||||
refresh: Effect.sync(currentSnapshot),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: makeLegacyAdapter(),
|
||||
orchestrationAdapter,
|
||||
textGeneration: makeUnsupportedTextGeneration(),
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -31,13 +31,11 @@ import {
|
||||
type ClaudeAdapterV2DriverEnv,
|
||||
} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
import {
|
||||
checkClaudeProviderStatus,
|
||||
makePendingClaudeProvider,
|
||||
probeClaudeCapabilities,
|
||||
} from "../Layers/ClaudeProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -91,7 +89,6 @@ export type ClaudeDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
@@ -127,7 +124,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
const { cwd } = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -146,12 +142,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
continuationGroupKey,
|
||||
});
|
||||
|
||||
const adapterOptions = {
|
||||
instanceId,
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
};
|
||||
const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);
|
||||
const orchestrationAdapter = yield* ClaudeAdapterV2Driver.create({
|
||||
instanceId,
|
||||
displayName,
|
||||
@@ -235,7 +225,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
orchestrationAdapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -38,9 +38,7 @@ import {
|
||||
type CodexAdapterV2DriverEnv,
|
||||
} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
@@ -82,7 +80,6 @@ export type CodexDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
@@ -121,7 +118,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
const continuationIdentity = codexContinuationIdentity(homeLayout);
|
||||
@@ -152,17 +148,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
|
||||
// channels at construction time — their failure modes are all on the
|
||||
// per-operation closures they return. No `mapError` wrapper is needed
|
||||
// here; the registry only has to worry about snapshot-build and
|
||||
// spawner-availability failures surfaced from `checkCodexProviderStatus`
|
||||
// below.
|
||||
const adapter = yield* makeCodexAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
});
|
||||
const orchestrationAdapter = yield* CodexAdapterV2Driver.create({
|
||||
instanceId,
|
||||
displayName,
|
||||
@@ -227,7 +212,6 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
orchestrationAdapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -29,14 +29,12 @@ import {
|
||||
type CursorAdapterV2DriverEnv,
|
||||
} from "../../orchestration-v2/Adapters/CursorAdapterV2.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
import {
|
||||
buildInitialCursorProviderSnapshot,
|
||||
checkCursorProviderStatus,
|
||||
enrichCursorSnapshot,
|
||||
} from "../Layers/CursorProvider.ts";
|
||||
import { CursorSdkCatalogLive } from "../Layers/CursorSdkCatalog.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -76,7 +74,6 @@ export type CursorDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
@@ -112,7 +109,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -130,11 +126,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeCursorAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
instanceId,
|
||||
});
|
||||
const orchestrationAdapter = yield* CursorAdapterV2Driver.create({
|
||||
instanceId,
|
||||
displayName,
|
||||
@@ -204,7 +195,6 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
orchestrationAdapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -16,13 +16,11 @@ import {
|
||||
type GrokAdapterV2DriverEnv,
|
||||
} from "../../orchestration-v2/Adapters/GrokAdapterV2.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
|
||||
import {
|
||||
buildInitialGrokProviderSnapshot,
|
||||
checkGrokProviderStatus,
|
||||
enrichGrokSnapshot,
|
||||
} from "../Layers/GrokProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -58,7 +56,6 @@ export type GrokDriverEnv =
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
@@ -92,7 +89,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -110,11 +106,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeGrokAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
instanceId,
|
||||
});
|
||||
const orchestrationAdapter = yield* GrokAdapterV2Driver.create({
|
||||
instanceId,
|
||||
displayName,
|
||||
@@ -178,7 +169,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
orchestrationAdapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -29,12 +29,10 @@ import {
|
||||
type OpenCodeAdapterV2DriverEnv,
|
||||
} from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
import {
|
||||
checkOpenCodeProviderStatus,
|
||||
makePendingOpenCodeProvider,
|
||||
} from "../Layers/OpenCodeProvider.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import { OpenCodeRuntime } from "../opencodeRuntime.ts";
|
||||
import {
|
||||
@@ -87,7 +85,6 @@ export type OpenCodeDriverEnv =
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
@@ -121,7 +118,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -139,11 +135,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
});
|
||||
const orchestrationAdapter = yield* OpenCodeAdapterV2Driver.create({
|
||||
instanceId,
|
||||
displayName,
|
||||
@@ -208,7 +199,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
accentColor,
|
||||
enabled,
|
||||
snapshot,
|
||||
adapter,
|
||||
orchestrationAdapter,
|
||||
textGeneration,
|
||||
} satisfies ProviderInstance;
|
||||
|
||||
@@ -1,126 +1,10 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { CheckpointServiceError } from "../checkpointing/Errors.ts";
|
||||
|
||||
/**
|
||||
* ProviderAdapterValidationError - Invalid adapter API input.
|
||||
*/
|
||||
export class ProviderAdapterValidationError extends Schema.TaggedErrorClass<ProviderAdapterValidationError>()(
|
||||
"ProviderAdapterValidationError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
operation: Schema.String,
|
||||
issue: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter validation failed (${this.provider}) in ${this.operation}: ${this.issue}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterSessionNotFoundError - Adapter-owned session id is unknown.
|
||||
*/
|
||||
export class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass<ProviderAdapterSessionNotFoundError>()(
|
||||
"ProviderAdapterSessionNotFoundError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unknown ${this.provider} adapter thread: ${this.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterSessionClosedError - Adapter session exists but is closed.
|
||||
*/
|
||||
export class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass<ProviderAdapterSessionClosedError>()(
|
||||
"ProviderAdapterSessionClosedError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.provider} adapter thread is closed: ${this.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterRequestError - Provider protocol request failed or timed out.
|
||||
*/
|
||||
export class ProviderAdapterRequestError extends Schema.TaggedErrorClass<ProviderAdapterRequestError>()(
|
||||
"ProviderAdapterRequestError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
method: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterProcessError - Provider process lifecycle failure.
|
||||
*/
|
||||
export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<ProviderAdapterProcessError>()(
|
||||
"ProviderAdapterProcessError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderValidationError - Invalid provider API input.
|
||||
*/
|
||||
export class ProviderValidationError extends Schema.TaggedErrorClass<ProviderValidationError>()(
|
||||
"ProviderValidationError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
issue: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider validation failed in ${this.operation}: ${this.issue}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderUnsupportedError - Requested provider is not implemented.
|
||||
*/
|
||||
export class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUnsupportedError>()(
|
||||
"ProviderUnsupportedError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider '${this.provider}' is not implemented`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderInstanceNotFoundError - Lookup against the instance registry failed.
|
||||
*
|
||||
* Distinct from `ProviderUnsupportedError`: the driver is registered, but no
|
||||
* instance with the requested id has been bootstrapped — typically because
|
||||
* The driver may be registered, but no instance with the requested id has
|
||||
* been bootstrapped — typically because
|
||||
* the persisted instance id refers to an instance the user removed from
|
||||
* settings, or because routing is asked for an instance before the registry
|
||||
* has finished its first reload.
|
||||
@@ -155,50 +39,3 @@ export class ProviderDriverError extends Schema.TaggedErrorClass<ProviderDriverE
|
||||
return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionNotFoundError - Provider-facing session not found.
|
||||
*/
|
||||
export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<ProviderSessionNotFoundError>()(
|
||||
"ProviderSessionNotFoundError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unknown provider thread: ${this.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionDirectoryPersistenceError - Session directory persistence failure.
|
||||
*/
|
||||
export class ProviderSessionDirectoryPersistenceError extends Schema.TaggedErrorClass<ProviderSessionDirectoryPersistenceError>()(
|
||||
"ProviderSessionDirectoryPersistenceError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider session directory persistence error in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type ProviderAdapterError =
|
||||
| ProviderAdapterValidationError
|
||||
| ProviderAdapterSessionNotFoundError
|
||||
| ProviderAdapterSessionClosedError
|
||||
| ProviderAdapterRequestError
|
||||
| ProviderAdapterProcessError;
|
||||
|
||||
export type ProviderServiceError =
|
||||
| ProviderValidationError
|
||||
| ProviderUnsupportedError
|
||||
| ProviderInstanceNotFoundError
|
||||
| ProviderSessionNotFoundError
|
||||
| ProviderSessionDirectoryPersistenceError
|
||||
| ProviderAdapterError
|
||||
| CheckpointServiceError;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,181 +0,0 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { it, assert, vi } from "@effect/vitest";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import { ProviderUnsupportedError } from "../Errors.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
|
||||
const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
|
||||
provider: CODEX_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
|
||||
provider: CLAUDE_AGENT_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
provider: "opencode",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
provider: "cursor",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
|
||||
// it walks `listInstances` once at boot and surfaces the default-instance
|
||||
// adapter keyed by its driver kind. To test the facade we supply four fake
|
||||
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
|
||||
// they pass the default-instance filter.
|
||||
const makeFakeInstance = (
|
||||
driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode",
|
||||
adapter: ProviderInstance["adapter"],
|
||||
): ProviderInstance => {
|
||||
const driverKind = ProviderDriverKind.make(driverKindString);
|
||||
return {
|
||||
instanceId: defaultInstanceIdForDriver(driverKind),
|
||||
driverKind,
|
||||
continuationIdentity: {
|
||||
driverKind,
|
||||
continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`,
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
|
||||
refresh: Effect.succeed({} as unknown as ServerProvider),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter,
|
||||
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
|
||||
textGeneration: {} as unknown as TextGenerationShape,
|
||||
};
|
||||
};
|
||||
|
||||
const fakeInstances: ReadonlyArray<ProviderInstance> = [
|
||||
makeFakeInstance("codex", fakeCodexAdapter),
|
||||
makeFakeInstance("claudeAgent", fakeClaudeAdapter),
|
||||
makeFakeInstance("opencode", fakeOpenCodeAdapter),
|
||||
makeFakeInstance("cursor", fakeCursorAdapter),
|
||||
];
|
||||
|
||||
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
|
||||
listInstances: Effect.succeed(fakeInstances),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
// Tests never drive changes through this fake; acquire a throwaway
|
||||
// subscription on an unused PubSub so the shape is satisfied.
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) => PubSub.subscribe(pubsub)),
|
||||
});
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer),
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
|
||||
it("resolves adapters and routing metadata from provider instances", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const codex = yield* registry.getByProvider("codex");
|
||||
const claude = yield* registry.getByProvider("claudeAgent");
|
||||
const openCode = yield* registry.getByProvider("opencode");
|
||||
const cursor = yield* registry.getByProvider("cursor");
|
||||
assert.equal(codex, fakeCodexAdapter);
|
||||
assert.equal(claude, fakeClaudeAdapter);
|
||||
assert.equal(openCode, fakeOpenCodeAdapter);
|
||||
assert.equal(cursor, fakeCursorAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails with ProviderUnsupportedError for unknown providers", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result);
|
||||
assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" }));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,123 +0,0 @@
|
||||
/**
|
||||
* ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.
|
||||
*
|
||||
* `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one
|
||||
* adapter via the four `<X>AdapterLive` singleton Layers. The per-instance
|
||||
* refactor moved adapter construction inside each `ProviderDriver.create()`:
|
||||
* adapters are now bundled on the `ProviderInstance` that the
|
||||
* `ProviderInstanceRegistry` owns.
|
||||
*
|
||||
* This facade fulfills the `ProviderAdapterRegistryShape` contract by doing
|
||||
* dynamic look-ups against `ProviderInstanceRegistry` on every call. That
|
||||
* means settings-driven hot-reload shows up here automatically — adding a
|
||||
* new instance via settings makes `getByInstance` resolve immediately
|
||||
* without rebuilding the facade.
|
||||
*
|
||||
* @module ProviderAdapterRegistryLive
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ProviderUnsupportedError } from "../Errors.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry;
|
||||
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
|
||||
options?: ProviderAdapterRegistryLiveOptions,
|
||||
) {
|
||||
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [
|
||||
yield* CodexAdapter,
|
||||
yield* ClaudeAdapter,
|
||||
yield* OpenCodeAdapter,
|
||||
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
|
||||
];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(
|
||||
new ProviderUnsupportedError({
|
||||
provider: instanceId,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
displayName: instance.displayName,
|
||||
accentColor: instance.accentColor,
|
||||
enabled: instance.enabled,
|
||||
continuationIdentity: instance.continuationIdentity,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
|
||||
);
|
||||
|
||||
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => {
|
||||
const kinds = new Set<ProviderDriverKind>();
|
||||
for (const instance of instances) {
|
||||
const defaultId = defaultInstanceIdForDriver(instance.driverKind);
|
||||
if (instance.instanceId === defaultId) {
|
||||
// Only the default-instance rows show up through the legacy
|
||||
// shim — custom instances like `codex_personal` have no
|
||||
// `ProviderDriverKind` equivalent.
|
||||
kinds.add(instance.driverKind);
|
||||
}
|
||||
}
|
||||
return Array.from(kinds);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
getByInstance,
|
||||
getInstanceInfo,
|
||||
listInstances,
|
||||
listProviders,
|
||||
// Proxy directly — the facade has no state of its own; the instance
|
||||
// registry already coalesces adds/removes/rebuilds into one emission.
|
||||
streamChanges: registry.streamChanges,
|
||||
subscribeChanges: registry.subscribeChanges,
|
||||
} satisfies ProviderAdapterRegistryShape;
|
||||
});
|
||||
|
||||
export const ProviderAdapterRegistryLive = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
makeProviderAdapterRegistry(),
|
||||
);
|
||||
|
||||
// Exposed for tests that want to build a facade over a pre-assembled
|
||||
// `ProviderInstanceRegistry` without pulling in the whole boot graph.
|
||||
export { makeProviderAdapterRegistry };
|
||||
|
||||
// Re-export for consumers that need the accessor shape. The service tag
|
||||
// itself lives in `Services/ProviderAdapterRegistry.ts`.
|
||||
export { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
// Re-export for consumers (including tests) that construct a
|
||||
// `ProviderInstanceId` before calling `getByInstance`.
|
||||
export { ProviderInstanceId };
|
||||
@@ -203,7 +203,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
const work = yield* registry.getInstance(workId);
|
||||
expect(personal).toBeDefined();
|
||||
expect(work).toBeDefined();
|
||||
expect(personal!.adapter).not.toBe(work!.adapter);
|
||||
expect(personal!.orchestrationAdapter).not.toBe(work!.orchestrationAdapter);
|
||||
expect(personal!.textGeneration).not.toBe(work!.textGeneration);
|
||||
expect(personal!.snapshot).not.toBe(work!.snapshot);
|
||||
|
||||
@@ -384,16 +384,16 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
expect(openCode?.displayName).toBe("OpenCode");
|
||||
|
||||
// Every instance owns its own set of closures — no sharing across
|
||||
// drivers. `adapter` / `textGeneration` / `snapshot` are all
|
||||
// drivers. `orchestrationAdapter` / `textGeneration` / `snapshot` are all
|
||||
// distinct references even when two instances happen to share a
|
||||
// trait (e.g. Cursor + others all use a stub-or-real
|
||||
// `textGeneration`; they must still be different object values).
|
||||
const adapters = [
|
||||
codex!.adapter,
|
||||
claude!.adapter,
|
||||
cursor!.adapter,
|
||||
grok!.adapter,
|
||||
openCode!.adapter,
|
||||
codex!.orchestrationAdapter,
|
||||
claude!.orchestrationAdapter,
|
||||
cursor!.orchestrationAdapter,
|
||||
grok!.orchestrationAdapter,
|
||||
openCode!.orchestrationAdapter,
|
||||
];
|
||||
expect(new Set(adapters).size).toBe(adapters.length);
|
||||
const textGenerations = [
|
||||
|
||||
@@ -658,7 +658,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
@@ -701,7 +700,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
refresh: Effect.succeed(refreshedProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
@@ -800,7 +798,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
refresh: Effect.die(new Error("simulated refresh failure")),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
@@ -890,7 +887,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,271 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { assertSome } from "@effect/vitest/utils";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
|
||||
function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlClient, E, R>) {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer));
|
||||
return Layer.mergeAll(
|
||||
runtimeRepositoryLayer,
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
NodeServices.layer,
|
||||
);
|
||||
}
|
||||
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const initialThreadId = ThreadId.make("thread-1");
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: initialThreadId,
|
||||
});
|
||||
|
||||
const provider = yield* directory.getProvider(initialThreadId);
|
||||
assert.equal(provider, "codex");
|
||||
const resolvedBinding = yield* directory.getBinding(initialThreadId);
|
||||
assertSome(resolvedBinding, {
|
||||
threadId: initialThreadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
if (Option.isSome(resolvedBinding)) {
|
||||
assert.equal(resolvedBinding.value.threadId, initialThreadId);
|
||||
}
|
||||
|
||||
const nextThreadId = ThreadId.make("thread-2");
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: nextThreadId,
|
||||
});
|
||||
const updatedBinding = yield* directory.getBinding(nextThreadId);
|
||||
assert.equal(Option.isSome(updatedBinding), true);
|
||||
if (Option.isSome(updatedBinding)) {
|
||||
assert.equal(updatedBinding.value.threadId, nextThreadId);
|
||||
}
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId: nextThreadId });
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.threadId, nextThreadId);
|
||||
assert.equal(runtime.value.status, "running");
|
||||
assert.equal(runtime.value.providerName, "codex");
|
||||
}
|
||||
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
assert.deepEqual(threadIds, [nextThreadId]);
|
||||
}));
|
||||
|
||||
it("persists runtime fields and merges payload updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const threadId = ThreadId.make("thread-runtime");
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
status: "starting",
|
||||
resumeCursor: {
|
||||
threadId: "provider-thread-runtime",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
status: "running",
|
||||
runtimePayload: {
|
||||
activeTurnId: "turn-1",
|
||||
},
|
||||
});
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.threadId, threadId);
|
||||
assert.equal(runtime.value.status, "running");
|
||||
assert.deepEqual(runtime.value.resumeCursor, {
|
||||
threadId: "provider-thread-runtime",
|
||||
});
|
||||
assert.deepEqual(runtime.value.runtimePayload, {
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5-codex",
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
it("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const olderThreadId = ThreadId.make("thread-runtime-older");
|
||||
const newerThreadId = ThreadId.make("thread-runtime-newer");
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId: newerThreadId,
|
||||
providerName: "codex",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T12:05:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-newer",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/newer",
|
||||
},
|
||||
});
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId: olderThreadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
status: "starting",
|
||||
lastSeenAt: "2026-04-14T12:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-older",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/older",
|
||||
},
|
||||
});
|
||||
|
||||
const bindings = yield* directory.listBindings();
|
||||
|
||||
assert.deepEqual(bindings, [
|
||||
{
|
||||
threadId: olderThreadId,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
status: "starting",
|
||||
lastSeenAt: "2026-04-14T12:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-older",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/older",
|
||||
},
|
||||
},
|
||||
{
|
||||
threadId: newerThreadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T12:05:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-newer",
|
||||
},
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/newer",
|
||||
},
|
||||
},
|
||||
]);
|
||||
}));
|
||||
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.make("thread-provider-change");
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-01-01T00:00:00.000Z",
|
||||
resumeCursor: null,
|
||||
runtimePayload: null,
|
||||
});
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
});
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.providerName, "codex");
|
||||
assert.equal(runtime.value.adapterKey, "codex");
|
||||
}
|
||||
}));
|
||||
|
||||
it("rehydrates persisted mappings across layer restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-directory-"));
|
||||
const dbPath = NodePath.join(tempDir, "orchestration.sqlite");
|
||||
const directoryLayer = makeDirectoryLayer(makeSqlitePersistenceLive(dbPath));
|
||||
|
||||
const threadId = ThreadId.make("thread-restart");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
});
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const provider = yield* directory.getProvider(threadId);
|
||||
assert.equal(provider, "codex");
|
||||
|
||||
const resolvedBinding = yield* directory.getBinding(threadId);
|
||||
assertSome(resolvedBinding, {
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
if (Option.isSome(resolvedBinding)) {
|
||||
assert.equal(resolvedBinding.value.threadId, threadId);
|
||||
}
|
||||
|
||||
const legacyTableRows = yield* sql<{ readonly name: string }>`
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'provider_sessions'
|
||||
`;
|
||||
assert.equal(legacyTableRows.length, 0);
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}));
|
||||
});
|
||||
@@ -1,201 +0,0 @@
|
||||
import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionDirectory,
|
||||
type ProviderRuntimeBinding,
|
||||
type ProviderRuntimeBindingWithMetadata,
|
||||
type ProviderSessionDirectoryShape,
|
||||
} from "../Services/ProviderSessionDirectory.ts";
|
||||
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
|
||||
|
||||
function toPersistenceError(operation: string) {
|
||||
return (cause: unknown) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Failed to execute ${operation}.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function decodeProviderDriverKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKindValue(providerName).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Unknown persisted provider '${providerName}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function mergeRuntimePayload(
|
||||
existing: unknown | null,
|
||||
next: unknown | null | undefined,
|
||||
): unknown | null {
|
||||
if (next === undefined) {
|
||||
return existing ?? null;
|
||||
}
|
||||
if (isRecord(existing) && isRecord(next)) {
|
||||
return { ...existing, ...next };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function toRuntimeBinding(
|
||||
runtime: ProviderSessionRuntime.ProviderSessionRuntime,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {
|
||||
return decodeProviderDriverKind(runtime.providerName, operation).pipe(
|
||||
Effect.map(
|
||||
(provider) =>
|
||||
({
|
||||
threadId: runtime.threadId,
|
||||
provider,
|
||||
// Migration boundary only: rows written before the instance split
|
||||
// have a null provider_instance_id. Promote them as they leave
|
||||
// persistence so hot routing code never has to infer an instance
|
||||
// from a driver kind.
|
||||
providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),
|
||||
adapterKey: runtime.adapterKey,
|
||||
runtimeMode: runtime.runtimeMode,
|
||||
status: runtime.status,
|
||||
resumeCursor: runtime.resumeCursor,
|
||||
runtimePayload: runtime.runtimePayload,
|
||||
lastSeenAt: runtime.lastSeenAt,
|
||||
}) satisfies ProviderRuntimeBindingWithMetadata,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const getBinding = (threadId: ThreadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")),
|
||||
Effect.flatMap((runtime) =>
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onSome: (value) =>
|
||||
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map((binding) => Option.some(binding)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
|
||||
const existing = yield* repository
|
||||
.getByThreadId({ threadId: binding.threadId })
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
|
||||
|
||||
const existingRuntime = Option.getOrUndefined(existing);
|
||||
const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;
|
||||
if (!resolvedThreadId) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "threadId must be a non-empty string.",
|
||||
});
|
||||
}
|
||||
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
const providerChanged =
|
||||
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
|
||||
const providerInstanceId =
|
||||
binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);
|
||||
if (providerInstanceId === null || providerInstanceId === undefined) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderSessionDirectory.upsert",
|
||||
issue: "providerInstanceId is required for provider session runtime bindings.",
|
||||
});
|
||||
}
|
||||
yield* repository
|
||||
.upsert({
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
providerInstanceId,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor:
|
||||
binding.resumeCursor !== undefined
|
||||
? binding.resumeCursor
|
||||
: (existingRuntime?.resumeCursor ?? null),
|
||||
runtimePayload: mergeRuntimePayload(
|
||||
existingRuntime?.runtimePayload ?? null,
|
||||
binding.runtimePayload,
|
||||
),
|
||||
})
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
|
||||
});
|
||||
|
||||
const getProvider: ProviderSessionDirectoryShape["getProvider"] = (threadId) =>
|
||||
getBinding(threadId).pipe(
|
||||
Effect.flatMap((binding) =>
|
||||
Option.match(binding, {
|
||||
onSome: (value) => Effect.succeed(value.provider),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getProvider",
|
||||
detail: `No persisted provider binding found for thread '${threadId}'.`,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
|
||||
Effect.map((rows) => rows.map((row) => row.threadId)),
|
||||
);
|
||||
|
||||
const listBindings: ProviderSessionDirectoryShape["listBindings"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listBindings:list")),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
listThreadIds,
|
||||
listBindings,
|
||||
} satisfies ProviderSessionDirectoryShape;
|
||||
});
|
||||
|
||||
export const ProviderSessionDirectoryLive = Layer.effect(
|
||||
ProviderSessionDirectory,
|
||||
makeProviderSessionDirectory,
|
||||
);
|
||||
|
||||
export function makeProviderSessionDirectoryLive() {
|
||||
return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);
|
||||
}
|
||||
@@ -1,592 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import { ProviderValidationError } from "../Errors.ts";
|
||||
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
|
||||
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
|
||||
|
||||
const defaultModelSelection = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
} as const;
|
||||
|
||||
async function waitFor(
|
||||
predicate: () => boolean | Promise<boolean>,
|
||||
timeoutMs = 2_000,
|
||||
): Promise<void> {
|
||||
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (await predicate()) {
|
||||
return;
|
||||
}
|
||||
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
|
||||
throw new Error("Timed out waiting for expectation.");
|
||||
}
|
||||
await Effect.runPromise(Effect.yieldNow);
|
||||
return poll();
|
||||
};
|
||||
|
||||
return poll();
|
||||
}
|
||||
|
||||
const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
|
||||
discard: true,
|
||||
});
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
|
||||
function makeReadModel(
|
||||
threads: ReadonlyArray<{
|
||||
readonly id: ThreadId;
|
||||
readonly session: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
|
||||
readonly providerName: "codex" | "claudeAgent";
|
||||
readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
|
||||
readonly activeTurnId: TurnId | null;
|
||||
readonly lastError: string | null;
|
||||
readonly updatedAt: string;
|
||||
} | null;
|
||||
}>,
|
||||
) {
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const projectId = ProjectId.make("project-provider-session-reaper");
|
||||
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
updatedAt: now,
|
||||
projects: [
|
||||
{
|
||||
id: projectId,
|
||||
title: "Provider Reaper Project",
|
||||
workspaceRoot: "/tmp/provider-reaper-project",
|
||||
defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId,
|
||||
title: `Thread ${thread.id}`,
|
||||
modelSelection: defaultModelSelection,
|
||||
interactionMode: "default" as const,
|
||||
runtimeMode: "full-access" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
latestTurn: null,
|
||||
messages: [],
|
||||
session: thread.session,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderSessionReaper", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
scope = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
async function createHarness(input: {
|
||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||
readonly stopSessionImplementation?: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||
}) {
|
||||
const stoppedThreadIds = new Set<ThreadId>();
|
||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||
(request) =>
|
||||
(input.stopSessionImplementation
|
||||
? input.stopSessionImplementation(request)
|
||||
: Effect.sync(() => {
|
||||
stoppedThreadIds.add(request.threadId);
|
||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||
);
|
||||
|
||||
const providerService: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession,
|
||||
listSessions: () => Effect.succeed([]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
getInstanceInfo: (instanceId) => {
|
||||
const driverKind = ProviderDriverKind.make(String(instanceId));
|
||||
return Effect.succeed({
|
||||
instanceId,
|
||||
driverKind,
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
continuationIdentity: {
|
||||
driverKind,
|
||||
continuationKey: `${driverKind}:instance:${instanceId}`,
|
||||
},
|
||||
});
|
||||
},
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const layer = makeProviderSessionReaperLive({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}).pipe(
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () =>
|
||||
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: (threadId) =>
|
||||
Effect.succeed(
|
||||
input.readModel.threads.find((thread) => thread.id === threadId)
|
||||
? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
|
||||
: Option.none(),
|
||||
),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
return { stopSession, stoppedThreadIds };
|
||||
}
|
||||
|
||||
it("reaps stale persisted sessions without active turns", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-stale");
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-stale",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
|
||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
|
||||
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips stale sessions when the thread still has an active turn", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-active-turn");
|
||||
const turnId = TurnId.make("turn-reaper-active");
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-active-turn",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not reap sessions that are still within the inactivity threshold", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-fresh");
|
||||
const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor: {
|
||||
opaque: "resume-fresh",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips persisted sessions that are already marked stopped", async () => {
|
||||
const threadId = ThreadId.make("thread-reaper-stopped");
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "stopped",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "stopped",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-stopped",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(drainFibers);
|
||||
|
||||
expect(harness.stopSession).not.toHaveBeenCalled();
|
||||
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
|
||||
expect(Option.isSome(remaining)).toBe(true);
|
||||
});
|
||||
|
||||
it("continues reaping other sessions when one stop attempt fails", async () => {
|
||||
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
|
||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: failedThreadId,
|
||||
session: {
|
||||
threadId: failedThreadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: reapedThreadId,
|
||||
session: {
|
||||
threadId: reapedThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
stopSessionImplementation: (request) =>
|
||||
request.threadId === failedThreadId
|
||||
? Effect.fail(
|
||||
new ProviderValidationError({
|
||||
operation: "ProviderSessionReaper.test",
|
||||
issue: "simulated stop failure",
|
||||
}),
|
||||
)
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: failedThreadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-failure",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-success",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
||||
failedThreadId,
|
||||
reapedThreadId,
|
||||
]);
|
||||
});
|
||||
|
||||
it("continues reaping other sessions when one stop attempt defects", async () => {
|
||||
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
|
||||
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const harness = await createHarness({
|
||||
readModel: makeReadModel([
|
||||
{
|
||||
id: defectThreadId,
|
||||
session: {
|
||||
threadId: defectThreadId,
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: reapedThreadId,
|
||||
session: {
|
||||
threadId: reapedThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
]),
|
||||
stopSessionImplementation: (request) =>
|
||||
request.threadId === defectThreadId
|
||||
? Effect.die(new Error("simulated stop defect"))
|
||||
: Effect.void,
|
||||
});
|
||||
const repository = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
|
||||
);
|
||||
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: defectThreadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:00:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-defect",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
await runtime!.runPromise(
|
||||
repository.upsert({
|
||||
threadId: reapedThreadId,
|
||||
providerName: "codex",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-04-14T00:01:00.000Z",
|
||||
resumeCursor: {
|
||||
opaque: "resume-after-defect",
|
||||
},
|
||||
runtimePayload: null,
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
|
||||
defectThreadId,
|
||||
reapedThreadId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,139 +0,0 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
type ProviderSessionReaperShape,
|
||||
} from "../Services/ProviderSessionReaper.ts";
|
||||
import { forkParked } from "../../serverActivation.ts";
|
||||
import { ProviderService } from "../Services/ProviderService.ts";
|
||||
|
||||
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
|
||||
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
export interface ProviderSessionReaperLiveOptions {
|
||||
readonly inactivityThresholdMs?: number;
|
||||
readonly sweepIntervalMs?: number;
|
||||
}
|
||||
|
||||
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
|
||||
);
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
|
||||
const sweep = Effect.gen(function* () {
|
||||
const bindings = yield* directory.listBindings();
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
let reapedCount = 0;
|
||||
|
||||
for (const binding of bindings) {
|
||||
if (binding.status === "stopped") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const lastSeenMs = Date.parse(binding.lastSeenAt);
|
||||
if (Number.isNaN(lastSeenMs)) {
|
||||
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
lastSeenAt: binding.lastSeenAt,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const idleDurationMs = now - lastSeenMs;
|
||||
if (idleDurationMs < inactivityThresholdMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const thread = yield* projectionSnapshotQuery
|
||||
.getThreadShellById(binding.threadId)
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
if (thread?.session?.activeTurnId != null) {
|
||||
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
|
||||
threadId: binding.threadId,
|
||||
activeTurnId: thread.session.activeTurnId,
|
||||
idleDurationMs,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.logInfo("provider.session.reaped", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
idleDurationMs,
|
||||
reason: "inactivity_threshold",
|
||||
}),
|
||||
),
|
||||
Effect.as(true),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider.session.reaper.stop-failed", {
|
||||
threadId: binding.threadId,
|
||||
provider: binding.provider,
|
||||
idleDurationMs,
|
||||
cause,
|
||||
}).pipe(Effect.as(false)),
|
||||
),
|
||||
);
|
||||
|
||||
if (reaped) {
|
||||
reapedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (reapedCount > 0) {
|
||||
yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
|
||||
reapedCount,
|
||||
totalBindings: bindings.length,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const start: ProviderSessionReaperShape["start"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* forkParked(
|
||||
sweep.pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-failed", {
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.catchDefect((defect: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-defect", {
|
||||
defect,
|
||||
}),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.logInfo("provider.session.reaper.started", {
|
||||
inactivityThresholdMs,
|
||||
sweepIntervalMs,
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies ProviderSessionReaperShape;
|
||||
});
|
||||
|
||||
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
|
||||
|
||||
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
|
||||
@@ -2,8 +2,8 @@
|
||||
* ProviderDriver / ProviderInstance — driver SPI as plain values.
|
||||
*
|
||||
* `ProviderDriver` is a record, not a Context.Service. The thing it produces
|
||||
* (`ProviderInstance`) is also a record — three captured closures
|
||||
* (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There
|
||||
* (`ProviderInstance`) is also a record of captured closures
|
||||
* (`snapshot`, `orchestrationAdapter`, `textGeneration`), an id, and a driver kind. There
|
||||
* are intentionally no per-driver Context tags because tags are
|
||||
* singleton-per-runtime and we need many instances of the same driver.
|
||||
*
|
||||
@@ -32,8 +32,7 @@ import type * as Scope from "effect/Scope";
|
||||
|
||||
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
|
||||
import type { ProviderAdapterV2Shape } from "../orchestration-v2/ProviderAdapter.ts";
|
||||
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import type { ProviderDriverError } from "./Errors.ts";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
|
||||
/**
|
||||
@@ -70,7 +69,6 @@ export interface ProviderInstance {
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly snapshot: ServerProviderShape;
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly orchestrationAdapter: ProviderAdapterV2Shape;
|
||||
readonly textGeneration: TextGenerationShape;
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* ClaudeAdapter — shape type for the Claude provider adapter.
|
||||
*
|
||||
* Historically this module exposed a `Context.Service` tag so consumers
|
||||
* could inject the adapter through the Effect layer graph. The driver
|
||||
* model ({@link ../Drivers/ClaudeDriver}) bundles one adapter per
|
||||
* instance as a captured closure instead, so the tag is gone — we only
|
||||
* retain the shape interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module ClaudeAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* ClaudeAdapterShape — per-instance Claude adapter contract. Carries
|
||||
* a branded driver kind as the nominal discriminant.
|
||||
*/
|
||||
export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* CodexAdapter — shape type for the Codex provider adapter.
|
||||
*
|
||||
* Historically this module exposed a `Context.Service` tag so consumers
|
||||
* could inject the adapter through the Effect layer graph. The driver
|
||||
* model ({@link ../Drivers/CodexDriver}) bundles one adapter per
|
||||
* instance as a captured closure instead, so the tag is gone — we only
|
||||
* retain the shape interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module CodexAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* CodexAdapterShape — per-instance Codex adapter contract. Carries
|
||||
* a branded driver kind as the nominal discriminant.
|
||||
*/
|
||||
export interface CodexAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* CursorAdapter — shape type for the Cursor provider adapter.
|
||||
*
|
||||
* Historically this module exposed a `Context.Service` tag so consumers
|
||||
* could inject the adapter through the Effect layer graph. The driver
|
||||
* model ({@link ../Drivers/CursorDriver}) bundles one adapter per
|
||||
* instance as a captured closure instead, so the tag is gone — we only
|
||||
* retain the shape interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module CursorAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* CursorAdapterShape — per-instance Cursor adapter contract. Carries
|
||||
* a branded driver kind as the nominal discriminant.
|
||||
*/
|
||||
export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -1,16 +0,0 @@
|
||||
/**
|
||||
* GrokAdapter — shape type for the Grok provider adapter.
|
||||
*
|
||||
* The driver model ({@link ../Drivers/GrokDriver}) bundles one adapter per
|
||||
* instance as a captured closure, so this module only retains the shape
|
||||
* interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module GrokAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* GrokAdapterShape — per-instance Grok adapter contract.
|
||||
*/
|
||||
export interface GrokAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* OpenCodeAdapter — shape type for the OpenCode provider adapter.
|
||||
*
|
||||
* Historically this module exposed a `Context.Service` tag so consumers
|
||||
* could inject the adapter through the Effect layer graph. The driver
|
||||
* model ({@link ../Drivers/OpenCodeDriver}) bundles one adapter per
|
||||
* instance as a captured closure instead, so the tag is gone — we only
|
||||
* retain the shape interface as a naming anchor for the driver bundle.
|
||||
*
|
||||
* @module OpenCodeAdapter
|
||||
*/
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* OpenCodeAdapterShape — per-instance OpenCode adapter contract. Carries
|
||||
* a branded driver kind as the nominal discriminant.
|
||||
*/
|
||||
export interface OpenCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
|
||||
@@ -1,126 +0,0 @@
|
||||
/**
|
||||
* ProviderAdapter - Provider-specific runtime adapter contract.
|
||||
*
|
||||
* Defines the provider-native session/protocol operations that `ProviderService`
|
||||
* routes to after resolving the target provider. Implementations should focus
|
||||
* on provider behavior only and avoid cross-provider orchestration concerns.
|
||||
*
|
||||
* @module ProviderAdapter
|
||||
*/
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderDriverKind,
|
||||
ProviderUserInputAnswers,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ThreadId,
|
||||
ProviderTurnStartResult,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
export type ProviderSessionModelSwitchMode = "in-session" | "unsupported";
|
||||
|
||||
export interface ProviderAdapterCapabilities {
|
||||
/**
|
||||
* Declares whether changing the model on an existing session is supported.
|
||||
*/
|
||||
readonly sessionModelSwitch: ProviderSessionModelSwitchMode;
|
||||
}
|
||||
|
||||
export interface ProviderThreadTurnSnapshot {
|
||||
readonly id: TurnId;
|
||||
readonly items: ReadonlyArray<unknown>;
|
||||
}
|
||||
|
||||
export interface ProviderThreadSnapshot {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turns: ReadonlyArray<ProviderThreadTurnSnapshot>;
|
||||
}
|
||||
|
||||
export interface ProviderAdapterShape<TError> {
|
||||
/**
|
||||
* Provider kind implemented by this adapter.
|
||||
*/
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly capabilities: ProviderAdapterCapabilities;
|
||||
|
||||
/**
|
||||
* Start a provider-backed session.
|
||||
*/
|
||||
readonly startSession: (
|
||||
input: ProviderSessionStartInput,
|
||||
) => Effect.Effect<ProviderSession, TError>;
|
||||
|
||||
/**
|
||||
* Send a turn to an active provider session.
|
||||
*/
|
||||
readonly sendTurn: (
|
||||
input: ProviderSendTurnInput,
|
||||
) => Effect.Effect<ProviderTurnStartResult, TError>;
|
||||
|
||||
/**
|
||||
* Interrupt an active turn.
|
||||
*/
|
||||
readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Respond to an interactive approval request.
|
||||
*/
|
||||
readonly respondToRequest: (
|
||||
threadId: ThreadId,
|
||||
requestId: ApprovalRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Respond to a structured user-input request.
|
||||
*/
|
||||
readonly respondToUserInput: (
|
||||
threadId: ThreadId,
|
||||
requestId: ApprovalRequestId,
|
||||
answers: ProviderUserInputAnswers,
|
||||
) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Stop one provider session.
|
||||
*/
|
||||
readonly stopSession: (threadId: ThreadId) => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* List currently active provider sessions for this adapter.
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;
|
||||
|
||||
/**
|
||||
* Check whether this adapter owns an active session id.
|
||||
*/
|
||||
readonly hasSession: (threadId: ThreadId) => Effect.Effect<boolean>;
|
||||
|
||||
/**
|
||||
* Read a provider thread snapshot.
|
||||
*/
|
||||
readonly readThread: (threadId: ThreadId) => Effect.Effect<ProviderThreadSnapshot, TError>;
|
||||
|
||||
/**
|
||||
* Roll back a provider thread by N turns.
|
||||
*/
|
||||
readonly rollbackThread: (
|
||||
threadId: ThreadId,
|
||||
numTurns: number,
|
||||
) => Effect.Effect<ProviderThreadSnapshot, TError>;
|
||||
|
||||
/**
|
||||
* Stop all sessions owned by this adapter.
|
||||
*/
|
||||
readonly stopAll: () => Effect.Effect<void, TError>;
|
||||
|
||||
/**
|
||||
* Canonical runtime event stream emitted by this adapter.
|
||||
*/
|
||||
readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/**
|
||||
* ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.
|
||||
*
|
||||
* Maps a `ProviderInstanceId` (the new per-instance routing key) or a
|
||||
* `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete
|
||||
* adapter service (Codex, Claude, etc). It does not own session lifecycle
|
||||
* or routing rules; `ProviderService` uses this registry together with
|
||||
* `ProviderSessionDirectory`.
|
||||
*
|
||||
* During the driver/instance migration this tag exposes both flavours:
|
||||
*
|
||||
* - `getByInstance` / `listInstances` — new per-instance routing. Callers
|
||||
* that already know an `instanceId` (threads, sessions, events)
|
||||
* should prefer these.
|
||||
* (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D
|
||||
* behaviour. New code should not grow additional callers of the kind-keyed
|
||||
* methods; they exist so the settings UI, WS refresh RPC, and a handful
|
||||
* of legacy persisted rows can still be routed during the rollout.
|
||||
*
|
||||
* @module ProviderAdapterRegistry
|
||||
*/
|
||||
import type { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as PubSub from "effect/PubSub";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
import type { ProviderContinuationIdentity } from "../ProviderDriver.ts";
|
||||
|
||||
export interface ProviderInstanceRoutingInfo {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly driverKind: ProviderDriverKind;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly continuationIdentity: ProviderContinuationIdentity;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterRegistryShape - Service API for adapter lookup.
|
||||
*/
|
||||
export interface ProviderAdapterRegistryShape {
|
||||
/**
|
||||
* Resolve the adapter for a specific instance id. Returns
|
||||
* `ProviderUnsupportedError` if no such instance is currently registered
|
||||
* (which covers "never configured" *and* "configured but the driver is
|
||||
* unavailable in this build" — both surface the same failure to callers
|
||||
* that expect a working adapter).
|
||||
*/
|
||||
readonly getByInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;
|
||||
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
|
||||
|
||||
/**
|
||||
* List all live instance ids. Excludes unavailable/shadow instances —
|
||||
* callers of this method want something they can pass to `getByInstance`.
|
||||
*/
|
||||
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
||||
|
||||
/**
|
||||
* Legacy: list provider kinds whose default instance is currently
|
||||
* registered.
|
||||
*
|
||||
* @deprecated Prefer `listInstances`. Retained for migration-era call
|
||||
* sites that iterate providers to build UI/metrics.
|
||||
*/
|
||||
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
|
||||
|
||||
/**
|
||||
* Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`.
|
||||
* Emits one `void` tick whenever the set of live instances changes
|
||||
* (instance added, removed, or rebuilt after a settings edit). Consumers
|
||||
* that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s
|
||||
* runtime event bus — re-pull `listInstances` on each tick and fork new
|
||||
* subscriptions for instances they haven't seen yet.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
|
||||
/**
|
||||
* Acquire a change subscription synchronously in the caller's current fiber.
|
||||
* Consumers that must avoid missing a publish between initial reconciliation
|
||||
* and watcher startup should use this, then fork `Stream.fromSubscription`.
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderAdapterRegistry - Service tag for provider adapter lookup.
|
||||
*/
|
||||
export class ProviderAdapterRegistry extends Context.Service<
|
||||
ProviderAdapterRegistry,
|
||||
ProviderAdapterRegistryShape
|
||||
>()("t3/provider/Services/ProviderAdapterRegistry") {}
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* ProviderService - Service interface for provider sessions, turns, and checkpoints.
|
||||
*
|
||||
* Acts as the cross-provider facade used by transports (WebSocket/RPC). It
|
||||
* resolves provider adapters through `ProviderAdapterRegistry`, routes
|
||||
* session-scoped calls via `ProviderSessionDirectory`, and exposes one unified
|
||||
* provider event stream to callers.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection and returns typed
|
||||
* domain errors for validation, session, codex, and checkpoint workflows.
|
||||
*
|
||||
* @module ProviderService
|
||||
*/
|
||||
import type {
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderInstanceId,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderRespondToUserInputInput,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ThreadId,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import type { ProviderServiceError } from "../Errors.ts";
|
||||
import type { ProviderAdapterCapabilities } from "./ProviderAdapter.ts";
|
||||
import type { ProviderInstanceRoutingInfo } from "./ProviderAdapterRegistry.ts";
|
||||
|
||||
/**
|
||||
* ProviderServiceShape - Service API for provider session and turn orchestration.
|
||||
*/
|
||||
export interface ProviderServiceShape {
|
||||
/**
|
||||
* Start a provider session.
|
||||
*/
|
||||
readonly startSession: (
|
||||
threadId: ThreadId,
|
||||
input: ProviderSessionStartInput,
|
||||
) => Effect.Effect<ProviderSession, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Send a provider turn.
|
||||
*/
|
||||
readonly sendTurn: (
|
||||
input: ProviderSendTurnInput,
|
||||
) => Effect.Effect<ProviderTurnStartResult, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Interrupt a running provider turn.
|
||||
*/
|
||||
readonly interruptTurn: (
|
||||
input: ProviderInterruptTurnInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Respond to a provider approval request.
|
||||
*/
|
||||
readonly respondToRequest: (
|
||||
input: ProviderRespondToRequestInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Respond to a provider structured user-input request.
|
||||
*/
|
||||
readonly respondToUserInput: (
|
||||
input: ProviderRespondToUserInputInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Stop a provider session.
|
||||
*/
|
||||
readonly stopSession: (
|
||||
input: ProviderStopSessionInput,
|
||||
) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* List active provider sessions.
|
||||
*
|
||||
* Aggregates runtime session lists from all registered adapters.
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;
|
||||
|
||||
/**
|
||||
* Read capabilities for the adapter bound to a configured provider instance.
|
||||
*/
|
||||
readonly getCapabilities: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;
|
||||
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Roll back provider conversation state by a number of turns.
|
||||
*/
|
||||
readonly rollbackConversation: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly numTurns: number;
|
||||
}) => Effect.Effect<void, ProviderServiceError>;
|
||||
|
||||
/**
|
||||
* Canonical provider runtime event stream.
|
||||
*
|
||||
* Fan-out is owned by ProviderService (not by a standalone event-bus service).
|
||||
*/
|
||||
readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderService - Service tag for provider orchestration.
|
||||
*/
|
||||
export class ProviderService extends Context.Service<ProviderService, ProviderServiceShape>()(
|
||||
"t3/provider/Services/ProviderService",
|
||||
) {}
|
||||
@@ -1,70 +0,0 @@
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ProviderSessionRuntimeStatus,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
import type {
|
||||
ProviderSessionDirectoryPersistenceError,
|
||||
ProviderValidationError,
|
||||
} from "../Errors.ts";
|
||||
|
||||
export interface ProviderRuntimeBinding {
|
||||
readonly threadId: ThreadId;
|
||||
readonly provider: ProviderDriverKind;
|
||||
/**
|
||||
* Routing key for the configured provider instance that owns this
|
||||
* session. The persistence layer promotes legacy null rows before
|
||||
* exposing bindings; runtime callers must not infer this from `provider`.
|
||||
*/
|
||||
readonly providerInstanceId?: ProviderInstanceId;
|
||||
readonly adapterKey?: string;
|
||||
readonly status?: ProviderSessionRuntimeStatus;
|
||||
readonly resumeCursor?: unknown | null;
|
||||
readonly runtimePayload?: unknown | null;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {
|
||||
readonly lastSeenAt: string;
|
||||
}
|
||||
|
||||
export type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
| ProviderValidationError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export interface ProviderSessionDirectoryShape {
|
||||
readonly upsert: (
|
||||
binding: ProviderRuntimeBinding,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
|
||||
|
||||
readonly getProvider: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;
|
||||
|
||||
readonly getBinding: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;
|
||||
|
||||
readonly listThreadIds: () => Effect.Effect<
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
|
||||
readonly listBindings: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
|
||||
export class ProviderSessionDirectory extends Context.Service<
|
||||
ProviderSessionDirectory,
|
||||
ProviderSessionDirectoryShape
|
||||
>()("t3/provider/Services/ProviderSessionDirectory") {}
|
||||
@@ -1,15 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
export interface ProviderSessionReaperShape {
|
||||
/**
|
||||
* Start the background provider session reaper within the provided scope.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ProviderSessionReaper extends Context.Service<
|
||||
ProviderSessionReaper,
|
||||
ProviderSessionReaperShape
|
||||
>()("t3/provider/Services/ProviderSessionReaper") {}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";
|
||||
|
||||
describe("AcpAdapterSupport", () => {
|
||||
it("maps ACP approval decisions to permission outcomes", () => {
|
||||
expect(acpPermissionOutcome("accept")).toBe("allow-once");
|
||||
expect(acpPermissionOutcome("acceptForSession")).toBe("allow-always");
|
||||
expect(acpPermissionOutcome("decline")).toBe("reject-once");
|
||||
});
|
||||
|
||||
it("maps ACP request errors to provider adapter request errors", () => {
|
||||
const error = mapAcpToAdapterError(
|
||||
ProviderDriverKind.make("cursor"),
|
||||
"thread-1" as never,
|
||||
"session/prompt",
|
||||
new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: "Invalid params",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error._tag).toBe("ProviderAdapterRequestError");
|
||||
expect(error.message).toContain("Invalid params");
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import {
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderDriverKind,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import {
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionClosedError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
|
||||
const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
|
||||
|
||||
export function mapAcpToAdapterError(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
method: string,
|
||||
error: EffectAcpErrors.AcpError,
|
||||
): ProviderAdapterError {
|
||||
if (isAcpProcessExitedError(error)) {
|
||||
return new ProviderAdapterSessionClosedError({
|
||||
provider,
|
||||
threadId,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
if (isAcpRequestError(error)) {
|
||||
return new ProviderAdapterRequestError({
|
||||
provider,
|
||||
method,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new ProviderAdapterRequestError({
|
||||
provider,
|
||||
method,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export function acpPermissionOutcome(decision: ProviderApprovalDecision): string {
|
||||
switch (decision) {
|
||||
case "acceptForSession":
|
||||
return "allow-always";
|
||||
case "accept":
|
||||
return "allow-once";
|
||||
case "decline":
|
||||
default:
|
||||
return "reject-once";
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/**
|
||||
* Test helpers for constructing a `ProviderAdapterRegistryShape` mock from a
|
||||
* kind-keyed adapter map.
|
||||
*
|
||||
* Tests historically assembled a `registry` object with only `getByProvider`
|
||||
* + `listProviders` populated. Slice D grew the shape with `getByInstance`
|
||||
* and `listInstances`; this helper fills both in from a single kind-keyed
|
||||
* input so individual fixtures can stay concise.
|
||||
*
|
||||
* Non-default instance ids (e.g. `codex_personal`) are not addressable via
|
||||
* the shim returned here — the legacy test fixtures only ever had
|
||||
* single-instance-per-driver data anyway.
|
||||
*
|
||||
* @module provider/testUtils/providerAdapterRegistryMock
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Record from "effect/Record";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import type { ProviderAdapterRegistryShape } from "../Services/ProviderAdapterRegistry.ts";
|
||||
|
||||
export type KindAdapterMap = Partial<
|
||||
Record<ProviderDriverKind, ProviderAdapterShape<ProviderAdapterError>>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Build a `ProviderAdapterRegistryShape` from a kind-keyed adapter map.
|
||||
* Every adapter present in the map is addressable via both the legacy
|
||||
* `getByProvider(kind)` path and the new `getByInstance(id)` path (where
|
||||
* `id = defaultInstanceIdForDriver(kind)`).
|
||||
*/
|
||||
export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapterRegistryShape => {
|
||||
const byInstanceId = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();
|
||||
for (const [kind, adapter] of Object.entries(adapters)) {
|
||||
if (!adapter) continue;
|
||||
const driverKind = ProviderDriverKind.make(kind);
|
||||
byInstanceId.set(defaultInstanceIdForDriver(driverKind), adapter);
|
||||
}
|
||||
|
||||
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) => {
|
||||
const adapter = byInstanceId.get(instanceId);
|
||||
return adapter
|
||||
? Effect.succeed(adapter)
|
||||
: Effect.fail(
|
||||
new ProviderUnsupportedError({
|
||||
provider: ProviderDriverKind.make(instanceId),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
getByInstance,
|
||||
getInstanceInfo: (instanceId) => {
|
||||
const adapter = byInstanceId.get(instanceId);
|
||||
if (!adapter) {
|
||||
return Effect.fail(
|
||||
new ProviderUnsupportedError({
|
||||
provider: ProviderDriverKind.make(instanceId),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed({
|
||||
instanceId,
|
||||
driverKind: ProviderDriverKind.make(adapter.provider),
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
continuationIdentity: {
|
||||
driverKind: ProviderDriverKind.make(adapter.provider),
|
||||
continuationKey: `${adapter.provider}:instance:${instanceId}`,
|
||||
},
|
||||
});
|
||||
},
|
||||
listInstances: () => Effect.succeed(Array.from(byInstanceId.keys())),
|
||||
listProviders: () =>
|
||||
Effect.succeed(
|
||||
Record.keys(
|
||||
Record.filterMap(adapters, (adapter, kind) =>
|
||||
adapter !== undefined ? Result.succeed(kind) : Result.failVoid,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Static test fixtures don't reload; an empty stream is enough to
|
||||
// satisfy the shape. Tests exercising hot-reload build their own
|
||||
// stream via the real `ProviderInstanceRegistry`.
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -1,725 +0,0 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
OrchestrationEvent,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadShell,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import type {
|
||||
RelayAgentActivityPublishProofPayload,
|
||||
RelayAgentActivityState,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { CommandId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
|
||||
RELAY_ISSUER_SECRET,
|
||||
RELAY_URL_SECRET,
|
||||
PUBLISH_AGENT_ACTIVITY_SECRET,
|
||||
} from "../cloud/config.ts";
|
||||
import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";
|
||||
|
||||
const state: RelayAgentActivityState = {
|
||||
environmentId: "env" as RelayAgentActivityState["environmentId"],
|
||||
threadId: "thread" as RelayAgentActivityState["threadId"],
|
||||
projectTitle: "Project",
|
||||
threadTitle: "Thread",
|
||||
modelTitle: "gpt-5.4",
|
||||
phase: "running",
|
||||
headline: "Running",
|
||||
updatedAt: "2026-05-25T00:00:00.000Z",
|
||||
deepLink: "/threads/env/thread",
|
||||
};
|
||||
|
||||
const encodeSecret = (value: string): Uint8Array => new TextEncoder().encode(value);
|
||||
|
||||
function makeMemorySecretStore() {
|
||||
const values = new Map<string, Uint8Array>();
|
||||
const store = {
|
||||
get: ((name) =>
|
||||
Effect.sync(() => {
|
||||
const value = values.get(name);
|
||||
return value === undefined ? Option.none() : Option.some(Uint8Array.from(value));
|
||||
})) satisfies ServerSecretStore.ServerSecretStore["Service"]["get"],
|
||||
set: ((name, value) =>
|
||||
Effect.sync(() => {
|
||||
values.set(name, Uint8Array.from(value));
|
||||
})) satisfies ServerSecretStore.ServerSecretStore["Service"]["set"],
|
||||
create: ((name, value) =>
|
||||
Effect.sync(() => {
|
||||
values.set(name, Uint8Array.from(value));
|
||||
})) satisfies ServerSecretStore.ServerSecretStore["Service"]["create"],
|
||||
getOrCreateRandom: ((name, bytes) =>
|
||||
Effect.sync(() => {
|
||||
const existing = values.get(name);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const generated = new Uint8Array(bytes);
|
||||
values.set(name, generated);
|
||||
return generated;
|
||||
})) satisfies ServerSecretStore.ServerSecretStore["Service"]["getOrCreateRandom"],
|
||||
remove: ((name) =>
|
||||
Effect.sync(() => {
|
||||
values.delete(name);
|
||||
})) satisfies ServerSecretStore.ServerSecretStore["Service"]["remove"],
|
||||
} satisfies ServerSecretStore.ServerSecretStore["Service"];
|
||||
return {
|
||||
store,
|
||||
setString: (name: string, value: string) => store.set(name, encodeSecret(value)),
|
||||
};
|
||||
}
|
||||
|
||||
describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
it("distinguishes pending link credentials from disabled publication", () => {
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
|
||||
relayConfigured: false,
|
||||
publishEnabled: false,
|
||||
}),
|
||||
).toBe("waiting-for-link");
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
|
||||
relayConfigured: true,
|
||||
publishEnabled: false,
|
||||
}),
|
||||
).toBe("disabled");
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({
|
||||
relayConfigured: true,
|
||||
publishEnabled: true,
|
||||
}),
|
||||
).toBe("enabled");
|
||||
});
|
||||
|
||||
it("derives the thread id from the aggregate id for thread events without payload thread ids", () => {
|
||||
const threadId = "thread-aggregate-1" as ThreadId;
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const event = {
|
||||
type: "thread.activity-appended",
|
||||
sequence: 1,
|
||||
eventId: "evt-aggregate-1",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
actor: { kind: "server" },
|
||||
payload: {},
|
||||
occurredAt: now,
|
||||
} as unknown as OrchestrationEvent;
|
||||
|
||||
expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
|
||||
});
|
||||
|
||||
it("does not publish start intents, streaming content, or non-awareness activity events", () => {
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const base = {
|
||||
sequence: 1,
|
||||
eventId: "evt-1",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1" as ThreadId,
|
||||
occurredAt: now,
|
||||
};
|
||||
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
streaming: true,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.activity-appended",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
activity: {
|
||||
kind: "task.progress",
|
||||
},
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.activity-appended",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
activity: {
|
||||
kind: "approval.requested",
|
||||
},
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(true);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
streaming: false,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
threadId: "thread-1" as ThreadId,
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
|
||||
expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).toBe(
|
||||
AgentAwarenessRelay.agentAwarenessPublishIdentity({
|
||||
...state,
|
||||
updatedAt: "2026-05-25T00:10:00.000Z",
|
||||
}),
|
||||
);
|
||||
expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).not.toBe(
|
||||
AgentAwarenessRelay.agentAwarenessPublishIdentity({
|
||||
...state,
|
||||
phase: "completed",
|
||||
headline: "Agent finished",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("requires an explicit opt-in before publishing agent activity", () => {
|
||||
expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled(null)).toBe(false);
|
||||
expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled("false")).toBe(false);
|
||||
expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled("true")).toBe(true);
|
||||
});
|
||||
|
||||
it("redacts failed activity details and caps other relay detail", () => {
|
||||
expect(
|
||||
AgentAwarenessRelay.sanitizeRelayAgentActivityState({
|
||||
...state,
|
||||
phase: "failed",
|
||||
detail: "Provider process exited with secret token.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
phase: "failed",
|
||||
detail: "The agent run failed.",
|
||||
});
|
||||
expect(
|
||||
AgentAwarenessRelay.sanitizeRelayAgentActivityState({
|
||||
...state,
|
||||
detail: "x".repeat(200),
|
||||
})?.detail,
|
||||
).toHaveLength(160);
|
||||
});
|
||||
|
||||
it("resolves a null publish state when a thread or project snapshot disappeared", () => {
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
const thread = {
|
||||
id: threadId,
|
||||
projectId: "project-1" as ProjectId,
|
||||
title: "Deleted thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
session: null,
|
||||
latestTurn: null,
|
||||
updatedAt: "2026-05-25T00:00:00.000Z",
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
} as OrchestrationThreadShell;
|
||||
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
|
||||
environmentId,
|
||||
threadId,
|
||||
thread: Option.none(),
|
||||
project: Option.none(),
|
||||
}),
|
||||
).toEqual({
|
||||
projectId: null,
|
||||
state: null,
|
||||
reason: "thread-not-found",
|
||||
});
|
||||
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({
|
||||
environmentId,
|
||||
threadId,
|
||||
thread: Option.some(thread),
|
||||
project: Option.none(),
|
||||
}),
|
||||
).toEqual({
|
||||
projectId: "project-1",
|
||||
state: null,
|
||||
reason: "project-not-found",
|
||||
});
|
||||
});
|
||||
|
||||
it("selects only active shell snapshot threads for startup catch-up", () => {
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
const projectId = "project-1" as ProjectId;
|
||||
const activeThreadId = "thread-active" as ThreadId;
|
||||
const idleThreadId = "thread-idle" as ThreadId;
|
||||
|
||||
const baseThread = {
|
||||
projectId,
|
||||
title: "Run remote agent",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
} satisfies Omit<OrchestrationThreadShell, "id">;
|
||||
|
||||
expect(
|
||||
AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({
|
||||
environmentId,
|
||||
projects: [
|
||||
{
|
||||
id: projectId,
|
||||
title: "T3 Code",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
...baseThread,
|
||||
id: activeThreadId,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as TurnId,
|
||||
state: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
...baseThread,
|
||||
id: idleThreadId,
|
||||
},
|
||||
{
|
||||
...baseThread,
|
||||
id: "thread-missing-project" as ThreadId,
|
||||
projectId: "missing-project" as ProjectId,
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as TurnId,
|
||||
state: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([activeThreadId]);
|
||||
});
|
||||
|
||||
it("signs the activity publish JWT and rejects tampering", async () => {
|
||||
const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
|
||||
privateKeyEncoding: { format: "pem", type: "pkcs8" },
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
const payload = {
|
||||
iss: "t3-env:env",
|
||||
aud: "https://relay.example.test",
|
||||
sub: "env",
|
||||
jti: "nonce-1",
|
||||
iat: 100,
|
||||
exp: 200,
|
||||
environmentId: state.environmentId,
|
||||
threadId: state.threadId,
|
||||
state,
|
||||
} satisfies RelayAgentActivityPublishProofPayload;
|
||||
const proof = await Effect.runPromise(
|
||||
AgentAwarenessRelay.signRelayAgentActivityPublishProof({
|
||||
privateKey: keyPair.privateKey,
|
||||
payload,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
verifyRelayJwt({
|
||||
publicKey: keyPair.publicKey,
|
||||
token: proof,
|
||||
typ: RELAY_ACTIVITY_PUBLISH_TYP,
|
||||
issuer: "t3-env:env",
|
||||
audience: "https://relay.example.test",
|
||||
nowEpochSeconds: 150,
|
||||
}),
|
||||
),
|
||||
).resolves.toMatchObject({ jti: "nonce-1", state });
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
verifyRelayJwt({
|
||||
publicKey: keyPair.publicKey,
|
||||
token: (() => {
|
||||
const [header, body, signature = ""] = proof.split(".");
|
||||
const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`;
|
||||
return `${header}.${body}.${corruptedSignature}`;
|
||||
})(),
|
||||
typ: RELAY_ACTIVITY_PUBLISH_TYP,
|
||||
issuer: "t3-env:env",
|
||||
audience: "https://relay.example.test",
|
||||
nowEpochSeconds: 150,
|
||||
}),
|
||||
),
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it.effect("keeps the orchestration listener armed until relay config is installed", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const events = yield* Queue.unbounded<OrchestrationEvent>();
|
||||
const threadShellRequested = yield* Deferred.make<void>();
|
||||
const secrets = makeMemorySecretStore();
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const projectId = "project-1" as ProjectId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "T3 Code",
|
||||
workspaceRoot: "/workspace",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationProjectShell;
|
||||
|
||||
const thread = {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Run remote agent",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as TurnId,
|
||||
state: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: "turn-1" as TurnId,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
latestUserMessageAt: now,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
} satisfies OrchestrationThreadShell;
|
||||
|
||||
const orchestrationEngine = {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
streamDomainEvents: Stream.fromQueue(events),
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape;
|
||||
|
||||
const snapshotQuery = {
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: [thread],
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationShellSnapshot),
|
||||
getThreadShellById: () =>
|
||||
Deferred.succeed(threadShellRequested, undefined).pipe(
|
||||
Effect.ignore,
|
||||
Effect.as(Option.some(thread)),
|
||||
),
|
||||
getProjectShellById: () => Effect.succeed(Option.some(project)),
|
||||
} as unknown as ProjectionSnapshotQueryShape;
|
||||
|
||||
const descriptor = {
|
||||
environmentId,
|
||||
label: "Test Desktop",
|
||||
platform: {
|
||||
os: "darwin",
|
||||
arch: "arm64",
|
||||
},
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
} satisfies ExecutionEnvironmentDescriptor;
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
|
||||
Layer.succeed(ServerEnvironment.ServerEnvironment, {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
}),
|
||||
Layer.succeed(OrchestrationEngineService, orchestrationEngine),
|
||||
Layer.succeed(ProjectionSnapshotQuery, snapshotQuery),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
yield* relay.start();
|
||||
yield* secrets.setString(RELAY_URL_SECRET, "http://127.0.0.1:1");
|
||||
yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
|
||||
yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
|
||||
yield* Queue.offer(events, {
|
||||
type: "thread.activity-appended",
|
||||
sequence: 1,
|
||||
eventId: "evt-1",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
actor: { kind: "server" },
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
kind: "approval.requested",
|
||||
},
|
||||
},
|
||||
occurredAt: now,
|
||||
} as unknown as OrchestrationEvent);
|
||||
|
||||
yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds"));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentAwarenessRelay.layer.pipe(
|
||||
Layer.provide(layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const context = yield* Effect.context<never>();
|
||||
const runFork = Effect.runForkWith(context);
|
||||
const events = yield* Queue.unbounded<OrchestrationEvent>();
|
||||
const fetchSeen = yield* Deferred.make<URL>();
|
||||
const userSpans: Array<string> = [];
|
||||
const productSpans: Array<string> = [];
|
||||
const collectingTracer = (spans: Array<string>) =>
|
||||
Tracer.make({
|
||||
span: (options) => {
|
||||
const span = new Tracer.NativeSpan(options);
|
||||
const end = span.end.bind(span);
|
||||
span.end = (endTime, exit) => {
|
||||
end(endTime, exit);
|
||||
spans.push(span.name);
|
||||
};
|
||||
return span;
|
||||
},
|
||||
});
|
||||
const secrets = makeMemorySecretStore();
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const projectId = "project-1" as ProjectId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "T3 Code",
|
||||
workspaceRoot: "/workspace",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationProjectShell;
|
||||
|
||||
const thread = {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Run remote agent",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as TurnId,
|
||||
state: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "Codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: "turn-1" as TurnId,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
latestUserMessageAt: now,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
} satisfies OrchestrationThreadShell;
|
||||
|
||||
const descriptor = {
|
||||
environmentId,
|
||||
label: "Test Desktop",
|
||||
platform: {
|
||||
os: "darwin",
|
||||
arch: "arm64",
|
||||
},
|
||||
serverVersion: "0.0.0-test",
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
} satisfies ExecutionEnvironmentDescriptor;
|
||||
|
||||
globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {
|
||||
const url = new URL(
|
||||
typeof input === "string" || input instanceof URL
|
||||
? input
|
||||
: (input as unknown as { readonly url: string }).url,
|
||||
);
|
||||
runFork(Deferred.succeed(fetchSeen, url));
|
||||
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
|
||||
}) as unknown as typeof fetch;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
}),
|
||||
);
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),
|
||||
Layer.succeed(ServerEnvironment.ServerEnvironment, {
|
||||
getEnvironmentId: Effect.succeed(environmentId),
|
||||
getDescriptor: Effect.succeed(descriptor),
|
||||
}),
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
streamDomainEvents: Stream.fromQueue(events),
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: [thread],
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationShellSnapshot),
|
||||
getThreadShellById: () => Effect.succeed(Option.some(thread)),
|
||||
getProjectShellById: () => Effect.succeed(Option.some(project)),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");
|
||||
yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test");
|
||||
yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
|
||||
yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
|
||||
yield* relay.start();
|
||||
yield* Queue.offer(events, {
|
||||
type: "thread.activity-appended",
|
||||
sequence: 1,
|
||||
eventId: "evt-1",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
actor: { kind: "server" },
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
kind: "approval.requested",
|
||||
},
|
||||
},
|
||||
occurredAt: now,
|
||||
} as unknown as OrchestrationEvent);
|
||||
|
||||
const url = yield* Deferred.await(fetchSeen).pipe(Effect.timeout("2 seconds"));
|
||||
expect(url.origin).toBe("https://transport.example.test");
|
||||
expect(productSpans).toContain("makePublishProof");
|
||||
expect(userSpans).not.toContain("makePublishProof");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentAwarenessRelay.layer.pipe(
|
||||
Layer.provide(layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),
|
||||
Effect.withTracer(collectingTracer(userSpans)),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationEvent,
|
||||
OrchestrationProjectShell,
|
||||
OrchestrationThreadShell,
|
||||
OrchestrationV2DomainEvent,
|
||||
OrchestrationV2ThreadShell,
|
||||
Project,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type RelayAgentActivityPublishProofPayload,
|
||||
type RelayAgentActivityState,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";
|
||||
import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import {
|
||||
@@ -42,9 +42,8 @@ import {
|
||||
} from "../cloud/config.ts";
|
||||
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { forkParked } from "../serverActivation.ts";
|
||||
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
|
||||
export class AgentAwarenessRelay extends Context.Service<
|
||||
AgentAwarenessRelay,
|
||||
@@ -54,43 +53,15 @@ export class AgentAwarenessRelay extends Context.Service<
|
||||
}
|
||||
>()("t3/relay/AgentAwarenessRelay") {}
|
||||
|
||||
export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
|
||||
const payload = event.payload as { readonly threadId?: unknown };
|
||||
if (typeof payload.threadId === "string") {
|
||||
return payload.threadId as ThreadId;
|
||||
}
|
||||
if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") {
|
||||
return event.aggregateId as ThreadId;
|
||||
}
|
||||
return null;
|
||||
export function eventThreadId(event: OrchestrationV2DomainEvent): ThreadId {
|
||||
return event.threadId;
|
||||
}
|
||||
|
||||
export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent":
|
||||
case "thread.turn-start-requested":
|
||||
// These events express intent to start work, but the shell still contains
|
||||
// the previous turn's terminal state until the provider acknowledges the
|
||||
// new turn. Publishing that snapshot can queue a fresh "Done" alert just
|
||||
// before the real running state arrives. Provider lifecycle events publish
|
||||
// the authoritative starting/running state instead.
|
||||
return false;
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.runtime-mode-set":
|
||||
case "thread.interaction-mode-set":
|
||||
return false;
|
||||
case "thread.activity-appended":
|
||||
return (
|
||||
event.payload.activity.kind === "approval.requested" ||
|
||||
event.payload.activity.kind === "approval.resolved" ||
|
||||
event.payload.activity.kind === "provider.approval.respond.failed" ||
|
||||
event.payload.activity.kind === "user-input.requested" ||
|
||||
event.payload.activity.kind === "user-input.resolved" ||
|
||||
event.payload.activity.kind === "runtime.error"
|
||||
);
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
export function shouldPublishAgentAwarenessEvent(_event: OrchestrationV2DomainEvent): boolean {
|
||||
// Publishing is identity-deduplicated below. Watching every V2 event keeps
|
||||
// this consumer correct as the shell projection evolves without duplicating
|
||||
// projection-specific relevance rules here.
|
||||
return true;
|
||||
}
|
||||
|
||||
export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {
|
||||
@@ -233,8 +204,8 @@ export function describeThreadShellForAwareness(
|
||||
export function resolveAgentAwarenessRelayPublishSnapshot(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly thread: Option.Option<OrchestrationThreadShell>;
|
||||
readonly project: Option.Option<OrchestrationProjectShell>;
|
||||
readonly thread: Option.Option<OrchestrationV2ThreadShell>;
|
||||
readonly project: Option.Option<Project>;
|
||||
}): {
|
||||
readonly projectId: string | null;
|
||||
readonly state: RelayAgentActivityState | null;
|
||||
@@ -257,7 +228,7 @@ export function resolveAgentAwarenessRelayPublishSnapshot(input: {
|
||||
return {
|
||||
projectId: input.thread.value.projectId,
|
||||
state: sanitizeRelayAgentActivityState(
|
||||
projectThreadAwareness({
|
||||
projectThreadAwarenessV2({
|
||||
environmentId: input.environmentId,
|
||||
project: input.project.value,
|
||||
thread: input.thread.value,
|
||||
@@ -269,8 +240,8 @@ export function resolveAgentAwarenessRelayPublishSnapshot(input: {
|
||||
|
||||
export function resolveAgentAwarenessRelayActiveThreadIds(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
|
||||
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
|
||||
readonly projects: ReadonlyArray<Pick<Project, "id" | "title">>;
|
||||
readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
|
||||
}): ReadonlyArray<ThreadId> {
|
||||
const projectById = new Map(input.projects.map((project) => [project.id, project]));
|
||||
return input.threads
|
||||
@@ -280,7 +251,7 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
projectThreadAwareness({
|
||||
projectThreadAwarenessV2({
|
||||
environmentId: input.environmentId,
|
||||
project,
|
||||
thread,
|
||||
@@ -293,8 +264,8 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: {
|
||||
export const make = Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
const threads = yield* ThreadManagement.ThreadManagementService;
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
|
||||
const activeSnapshotPublishedRef = yield* Ref.make(false);
|
||||
@@ -404,10 +375,12 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const thread = yield* snapshotQuery.getThreadShellById(threadId);
|
||||
const shell = yield* threads.getShellSnapshot();
|
||||
const threadValue = shell.threads.find((candidate) => candidate.id === threadId);
|
||||
const thread = threadValue === undefined ? Option.none() : Option.some(threadValue);
|
||||
const project = Option.isSome(thread)
|
||||
? yield* snapshotQuery.getProjectShellById(thread.value.projectId)
|
||||
: Option.none<OrchestrationProjectShell>();
|
||||
? yield* projects.getById(thread.value.projectId)
|
||||
: Option.none<Project>();
|
||||
const snapshot = resolveAgentAwarenessRelayPublishSnapshot({
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -525,11 +498,14 @@ export const make = Effect.gen(function* () {
|
||||
return false;
|
||||
}
|
||||
const environmentId = yield* serverEnvironment.getEnvironmentId;
|
||||
const snapshot = yield* snapshotQuery.getShellSnapshot();
|
||||
const [projectSnapshot, shellSnapshot] = yield* Effect.all([
|
||||
projects.snapshot,
|
||||
threads.getShellSnapshot(),
|
||||
]);
|
||||
const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({
|
||||
environmentId,
|
||||
projects: snapshot.projects,
|
||||
threads: snapshot.threads,
|
||||
projects: projectSnapshot.projects,
|
||||
threads: shellSnapshot.threads,
|
||||
});
|
||||
if (activeThreadIds.length === 0) {
|
||||
yield* Effect.logDebug("agent activity snapshot has no publishable threads");
|
||||
@@ -605,14 +581,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),
|
||||
),
|
||||
);
|
||||
yield* forkParked(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(threads.streamDomainEvents, (event) => {
|
||||
const threadId = eventThreadId(event);
|
||||
if (threadId === null) {
|
||||
return Effect.logDebug("agent activity publishing ignored event without thread id", {
|
||||
eventType: event.type,
|
||||
});
|
||||
}
|
||||
if (!shouldPublishAgentAwarenessEvent(event)) {
|
||||
return Effect.logDebug(
|
||||
"agent activity publishing ignored event without activity changes",
|
||||
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user