Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e66c61cc5 | ||
|
|
8e2d5d326a | ||
|
|
b239fa9c6d | ||
|
|
a03b7bce5a | ||
|
|
041f875ae5 | ||
|
|
1732212b43 | ||
|
|
1115b14e4d | ||
|
|
c6c64918f8 | ||
|
|
4abf8b46c5 | ||
|
|
3083d712ee | ||
|
|
6672a1d210 | ||
|
|
92e54fb96c | ||
|
|
8cc9a6fa6b | ||
|
|
b2d17b7108 | ||
|
|
fb1034546f | ||
|
|
f5f98cf0ae | ||
|
|
37ac970e28 | ||
|
|
8919ae7c53 | ||
|
|
c1e2408e1f | ||
|
|
8b993bc9ff | ||
|
|
ea52bb1dbd | ||
|
|
28107e89c2 | ||
|
|
82a9bcc7f4 | ||
|
|
61f8d46fa2 | ||
|
|
0debebafbb |
No files matched your search
@@ -22,6 +22,9 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
@@ -31,6 +34,9 @@ jobs:
|
||||
- name: Typecheck
|
||||
run: vpr typecheck
|
||||
|
||||
- name: Check resource monitor formatting
|
||||
run: cargo fmt --manifest-path native/resource-monitor/Cargo.toml -- --check
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: vp run build:desktop
|
||||
|
||||
@@ -55,12 +61,18 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Ensure Electron runtime is installed
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
run: vp run test
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
|
||||
@@ -272,21 +272,29 @@ jobs:
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
rust_target: aarch64-apple-darwin
|
||||
resource_key: darwin-arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
rust_target: x86_64-apple-darwin
|
||||
resource_key: darwin-x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
rust_target: x86_64-unknown-linux-gnu
|
||||
resource_key: linux-x64
|
||||
- label: Windows x64
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
rust_target: x86_64-pc-windows-msvc
|
||||
resource_key: win32-x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
@@ -306,6 +314,11 @@ jobs:
|
||||
cache: true
|
||||
run-install: true
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.rust_target }}
|
||||
|
||||
- name: Download relay client tracing config
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -533,6 +546,19 @@ jobs:
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Collect resource monitor
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
binary_name="t3-resource-monitor"
|
||||
if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
binary_name="${binary_name}.exe"
|
||||
fi
|
||||
source_path="native/resource-monitor/target/${{ matrix.rust_target }}/release/${binary_name}"
|
||||
target_dir="resource-monitor-publish/${{ matrix.resource_key }}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$source_path" "$target_dir/$binary_name"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -540,6 +566,13 @@ jobs:
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload resource monitor
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: resource-monitor-${{ matrix.resource_key }}
|
||||
path: resource-monitor-publish/${{ matrix.resource_key }}/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, relay_public_config, build]
|
||||
@@ -594,6 +627,24 @@ jobs:
|
||||
- name: Build CLI package
|
||||
run: vp run --filter t3 build
|
||||
|
||||
- name: Download resource monitors
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: resource-monitor-*
|
||||
path: ${{ runner.temp }}/resource-monitors
|
||||
|
||||
- name: Bundle resource monitors into CLI package
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for artifact_dir in "$RUNNER_TEMP"/resource-monitors/resource-monitor-*; do
|
||||
resource_key="${artifact_dir##*/resource-monitor-}"
|
||||
target_dir="apps/server/dist/resource-monitor/${resource_key}"
|
||||
mkdir -p "$target_dir"
|
||||
cp "$artifact_dir"/t3-resource-monitor* "$target_dir/"
|
||||
chmod +x "$target_dir"/t3-resource-monitor 2>/dev/null || true
|
||||
done
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ squashfs-root/
|
||||
.gstack/
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
native/**/target/
|
||||
node_modules/
|
||||
.alchemy/
|
||||
*.log
|
||||
|
||||
@@ -48,7 +48,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
@@ -56,6 +58,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
@@ -73,4 +78,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -55,6 +55,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("DesktopBackendOutputLog", () => {
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
yield* outputLog.beginSession({ details: "test" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
|
||||
@@ -102,7 +102,8 @@ describe("DesktopBackendOutputLog", () => {
|
||||
return withOutputLog(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
|
||||
yield* outputLog.beginSession({ details: "test" });
|
||||
yield* outputLog.persistFailure({ details: "failed" });
|
||||
|
||||
const error = loggedError(messages);
|
||||
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
|
||||
|
||||
@@ -17,6 +17,8 @@ export const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
export const DESKTOP_LOG_FILE_MAX_FILES = 10;
|
||||
|
||||
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES = 1024 * 1024;
|
||||
const DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS = 256;
|
||||
|
||||
interface RotatingLogFileWriter {
|
||||
readonly filePath: string;
|
||||
@@ -93,14 +95,13 @@ export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<Des
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
{
|
||||
readonly writeSessionBoundary: (input: {
|
||||
readonly phase: "START" | "END";
|
||||
readonly details: string;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly beginSession: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly writeOutputChunk: (
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
) => Effect.Effect<void>;
|
||||
readonly persistFailure: (input: { readonly details: string }) => Effect.Effect<void>;
|
||||
readonly discardSession: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
|
||||
|
||||
@@ -122,10 +123,76 @@ const encodeDesktopBackendChildLogRecord = Schema.encodeEffect(
|
||||
);
|
||||
|
||||
const DesktopBackendOutputLogNoop: DesktopBackendOutputLog["Service"] = {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
};
|
||||
|
||||
interface BufferedBackendOutputChunk {
|
||||
readonly streamName: "stdout" | "stderr";
|
||||
readonly chunk: Uint8Array;
|
||||
}
|
||||
|
||||
interface BackendOutputSession {
|
||||
readonly runId: string;
|
||||
readonly startDetails: string;
|
||||
readonly chunks: ReadonlyArray<BufferedBackendOutputChunk>;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
|
||||
function appendBoundedOutputChunk(
|
||||
session: BackendOutputSession,
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: Uint8Array,
|
||||
): BackendOutputSession {
|
||||
if (chunk.byteLength === 0) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const retainedChunk =
|
||||
chunk.byteLength > DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES
|
||||
? chunk.slice(chunk.byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES)
|
||||
: chunk.slice();
|
||||
const chunks = [...session.chunks, { streamName, chunk: retainedChunk }];
|
||||
let byteLength = session.byteLength + retainedChunk.byteLength;
|
||||
let overflow = Math.max(0, byteLength - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_BYTES);
|
||||
let firstRetainedIndex = 0;
|
||||
|
||||
while (overflow > 0) {
|
||||
const first = chunks[firstRetainedIndex];
|
||||
if (!first) break;
|
||||
if (first.chunk.byteLength <= overflow) {
|
||||
overflow -= first.chunk.byteLength;
|
||||
byteLength -= first.chunk.byteLength;
|
||||
firstRetainedIndex += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
chunks[firstRetainedIndex] = {
|
||||
...first,
|
||||
chunk: first.chunk.slice(overflow),
|
||||
};
|
||||
byteLength -= overflow;
|
||||
overflow = 0;
|
||||
}
|
||||
|
||||
const excessChunks = Math.max(
|
||||
0,
|
||||
chunks.length - firstRetainedIndex - DESKTOP_BACKEND_OUTPUT_BUFFER_MAX_CHUNKS,
|
||||
);
|
||||
for (let index = firstRetainedIndex; index < firstRetainedIndex + excessChunks; index += 1) {
|
||||
byteLength -= chunks[index]?.chunk.byteLength ?? 0;
|
||||
}
|
||||
firstRetainedIndex += excessChunks;
|
||||
|
||||
return {
|
||||
...session,
|
||||
chunks: chunks.slice(firstRetainedIndex),
|
||||
byteLength,
|
||||
};
|
||||
}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
@@ -338,44 +405,78 @@ export const make = Effect.gen(function* () {
|
||||
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
|
||||
}),
|
||||
);
|
||||
const sessionRef = yield* Ref.make(Option.none<BackendOutputSession>());
|
||||
|
||||
const service = Option.match(writer, {
|
||||
onNone: () => DesktopBackendOutputLogNoop,
|
||||
onSome: (logFile) =>
|
||||
({
|
||||
writeSessionBoundary: Effect.fn("desktop.observability.backendOutput.writeSessionBoundary")(
|
||||
function* ({ phase, details }) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: `backend child process session ${phase.toLowerCase()}`,
|
||||
level: "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
phase,
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
|
||||
function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
const runId = yield* currentDesktopRunId;
|
||||
beginSession: Effect.fn("desktop.observability.backendOutput.beginSession")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const runId = yield* currentDesktopRunId;
|
||||
yield* Ref.set(
|
||||
sessionRef,
|
||||
Option.some({
|
||||
runId,
|
||||
startDetails: sanitizeLogValue(details),
|
||||
chunks: [],
|
||||
byteLength: 0,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {
|
||||
if (environment.isDevelopment) {
|
||||
yield* writeDevelopmentConsoleOutput(streamName, chunk);
|
||||
}
|
||||
yield* Ref.update(
|
||||
sessionRef,
|
||||
Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),
|
||||
);
|
||||
}),
|
||||
persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({
|
||||
details,
|
||||
}) {
|
||||
const session = yield* Ref.modify(sessionRef, (current) => [
|
||||
current,
|
||||
Option.map(current, (value) => ({ ...value, chunks: [], byteLength: 0 })),
|
||||
]);
|
||||
if (Option.isNone(session)) return;
|
||||
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output start",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "START",
|
||||
details: session.value.startDetails,
|
||||
},
|
||||
});
|
||||
for (const output of session.value.chunks) {
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process output",
|
||||
level: streamName === "stderr" ? "ERROR" : "INFO",
|
||||
level: output.streamName === "stderr" ? "ERROR" : "INFO",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId,
|
||||
stream: streamName,
|
||||
text: textDecoder.decode(chunk),
|
||||
runId: session.value.runId,
|
||||
stream: output.streamName,
|
||||
text: textDecoder.decode(output.chunk),
|
||||
},
|
||||
});
|
||||
},
|
||||
),
|
||||
}
|
||||
yield* writeBackendChildLogRecord(logFile, {
|
||||
message: "backend child process failure output end",
|
||||
level: "ERROR",
|
||||
annotations: {
|
||||
component: "desktop-backend-child",
|
||||
runId: session.value.runId,
|
||||
phase: "END",
|
||||
details: sanitizeLogValue(details),
|
||||
},
|
||||
});
|
||||
}),
|
||||
discardSession: Ref.set(sessionRef, Option.none()),
|
||||
}) satisfies DesktopBackendOutputLog["Service"],
|
||||
});
|
||||
|
||||
|
||||
@@ -49,14 +49,14 @@ const environmentInput = (baseDir: string) =>
|
||||
runningUnderArm64Translation: false,
|
||||
}) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput;
|
||||
|
||||
const makeEnvironmentLayer = (baseDir: string) =>
|
||||
const makeEnvironmentLayer = (baseDir: string, isDevelopment = true) =>
|
||||
DesktopEnvironment.layer(environmentInput(baseDir)).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: baseDir,
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5733",
|
||||
VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -112,41 +112,56 @@ describe("DesktopObservability", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists backend child output as structured JSON records in development", () =>
|
||||
it.effect("buffers backend child output and persists it only when a failure is reported", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-log-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir);
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const tracePath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "desktop.trace.ndjson");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({
|
||||
details: "pid=123 port=3773 cwd=/repo",
|
||||
});
|
||||
yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n"));
|
||||
assert.isFalse(yield* fileSystem.exists(logPath));
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
yield* outputLog.beginSession({ details: "pid=456" });
|
||||
yield* outputLog.writeOutputChunk(
|
||||
"stderr",
|
||||
new TextEncoder().encode("normal shutdown\n"),
|
||||
);
|
||||
yield* outputLog.discardSession;
|
||||
}).pipe(
|
||||
Effect.annotateLogs({ runId: "test-run" }),
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const log = yield* fileSystem.readFileString(logPath);
|
||||
const lines = log.trimEnd().split("\n");
|
||||
const boundary = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? "");
|
||||
const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? "");
|
||||
|
||||
assert.equal(boundary.message, "backend child process session start");
|
||||
assert.equal(boundary.level, "INFO");
|
||||
assert.equal(boundary.annotations.component, "desktop-backend-child");
|
||||
assert.equal(boundary.annotations.runId, "test-run");
|
||||
assert.equal(boundary.annotations.phase, "START");
|
||||
assert.equal(boundary.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
assert.equal(lines.length, 3);
|
||||
assert.equal(start.message, "backend child process failure output start");
|
||||
assert.equal(start.level, "ERROR");
|
||||
assert.equal(start.annotations.component, "desktop-backend-child");
|
||||
assert.equal(start.annotations.runId, "test-run");
|
||||
assert.equal(start.annotations.phase, "START");
|
||||
assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo");
|
||||
|
||||
assert.equal(output.message, "backend child process output");
|
||||
assert.equal(output.level, "INFO");
|
||||
@@ -154,6 +169,98 @@ describe("DesktopObservability", () => {
|
||||
assert.equal(output.annotations.runId, "test-run");
|
||||
assert.equal(output.annotations.stream, "stdout");
|
||||
assert.equal(output.annotations.text, "hello server\n");
|
||||
|
||||
assert.equal(end.message, "backend child process failure output end");
|
||||
assert.equal(end.level, "ERROR");
|
||||
assert.equal(end.annotations.phase, "END");
|
||||
assert.equal(end.annotations.details, "code=1");
|
||||
|
||||
const traceRecords = (yield* fileSystem.readFileString(tracePath))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => decodeTraceRecordLine(line));
|
||||
assert.isFalse(
|
||||
traceRecords.some(
|
||||
(record) => record.name === "desktop.observability.backendOutput.writeOutputChunk",
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("retains only the last mebibyte of backend child output", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-bound-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
const maxBufferedBytes = 1024 * 1024;
|
||||
const discardedPrefixBytes = 128;
|
||||
const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes);
|
||||
output.fill("x".charCodeAt(0));
|
||||
output.fill("y".charCodeAt(0), 0, discardedPrefixBytes);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
yield* outputLog.writeOutputChunk("stderr", output);
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? "");
|
||||
const text = record.annotations.text;
|
||||
assert.equal(typeof text, "string");
|
||||
if (typeof text !== "string") {
|
||||
return;
|
||||
}
|
||||
assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes);
|
||||
assert.isFalse(text.includes("y"));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds the number of retained backend child output chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-output-chunks-test-",
|
||||
});
|
||||
const environmentLayer = makeEnvironmentLayer(baseDir, false);
|
||||
const logPath = yield* Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return environment.path.join(environment.logDir, "server-child.log");
|
||||
}).pipe(Effect.provide(environmentLayer));
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const outputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
yield* outputLog.beginSession({ details: "pid=123" });
|
||||
for (let index = 0; index < 300; index += 1) {
|
||||
yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128));
|
||||
}
|
||||
yield* outputLog.persistFailure({ details: "code=1" });
|
||||
}).pipe(
|
||||
Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(environmentLayer))),
|
||||
),
|
||||
);
|
||||
|
||||
const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n");
|
||||
assert.equal(lines.length, 258);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici)),
|
||||
|
||||
@@ -12,7 +12,7 @@ import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
import * as DesktopBackendOutputLogModule from "./DesktopBackendOutputLog.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;
|
||||
const DESKTOP_TRACE_BATCH_WINDOW_MS = 1_000;
|
||||
|
||||
export { DesktopBackendOutputLog } from "./DesktopBackendOutputLog.ts";
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ function makeEnvironmentLayer(
|
||||
options?: {
|
||||
readonly isPackaged?: boolean;
|
||||
readonly devServerUrl?: string;
|
||||
readonly resourcesPath?: string;
|
||||
},
|
||||
) {
|
||||
return DesktopEnvironment.layer({
|
||||
@@ -57,7 +58,7 @@ function makeEnvironmentLayer(
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: options?.isPackaged ?? true,
|
||||
resourcesPath: "/missing/resources",
|
||||
resourcesPath: options?.resourcesPath ?? "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -254,4 +255,39 @@ describe("DesktopBackendConfiguration", () => {
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("passes the packaged resource monitor path to the backend", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
|
||||
yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(monitorPath, "binary");
|
||||
yield* fileSystem.chmod(monitorPath, 0o755);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolve;
|
||||
assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
|
||||
assert.equal(config.bootstrap.desktopTelemetryFd, 4);
|
||||
assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -75,6 +75,42 @@ const logBackendObservabilitySettingsReadFailure = (
|
||||
);
|
||||
};
|
||||
|
||||
function resourceMonitorBinaryName(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
|
||||
}
|
||||
|
||||
const resolveResourceMonitorPath = Effect.fn(
|
||||
"desktop.backendConfiguration.resolveResourceMonitorPath",
|
||||
)(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const binaryName = resourceMonitorBinaryName(environment.platform);
|
||||
const candidates = environment.isDevelopment
|
||||
? [
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/debug",
|
||||
binaryName,
|
||||
),
|
||||
environment.path.join(
|
||||
environment.rootDir,
|
||||
"native/resource-monitor/target/release",
|
||||
binaryName,
|
||||
),
|
||||
]
|
||||
: environment.resolveResourcePathCandidates(
|
||||
environment.path.join("resource-monitor", binaryName),
|
||||
);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
|
||||
return Option.some(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const readPersistedBackendObservabilitySettings = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
@@ -104,6 +140,7 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
function* (input: {
|
||||
readonly bootstrapToken: string;
|
||||
readonly observabilitySettings: BackendObservabilitySettings;
|
||||
readonly resourceMonitorPath: Option.Option<string>;
|
||||
}): Effect.fn.Return<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
never,
|
||||
@@ -130,6 +167,12 @@ const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolv
|
||||
desktopBootstrapToken: input.bootstrapToken,
|
||||
tailscaleServeEnabled: backendExposure.tailscaleServeEnabled,
|
||||
tailscaleServePort: backendExposure.tailscaleServePort,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
...Option.match(input.resourceMonitorPath, {
|
||||
onNone: () => ({}),
|
||||
onSome: (resourceMonitorPath) => ({ resourceMonitorPath }),
|
||||
}),
|
||||
...Option.match(input.observabilitySettings.otlpTracesUrl, {
|
||||
onNone: () => ({}),
|
||||
onSome: (otlpTracesUrl) => ({ otlpTracesUrl }),
|
||||
@@ -169,9 +212,14 @@ export const make = Effect.gen(function* () {
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
const resourceMonitorPath = yield* resolveResourceMonitorPath().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
);
|
||||
return yield* resolveBackendStartConfig({
|
||||
bootstrapToken,
|
||||
observabilitySettings,
|
||||
resourceMonitorPath,
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopServerExposure.DesktopServerExposure, serverExposure),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -26,12 +27,16 @@ import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
|
||||
Schema.fromJsonString(DesktopBackendBootstrap),
|
||||
);
|
||||
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
|
||||
const encodeDesktopTelemetryControl = Schema.encodeSync(
|
||||
Schema.fromJsonString(DesktopTelemetryControlMessage),
|
||||
);
|
||||
|
||||
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
executablePath: "/electron",
|
||||
@@ -47,6 +52,8 @@ const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
|
||||
desktopBootstrapToken: "token",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
},
|
||||
httpBaseUrl: new URL("http://127.0.0.1:3773"),
|
||||
captureOutput: true,
|
||||
@@ -63,6 +70,7 @@ function makeProcess(options?: {
|
||||
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
|
||||
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
|
||||
readonly getOutputFd?: ChildProcessSpawner.ChildProcessHandle["getOutputFd"];
|
||||
}): ChildProcessSpawner.ChildProcessHandle {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(123),
|
||||
@@ -74,7 +82,7 @@ function makeProcess(options?: {
|
||||
kill: options?.kill ?? (() => Effect.void),
|
||||
stdin: Sink.drain,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
getOutputFd: options?.getOutputFd ?? (() => Stream.empty),
|
||||
unref: Effect.succeed(Effect.void),
|
||||
});
|
||||
}
|
||||
@@ -111,6 +119,9 @@ function makeManagerLayer(input: {
|
||||
readonly backendOutputLog?: Partial<DesktopObservability.DesktopBackendOutputLog["Service"]>;
|
||||
readonly desktopState?: DesktopState.DesktopState["Service"];
|
||||
readonly desktopWindow?: Partial<DesktopWindow.DesktopWindow["Service"]>;
|
||||
readonly desktopTelemetryPublisher?: Partial<
|
||||
DesktopTelemetryPublisher.DesktopTelemetryPublisher["Service"]
|
||||
>;
|
||||
readonly config?: DesktopBackendManager.DesktopBackendStartConfig;
|
||||
}) {
|
||||
return DesktopBackendManager.layer.pipe(
|
||||
@@ -124,12 +135,21 @@ function makeManagerLayer(input: {
|
||||
}),
|
||||
input.spawnerLayer,
|
||||
input.httpClientLayer ?? healthyHttpClientLayer,
|
||||
Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
|
||||
latest: Effect.succeed(Option.none()),
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
input.desktopState
|
||||
? Layer.succeed(DesktopState.DesktopState, input.desktopState)
|
||||
: DesktopState.layer,
|
||||
Layer.succeed(DesktopObservability.DesktopBackendOutputLog, {
|
||||
writeSessionBoundary: () => Effect.void,
|
||||
beginSession: () => Effect.void,
|
||||
writeOutputChunk: () => Effect.void,
|
||||
persistFailure: () => Effect.void,
|
||||
discardSession: Effect.void,
|
||||
...input.backendOutputLog,
|
||||
} satisfies DesktopObservability.DesktopBackendOutputLog["Service"]),
|
||||
Layer.succeed(DesktopWindow.DesktopWindow, {
|
||||
@@ -205,8 +225,7 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -229,6 +248,8 @@ describe("DesktopBackendManager", () => {
|
||||
assert.equal(spawnedCommand.options.stderr, "pipe");
|
||||
assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
|
||||
assert.isDefined(spawnedCommand.options.forceKillAfter);
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
|
||||
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
|
||||
assert.equal(
|
||||
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
|
||||
2_000,
|
||||
@@ -288,6 +309,7 @@ describe("DesktopBackendManager", () => {
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
bootstrap: {
|
||||
...baseConfig.bootstrap,
|
||||
port: 0,
|
||||
@@ -327,7 +349,10 @@ describe("DesktopBackendManager", () => {
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
@@ -368,7 +393,10 @@ describe("DesktopBackendManager", () => {
|
||||
),
|
||||
),
|
||||
);
|
||||
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
|
||||
const error = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.scoped,
|
||||
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
|
||||
@@ -412,6 +440,7 @@ describe("DesktopBackendManager", () => {
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
const error = yield* Deferred.await(reported);
|
||||
@@ -451,6 +480,7 @@ describe("DesktopBackendManager", () => {
|
||||
|
||||
const exit = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
onOutput: () => Effect.fail(outputCause),
|
||||
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
|
||||
@@ -476,6 +506,88 @@ describe("DesktopBackendManager", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes desktop telemetry control messages from fd5 to the publisher", () =>
|
||||
Effect.gen(function* () {
|
||||
const handled = yield* Deferred.make<boolean>();
|
||||
const controlMessage = encodeDesktopTelemetryControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
getOutputFd: (fd) =>
|
||||
fd === 5 ? Stream.encodeText(Stream.make(`${controlMessage}\n`)) : Stream.empty,
|
||||
exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
desktopTelemetryPublisher: {
|
||||
handleControl: (message) =>
|
||||
Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
assert.isTrue(yield* Deferred.await(handled));
|
||||
}).pipe(Effect.provide(managerLayer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains trailing child output before persisting an unexpected exit", () =>
|
||||
Effect.gen(function* () {
|
||||
const persistedOutput = yield* Deferred.make<ReadonlyArray<string>>();
|
||||
const outputDrainStarted = yield* Deferred.make<void>();
|
||||
const outputChunks = yield* Ref.make<Array<string>>([]);
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
stdout: Stream.fromEffect(
|
||||
Deferred.succeed(outputDrainStarted, void 0).pipe(
|
||||
Effect.andThen(Effect.sleep(Duration.millis(50))),
|
||||
Effect.as(new TextEncoder().encode("trailing output\n")),
|
||||
),
|
||||
),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
writeOutputChunk: (_streamName, chunk) =>
|
||||
Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]),
|
||||
persistFailure: () =>
|
||||
Ref.get(outputChunks).pipe(
|
||||
Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const manager = yield* DesktopBackendManager.DesktopBackendManager;
|
||||
yield* manager.start;
|
||||
yield* Deferred.await(outputDrainStarted);
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
|
||||
assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]);
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), managerLayer)));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retries HTTP readiness before reporting the backend ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
@@ -513,8 +625,7 @@ describe("DesktopBackendManager", () => {
|
||||
}).pipe(Effect.andThen(Deferred.succeed(ready, void 0))),
|
||||
},
|
||||
backendOutputLog: {
|
||||
writeSessionBoundary: ({ phase }) =>
|
||||
phase === "END" ? Queue.offer(exited, void 0).pipe(Effect.asVoid) : Effect.void,
|
||||
persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -547,6 +658,8 @@ describe("DesktopBackendManager", () => {
|
||||
const ready = yield* Deferred.make<void>();
|
||||
const backendReady = yield* Ref.make(false);
|
||||
const quitting = yield* Ref.make(false);
|
||||
let persistedFailureCount = 0;
|
||||
let discardedSessionCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
@@ -578,6 +691,15 @@ describe("DesktopBackendManager", () => {
|
||||
desktopWindow: {
|
||||
handleBackendReady: Deferred.succeed(ready, void 0).pipe(Effect.asVoid),
|
||||
},
|
||||
backendOutputLog: {
|
||||
persistFailure: () =>
|
||||
Effect.sync(() => {
|
||||
persistedFailureCount += 1;
|
||||
}),
|
||||
discardSession: Effect.sync(() => {
|
||||
discardedSessionCount += 1;
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -597,6 +719,8 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.stop();
|
||||
assert.equal(startCount, 1);
|
||||
assert.equal(closedCount, 1);
|
||||
assert.equal(persistedFailureCount, 0);
|
||||
assert.equal(discardedSessionCount, 1);
|
||||
|
||||
const stoppedSnapshot = yield* manager.snapshot;
|
||||
assert.isFalse(yield* Ref.get(backendReady));
|
||||
@@ -610,6 +734,7 @@ describe("DesktopBackendManager", () => {
|
||||
it.effect("restarts an unexpectedly exited backend with the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Queue.unbounded<number>();
|
||||
const failures = yield* Queue.unbounded<string>();
|
||||
let startCount = 0;
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
@@ -629,6 +754,9 @@ describe("DesktopBackendManager", () => {
|
||||
const managerLayer = makeManagerLayer({
|
||||
spawnerLayer,
|
||||
httpClientLayer: httpClientLayer(() => Effect.never),
|
||||
backendOutputLog: {
|
||||
persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -636,6 +764,7 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
assert.equal(yield* Queue.take(failures), "pid=123 code=1");
|
||||
|
||||
yield* TestClock.adjust(Duration.millis(499));
|
||||
assert.equal(yield* Queue.size(starts), 0);
|
||||
@@ -692,6 +821,13 @@ describe("DesktopBackendManager", () => {
|
||||
yield* manager.start;
|
||||
|
||||
assert.equal(yield* Queue.take(starts), 1);
|
||||
let restartScheduled = false;
|
||||
while (!restartScheduled) {
|
||||
restartScheduled = (yield* manager.snapshot).restartScheduled;
|
||||
if (!restartScheduled) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
}
|
||||
|
||||
yield* manager.start;
|
||||
assert.equal(yield* Queue.take(starts), 2);
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Ndjson from "effect/unstable/encoding/Ndjson";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -21,11 +22,14 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
|
||||
import {
|
||||
DesktopBackendBootstrap,
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
|
||||
const INITIAL_RESTART_DELAY = Duration.millis(500);
|
||||
@@ -34,6 +38,7 @@ const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
|
||||
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
|
||||
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
|
||||
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
|
||||
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.millis(250);
|
||||
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
|
||||
|
||||
type BackendProcessLayerServices = ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient;
|
||||
@@ -172,6 +177,10 @@ export const BackendProcessError = Schema.Union([
|
||||
export type BackendProcessError = typeof BackendProcessError.Type;
|
||||
|
||||
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
|
||||
readonly desktopTelemetryStream: Stream.Stream<Uint8Array>;
|
||||
readonly onDesktopTelemetryControl?: (
|
||||
message: DesktopTelemetryControlMessageValue,
|
||||
) => Effect.Effect<void>;
|
||||
readonly readinessTimeout?: Duration.Duration;
|
||||
readonly onStarted?: (pid: number) => Effect.Effect<void>;
|
||||
readonly onReady?: () => Effect.Effect<void>;
|
||||
@@ -327,6 +336,7 @@ function drainBackendOutput(
|
||||
}
|
||||
|
||||
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
|
||||
const decodeDesktopTelemetryControl = Schema.decodeUnknownEffect(DesktopTelemetryControlMessage);
|
||||
|
||||
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
options: RunBackendProcessOptions,
|
||||
@@ -345,6 +355,23 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
),
|
||||
);
|
||||
const onOutput = options.onOutput ?? (() => Effect.void);
|
||||
const additionalFds: Record<`fd${number}`, ChildProcess.AdditionalFdConfig> = {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
};
|
||||
if (options.bootstrap.desktopTelemetryFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryFd}`] = {
|
||||
type: "input",
|
||||
stream: options.desktopTelemetryStream,
|
||||
};
|
||||
}
|
||||
if (options.bootstrap.desktopTelemetryControlFd !== undefined) {
|
||||
additionalFds[`fd${options.bootstrap.desktopTelemetryControlFd}`] = {
|
||||
type: "output",
|
||||
};
|
||||
}
|
||||
const command = ChildProcess.make(
|
||||
options.executablePath,
|
||||
[options.entryPath, "--bootstrap-fd", "3"],
|
||||
@@ -359,12 +386,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
stderr: options.captureOutput ? "pipe" : "inherit",
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE,
|
||||
additionalFds: {
|
||||
fd3: {
|
||||
type: "input",
|
||||
stream: Stream.encodeText(Stream.make(`${bootstrapJson}\n`)),
|
||||
},
|
||||
},
|
||||
additionalFds,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -380,8 +402,35 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
}),
|
||||
),
|
||||
);
|
||||
const outputFibers: Array<Fiber.Fiber<void, never>> = [];
|
||||
|
||||
yield* options.onStarted?.(handle.pid) ?? Effect.void;
|
||||
if (
|
||||
options.bootstrap.desktopTelemetryControlFd !== undefined &&
|
||||
options.onDesktopTelemetryControl !== undefined
|
||||
) {
|
||||
const controlFd = options.bootstrap.desktopTelemetryControlFd;
|
||||
const handleControl = options.onDesktopTelemetryControl;
|
||||
yield* handle.getOutputFd(controlFd).pipe(
|
||||
Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),
|
||||
Stream.mapEffect((message) => decodeDesktopTelemetryControl(message)),
|
||||
Stream.runForEach(handleControl),
|
||||
Effect.catchCause((cause) =>
|
||||
logBackendManagerWarning("desktop telemetry control stream stopped", {
|
||||
fd: controlFd,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(
|
||||
handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
}
|
||||
if (options.captureOutput) {
|
||||
const outputContext = {
|
||||
executablePath: options.executablePath,
|
||||
@@ -391,20 +440,22 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
pid: Number(handle.pid),
|
||||
};
|
||||
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped);
|
||||
outputFibers.push(
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stdout",
|
||||
handle.stdout,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped),
|
||||
yield* drainBackendOutput(
|
||||
outputContext,
|
||||
"stderr",
|
||||
handle.stderr,
|
||||
onOutput,
|
||||
onOutputFailure,
|
||||
).pipe(Effect.forkScoped),
|
||||
);
|
||||
}
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
@@ -420,7 +471,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const exitCode = yield* handle.exitCode.pipe(
|
||||
const exit = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BackendProcessExitStatusError({
|
||||
@@ -432,7 +483,16 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.exit,
|
||||
);
|
||||
yield* Effect.forEach(outputFibers, Fiber.await, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.timeout(DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore);
|
||||
if (Exit.isFailure(exit)) {
|
||||
return yield* Effect.failCause(exit.cause);
|
||||
}
|
||||
const exitCode = exit.value;
|
||||
return {
|
||||
code: Option.some(exitCode),
|
||||
reason: `code=${exitCode}`,
|
||||
@@ -445,6 +505,7 @@ export const make = Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const backendOutputLog = yield* DesktopObservability.DesktopBackendOutputLog;
|
||||
const desktopState = yield* DesktopState.DesktopState;
|
||||
const desktopTelemetryPublisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -581,10 +642,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
if (isCurrentRun) {
|
||||
if (Option.isSome(pid)) {
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "END",
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
if (nextState.desiredRunning) {
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: `pid=${pid.value} ${reason}`,
|
||||
});
|
||||
} else {
|
||||
yield* backendOutputLog.discardSession;
|
||||
}
|
||||
}
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
}
|
||||
@@ -598,13 +662,14 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config.value,
|
||||
desktopTelemetryStream: desktopTelemetryPublisher.encoded,
|
||||
onDesktopTelemetryControl: desktopTelemetryPublisher.handleControl,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
pid: Option.some(pid),
|
||||
}));
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
yield* backendOutputLog.beginSession({
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
@@ -637,10 +702,16 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
}),
|
||||
onReadinessFailure: (error) =>
|
||||
logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
}),
|
||||
onReadinessFailure: Effect.fn("desktop.backendManager.onReadinessFailure")(
|
||||
function* (error) {
|
||||
yield* logBackendManagerWarning("backend readiness check failed during bootstrap", {
|
||||
error,
|
||||
});
|
||||
yield* backendOutputLog.persistFailure({
|
||||
details: error.message,
|
||||
});
|
||||
},
|
||||
),
|
||||
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
|
||||
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
|
||||
}).pipe(
|
||||
@@ -761,7 +832,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
yield* Option.match(active, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (run) => closeRun(run, options),
|
||||
onSome: (run) => closeRun(run, options).pipe(Effect.andThen(backendOutputLog.discardSession)),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ export class ElectronApp extends Context.Service<
|
||||
) => Effect.Effect<void>;
|
||||
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
|
||||
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
|
||||
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
|
||||
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
|
||||
readonly setAsDefaultProtocolClient: (
|
||||
protocol: string,
|
||||
@@ -150,6 +151,7 @@ export const make = ElectronApp.of({
|
||||
Electron.app.setAppUserModelId(id);
|
||||
}),
|
||||
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
|
||||
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
|
||||
isDefaultProtocolClient: (protocol) =>
|
||||
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
|
||||
setAsDefaultProtocolClient: (protocol, path, args) =>
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
export type ElectronThermalState = ReturnType<Electron.PowerMonitor["getCurrentThermalState"]>;
|
||||
export type ElectronIdleState = ReturnType<Electron.PowerMonitor["getSystemIdleState"]>;
|
||||
|
||||
export interface ElectronPowerMonitorShape {
|
||||
readonly isOnBatteryPower: Effect.Effect<boolean>;
|
||||
readonly getSystemIdleTime: Effect.Effect<number>;
|
||||
readonly getSystemIdleState: (idleThresholdSeconds: number) => Effect.Effect<ElectronIdleState>;
|
||||
readonly getCurrentThermalState: Effect.Effect<ElectronThermalState>;
|
||||
readonly onSimpleEvent: (
|
||||
eventName: "lock-screen" | "unlock-screen" | "on-ac" | "on-battery" | "suspend" | "resume",
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onThermalStateChange: (
|
||||
listener: (state: ElectronThermalState) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly onSpeedLimitChange: (
|
||||
listener: (limit: number) => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ElectronPowerMonitor extends Context.Service<
|
||||
ElectronPowerMonitor,
|
||||
ElectronPowerMonitorShape
|
||||
>()("@t3tools/desktop/electron/ElectronPowerMonitor") {}
|
||||
|
||||
const onSimpleEvent: ElectronPowerMonitorShape["onSimpleEvent"] = (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on(eventName as any, listener as any);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener(eventName as any, listener as any);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const onThermalStateChange: ElectronPowerMonitorShape["onThermalStateChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorThermalStateChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.state);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("thermal-state-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("thermal-state-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const onSpeedLimitChange: ElectronPowerMonitorShape["onSpeedLimitChange"] = (listener) => {
|
||||
const wrapped = (
|
||||
event: Electron.Event<Electron.PowerMonitorSpeedLimitChangeEventParams>,
|
||||
): void => {
|
||||
listener(event.limit);
|
||||
};
|
||||
return Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.on("speed-limit-change", wrapped);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
Electron.powerMonitor.removeListener("speed-limit-change", wrapped);
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
export const make = ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()),
|
||||
getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()),
|
||||
getSystemIdleState: (idleThresholdSeconds) =>
|
||||
Effect.sync(() => Electron.powerMonitor.getSystemIdleState(idleThresholdSeconds)),
|
||||
getCurrentThermalState: Effect.sync(() => Electron.powerMonitor.getCurrentThermalState()),
|
||||
onSimpleEvent,
|
||||
onThermalStateChange,
|
||||
onSpeedLimitChange,
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronPowerMonitor, make);
|
||||
@@ -18,6 +18,7 @@ import * as DesktopIpc from "./ipc/DesktopIpc.ts";
|
||||
import * as ElectronApp from "./electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "./electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "./electron/ElectronMenu.ts";
|
||||
import * as ElectronPowerMonitor from "./electron/ElectronPowerMonitor.ts";
|
||||
import * as ElectronProtocol from "./electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "./electron/ElectronSafeStorage.ts";
|
||||
import * as ElectronShell from "./electron/ElectronShell.ts";
|
||||
@@ -46,6 +47,7 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserSession from "./preview/BrowserSession.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
@@ -105,6 +107,7 @@ const electronLayer = Layer.mergeAll(
|
||||
ElectronApp.layer,
|
||||
ElectronDialog.layer,
|
||||
ElectronMenu.layer,
|
||||
ElectronPowerMonitor.layer,
|
||||
ElectronProtocol.layer,
|
||||
ElectronSafeStorage.layer,
|
||||
ElectronShell.layer,
|
||||
@@ -146,6 +149,7 @@ const desktopWindowLayer = DesktopWindow.layer.pipe(
|
||||
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
|
||||
@@ -534,9 +534,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
),
|
||||
);
|
||||
|
||||
const tabIdForWebContents = Effect.fn("PreviewManager.tabIdForWebContents")(function* (
|
||||
webContentsId: number,
|
||||
) {
|
||||
const tabIdForWebContents = Effect.fnUntraced(function* (webContentsId: number) {
|
||||
const tabs = yield* SynchronizedRef.get(tabsRef);
|
||||
return (
|
||||
Array.from(tabs.entries()).find(([, tab]) => tab.webContentsId === webContentsId)?.[0] ?? null
|
||||
@@ -546,7 +544,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const pushBounded = <A>(buffer: ReadonlyArray<A>, entry: A): ReadonlyArray<A> =>
|
||||
[...buffer, entry].slice(-DIAGNOSTIC_BUFFER_LIMIT);
|
||||
|
||||
const captureDiagnosticMessage = Effect.fn("PreviewManager.captureDiagnosticMessage")(function* (
|
||||
const captureDiagnosticMessage = Effect.fnUntraced(function* (
|
||||
webContentsId: number,
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -724,47 +722,46 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const createControlSession = Effect.fn("PreviewManager.createControlSession")(function* () {
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const handleDebuggerMessage = Effect.fn("PreviewManager.handleDebuggerMessage")(
|
||||
function* (method: string, params: Record<string, unknown>) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width:
|
||||
typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) =>
|
||||
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
const handleDebuggerMessage = Effect.fnUntraced(function* (
|
||||
method: string,
|
||||
params: Record<string, unknown>,
|
||||
) {
|
||||
if (method === "Page.screencastFrame") {
|
||||
const sessionId = params["sessionId"];
|
||||
if (typeof sessionId === "number") {
|
||||
yield* attemptPromise(
|
||||
{
|
||||
operation: "ackScreencastFrame",
|
||||
webContentsId: wc.id,
|
||||
},
|
||||
() => wc.debugger.sendCommand("Page.screencastFrameAck", { sessionId }),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
},
|
||||
);
|
||||
const tabId = yield* tabIdForWebContents(wc.id);
|
||||
const metadata =
|
||||
typeof params["metadata"] === "object" && params["metadata"] !== null
|
||||
? (params["metadata"] as Record<string, unknown>)
|
||||
: {};
|
||||
if (tabId && typeof params["data"] === "string") {
|
||||
const receivedAt = yield* currentIso;
|
||||
const listeners = yield* Ref.get(recordingFrameListenersRef);
|
||||
const frame: DesktopPreviewRecordingFrame = {
|
||||
tabId,
|
||||
data: params["data"],
|
||||
width: typeof metadata["deviceWidth"] === "number" ? metadata["deviceWidth"] : 0,
|
||||
height:
|
||||
typeof metadata["deviceHeight"] === "number" ? metadata["deviceHeight"] : 0,
|
||||
receivedAt,
|
||||
};
|
||||
yield* Effect.forEach(
|
||||
listeners,
|
||||
(listener) => deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
yield* captureDiagnosticMessage(wc.id, method, params);
|
||||
});
|
||||
const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => {
|
||||
runFork(handleDebuggerMessage(method, params));
|
||||
};
|
||||
|
||||
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
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 Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import type * as Electron from "electron";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts";
|
||||
|
||||
function makeElectronAppLayer(
|
||||
metrics: ReadonlyArray<Electron.ProcessMetric>,
|
||||
onMetricsRead: () => void = () => undefined,
|
||||
) {
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
relaunch: () => Effect.void,
|
||||
setPath: () => Effect.void,
|
||||
setName: () => Effect.void,
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.sync(() => {
|
||||
onMetricsRead();
|
||||
return metrics;
|
||||
}),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
}
|
||||
|
||||
describe("DesktopTelemetryPublisher", () => {
|
||||
it.effect("publishes Electron metrics and event-driven power state over NDJSON", () =>
|
||||
Effect.gen(function* () {
|
||||
const onBattery = yield* Ref.make(false);
|
||||
let metricsReadCount = 0;
|
||||
const simpleListeners = new Map<string, () => void>();
|
||||
let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null =
|
||||
null;
|
||||
let speedLimitListener: ((limit: number) => void) | null = null;
|
||||
const metrics = [
|
||||
{
|
||||
pid: 4_242,
|
||||
type: "Browser",
|
||||
creationTime: 1_000,
|
||||
name: "electron",
|
||||
cpu: {
|
||||
percentCPUUsage: 12.5,
|
||||
cumulativeCPUUsage: 3.25,
|
||||
idleWakeupsPerSecond: 7,
|
||||
},
|
||||
memory: {
|
||||
workingSetSize: 2_048,
|
||||
peakWorkingSetSize: 4_096,
|
||||
},
|
||||
} as Electron.ProcessMetric,
|
||||
];
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Ref.get(onBattery),
|
||||
getSystemIdleTime: Effect.succeed(5),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: (eventName, listener) =>
|
||||
Effect.sync(() => {
|
||||
simpleListeners.set(eventName, listener);
|
||||
}),
|
||||
onThermalStateChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
thermalListener = listener;
|
||||
}),
|
||||
onSpeedLimitChange: (listener) =>
|
||||
Effect.sync(() => {
|
||||
speedLimitListener = listener;
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
makeElectronAppLayer(metrics, () => {
|
||||
metricsReadCount += 1;
|
||||
}),
|
||||
powerLayer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect);
|
||||
const decoder = new TextDecoder();
|
||||
const messages = Array.from(encoded, (bytes) => JSON.parse(decoder.decode(bytes).trim()));
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
assert.equal(messages[1]?.type, "desktopTelemetry");
|
||||
assert.deepEqual(messages[1]?.electronProcesses, []);
|
||||
assert.equal(messages[1]?.electronPid, process.pid);
|
||||
assert.equal(metricsReadCount, 0);
|
||||
|
||||
const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: true,
|
||||
});
|
||||
const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber));
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5);
|
||||
assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024);
|
||||
assert.equal(metricsReadCount, 1);
|
||||
|
||||
const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* Ref.set(onBattery, true);
|
||||
simpleListeners.get("on-battery")?.();
|
||||
const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber));
|
||||
assert.equal(batterySnapshot.power.onBattery, "true");
|
||||
|
||||
const metricsAfterBatteryEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(4_999));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1);
|
||||
|
||||
const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
thermalListener?.("serious");
|
||||
const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber));
|
||||
assert.equal(constrainedSnapshot.power.thermalState, "serious");
|
||||
|
||||
const metricsAfterThermalEvent = metricsReadCount;
|
||||
yield* TestClock.adjust(Duration.millis(14_999));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent);
|
||||
yield* TestClock.adjust(Duration.millis(1));
|
||||
assert.equal(metricsReadCount, metricsAfterThermalEvent + 1);
|
||||
|
||||
const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
speedLimitListener?.(65);
|
||||
const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber));
|
||||
assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65);
|
||||
|
||||
const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControl({
|
||||
version: 1,
|
||||
type: "setDiagnosticsDemand",
|
||||
enabled: false,
|
||||
});
|
||||
const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber));
|
||||
assert.deepEqual(stoppedSnapshot.electronProcesses, []);
|
||||
const backgroundSequence = stoppedSnapshot.sequence;
|
||||
const metricsAfterStopping = metricsReadCount;
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(29));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
assert.equal(
|
||||
(yield* publisher.latest).pipe(Option.getOrThrow).sequence,
|
||||
backgroundSequence + 1,
|
||||
);
|
||||
assert.equal(metricsReadCount, metricsAfterStopping);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts";
|
||||
|
||||
const LIVE_SAMPLE_INTERVAL = Duration.seconds(1);
|
||||
const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5);
|
||||
const CONSTRAINED_SAMPLE_INTERVAL = Duration.seconds(15);
|
||||
const BACKGROUND_HEARTBEAT_INTERVAL = Duration.seconds(30);
|
||||
const IDLE_THRESHOLD_SECONDS = 60;
|
||||
const encodeMessage = Schema.encodeSync(Schema.fromJsonString(DesktopHostTelemetryMessage));
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
type PowerEvent =
|
||||
| { readonly type: "locked"; readonly value: boolean }
|
||||
| { readonly type: "suspended"; readonly value: boolean }
|
||||
| { readonly type: "onBattery"; readonly value: boolean }
|
||||
| { readonly type: "thermal"; readonly value: HostPowerSnapshot["thermalState"] }
|
||||
| { readonly type: "speedLimit"; readonly value: number };
|
||||
|
||||
interface PowerState {
|
||||
readonly locked: HostPowerSnapshot["locked"];
|
||||
readonly suspended: boolean;
|
||||
readonly onBattery: HostPowerSnapshot["onBattery"];
|
||||
readonly thermalState: HostPowerSnapshot["thermalState"];
|
||||
readonly speedLimitPercent: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface DesktopTelemetryPublisherShape {
|
||||
readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;
|
||||
readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;
|
||||
readonly encoded: Stream.Stream<Uint8Array>;
|
||||
readonly handleControl: (message: DesktopTelemetryControlMessage) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class DesktopTelemetryPublisher extends Context.Service<
|
||||
DesktopTelemetryPublisher,
|
||||
DesktopTelemetryPublisherShape
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
function booleanState(value: boolean): HostPowerSnapshot["onBattery"] {
|
||||
return value ? "true" : "false";
|
||||
}
|
||||
|
||||
function idleState(value: ElectronPowerMonitor.ElectronIdleState): HostPowerSnapshot["idle"] {
|
||||
switch (value) {
|
||||
case "active":
|
||||
return "false";
|
||||
case "idle":
|
||||
case "locked":
|
||||
return "true";
|
||||
case "unknown":
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePowerState(state: PowerState, event: PowerEvent): PowerState {
|
||||
switch (event.type) {
|
||||
case "locked":
|
||||
return { ...state, locked: booleanState(event.value) };
|
||||
case "suspended":
|
||||
return { ...state, suspended: event.value };
|
||||
case "onBattery":
|
||||
return { ...state, onBattery: booleanState(event.value) };
|
||||
case "thermal":
|
||||
return { ...state, thermalState: event.value };
|
||||
case "speedLimit":
|
||||
return { ...state, speedLimitPercent: Option.some(event.value) };
|
||||
}
|
||||
}
|
||||
|
||||
function sampleInterval(power: PowerState, diagnosticsDemand: boolean): Duration.Duration {
|
||||
if (!diagnosticsDemand) return BACKGROUND_HEARTBEAT_INTERVAL;
|
||||
if (
|
||||
power.suspended ||
|
||||
power.locked === "true" ||
|
||||
power.thermalState === "serious" ||
|
||||
power.thermalState === "critical"
|
||||
) {
|
||||
return CONSTRAINED_SAMPLE_INTERVAL;
|
||||
}
|
||||
if (power.onBattery === "true") return BATTERY_SAMPLE_INTERVAL;
|
||||
return LIVE_SAMPLE_INTERVAL;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor;
|
||||
yield* electronApp.whenReady;
|
||||
|
||||
const initialPowerState: PowerState = {
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: booleanState(yield* powerMonitor.isOnBatteryPower),
|
||||
thermalState: yield* powerMonitor.getCurrentThermalState,
|
||||
speedLimitPercent: Option.none(),
|
||||
};
|
||||
const powerState = yield* Ref.make(initialPowerState);
|
||||
const powerEvents = yield* Queue.unbounded<PowerEvent>();
|
||||
const sampleTriggers = yield* Queue.sliding<void>(1);
|
||||
const diagnosticsDemand = yield* Ref.make(false);
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
};
|
||||
yield* Effect.all(
|
||||
[
|
||||
powerMonitor.onSimpleEvent("lock-screen", () => offer({ type: "locked", value: true })),
|
||||
powerMonitor.onSimpleEvent("unlock-screen", () => offer({ type: "locked", value: false })),
|
||||
powerMonitor.onSimpleEvent("suspend", () => offer({ type: "suspended", value: true })),
|
||||
powerMonitor.onSimpleEvent("resume", () => offer({ type: "suspended", value: false })),
|
||||
powerMonitor.onSimpleEvent("on-battery", () => offer({ type: "onBattery", value: true })),
|
||||
powerMonitor.onSimpleEvent("on-ac", () => offer({ type: "onBattery", value: false })),
|
||||
powerMonitor.onThermalStateChange((value) => offer({ type: "thermal", value })),
|
||||
powerMonitor.onSpeedLimitChange((value) => offer({ type: "speedLimit", value })),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* Effect.forever(
|
||||
Queue.take(powerEvents).pipe(
|
||||
Effect.flatMap((event) => Ref.update(powerState, (state) => updatePowerState(state, event))),
|
||||
Effect.andThen(Queue.offer(sampleTriggers, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt);
|
||||
const demand = yield* Ref.get(diagnosticsDemand);
|
||||
const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all(
|
||||
[
|
||||
Ref.get(powerState),
|
||||
powerMonitor.getSystemIdleTime,
|
||||
powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS),
|
||||
powerMonitor.isOnBatteryPower,
|
||||
demand ? electronApp.getAppMetrics : Effect.succeed([]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]);
|
||||
const locked = systemIdleState === "locked" ? "true" : currentPower.locked;
|
||||
const snapshot: DesktopHostTelemetrySnapshot = {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: nextSequence,
|
||||
sampledAtUnixMs,
|
||||
electronPid: process.pid,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: idleState(systemIdleState),
|
||||
idleSeconds,
|
||||
locked,
|
||||
suspended: currentPower.suspended,
|
||||
onBattery: booleanState(onBattery),
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: currentPower.thermalState,
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: currentPower.speedLimitPercent,
|
||||
electronProcesses: metrics.map((metric) => ({
|
||||
pid: metric.pid,
|
||||
creationTimeMs: metric.creationTime,
|
||||
type: metric.type,
|
||||
...(metric.name === undefined ? {} : { name: metric.name }),
|
||||
...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }),
|
||||
cpuPercent: metric.cpu.percentCPUUsage,
|
||||
...(metric.cpu.cumulativeCPUUsage === undefined
|
||||
? {}
|
||||
: { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }),
|
||||
idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond,
|
||||
workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)),
|
||||
peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)),
|
||||
})),
|
||||
};
|
||||
|
||||
yield* Ref.set(latest, Option.some(snapshot));
|
||||
yield* PubSub.publish(changes, snapshot);
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to sample Electron telemetry", {
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* sampleOnce;
|
||||
while (true) {
|
||||
const [currentPower, demand] = yield* Effect.all([
|
||||
Ref.get(powerState),
|
||||
Ref.get(diagnosticsDemand),
|
||||
]);
|
||||
yield* Effect.raceFirst(
|
||||
Queue.take(sampleTriggers),
|
||||
Effect.sleep(sampleInterval(currentPower, demand)),
|
||||
);
|
||||
yield* sampleOnce;
|
||||
}
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {
|
||||
switch (message.type) {
|
||||
case "setDiagnosticsDemand":
|
||||
return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === message.enabled
|
||||
? Effect.void
|
||||
: Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const snapshots = Stream.concat(
|
||||
Stream.unwrap(
|
||||
Ref.get(latest).pipe(
|
||||
Effect.map(
|
||||
Option.match({
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Stream.fromPubSub(changes),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
encoded,
|
||||
handleControl,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopTelemetryPublisher, make());
|
||||
@@ -40,6 +40,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setAboutPanelOptions: () => Effect.void,
|
||||
setAppUserModelId: () => Effect.void,
|
||||
requestSingleInstanceLock: Effect.succeed(true),
|
||||
getAppMetrics: Effect.succeed([]),
|
||||
isDefaultProtocolClient: () => Effect.succeed(false),
|
||||
setAsDefaultProtocolClient: () => Effect.succeed(true),
|
||||
setDesktopName: () => Effect.void,
|
||||
|
||||
@@ -30,7 +30,9 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
@@ -63,6 +65,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
@@ -105,10 +114,16 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
loadedBranchesProjectKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
|
||||
if (loadedBranchesProjectKeyRef.current === projectKey) {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
}, [flow, selectedProject]);
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
// Defer state update so the native menu dismiss animation completes
|
||||
// before re-rendering the menu actions (prevents submenu jump).
|
||||
setTimeout(() => {
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}, 150);
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
flow.submitting ||
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
(workspaceMode === "worktree" && !selectedBranchName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
const result = await createProjectThread({
|
||||
project: flow.selectedProject,
|
||||
modelSelection: flow.selectedModel,
|
||||
envMode: flow.workspaceMode,
|
||||
branch: flow.selectedBranchName,
|
||||
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
initialMessageText: flow.prompt.trim(),
|
||||
initialAttachments: flow.attachments,
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -79,18 +73,6 @@ export function ThreadRouteScreen() {
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
"thread metadata update",
|
||||
);
|
||||
const setThreadRuntimeMode = useAtomCommand(
|
||||
threadEnvironment.setRuntimeMode,
|
||||
"thread runtime mode",
|
||||
);
|
||||
const setThreadInteractionMode = useAtomCommand(
|
||||
threadEnvironment.setInteractionMode,
|
||||
"thread interaction mode",
|
||||
);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -105,6 +87,18 @@ export function ThreadRouteScreen() {
|
||||
const routeConnectionState =
|
||||
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
|
||||
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
|
||||
const selectedThreadWithDraftSettings = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? {
|
||||
...selectedThread,
|
||||
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
|
||||
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
|
||||
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
|
||||
}
|
||||
: null,
|
||||
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
@@ -157,51 +151,6 @@ export function ThreadRouteScreen() {
|
||||
const handleOpenConnectionEditor = useCallback(() => {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleUpdateThreadModelSelection = useCallback(
|
||||
(modelSelection: ModelSelection) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return updateThreadMetadata({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
modelSelection,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, updateThreadMetadata],
|
||||
);
|
||||
const handleUpdateThreadRuntimeMode = useCallback(
|
||||
(runtimeMode: RuntimeMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadRuntimeMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runtimeMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadRuntimeMode],
|
||||
);
|
||||
const handleUpdateThreadInteractionMode = useCallback(
|
||||
(interactionMode: ProviderInteractionMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadInteractionMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
interactionMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadInteractionMode],
|
||||
);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThread}
|
||||
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
|
||||
contentPresentation={contentPresentation}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
|
||||
onStopThread={handleStopThread}
|
||||
onSendMessage={composer.onSendMessage}
|
||||
onReconnectEnvironment={handleReconnectEnvironment}
|
||||
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
|
||||
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
|
||||
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
|
||||
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useMemo, useRef, useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
@@ -158,34 +159,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
? selectedEnvironmentIdOverride
|
||||
: (projects[0]?.environmentId ?? null);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
|
||||
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
|
||||
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
|
||||
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
|
||||
const branchLoadVersionRef = useRef(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
|
||||
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
);
|
||||
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
|
||||
Record<string, ModelSelection>
|
||||
>({});
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedModelKey(null);
|
||||
setWorkspaceMode("local");
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setRuntimeMode(DEFAULT_RUNTIME_MODE);
|
||||
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
setModelSelectionOverrides({});
|
||||
setExpandedProvider(null);
|
||||
}, []);
|
||||
|
||||
@@ -247,33 +229,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
),
|
||||
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
);
|
||||
|
||||
const defaultModelKey = selectedProject?.defaultModelSelection
|
||||
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
|
||||
: null;
|
||||
const baseSelectedModel =
|
||||
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
|
||||
(defaultModelKey
|
||||
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
|
||||
: null) ??
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelIdentity = baseSelectedModel
|
||||
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
|
||||
const selectedModelKey = selectedModel
|
||||
? `${selectedModel.instanceId}:${selectedModel.model}`
|
||||
: null;
|
||||
const selectedModel =
|
||||
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
|
||||
baseSelectedModel;
|
||||
|
||||
const selectedModelOption =
|
||||
modelOptions.find(
|
||||
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
option.selection.instanceId === selectedModel.instanceId &&
|
||||
option.selection.model === selectedModel.model,
|
||||
) ?? null;
|
||||
const selectedProviderSkills =
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [];
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [],
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const option = modelOptions.find((candidate) => candidate.key === key);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
);
|
||||
const setSelectedModelOptions = useCallback(
|
||||
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
|
||||
if (!selectedModel || !selectedModelIdentity) {
|
||||
if (!selectedModel || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const nextSelection: ModelSelection = options
|
||||
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
instanceId: selectedModel.instanceId,
|
||||
model: selectedModel.model,
|
||||
};
|
||||
setModelSelectionOverrides((current) => ({
|
||||
...current,
|
||||
[selectedModelIdentity]: nextSelection,
|
||||
}));
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: nextSelection,
|
||||
});
|
||||
},
|
||||
[selectedModel, selectedModelIdentity],
|
||||
[selectedModel, selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
|
||||
@@ -381,62 +380,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
setSelectedBranchName(branch.name);
|
||||
setSelectedWorktreePath(
|
||||
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
|
||||
);
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedProject],
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
refreshBranches();
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
const loadVersion = ++branchLoadVersionRef.current;
|
||||
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
|
||||
branchState.refresh();
|
||||
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
|
||||
useEffect(() => {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
if (workspaceMode === "worktree" && !selectedBranchName) {
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current)?.name ??
|
||||
availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
setSelectedBranchName(preferredBranch);
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
}
|
||||
}, [
|
||||
availableBranches,
|
||||
branchState,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const setInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setProject,
|
||||
selectBranch,
|
||||
selectEnvironment,
|
||||
setInteractionMode,
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
@@ -1,32 +1,38 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -40,9 +46,37 @@ export interface QueuedThreadMessage {
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadSettingsSnapshot {
|
||||
readonly modelSelection: ModelSelectionType;
|
||||
readonly runtimeMode: RuntimeModeType;
|
||||
readonly interactionMode: ProviderInteractionModeType;
|
||||
}
|
||||
|
||||
export function resolveQueuedThreadSettings(
|
||||
message: QueuedThreadMessage,
|
||||
thread: ThreadSettingsSnapshot,
|
||||
): ThreadSettingsSnapshot {
|
||||
return {
|
||||
modelSelection: message.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: message.interactionMode ?? thread.interactionMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
|
||||
return (
|
||||
left.instanceId === right.instanceId &&
|
||||
left.model === right.model &&
|
||||
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
|
||||
return encodeStoredQueuedThreadMessage({
|
||||
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
|
||||
@@ -119,3 +153,21 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
return isTransportConnectionErrorMessage(errorMessage(error));
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
readonly error: unknown;
|
||||
readonly interrupted: boolean;
|
||||
}): ThreadOutboxFailureAction {
|
||||
if (
|
||||
input.stage === "settings-sync" ||
|
||||
input.interrupted ||
|
||||
shouldRetryThreadOutboxDelivery(input.error)
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
@@ -66,6 +76,54 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const selectedMessage = {
|
||||
...legacyMessage,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
|
||||
selectedMessage,
|
||||
);
|
||||
expect(
|
||||
resolveQueuedThreadSettings(legacyMessage, {
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
}),
|
||||
).toEqual({
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
});
|
||||
});
|
||||
|
||||
it("compares model options as part of the queued settings change", () => {
|
||||
const base = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
} as const;
|
||||
|
||||
expect(modelSelectionsEqual(base, base)).toBe(true);
|
||||
expect(
|
||||
modelSelectionsEqual(base, {
|
||||
...base,
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
|
||||
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
|
||||
@@ -271,4 +329,23 @@ describe("thread outbox", () => {
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retains queued messages when settings synchronization fails before startTurn", () => {
|
||||
const deterministicFailure = new Error("Thread no longer exists");
|
||||
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "settings-sync",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("retry");
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "start-turn",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("discard");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,136 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
clearComposerDraftContentState,
|
||||
composerDraftsAtom,
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftsForEnvironment,
|
||||
} from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
});
|
||||
|
||||
describe("mobile composer drafts", () => {
|
||||
it("hydrates selector state even when the message content is empty", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": DRAFT,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"environment-1:thread-1": DRAFT,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": {
|
||||
...DRAFT,
|
||||
runtimeMode: "sometimes-safe",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("clears sent content without clearing the selected model or workspace", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
};
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the latest selector state synchronously for send", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const selectedDraft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
};
|
||||
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
|
||||
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -17,12 +139,15 @@ describe("mobile composer drafts", () => {
|
||||
removeComposerDraftsForEnvironment(
|
||||
{
|
||||
[`${environmentId}:thread-cloud`]: DRAFT,
|
||||
[`new-task:${environmentId}:project-cloud`]: DRAFT,
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
},
|
||||
environmentId,
|
||||
),
|
||||
).toEqual({
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,18 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
ModelSelection as ModelSelectionSchema,
|
||||
ProviderInteractionMode as ProviderInteractionModeSchema,
|
||||
RuntimeMode as RuntimeModeSchema,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
@@ -29,13 +38,47 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
readonly interactionMode?: ProviderInteractionMode;
|
||||
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
|
||||
}
|
||||
|
||||
interface PersistedComposerDrafts {
|
||||
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
}
|
||||
|
||||
export type ComposerDraftSettingsUpdate = Pick<
|
||||
ComposerDraft,
|
||||
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
|
||||
>;
|
||||
|
||||
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
mode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
interactionMode: Schema.optional(ProviderInteractionModeSchema),
|
||||
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
|
||||
});
|
||||
|
||||
const PersistedComposerDraftsSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
});
|
||||
|
||||
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
|
||||
PersistedComposerDraftsSchema,
|
||||
);
|
||||
|
||||
const EMPTY_DRAFT: ComposerDraft = {
|
||||
text: "",
|
||||
attachments: [],
|
||||
@@ -54,13 +97,32 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
|
||||
return EMPTY_DRAFT;
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
text: draft.text,
|
||||
attachments: draft.attachments,
|
||||
};
|
||||
}
|
||||
|
||||
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
|
||||
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
|
||||
}
|
||||
|
||||
function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
return draft.text.length === 0 && draft.attachments.length === 0;
|
||||
return (
|
||||
draft.text.length === 0 &&
|
||||
draft.attachments.length === 0 &&
|
||||
draft.modelSelection === undefined &&
|
||||
draft.runtimeMode === undefined &&
|
||||
draft.interactionMode === undefined &&
|
||||
draft.workspaceSelection === undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
|
||||
const parsed = decodePersistedComposerDraftsDocument(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
}
|
||||
|
||||
async function getComposerDraftsFile() {
|
||||
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
operation = "decode";
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
|
||||
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
|
||||
return {};
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
|
||||
const draft = entry[1];
|
||||
return (
|
||||
typeof draft?.text === "string" &&
|
||||
Array.isArray(draft.attachments) &&
|
||||
!isEmptyDraft(draft)
|
||||
);
|
||||
}),
|
||||
);
|
||||
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-drafts] ignored persisted draft failure",
|
||||
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document: PersistedComposerDrafts = {
|
||||
const document = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
};
|
||||
} as const;
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
@@ -282,6 +331,55 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
});
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
draftKey: string,
|
||||
settings: Partial<ComposerDraftSettingsUpdate>,
|
||||
): void {
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = {
|
||||
...normalizeDraft(current[draftKey]),
|
||||
...settings,
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function clearComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = current[draftKey];
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const draft = {
|
||||
...existing,
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
updateComposerDrafts((current) => {
|
||||
if (!current[draftKey]) {
|
||||
@@ -298,8 +396,12 @@ export function removeComposerDraftsForEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
): Record<string, ComposerDraft> {
|
||||
const environmentPrefix = `${environmentId}:`;
|
||||
const newTaskPrefix = `new-task:${environmentId}:`;
|
||||
return Object.fromEntries(
|
||||
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
|
||||
Object.entries(drafts).filter(
|
||||
([draftKey]) =>
|
||||
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
appendComposerDraftText,
|
||||
clearComposerDraft,
|
||||
clearComposerDraftContent,
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
@@ -98,6 +108,10 @@ export function useThreadComposerState() {
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
@@ -130,7 +144,6 @@ export function useThreadComposerState() {
|
||||
selectedThreadShell,
|
||||
]);
|
||||
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
@@ -141,9 +154,10 @@ export function useThreadComposerState() {
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = composerDrafts[threadKey];
|
||||
const text = (draft?.text ?? "").trim();
|
||||
const attachments = draft?.attachments ?? [];
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -157,15 +171,18 @@ export function useThreadComposerState() {
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraft(threadKey);
|
||||
clearComposerDraftContent(threadKey);
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
}
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -255,12 +272,45 @@ export function useThreadComposerState() {
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = useCallback(
|
||||
(value: ModelSelection) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
draftAttachments,
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
@@ -268,5 +318,8 @@ export function useThreadComposerState() {
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
onSendMessage,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
onUpdateInteractionMode,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
@@ -44,8 +48,21 @@ function findThread(
|
||||
);
|
||||
}
|
||||
|
||||
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
|
||||
export function useThreadOutboxDrain(): void {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
@@ -68,6 +85,98 @@ export function useThreadOutboxDrain(): void {
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "model-selection"),
|
||||
threadId: queuedMessage.threadId,
|
||||
modelSelection: settings.modelSelection,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(updateResult)) {
|
||||
reportFailure(updateResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.runtimeMode !== thread.runtimeMode) {
|
||||
const runtimeResult = await setThreadRuntimeMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(runtimeResult)) {
|
||||
reportFailure(runtimeResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.interactionMode !== thread.interactionMode) {
|
||||
const interactionResult = await setThreadInteractionMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(interactionResult)) {
|
||||
reportFailure(interactionResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
},
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(deliveryResult)) {
|
||||
const error = Cause.squash(deliveryResult.cause);
|
||||
const retry =
|
||||
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
cause: deliveryResult.cause,
|
||||
retry,
|
||||
});
|
||||
if (retry) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return completeDelivery(deliveryResult);
|
||||
},
|
||||
[startTurn],
|
||||
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -33,13 +33,17 @@ import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
|
||||
import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import * as ProviderService from "../src/provider/ProviderService.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
|
||||
@@ -174,7 +178,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService.ProviderService["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];
|
||||
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
|
||||
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
|
||||
@@ -237,7 +241,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
ProviderAdapterRegistry,
|
||||
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
|
||||
)
|
||||
: null;
|
||||
@@ -258,11 +262,11 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry.ProviderAdapterRegistry,
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexSettings = yield* decodeCodexSettings({});
|
||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
||||
@@ -275,18 +279,15 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
|
||||
const providerLayer = useRealCodex
|
||||
? ProviderService.layer.pipe(
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
)
|
||||
: ProviderService.layer.pipe(
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
@@ -394,7 +395,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService.ProviderService)),
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),
|
||||
|
||||
@@ -206,16 +206,21 @@ function nowIso(): string {
|
||||
return "2026-01-01T00:00:00.000Z";
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
}),
|
||||
);
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
@@ -512,12 +517,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
}),
|
||||
),
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -10,13 +10,20 @@ import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ProviderAdapterRegistry from "../src/provider/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import * as ProviderSessionDirectory from "../src/provider/ProviderSessionDirectory.ts";
|
||||
import * as ProviderEventLoggers from "../src/provider/ProviderEventLoggers.ts";
|
||||
import * as ProviderService from "../src/provider/ProviderService.ts";
|
||||
import * as ServerSettings from "../src/serverSettings.ts";
|
||||
import * as AnalyticsService from "../src/telemetry/AnalyticsService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
|
||||
|
||||
@@ -44,7 +51,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
interface IntegrationFixture {
|
||||
readonly cwd: string;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly layer: Layer.Layer<ProviderService.ProviderService, unknown, never>;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
@@ -55,22 +62,19 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry),
|
||||
ServerSettings.ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = ProviderService.layer.pipe(Layer.provide(shared));
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
@@ -101,7 +105,7 @@ const collectEventsDuring = <A, E, R>(
|
||||
});
|
||||
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderService.ProviderService["Service"];
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly threadId: ThreadId;
|
||||
readonly userText: string;
|
||||
@@ -125,7 +129,7 @@ it.live("replays typed runtime fixture events", () =>
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -162,7 +166,7 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -199,7 +203,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -251,7 +255,7 @@ it.live("rolls back provider conversation state only", () =>
|
||||
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
|
||||
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
|
||||
create: () => Effect.void,
|
||||
getById: () => Effect.fail(repositoryFailure),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.succeed(false),
|
||||
revokeAllExcept: () => Effect.succeed([]),
|
||||
revoke: () => Effect.fail(repositoryFailure),
|
||||
revokeAllExcept: () => Effect.fail(repositoryFailure),
|
||||
setLastConnectedAt: () => Effect.void,
|
||||
});
|
||||
|
||||
@@ -104,11 +104,29 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
|
||||
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
|
||||
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
|
||||
expect(sessionError.cause).toBe(repositoryFailure);
|
||||
expect(websocketError.cause).toBe(repositoryFailure);
|
||||
if (sessionError._tag === "SessionCredentialVerificationError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
if (websocketError._tag === "WebSocketTokenVerificationError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
expect(revokeError).toMatchObject({
|
||||
_tag: "SessionRevocationError",
|
||||
sessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
expect(revokeOthersError).toMatchObject({
|
||||
_tag: "OtherSessionsRevocationError",
|
||||
currentSessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
@@ -145,7 +163,52 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error.message).toContain("expired");
|
||||
expect(error._tag).toBe("WebSocketSessionExpiredError");
|
||||
if (error._tag === "WebSocketSessionExpiredError") {
|
||||
expect(error.sessionId).toBe(issued.sessionId);
|
||||
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
error.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("includes expiry context when session and websocket tokens expire", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-access-token",
|
||||
subject: "short-lived-token",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionTokenExpiredError");
|
||||
if (sessionError._tag === "SessionTokenExpiredError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
sessionError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
|
||||
if (websocketError._tag === "WebSocketTokenExpiredError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
expect(websocketError.expiresAt.epochMilliseconds).toBe(
|
||||
websocket.expiresAt.epochMilliseconds,
|
||||
);
|
||||
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
websocketError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
@@ -173,12 +236,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
const revokedClientWebSocket = yield* Effect.flip(
|
||||
sessions.verifyWebSocketToken(clientWebSocket.token),
|
||||
);
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
@@ -194,7 +261,16 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
|
||||
if (revokedClient._tag === "SessionTokenRevokedError") {
|
||||
expect(revokedClient.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
|
||||
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
|
||||
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
}).pipe(Effect.provide(makeSessionStoreLayer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
type AuthEnvironmentScope,
|
||||
type ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -93,7 +92,11 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
|
||||
|
||||
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
|
||||
"SessionTokenExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token expired.";
|
||||
@@ -102,7 +105,9 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
|
||||
"UnknownSessionTokenError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown session token.";
|
||||
@@ -111,7 +116,10 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
|
||||
|
||||
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
|
||||
"SessionTokenRevokedError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token revoked.";
|
||||
@@ -120,7 +128,10 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
|
||||
"InvalidSessionExpirationClaimError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expirationClaim: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid `exp` claim";
|
||||
@@ -158,7 +169,11 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
|
||||
|
||||
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
|
||||
"WebSocketTokenExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket token expired.";
|
||||
@@ -167,7 +182,9 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
|
||||
|
||||
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
|
||||
"UnknownWebSocketSessionError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown websocket session.";
|
||||
@@ -176,7 +193,11 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
|
||||
|
||||
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
|
||||
"WebSocketSessionExpiredError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session expired.";
|
||||
@@ -185,7 +206,10 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
|
||||
|
||||
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
|
||||
"WebSocketSessionRevokedError",
|
||||
{},
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session revoked.";
|
||||
@@ -218,6 +242,7 @@ const sessionCredentialInternalErrorContext = {
|
||||
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
|
||||
"SessionClaimsEncodingError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
@@ -230,6 +255,7 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
|
||||
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
|
||||
"SessionCredentialIssueError",
|
||||
{
|
||||
sessionId: Schema.optional(AuthSessionId),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -241,6 +267,7 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
|
||||
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
|
||||
"SessionCredentialVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -252,6 +279,7 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
|
||||
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
|
||||
"WebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -263,6 +291,7 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
|
||||
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
|
||||
"WebSocketTokenVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -285,6 +314,7 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
|
||||
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
|
||||
"SessionRevocationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -296,6 +326,7 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
|
||||
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
|
||||
"OtherSessionsRevocationError",
|
||||
{
|
||||
currentSessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -539,7 +570,11 @@ export const make = Effect.gen(function* () {
|
||||
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
|
||||
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
|
||||
function* (input) {
|
||||
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
|
||||
const sessionId = AuthSessionId.make(
|
||||
yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
),
|
||||
);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -559,27 +594,37 @@ export const make = Effect.gen(function* () {
|
||||
const encodedPayload = yield* encodeClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
|
||||
(cause) =>
|
||||
new SessionCredentialIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_session_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* authSessions
|
||||
.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
@@ -604,7 +649,6 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies IssuedSession;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
|
||||
@@ -623,22 +667,37 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({});
|
||||
}
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({});
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new SessionTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -652,95 +711,111 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new SessionCredentialVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.issueWebSocketToken",
|
||||
)(
|
||||
function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
|
||||
);
|
||||
)(function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WebSocketTokenIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_websocket_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
|
||||
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.verifyWebSocketToken",
|
||||
)(
|
||||
function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
)(function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new WebSocketTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new WebSocketSessionExpiredError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketSessionExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new WebSocketTokenVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
});
|
||||
|
||||
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
|
||||
function* () {
|
||||
@@ -768,10 +843,12 @@ export const make = Effect.gen(function* () {
|
||||
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
const revoked = yield* authSessions
|
||||
.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
@@ -782,39 +859,41 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return revoked;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionRevocationError({ cause })),
|
||||
);
|
||||
|
||||
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
|
||||
"SessionStore.revokeAllExcept",
|
||||
)(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
)(function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions
|
||||
.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
|
||||
),
|
||||
);
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
},
|
||||
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
});
|
||||
|
||||
return SessionStore.of({
|
||||
cookieName,
|
||||
|
||||
@@ -3,7 +3,8 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
@@ -13,22 +14,6 @@ import {
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
function firstHeaderValue(value: string | undefined): string | undefined {
|
||||
const first = value?.split(",")[0]?.trim();
|
||||
return first && first.length > 0 ? first : undefined;
|
||||
}
|
||||
|
||||
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
|
||||
try {
|
||||
return new URL(request.originalUrl).href;
|
||||
} catch {
|
||||
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
|
||||
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
|
||||
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
|
||||
return new URL(request.originalUrl, `${proto}://${host}`).href;
|
||||
}
|
||||
}
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
@@ -48,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const proof = input.request.headers.dpop;
|
||||
const url = HttpServerRequest.toURL(input.request);
|
||||
if (Option.isNone(url)) {
|
||||
return yield* new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "Invalid DPoP request URL.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const result = verifyDpopProof({
|
||||
proof,
|
||||
method: input.request.method,
|
||||
url: requestAbsoluteUrl(input.request),
|
||||
url: url.value.href,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import {
|
||||
AuthSessionId,
|
||||
RpcClientId,
|
||||
type HostPowerSnapshot,
|
||||
type ClientActivityReportInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "./BackgroundPolicy.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
const TEST_NOW = DateTime.makeUnsafe("2026-05-13T00:00:00.000Z");
|
||||
|
||||
const nominalHostPower: HostPowerSnapshot = {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_NOW,
|
||||
};
|
||||
|
||||
const constrainedHostPower: HostPowerSnapshot = {
|
||||
...nominalHostPower,
|
||||
lowPowerMode: "true",
|
||||
stale: false,
|
||||
};
|
||||
|
||||
function makeReport(overrides: Partial<ClientActivityReportInput> = {}): ClientActivityReportInput {
|
||||
return {
|
||||
clientId: "client-1",
|
||||
clientKind: "web",
|
||||
visible: true,
|
||||
focused: true,
|
||||
recentlyInteracted: true,
|
||||
scopes: [{ type: "vcs-status", cwd: "/repo" }],
|
||||
ttlMs: 45_000,
|
||||
observedAt: TEST_NOW,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLayer(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settingsOverrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {},
|
||||
) {
|
||||
const hostLayer = Layer.effect(
|
||||
HostPowerMonitor.HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
let snapshot = hostPower;
|
||||
return HostPowerMonitor.HostPowerMonitor.of({
|
||||
snapshot: Effect.sync(() => snapshot),
|
||||
report: (next) =>
|
||||
Effect.sync(() => {
|
||||
snapshot = next;
|
||||
}).pipe(Effect.andThen(PubSub.publish(changes, next)), Effect.asVoid),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(Layer.merge(hostLayer, ServerSettingsService.layerTest(settingsOverrides))),
|
||||
);
|
||||
}
|
||||
|
||||
describe("BackgroundPolicy", () => {
|
||||
it.effect("records foreground scoped client demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/other" }), false);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/other" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("removes all leases for a disconnected websocket connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
yield* policy.removeRpcClient(RpcClientId.make(1));
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, []);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect("host low power mode disables opportunistic work without dropping scoped demand", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 1);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(snapshot.shouldRunOpportunisticWork, false);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(constrainedHostPower))),
|
||||
);
|
||||
|
||||
it.effect("keeps background demand visible while preventing scoped work", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
const snapshot = yield* policy.snapshot;
|
||||
assert.equal(snapshot.activeForegroundLeaseCount, 0);
|
||||
assert.deepStrictEqual(snapshot.activeScopeKeys, ["vcs-status:/repo"]);
|
||||
assert.equal(yield* policy.hasDemand({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(Effect.provide(makeLayer(nominalHostPower))),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"performance profile allows background scoped work while a scoped lease is active",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport({ focused: false, visible: false }),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(makeLayer(nominalHostPower, { backgroundActivityProfile: "performance" })),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("battery saver profile pauses scoped work on battery", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
onBattery: "true",
|
||||
stale: false,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not gate work on stale host power values", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
yield* policy.reportClientActivity(
|
||||
AuthSessionId.make("session-1"),
|
||||
RpcClientId.make(1),
|
||||
makeReport(),
|
||||
);
|
||||
|
||||
assert.equal(yield* policy.shouldRunScopeWork({ type: "vcs-status", cwd: "/repo" }), true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer(
|
||||
{
|
||||
...nominalHostPower,
|
||||
locked: "true",
|
||||
onBattery: "true",
|
||||
lowPowerMode: "true",
|
||||
thermalState: "critical",
|
||||
stale: true,
|
||||
},
|
||||
{ backgroundActivityProfile: "battery-saver" },
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
type AuthSessionId,
|
||||
type BackgroundPolicySnapshot,
|
||||
type BackgroundScope,
|
||||
type ClientActivityLease,
|
||||
type ClientActivityReportInput,
|
||||
type HostPowerSnapshot,
|
||||
type RpcClientId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getBackgroundActivityPresetSettings,
|
||||
resolveServerBackgroundActivitySettings,
|
||||
type ResolvedBackgroundActivitySettings,
|
||||
} from "@t3tools/shared/backgroundActivitySettings";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
export interface BackgroundPolicyShape {
|
||||
readonly reportClientActivity: (
|
||||
sessionId: AuthSessionId,
|
||||
rpcClientId: RpcClientId,
|
||||
input: ClientActivityReportInput,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;
|
||||
readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;
|
||||
readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;
|
||||
readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;
|
||||
readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;
|
||||
}
|
||||
|
||||
export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(
|
||||
"t3/background/BackgroundPolicy",
|
||||
) {}
|
||||
|
||||
const DEFAULT_LEASE_TTL_MS = 45_000;
|
||||
const MAX_LEASE_TTL_MS = 120_000;
|
||||
|
||||
function scopeKey(scope: BackgroundScope): string {
|
||||
switch (scope.type) {
|
||||
case "server-config":
|
||||
case "diagnostics":
|
||||
return scope.type;
|
||||
case "provider-status":
|
||||
return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;
|
||||
case "vcs-status":
|
||||
case "git-refs":
|
||||
return `${scope.type}:${scope.cwd}`;
|
||||
case "thread":
|
||||
return `${scope.type}:${scope.threadId}`;
|
||||
}
|
||||
}
|
||||
|
||||
function isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return DateTime.isGreaterThan(lease.expiresAt, now);
|
||||
}
|
||||
|
||||
function isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {
|
||||
return isLeaseActive(lease, now) && lease.visible && lease.focused;
|
||||
}
|
||||
|
||||
function leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {
|
||||
const key = scopeKey(scope);
|
||||
return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);
|
||||
}
|
||||
|
||||
function hasThermalPressure(hostPower: HostPowerSnapshot): boolean {
|
||||
return hostPower.thermalState === "serious" || hostPower.thermalState === "critical";
|
||||
}
|
||||
|
||||
function isHostConstrained(
|
||||
hostPower: HostPowerSnapshot,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (hostPower.stale) return false;
|
||||
if (
|
||||
(settings.pauseWhenHostLocked && hostPower.locked === "true") ||
|
||||
hasThermalPressure(hostPower)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && hostPower.onBattery === "true";
|
||||
}
|
||||
|
||||
function isClientConstrained(
|
||||
lease: ClientActivityLease,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
if (settings.pauseWhenClientLowPower && lease.lowPowerMode === "true") return true;
|
||||
return settings.pauseWhenOnBattery && lease.batteryState === "unplugged";
|
||||
}
|
||||
|
||||
function leaseMayRunScopedWork(
|
||||
lease: ClientActivityLease,
|
||||
scope: BackgroundScope,
|
||||
now: DateTime.Utc,
|
||||
settings: ResolvedBackgroundActivitySettings,
|
||||
): boolean {
|
||||
const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);
|
||||
if (!activeWithScope || isClientConstrained(lease, settings)) {
|
||||
return false;
|
||||
}
|
||||
if (settings.profile === "performance") {
|
||||
return true;
|
||||
}
|
||||
return isForegroundLease(lease, now);
|
||||
}
|
||||
|
||||
function computeSnapshot(input: {
|
||||
readonly hostPower: HostPowerSnapshot;
|
||||
readonly leases: ReadonlyMap<string, ClientActivityLease>;
|
||||
readonly now: DateTime.Utc;
|
||||
readonly settings: ResolvedBackgroundActivitySettings;
|
||||
readonly updatedAt: DateTime.Utc;
|
||||
}): BackgroundPolicySnapshot {
|
||||
const activeLeases = [...input.leases.values()].filter((lease) =>
|
||||
isLeaseActive(lease, input.now),
|
||||
);
|
||||
const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));
|
||||
const activeScopeKeys = new Set<string>();
|
||||
for (const lease of activeLeases) {
|
||||
for (const scope of lease.scopes) {
|
||||
activeScopeKeys.add(scopeKey(scope));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hostPower: input.hostPower,
|
||||
leases: activeLeases,
|
||||
activeForegroundLeaseCount: foregroundLeases.length,
|
||||
activeScopeKeys: [...activeScopeKeys].toSorted(),
|
||||
shouldRunOpportunisticWork:
|
||||
foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&
|
||||
!isHostConstrained(input.hostPower, input.settings),
|
||||
updatedAt: input.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.policy.make")(function* () {
|
||||
const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());
|
||||
const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);
|
||||
|
||||
const backgroundActivitySettings = serverSettings.getSettings.pipe(
|
||||
Effect.map(resolveServerBackgroundActivitySettings),
|
||||
Effect.orElseSucceed(() => getBackgroundActivityPresetSettings("balanced")),
|
||||
);
|
||||
|
||||
const snapshot = Effect.gen(function* () {
|
||||
const [hostPower, leases, now, settings] = yield* Effect.all([
|
||||
hostPowerMonitor.snapshot,
|
||||
Ref.get(leasesRef),
|
||||
DateTime.now,
|
||||
backgroundActivitySettings,
|
||||
]);
|
||||
return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });
|
||||
});
|
||||
|
||||
const publishSnapshot = snapshot.pipe(Effect.flatMap((next) => PubSub.publish(changes, next)));
|
||||
|
||||
const reportClientActivity: BackgroundPolicyShape["reportClientActivity"] = (
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const ttlMs = Math.min(
|
||||
Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),
|
||||
MAX_LEASE_TTL_MS,
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: ttlMs });
|
||||
const lease: ClientActivityLease = {
|
||||
sessionId,
|
||||
rpcClientId,
|
||||
clientId: input.clientId,
|
||||
clientKind: input.clientKind,
|
||||
visible: input.visible,
|
||||
focused: input.focused,
|
||||
recentlyInteracted: input.recentlyInteracted,
|
||||
...(input.appState !== undefined ? { appState: input.appState } : {}),
|
||||
...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),
|
||||
...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),
|
||||
...(input.networkType !== undefined ? { networkType: input.networkType } : {}),
|
||||
scopes: input.scopes,
|
||||
updatedAt: now,
|
||||
expiresAt,
|
||||
};
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
next.set(`${rpcClientId}:${input.clientId}`, lease);
|
||||
return next;
|
||||
});
|
||||
yield* publishSnapshot;
|
||||
});
|
||||
|
||||
const removeRpcClient: BackgroundPolicyShape["removeRpcClient"] = (rpcClientId) =>
|
||||
Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const key of next.keys()) {
|
||||
if (key.startsWith(`${rpcClientId}:`)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}).pipe(Effect.andThen(publishSnapshot), Effect.asVoid);
|
||||
|
||||
const hasDemand: BackgroundPolicyShape["hasDemand"] = (scope) =>
|
||||
Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));
|
||||
|
||||
const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>
|
||||
Effect.gen(function* () {
|
||||
const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);
|
||||
if (isHostConstrained(current.hostPower, settings)) {
|
||||
return false;
|
||||
}
|
||||
return current.leases.some((lease) =>
|
||||
leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),
|
||||
);
|
||||
});
|
||||
|
||||
const shouldRunOpportunisticWork = Effect.map(
|
||||
snapshot,
|
||||
(current) => current.shouldRunOpportunisticWork,
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep("15 seconds").pipe(
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
yield* Ref.update(leasesRef, (leases) => {
|
||||
const next = new Map(leases);
|
||||
for (const [key, lease] of next) {
|
||||
if (!isLeaseActive(lease, now)) {
|
||||
next.delete(key);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
),
|
||||
Effect.andThen(publishSnapshot),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return BackgroundPolicy.of({
|
||||
reportClientActivity,
|
||||
removeRpcClient,
|
||||
reportHostPowerState: hostPowerMonitor.report,
|
||||
snapshot,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
hasDemand,
|
||||
shouldRunScopeWork,
|
||||
shouldRunOpportunisticWork,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(BackgroundPolicy, make());
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as HostPowerMonitor from "./HostPowerMonitor.ts";
|
||||
|
||||
describe("HostPowerMonitor", () => {
|
||||
it.effect("publishes semantic power changes without idle-time heartbeat churn", () =>
|
||||
Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.make();
|
||||
const initial = {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"),
|
||||
} as const;
|
||||
yield* monitor.report(initial);
|
||||
|
||||
const nextChange = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
idleSeconds: 1,
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:01.000Z"),
|
||||
});
|
||||
yield* monitor.report({
|
||||
...initial,
|
||||
locked: "true",
|
||||
updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:02.000Z"),
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextChange)).locked).toBe("true");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("consumes desktop power directly without retaining diagnostics telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-06-17T12:00:00.000Z");
|
||||
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
|
||||
const diagnosticsDemandWrites = yield* Ref.make(0);
|
||||
const receiverLayer = DesktopTelemetryReceiver.layerTest({
|
||||
changes: Stream.fromPubSub(desktopChanges),
|
||||
setDiagnosticsDemand: () => Ref.update(diagnosticsDemandWrites, (count) => count + 1),
|
||||
});
|
||||
const layer = HostPowerMonitor.layer.pipe(Layer.provide(receiverLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
|
||||
const nextPower = yield* Stream.runHead(monitor.streamChanges).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* PubSub.publish(desktopChanges, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(sampledAt),
|
||||
electronPid: 100,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "true",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [],
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* Fiber.join(nextPower)).onBattery).toBe("true");
|
||||
expect(yield* Ref.get(diagnosticsDemandWrites)).toBe(0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { HostPowerSnapshot } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
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 Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
|
||||
export interface HostPowerMonitorShape {
|
||||
readonly snapshot: Effect.Effect<HostPowerSnapshot>;
|
||||
readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;
|
||||
readonly streamChanges: Stream.Stream<HostPowerSnapshot>;
|
||||
}
|
||||
|
||||
export class HostPowerMonitor extends Context.Service<HostPowerMonitor, HostPowerMonitorShape>()(
|
||||
"t3/background/HostPowerMonitor",
|
||||
) {}
|
||||
|
||||
export const makeUnknownSnapshot = (
|
||||
source: HostPowerSnapshot["source"],
|
||||
updatedAt: HostPowerSnapshot["updatedAt"],
|
||||
): HostPowerSnapshot => ({
|
||||
source,
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
function samePowerState(left: HostPowerSnapshot, right: HostPowerSnapshot): boolean {
|
||||
return (
|
||||
left.source === right.source &&
|
||||
left.idle === right.idle &&
|
||||
left.locked === right.locked &&
|
||||
left.suspended === right.suspended &&
|
||||
left.onBattery === right.onBattery &&
|
||||
left.lowPowerMode === right.lowPowerMode &&
|
||||
left.thermalState === right.thermalState &&
|
||||
left.stale === right.stale
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("background.hostPower.make")(function* (
|
||||
initialSource: HostPowerSnapshot["source"] = "unknown",
|
||||
) {
|
||||
const initial = makeUnknownSnapshot(initialSource, yield* DateTime.now);
|
||||
const latestRef = yield* Ref.make(initial);
|
||||
const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);
|
||||
|
||||
const report: HostPowerMonitorShape["report"] = (snapshot) =>
|
||||
Ref.modify(latestRef, (current) => [!samePowerState(current, snapshot), snapshot]).pipe(
|
||||
Effect.flatMap((changed) => (changed ? PubSub.publish(changes, snapshot) : Effect.void)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return HostPowerMonitor.of({
|
||||
snapshot: Ref.get(latestRef),
|
||||
report,
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(
|
||||
HostPowerMonitor,
|
||||
Effect.gen(function* () {
|
||||
const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
|
||||
const initial = yield* desktopTelemetry.latest;
|
||||
const monitor = yield* make(
|
||||
Option.match(initial, {
|
||||
onNone: () => "unknown" as const,
|
||||
onSome: (snapshot) => snapshot.power.source,
|
||||
}),
|
||||
);
|
||||
if (Option.isSome(initial)) {
|
||||
yield* monitor.report(initial.value.power);
|
||||
}
|
||||
yield* desktopTelemetry.changes.pipe(
|
||||
Stream.map((snapshot) => snapshot.power),
|
||||
Stream.runForEach(monitor.report),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
return monitor;
|
||||
}),
|
||||
);
|
||||
@@ -38,7 +38,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceBatchWindowMs: 1_000,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
@@ -268,6 +268,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
t3Home: baseDir,
|
||||
noBrowser: true,
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
@@ -323,12 +325,17 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: "desktop-token",
|
||||
desktopTelemetryFd: 4,
|
||||
desktopTelemetryControlFd: 5,
|
||||
resourceMonitorPath: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
|
||||
assert.equal(resolved.desktopTelemetryFd, 4);
|
||||
assert.equal(resolved.desktopTelemetryControlFd, 5);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ const EnvServerConfig = Config.all({
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
@@ -290,6 +290,9 @@ export const resolveServerConfig = (
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
|
||||
const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
|
||||
const resourceMonitorPath = bootstrap?.resourceMonitorPath;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
@@ -362,6 +365,9 @@ export const resolveServerConfig = (
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
desktopTelemetryFd,
|
||||
desktopTelemetryControlFd,
|
||||
resourceMonitorPath,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
|
||||
@@ -71,6 +71,9 @@ export class ServerConfig extends Context.Service<
|
||||
readonly noBrowser: boolean;
|
||||
readonly startupPresentation: StartupPresentation;
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly desktopTelemetryFd?: number | undefined;
|
||||
readonly desktopTelemetryControlFd?: number | undefined;
|
||||
readonly resourceMonitorPath?: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
@@ -177,6 +180,9 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
desktopTelemetryFd: undefined,
|
||||
desktopTelemetryControlFd: undefined,
|
||||
resourceMonitorPath: undefined,
|
||||
staticDir: undefined,
|
||||
devUrl,
|
||||
noBrowser: false,
|
||||
|
||||
@@ -1,282 +1,131 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopHostTelemetrySnapshot,
|
||||
ResourceMonitorSnapshotEvent,
|
||||
} 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 Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
|
||||
import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
function makeNativeSnapshot(
|
||||
processes: ResourceMonitorSnapshotEvent["processes"],
|
||||
): ResourceMonitorSnapshotEvent {
|
||||
return {
|
||||
version: 2,
|
||||
type: "snapshot",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-05-05T10:00:00.000Z")),
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: processes.length,
|
||||
retainedProcessCount: processes.length,
|
||||
inaccessibleProcessCount: 0,
|
||||
processes,
|
||||
};
|
||||
}
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
function makeTelemetryLayer(
|
||||
snapshot: ResourceMonitorSnapshotEvent,
|
||||
desktopSnapshot?: DesktopHostTelemetrySnapshot,
|
||||
) {
|
||||
const nativeLayer = NativeTelemetryClient.layerTest({
|
||||
sampleNow: Effect.succeed(snapshot),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
hello: Option.none(),
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(snapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
restartCount: 0,
|
||||
sampleIntervalMs: 1_000,
|
||||
}),
|
||||
});
|
||||
const desktopLayer = desktopSnapshot
|
||||
? DesktopTelemetryReceiver.layerTest({
|
||||
latest: Effect.succeedSome(desktopSnapshot),
|
||||
health: Effect.succeed({
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(DateTime.makeUnsafe(desktopSnapshot.sampledAtUnixMs)),
|
||||
lastError: Option.none(),
|
||||
}),
|
||||
})
|
||||
: DesktopTelemetryReceiver.layerTest();
|
||||
return ResourceTelemetry.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(nativeLayer, desktopLayer, ResourceAttribution.layer)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("ProcessDiagnostics", () => {
|
||||
it.effect("parses POSIX ps rows with full commands", () =>
|
||||
Effect.sync(() => {
|
||||
const rows = ProcessDiagnostics.parsePosixProcessRows(
|
||||
[
|
||||
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
|
||||
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
it.effect("projects live process data from resource telemetry", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
pid: 10,
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
pgid: 10,
|
||||
status: "Ss",
|
||||
startTimeMs: 1_000,
|
||||
runTimeMs: 60_000,
|
||||
name: "node",
|
||||
command: "t3 server",
|
||||
status: "Running",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1024 * 1024,
|
||||
elapsed: "01:02.03",
|
||||
command: "/usr/bin/node server.js",
|
||||
cpuTimeMs: 100,
|
||||
residentBytes: 1_024,
|
||||
virtualBytes: 2_048,
|
||||
ioReadBytes: 100,
|
||||
ioWriteBytes: 200,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
{
|
||||
pid: 11,
|
||||
ppid: 10,
|
||||
pgid: 10,
|
||||
status: "S+",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 20480 * 1024,
|
||||
elapsed: "00:04",
|
||||
command: "codex app-server --config /tmp/one two",
|
||||
pid: 4_242,
|
||||
ppid: process.pid,
|
||||
startTimeMs: 2_000,
|
||||
runTimeMs: 4_000,
|
||||
name: "agent",
|
||||
command: "codex app-server",
|
||||
status: "Running",
|
||||
cpuPercent: 1.5,
|
||||
cpuTimeMs: 60,
|
||||
residentBytes: 2_048,
|
||||
virtualBytes: 4_096,
|
||||
ioReadBytes: 300,
|
||||
ioWriteBytes: 400,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provideMerge(telemetryLayer));
|
||||
|
||||
it.effect("aggregates only descendants of the server process", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1.5,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 3.25,
|
||||
rssBytes: 4_000,
|
||||
elapsed: "00:05",
|
||||
command: "git status",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "S",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 8_000,
|
||||
elapsed: "00:01",
|
||||
command: "unrelated",
|
||||
},
|
||||
{
|
||||
pid: 201,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 9,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:00",
|
||||
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.serverPid).toBe(100);
|
||||
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
|
||||
expect(diagnostics.processCount).toBe(2);
|
||||
expect(diagnostics.totalRssBytes).toBe(6_000);
|
||||
expect(diagnostics.totalCpuPercent).toBe(4.75);
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
|
||||
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
|
||||
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
|
||||
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves ascending sibling order for nested descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "agent",
|
||||
},
|
||||
{
|
||||
pid: 103,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-b",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-a",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries processes through the ChildProcessSpawner service", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
const diagnostics = yield* Effect.gen(function* () {
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
return yield* processDiagnostics.read;
|
||||
}).pipe(Effect.provide(layer));
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
},
|
||||
]);
|
||||
expect(diagnostics.processes[0]?.startTimeMs).toBe(2_000);
|
||||
expect(diagnostics.processes[0]?.cpuPercent).toBe(1.5);
|
||||
expect(diagnostics.processes[0]?.rssBytes).toBe(2_048);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps bounded command diagnostics when the process query exits unsuccessfully", () =>
|
||||
it.effect("rejects stale process identities before signaling", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
code: 17,
|
||||
stdout: "partial process output",
|
||||
stderr: "process access denied",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provide(spawnerLayer),
|
||||
Effect.provideService(HostProcessPlatform, "linux"),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ProcessDiagnosticsQueryFailedError",
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: process.cwd(),
|
||||
exitCode: 17,
|
||||
stdoutBytes: 22,
|
||||
stderrBytes: 21,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
expect(error.message).toBe(
|
||||
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
const snapshot = makeNativeSnapshot([]);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
|
||||
Effect.flatMap((processDiagnostics) =>
|
||||
processDiagnostics.signal({
|
||||
pid: 4_242,
|
||||
startTimeMs: 2_000,
|
||||
signal: "SIGINT",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
@@ -284,7 +133,85 @@ describe("ProcessDiagnostics", () => {
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
|
||||
message: Option.some("Process 4242 no longer matches the selected process identity."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects Electron processes as signal targets", () =>
|
||||
Effect.gen(function* () {
|
||||
const sampledAtUnixMs = DateTime.toEpochMillis(
|
||||
DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
);
|
||||
const snapshot = makeNativeSnapshot([
|
||||
{
|
||||
pid: 4_242,
|
||||
ppid: 1,
|
||||
startTimeMs: 2_000,
|
||||
runTimeMs: 4_000,
|
||||
name: "electron",
|
||||
command: "electron",
|
||||
status: "Running",
|
||||
cpuPercent: 1.5,
|
||||
cpuTimeMs: 60,
|
||||
residentBytes: 2_048,
|
||||
virtualBytes: 4_096,
|
||||
ioReadBytes: 300,
|
||||
ioWriteBytes: 400,
|
||||
ioSemantics: "storage",
|
||||
},
|
||||
]);
|
||||
const sampledAt = DateTime.makeUnsafe(sampledAtUnixMs);
|
||||
const telemetryLayer = makeTelemetryLayer(snapshot, {
|
||||
version: 1,
|
||||
type: "desktopTelemetry",
|
||||
sequence: 1,
|
||||
sampledAtUnixMs,
|
||||
electronPid: 4_242,
|
||||
power: {
|
||||
source: "electron-main",
|
||||
idle: "false",
|
||||
idleSeconds: 0,
|
||||
locked: "false",
|
||||
suspended: false,
|
||||
onBattery: "false",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "nominal",
|
||||
stale: false,
|
||||
updatedAt: sampledAt,
|
||||
},
|
||||
speedLimitPercent: Option.none(),
|
||||
electronProcesses: [
|
||||
{
|
||||
pid: 4_242,
|
||||
creationTimeMs: 2_000,
|
||||
type: "Browser",
|
||||
name: "electron",
|
||||
cpuPercent: 1.5,
|
||||
idleWakeupsPerSecond: 0,
|
||||
workingSetBytes: 2_048,
|
||||
peakWorkingSetBytes: 2_048,
|
||||
},
|
||||
],
|
||||
});
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(telemetryLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((processDiagnostics) =>
|
||||
processDiagnostics.signal({
|
||||
pid: 4_242,
|
||||
startTimeMs: 2_000,
|
||||
signal: "SIGKILL",
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4_242,
|
||||
signal: "SIGKILL",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a signalable T3 backend descendant."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,105 +1,46 @@
|
||||
import type {
|
||||
ResourceTelemetryProcessCategory,
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
export interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
readonly status: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly elapsed: string;
|
||||
readonly command: string;
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly startTimeMs: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
{
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsQueryTimeoutError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryTimeoutError>()(
|
||||
"ProcessDiagnosticsQueryTimeoutError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
timeoutMillis: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process diagnostics query '${this.command}' timed out after ${this.timeoutMillis}ms in '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsQueryFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsQueryFailedError>()(
|
||||
"ProcessDiagnosticsQueryFailedError",
|
||||
{
|
||||
command: Schema.String,
|
||||
argCount: Schema.Number,
|
||||
cwd: Schema.String,
|
||||
exitCode: Schema.optional(Schema.Number),
|
||||
stdoutBytes: Schema.optional(Schema.Number),
|
||||
stderrBytes: Schema.optional(Schema.Number),
|
||||
stdoutTruncated: Schema.optional(Schema.Boolean),
|
||||
stderrTruncated: Schema.optional(Schema.Boolean),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : ` with exit code ${this.exitCode}`;
|
||||
return `Process diagnostics query '${this.command}' failed${exitCode} in '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsServerProcessSignalError extends Schema.TaggedErrorClass<ProcessDiagnosticsServerProcessSignalError>()(
|
||||
"ProcessDiagnosticsServerProcessSignalError",
|
||||
{ pid: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to signal the T3 server process.";
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsNotDescendantError extends Schema.TaggedErrorClass<ProcessDiagnosticsNotDescendantError>()(
|
||||
"ProcessDiagnosticsNotDescendantError",
|
||||
export class ProcessIdentityChanged extends Schema.TaggedErrorClass<ProcessIdentityChanged>()(
|
||||
"ProcessIdentityChanged",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
serverPid: Schema.Number,
|
||||
startTimeMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Process ${this.pid} is not a live descendant of the T3 server.`;
|
||||
return `Process ${this.pid} no longer matches start time ${this.startTimeMs}.`;
|
||||
}
|
||||
}
|
||||
|
||||
class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<ProcessDiagnosticsSignalFailedError>()(
|
||||
"ProcessDiagnosticsSignalFailedError",
|
||||
export class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(
|
||||
"ProcessSignalFailed",
|
||||
{
|
||||
pid: Schema.Number,
|
||||
signal: Schema.String,
|
||||
@@ -111,465 +52,141 @@ class ProcessDiagnosticsSignalFailedError extends Schema.TaggedErrorClass<Proces
|
||||
}
|
||||
}
|
||||
|
||||
const ProcessDiagnosticsError = Schema.Union([
|
||||
ProcessDiagnosticsQueryTimeoutError,
|
||||
ProcessDiagnosticsQueryFailedError,
|
||||
ProcessDiagnosticsServerProcessSignalError,
|
||||
ProcessDiagnosticsNotDescendantError,
|
||||
ProcessDiagnosticsSignalFailedError,
|
||||
]);
|
||||
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
|
||||
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
|
||||
export type ProcessDiagnosticsError = ProcessIdentityChanged | ProcessSignalFailed;
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
function formatElapsed(runTimeMs: number): string {
|
||||
const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));
|
||||
const hours = Math.floor(totalSeconds / 3_600);
|
||||
const minutes = Math.floor((totalSeconds % 3_600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return hours > 0
|
||||
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
|
||||
: `${minutes}:${String(seconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function parseNonNegativeInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number | null {
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const match = rowPattern.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const pidText = match[1];
|
||||
const ppidText = match[2];
|
||||
const pgidText = match[3];
|
||||
const status = match[4];
|
||||
const cpuText = match[5];
|
||||
const rssText = match[6];
|
||||
const elapsed = match[7];
|
||||
const command = match[8];
|
||||
if (
|
||||
pidText === undefined ||
|
||||
ppidText === undefined ||
|
||||
pgidText === undefined ||
|
||||
status === undefined ||
|
||||
cpuText === undefined ||
|
||||
rssText === undefined ||
|
||||
elapsed === undefined ||
|
||||
command === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = parsePositiveInt(pidText);
|
||||
const ppid = parseNonNegativeInt(ppidText);
|
||||
const pgid = Number.parseInt(pgidText, 10);
|
||||
const cpuPercent = parseNumber(cpuText);
|
||||
const rssKiB = parseNonNegativeInt(rssText);
|
||||
if (
|
||||
pid === null ||
|
||||
ppid === null ||
|
||||
!Number.isInteger(pgid) ||
|
||||
cpuPercent === null ||
|
||||
rssKiB === null ||
|
||||
!status ||
|
||||
!elapsed ||
|
||||
!command
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.push({
|
||||
pid,
|
||||
ppid,
|
||||
pgid,
|
||||
status,
|
||||
cpuPercent,
|
||||
rssBytes: rssKiB * 1024,
|
||||
elapsed,
|
||||
command,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
|
||||
? record.CommandLine
|
||||
: typeof record.Name === "string"
|
||||
? record.Name
|
||||
: null;
|
||||
const workingSet =
|
||||
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
|
||||
? Math.max(0, Math.round(record.WorkingSetSize))
|
||||
: 0;
|
||||
const cpuPercent =
|
||||
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
|
||||
? Math.max(0, record.PercentProcessorTime)
|
||||
: 0;
|
||||
|
||||
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
|
||||
return {
|
||||
pid,
|
||||
ppid,
|
||||
pgid: null,
|
||||
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
|
||||
cpuPercent,
|
||||
rssBytes: workingSet,
|
||||
elapsed: "",
|
||||
command: commandLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(output) as unknown;
|
||||
const records = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const children = childrenByParent.get(row.ppid) ?? [];
|
||||
children.push(row);
|
||||
childrenByParent.set(row.ppid, children);
|
||||
}
|
||||
|
||||
const entries: ServerProcessDiagnosticsEntry[] = [];
|
||||
const visited = new Set<number>();
|
||||
const stack = [...(childrenByParent.get(serverPid) ?? [])]
|
||||
.toSorted((left, right) => left.pid - right.pid)
|
||||
.map((row) => ({ row, depth: 0 }));
|
||||
|
||||
while (stack.length > 0) {
|
||||
const item = stack.shift();
|
||||
if (!item || visited.has(item.row.pid)) continue;
|
||||
visited.add(item.row.pid);
|
||||
|
||||
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
|
||||
(left, right) => left.pid - right.pid,
|
||||
);
|
||||
entries.push({
|
||||
pid: item.row.pid,
|
||||
ppid: item.row.ppid,
|
||||
pgid: Option.fromNullishOr(item.row.pgid),
|
||||
status: item.row.status,
|
||||
cpuPercent: item.row.cpuPercent,
|
||||
rssBytes: item.row.rssBytes,
|
||||
elapsed: item.row.elapsed || "n/a",
|
||||
command: item.row.command,
|
||||
depth: item.depth,
|
||||
childPids: children.map((child) => child.pid),
|
||||
});
|
||||
|
||||
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
function canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {
|
||||
return (
|
||||
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
|
||||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
|
||||
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
|
||||
category === "server-child" || category === "provider-root" || category === "terminal-root"
|
||||
);
|
||||
}
|
||||
|
||||
function makeResult(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: string;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const processes = buildDescendantEntries(rows, input.serverPid);
|
||||
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
|
||||
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
|
||||
|
||||
return {
|
||||
serverPid: input.serverPid,
|
||||
readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes,
|
||||
totalCpuPercent,
|
||||
processes,
|
||||
error: input.error ? Option.some({ message: input.error }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly cwd: string;
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stdoutBytes: number;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderr: string;
|
||||
readonly stderrBytes: number;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const cwd = process.cwd();
|
||||
return yield* Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
// `ps` and `powershell.exe` are real executables; spawning through cmd.exe
|
||||
// shell mode would re-tokenize the PowerShell `-Command` payload (which
|
||||
// contains pipes) before PowerShell ever sees it.
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd,
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
cwd,
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stdoutBytes: stdout.bytes,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderr: stderr.text,
|
||||
stderrBytes: stderr.bytes,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProcessOutput;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProcessDiagnosticsQueryTimeoutError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
timeoutMillis: PROCESS_QUERY_TIMEOUT_MS,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isProcessDiagnosticsError(cause)
|
||||
? cause
|
||||
: new ProcessDiagnosticsQueryFailedError({
|
||||
command: input.command,
|
||||
argCount: input.args.length,
|
||||
cwd,
|
||||
cause,
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const read: ProcessDiagnosticsShape["read"] = telemetry.refresh.pipe(
|
||||
Effect.catch(() => telemetry.latest),
|
||||
Effect.map((snapshot) => {
|
||||
const processes = snapshot.processes
|
||||
.filter((entry) => entry.identity.pid !== process.pid)
|
||||
.map(
|
||||
(entry): ServerProcessDiagnosticsEntry => ({
|
||||
pid: entry.identity.pid,
|
||||
startTimeMs: entry.identity.startTimeMs,
|
||||
ppid: entry.ppid,
|
||||
pgid: Option.none(),
|
||||
status: entry.status || "Unknown",
|
||||
cpuPercent: entry.cpuPercent,
|
||||
rssBytes: entry.residentBytes,
|
||||
elapsed: formatElapsed(entry.runTimeMs),
|
||||
command: entry.command || entry.name || "unknown",
|
||||
depth: Math.max(0, entry.depth - 1),
|
||||
childPids: entry.childPids,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "ps",
|
||||
argCount: 2,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function readWindowsProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = [
|
||||
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
|
||||
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
|
||||
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
|
||||
"};",
|
||||
"$processes | ConvertTo-Json -Compress -Depth 3",
|
||||
].join(" ");
|
||||
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
new ProcessDiagnosticsQueryFailedError({
|
||||
command: "powershell.exe",
|
||||
argCount: 4,
|
||||
cwd: result.cwd,
|
||||
exitCode: result.exitCode,
|
||||
stdoutBytes: result.stdoutBytes,
|
||||
stderrBytes: result.stderrBytes,
|
||||
stdoutTruncated: result.stdoutTruncated,
|
||||
stderrTruncated: result.stderrTruncated,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const readProcessRows = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
});
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
return makeResult(input);
|
||||
}
|
||||
|
||||
function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(
|
||||
new ProcessDiagnosticsServerProcessSignalError({
|
||||
pid,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return readProcessRows.pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
(entry) => entry.pid === pid,
|
||||
);
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new ProcessDiagnosticsNotDescendantError({
|
||||
pid,
|
||||
serverPid: process.pid,
|
||||
}),
|
||||
);
|
||||
);
|
||||
return {
|
||||
serverPid: process.pid,
|
||||
readAt: snapshot.readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),
|
||||
totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),
|
||||
processes,
|
||||
error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnostics["Service"]["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
}).pipe(
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((readAt) =>
|
||||
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnostics["Service"]["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProcessDiagnosticsSignalFailedError({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
if (input.pid === process.pid) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some("Refusing to signal the T3 server process."),
|
||||
};
|
||||
}
|
||||
const current = yield* telemetry.latest;
|
||||
const selected = current.processes.find(
|
||||
(entry) =>
|
||||
entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,
|
||||
);
|
||||
if (!selected) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
`Process ${input.pid} no longer matches the selected process identity.`,
|
||||
),
|
||||
};
|
||||
}
|
||||
if (!canSignalCategory(selected.category)) {
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(`Process ${input.pid} is not a signalable T3 backend descendant.`),
|
||||
};
|
||||
}
|
||||
return yield* telemetry
|
||||
.validateProcessIdentity({
|
||||
pid: input.pid,
|
||||
startTimeMs: input.startTimeMs,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((valid) =>
|
||||
valid
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new ProcessIdentityChanged({
|
||||
pid: input.pid,
|
||||
startTimeMs: input.startTimeMs,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProcessSignalFailed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(
|
||||
error instanceof Error ? error.message : "Failed to signal process.",
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make);
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -1,255 +1,137 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import type { ResourceTelemetryHistory } 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 Stream from "effect/Stream";
|
||||
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
import * as ProcessResourceMonitor from "./ProcessResourceMonitor.ts";
|
||||
|
||||
describe("ProcessResourceMonitor", () => {
|
||||
it.effect("samples the server root process and descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 50,
|
||||
rssBytes: 3_000,
|
||||
elapsed: "00:05",
|
||||
command: "rg needle",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "R",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:05",
|
||||
command: "unrelated",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
|
||||
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
|
||||
expect(samples[0]?.isServerRoot).toBe(true);
|
||||
expect(samples[1]?.isServerRoot).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rolls samples up by process and CPU time", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
|
||||
const samples = [
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 10,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 30,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:05",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(Option.isNone(result.error)).toBe(true);
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
|
||||
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
|
||||
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
|
||||
expect(result.totalCpuSecondsApprox).toBe(2);
|
||||
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
|
||||
Effect.sync(() => {
|
||||
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
|
||||
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
|
||||
const samples = [
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: firstAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(firstAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
...ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt: secondAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(secondAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 2,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "01:06",
|
||||
command: "t3 server",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: secondAt,
|
||||
readAtMs: DateTime.toEpochMillis(secondAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(1);
|
||||
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
|
||||
expect(result.topProcesses[0]?.sampleCount).toBe(2);
|
||||
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns all process summaries in the selected window", () =>
|
||||
Effect.sync(() => {
|
||||
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const samples = ProcessResourceMonitor.collectMonitoredSamples({
|
||||
serverPid: 100,
|
||||
sampledAt,
|
||||
sampledAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
...Array.from({ length: 35 }, (_, index) => ({
|
||||
pid: 200 + index,
|
||||
ppid: index === 0 ? 100 : 199 + index,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 35 - index,
|
||||
rssBytes: 2_000 + index,
|
||||
elapsed: "00:10",
|
||||
command: `worker ${index}`,
|
||||
})),
|
||||
],
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples,
|
||||
readAt: sampledAt,
|
||||
readAtMs: DateTime.toEpochMillis(sampledAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: null,
|
||||
});
|
||||
|
||||
expect(result.topProcesses).toHaveLength(36);
|
||||
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("exposes bounded failure diagnostics while retaining the exact cause", () =>
|
||||
Effect.sync(() => {
|
||||
it.effect("projects resource telemetry history into the legacy diagnostics contract", () =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
|
||||
const cause = new Error("stderr included credential=secret-value");
|
||||
const failure = new ProcessResourceMonitor.ProcessResourceSamplingError({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
cause,
|
||||
});
|
||||
|
||||
const result = ProcessResourceMonitor.aggregateProcessResourceHistory({
|
||||
samples: [],
|
||||
const history: ResourceTelemetryHistory = {
|
||||
readAt,
|
||||
readAtMs: DateTime.toEpochMillis(readAt),
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
lastFailure: failure,
|
||||
});
|
||||
sampleIntervalMs: 1_000,
|
||||
retainedSampleCount: 2,
|
||||
buckets: [
|
||||
{
|
||||
startedAt: DateTime.makeUnsafe("2026-05-05T09:59:50.000Z"),
|
||||
endedAt: readAt,
|
||||
avgCpuPercent: 15,
|
||||
maxCpuPercent: 25,
|
||||
maxRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
maxProcessCount: 2,
|
||||
},
|
||||
],
|
||||
topProcesses: [
|
||||
{
|
||||
identity: { pid: process.pid, startTimeMs: 100 },
|
||||
ppid: 1,
|
||||
depth: 0,
|
||||
name: "node",
|
||||
command: "t3 server",
|
||||
category: "server",
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 5,
|
||||
avgCpuPercent: 4,
|
||||
maxCpuPercent: 8,
|
||||
cpuTimeMs: 1_500,
|
||||
currentRssBytes: 2_048,
|
||||
peakRssBytes: 4_096,
|
||||
ioReadBytes: 1_024,
|
||||
ioWriteBytes: 2_048,
|
||||
ioSemantics: "storage",
|
||||
sampleCount: 2,
|
||||
},
|
||||
],
|
||||
health: {
|
||||
native: {
|
||||
status: "degraded",
|
||||
lastSampleAt: Option.some(readAt),
|
||||
lastError: Option.some("collector stalled"),
|
||||
},
|
||||
desktop: {
|
||||
status: "healthy",
|
||||
lastSampleAt: Option.some(readAt),
|
||||
lastError: Option.none(),
|
||||
},
|
||||
sidecarVersion: Option.some("0.1.0"),
|
||||
sidecarPid: Option.some(9_000),
|
||||
restartCount: 1,
|
||||
collectionDurationMicros: 250,
|
||||
scannedProcessCount: 80,
|
||||
retainedProcessCount: 2,
|
||||
inaccessibleProcessCount: 0,
|
||||
},
|
||||
};
|
||||
const telemetry: ResourceTelemetry.ResourceTelemetryShape = {
|
||||
latest: Effect.die("unused"),
|
||||
changes: Stream.empty,
|
||||
readHistory: () => Effect.succeed(history),
|
||||
refresh: Effect.die("unused"),
|
||||
validateProcessIdentity: () => Effect.die("unused"),
|
||||
retry: Effect.die("unused"),
|
||||
};
|
||||
const layer = ProcessResourceMonitor.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
ResourceTelemetry.ResourceTelemetry,
|
||||
ResourceTelemetry.ResourceTelemetry.of(telemetry),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(failure.cause).toBe(cause);
|
||||
expect(Option.getOrThrow(result.error)).toEqual({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "Failed to sample process resources (ProcessDiagnosticsQueryFailedError).",
|
||||
const result = yield* Effect.service(ProcessResourceMonitor.ProcessResourceMonitor).pipe(
|
||||
Effect.flatMap((monitor) =>
|
||||
monitor.readHistory({
|
||||
windowMs: 60_000,
|
||||
bucketMs: 10_000,
|
||||
}),
|
||||
),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result.totalCpuSecondsApprox).toBe(1.5);
|
||||
expect(result.topProcesses).toEqual([
|
||||
{
|
||||
processKey: `${process.pid}:100`,
|
||||
pid: process.pid,
|
||||
ppid: 1,
|
||||
command: "t3 server",
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
firstSeenAt: DateTime.makeUnsafe("2026-05-05T09:59:55.000Z"),
|
||||
lastSeenAt: readAt,
|
||||
currentCpuPercent: 5,
|
||||
avgCpuPercent: 4,
|
||||
maxCpuPercent: 8,
|
||||
cpuSecondsApprox: 1.5,
|
||||
currentRssBytes: 2_048,
|
||||
maxRssBytes: 4_096,
|
||||
sampleCount: 2,
|
||||
},
|
||||
]);
|
||||
expect(result.buckets[0]).toMatchObject({
|
||||
avgCpuPercent: 15,
|
||||
maxCpuPercent: 25,
|
||||
maxRssBytes: 4_096,
|
||||
maxProcessCount: 2,
|
||||
});
|
||||
expect(Option.getOrThrow(result.error).message).not.toContain("secret-value");
|
||||
expect(result.error).toEqual(
|
||||
Option.some({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError",
|
||||
message: "collector stalled",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,329 +1,77 @@
|
||||
import {
|
||||
ServerProcessResourceHistoryFailureTag,
|
||||
type ServerProcessResourceHistoryBucket,
|
||||
type ServerProcessResourceHistoryFailureTag as ServerProcessResourceHistoryFailureTagType,
|
||||
type ServerProcessResourceHistoryInput,
|
||||
type ServerProcessResourceHistoryResult,
|
||||
type ServerProcessResourceHistorySummary,
|
||||
import type {
|
||||
ServerProcessResourceHistoryInput,
|
||||
ServerProcessResourceHistoryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
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 Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
import * as ResourceTelemetry from "../resourceTelemetry/ResourceTelemetry.ts";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 5_000;
|
||||
const RETENTION_MS = 60 * 60_000;
|
||||
const MAX_RETAINED_SAMPLES = 20_000;
|
||||
|
||||
export interface ProcessResourceSample {
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
readonly processKey: string;
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly command: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly depth: number;
|
||||
readonly isServerRoot: boolean;
|
||||
}
|
||||
|
||||
export class ProcessResourceSamplingError extends Schema.TaggedErrorClass<ProcessResourceSamplingError>()(
|
||||
"ProcessResourceSamplingError",
|
||||
{
|
||||
failureTag: ServerProcessResourceHistoryFailureTag,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to sample process resources (${this.failureTag}).`;
|
||||
}
|
||||
}
|
||||
|
||||
interface MonitorState {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
export interface ProcessResourceMonitorShape {
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
|
||||
export class ProcessResourceMonitor extends Context.Service<
|
||||
ProcessResourceMonitor,
|
||||
{
|
||||
readonly readHistory: (
|
||||
input: ServerProcessResourceHistoryInput,
|
||||
) => Effect.Effect<ServerProcessResourceHistoryResult>;
|
||||
}
|
||||
ProcessResourceMonitorShape
|
||||
>()("t3/diagnostics/ProcessResourceMonitor") {}
|
||||
|
||||
function dateTimeFromMillis(ms: number): DateTime.Utc {
|
||||
return DateTime.makeUnsafe(ms);
|
||||
}
|
||||
|
||||
function sampleKey(row: Pick<ProcessDiagnostics.ProcessRow, "pid" | "command">): string {
|
||||
return `${row.pid}:${row.command}`;
|
||||
}
|
||||
|
||||
function findServerRootRow(
|
||||
rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>,
|
||||
serverPid: number,
|
||||
): ProcessDiagnostics.ProcessRow | null {
|
||||
return rows.find((row) => row.pid === serverPid) ?? null;
|
||||
}
|
||||
|
||||
export function collectMonitoredSamples(input: {
|
||||
readonly rows: ReadonlyArray<ProcessDiagnostics.ProcessRow>;
|
||||
readonly serverPid: number;
|
||||
readonly sampledAt: DateTime.Utc;
|
||||
readonly sampledAtMs: number;
|
||||
}): ReadonlyArray<ProcessResourceSample> {
|
||||
const rows = input.rows.filter(
|
||||
(row) => !ProcessDiagnostics.isDiagnosticsQueryProcess(row, input.serverPid),
|
||||
);
|
||||
const root = findServerRootRow(rows, input.serverPid);
|
||||
const descendants = ProcessDiagnostics.buildDescendantEntries(rows, input.serverPid);
|
||||
const samples: ProcessResourceSample[] = [];
|
||||
|
||||
if (root) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(root),
|
||||
pid: root.pid,
|
||||
ppid: root.ppid,
|
||||
command: root.command,
|
||||
cpuPercent: root.cpuPercent,
|
||||
rssBytes: root.rssBytes,
|
||||
depth: 0,
|
||||
isServerRoot: true,
|
||||
});
|
||||
}
|
||||
|
||||
for (const process of descendants) {
|
||||
samples.push({
|
||||
sampledAt: input.sampledAt,
|
||||
sampledAtMs: input.sampledAtMs,
|
||||
processKey: sampleKey(process),
|
||||
pid: process.pid,
|
||||
ppid: process.ppid,
|
||||
command: process.command,
|
||||
cpuPercent: process.cpuPercent,
|
||||
rssBytes: process.rssBytes,
|
||||
depth: process.depth + 1,
|
||||
isServerRoot: false,
|
||||
});
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
function trimSamples(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
nowMs: number,
|
||||
): ReadonlyArray<ProcessResourceSample> {
|
||||
const minSampledAtMs = nowMs - RETENTION_MS;
|
||||
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
return retained.length <= MAX_RETAINED_SAMPLES
|
||||
? retained
|
||||
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
|
||||
}
|
||||
|
||||
function summarizeProcesses(
|
||||
samples: ReadonlyArray<ProcessResourceSample>,
|
||||
): ReadonlyArray<ServerProcessResourceHistorySummary> {
|
||||
const groups = new Map<string, ProcessResourceSample[]>();
|
||||
for (const sample of samples) {
|
||||
const processSamples = groups.get(sample.processKey) ?? [];
|
||||
processSamples.push(sample);
|
||||
groups.set(sample.processKey, processSamples);
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.map(([processKey, processSamples]) => {
|
||||
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
|
||||
const first = sorted[0]!;
|
||||
const latest = sorted[sorted.length - 1]!;
|
||||
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
|
||||
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
|
||||
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
|
||||
const cpuSecondsApprox = sorted.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
processKey,
|
||||
pid: latest.pid,
|
||||
ppid: latest.ppid,
|
||||
command: latest.command,
|
||||
depth: latest.depth,
|
||||
isServerRoot: latest.isServerRoot,
|
||||
firstSeenAt: first.sampledAt,
|
||||
lastSeenAt: latest.sampledAt,
|
||||
currentCpuPercent: latest.cpuPercent,
|
||||
avgCpuPercent: cpuPercentTotal / sorted.length,
|
||||
maxCpuPercent,
|
||||
cpuSecondsApprox,
|
||||
currentRssBytes: latest.rssBytes,
|
||||
maxRssBytes,
|
||||
sampleCount: sorted.length,
|
||||
} satisfies ServerProcessResourceHistorySummary;
|
||||
})
|
||||
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
|
||||
}
|
||||
|
||||
function buildBuckets(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly nowMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const windowStartMs = input.nowMs - input.windowMs;
|
||||
const buckets: ServerProcessResourceHistoryBucket[] = [];
|
||||
|
||||
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
|
||||
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
|
||||
const bucketSamples = input.samples.filter(
|
||||
(sample) =>
|
||||
sample.sampledAtMs >= startedAtMs &&
|
||||
(endedAtMs === input.nowMs
|
||||
? sample.sampledAtMs <= endedAtMs
|
||||
: sample.sampledAtMs < endedAtMs),
|
||||
);
|
||||
const samplesByRead = new Map<number, ProcessResourceSample[]>();
|
||||
for (const sample of bucketSamples) {
|
||||
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
|
||||
samplesAtTime.push(sample);
|
||||
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
|
||||
}
|
||||
|
||||
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
|
||||
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
|
||||
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
|
||||
processCount: samplesAtTime.length,
|
||||
}));
|
||||
const avgCpuPercent =
|
||||
readTotals.length === 0
|
||||
? 0
|
||||
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
|
||||
|
||||
buckets.push({
|
||||
startedAt: dateTimeFromMillis(startedAtMs),
|
||||
endedAt: dateTimeFromMillis(endedAtMs),
|
||||
avgCpuPercent,
|
||||
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
|
||||
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
|
||||
maxProcessCount: readTotals.length
|
||||
? Math.max(...readTotals.map((read) => read.processCount))
|
||||
: 0,
|
||||
});
|
||||
}
|
||||
|
||||
return buckets;
|
||||
}
|
||||
|
||||
export function aggregateProcessResourceHistory(input: {
|
||||
readonly samples: ReadonlyArray<ProcessResourceSample>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly readAtMs: number;
|
||||
readonly windowMs: number;
|
||||
readonly bucketMs: number;
|
||||
readonly lastFailure: ProcessResourceSamplingError | null;
|
||||
}): ServerProcessResourceHistoryResult {
|
||||
const windowMs = Math.max(1_000, input.windowMs);
|
||||
const bucketMs = Math.max(1_000, input.bucketMs);
|
||||
const minSampledAtMs = input.readAtMs - windowMs;
|
||||
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
|
||||
const topProcesses = summarizeProcesses(samples);
|
||||
const totalCpuSecondsApprox = samples.reduce(
|
||||
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
|
||||
0,
|
||||
);
|
||||
|
||||
return {
|
||||
readAt: input.readAt,
|
||||
windowMs,
|
||||
bucketMs,
|
||||
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
||||
retainedSampleCount: input.samples.length,
|
||||
totalCpuSecondsApprox,
|
||||
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
|
||||
topProcesses,
|
||||
error: input.lastFailure
|
||||
? Option.some({
|
||||
failureTag: input.lastFailure.failureTag,
|
||||
message: input.lastFailure.message,
|
||||
})
|
||||
: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const state = yield* Ref.make<MonitorState>({ samples: [], lastFailure: null });
|
||||
|
||||
const recordSamplingFailure = (cause: {
|
||||
readonly _tag: ServerProcessResourceHistoryFailureTagType;
|
||||
}) =>
|
||||
Ref.update(state, (current) => ({
|
||||
...current,
|
||||
lastFailure: new ProcessResourceSamplingError({
|
||||
failureTag: cause._tag,
|
||||
cause,
|
||||
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
|
||||
const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
|
||||
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
|
||||
telemetry.readHistory(input).pipe(
|
||||
Effect.map((history) => {
|
||||
const topProcesses = history.topProcesses.map((entry) => ({
|
||||
processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,
|
||||
pid: entry.identity.pid,
|
||||
ppid: entry.ppid,
|
||||
command: entry.command || entry.name || "unknown",
|
||||
depth: entry.depth,
|
||||
isServerRoot: entry.category === "server",
|
||||
firstSeenAt: entry.firstSeenAt,
|
||||
lastSeenAt: entry.lastSeenAt,
|
||||
currentCpuPercent: entry.currentCpuPercent,
|
||||
avgCpuPercent: entry.avgCpuPercent,
|
||||
maxCpuPercent: entry.maxCpuPercent,
|
||||
cpuSecondsApprox: entry.cpuTimeMs / 1_000,
|
||||
currentRssBytes: entry.currentRssBytes,
|
||||
maxRssBytes: entry.peakRssBytes,
|
||||
sampleCount: entry.sampleCount,
|
||||
}));
|
||||
return {
|
||||
readAt: history.readAt,
|
||||
windowMs: history.windowMs,
|
||||
bucketMs: history.bucketMs,
|
||||
sampleIntervalMs: history.sampleIntervalMs,
|
||||
retainedSampleCount: history.retainedSampleCount,
|
||||
totalCpuSecondsApprox: topProcesses.reduce(
|
||||
(total, entry) => total + entry.cpuSecondsApprox,
|
||||
0,
|
||||
),
|
||||
buckets: history.buckets.map((bucket) => ({
|
||||
startedAt: bucket.startedAt,
|
||||
endedAt: bucket.endedAt,
|
||||
avgCpuPercent: bucket.avgCpuPercent,
|
||||
maxCpuPercent: bucket.maxCpuPercent,
|
||||
maxRssBytes: bucket.maxRssBytes,
|
||||
maxProcessCount: bucket.maxProcessCount,
|
||||
})),
|
||||
topProcesses,
|
||||
error: history.health.native.lastError.pipe(
|
||||
Option.map((message) => ({
|
||||
failureTag: "ProcessDiagnosticsQueryFailedError" as const,
|
||||
message,
|
||||
})),
|
||||
),
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
const sampleOnce = Effect.gen(function* () {
|
||||
const sampledAt = yield* DateTime.now;
|
||||
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
|
||||
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const samples = collectMonitoredSamples({
|
||||
rows,
|
||||
serverPid: process.pid,
|
||||
sampledAt,
|
||||
sampledAtMs,
|
||||
});
|
||||
yield* Ref.update(state, (current) => ({
|
||||
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
|
||||
lastFailure: null,
|
||||
}));
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
ProcessDiagnosticsQueryTimeoutError: recordSamplingFailure,
|
||||
ProcessDiagnosticsQueryFailedError: recordSamplingFailure,
|
||||
ProcessDiagnosticsServerProcessSignalError: recordSamplingFailure,
|
||||
ProcessDiagnosticsNotDescendantError: recordSamplingFailure,
|
||||
ProcessDiagnosticsSignalFailedError: recordSamplingFailure,
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const readHistory: ProcessResourceMonitor["Service"]["readHistory"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const readAtMs = DateTime.toEpochMillis(readAt);
|
||||
const current = yield* Ref.get(state);
|
||||
return aggregateProcessResourceHistory({
|
||||
samples: current.samples,
|
||||
readAt,
|
||||
readAtMs,
|
||||
windowMs: input.windowMs,
|
||||
bucketMs: input.bucketMs,
|
||||
lastFailure: current.lastFailure,
|
||||
});
|
||||
});
|
||||
|
||||
return ProcessResourceMonitor.of({ readHistory });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make);
|
||||
export const layer = Layer.effect(ProcessResourceMonitor, make());
|
||||
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
|
||||
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
|
||||
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as OtlpSerialization from "effect/unstable/observability/OtlpSerializat
|
||||
import * as OtlpTracer from "effect/unstable/observability/OtlpTracer";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import { ServerLoggerLive } from "../../serverLogger.ts";
|
||||
import * as BrowserTraceCollector from "../BrowserTraceCollector.ts";
|
||||
|
||||
@@ -17,6 +18,7 @@ const otlpSerializationLayer = OtlpSerialization.layerJson;
|
||||
export const ObservabilityLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
|
||||
const traceReferencesLayer = Layer.mergeAll(
|
||||
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
|
||||
@@ -31,6 +33,14 @@ export const ObservabilityLive = Layer.unwrap(
|
||||
maxBytes: config.traceMaxBytes,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
batchWindowMs: config.traceBatchWindowMs,
|
||||
onFlush: (stats) =>
|
||||
attribution.record({
|
||||
component: "server-trace",
|
||||
operation: "append",
|
||||
logicalWriteBytes: stats.logicalWriteBytes,
|
||||
count: stats.count,
|
||||
durationMs: stats.durationMs,
|
||||
}),
|
||||
});
|
||||
const delegate =
|
||||
config.otlpTracesUrl === undefined
|
||||
|
||||
@@ -49,7 +49,10 @@ import {
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
|
||||
@@ -99,7 +102,7 @@ function createProviderServiceHarness(
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderSession>)
|
||||
: Effect.succeed([] as ReadonlyArray<ProviderSession>);
|
||||
const service: ProviderService.ProviderService["Service"] = {
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
@@ -325,7 +328,7 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(vcsStatusBroadcasterLayer),
|
||||
Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer))),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
@@ -80,7 +80,7 @@ const make = Effect.gen(function* () {
|
||||
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore.CheckpointStore;
|
||||
const receiptBus = yield* RuntimeReceiptBus;
|
||||
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
|
||||
|
||||
@@ -37,7 +37,10 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
|
||||
@@ -219,12 +222,8 @@ describe("ProviderCommandReactor", () => {
|
||||
}),
|
||||
);
|
||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||
const respondToRequest = vi.fn<ProviderService.ProviderService["Service"]["respondToRequest"]>(
|
||||
() => Effect.void,
|
||||
);
|
||||
const respondToUserInput = vi.fn<
|
||||
ProviderService.ProviderService["Service"]["respondToUserInput"]
|
||||
>(() => Effect.void);
|
||||
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
|
||||
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
|
||||
const stopSession = vi.fn((input: unknown) =>
|
||||
Effect.sync(() => {
|
||||
const threadId =
|
||||
@@ -295,15 +294,13 @@ describe("ProviderCommandReactor", () => {
|
||||
];
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderService.ProviderService["Service"] = {
|
||||
startSession: startSession as ProviderService.ProviderService["Service"]["startSession"],
|
||||
sendTurn: sendTurn as ProviderService.ProviderService["Service"]["sendTurn"],
|
||||
interruptTurn: interruptTurn as ProviderService.ProviderService["Service"]["interruptTurn"],
|
||||
respondToRequest:
|
||||
respondToRequest as ProviderService.ProviderService["Service"]["respondToRequest"],
|
||||
respondToUserInput:
|
||||
respondToUserInput as ProviderService.ProviderService["Service"]["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderService.ProviderService["Service"]["stopSession"],
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: startSession as ProviderServiceShape["startSession"],
|
||||
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
|
||||
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
|
||||
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (_provider) =>
|
||||
Effect.succeed({
|
||||
@@ -349,7 +346,7 @@ describe("ProviderCommandReactor", () => {
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, service)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(GitWorkflowService.GitWorkflowService)({
|
||||
|
||||
@@ -30,8 +30,8 @@ import { increment, orchestrationEventsProcessedTotal } from "../../observabilit
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import type { ProviderServiceError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -190,8 +190,8 @@ const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerService = yield* ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
@@ -35,7 +35,10 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
@@ -94,7 +97,7 @@ function createProviderServiceHarness() {
|
||||
const runtimeSessions: ProviderSession[] = [];
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderService.ProviderService["Service"] = {
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
@@ -234,7 +237,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(projectionSnapshotLayer),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, provider.service)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -27,7 +27,7 @@ import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
@@ -631,7 +631,7 @@ const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ProviderService from "../../provider/ProviderService.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
@@ -38,7 +38,7 @@ export const logCleanupCauseUnlessInterrupted = <R, E>({
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
|
||||
@@ -20,12 +20,13 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
import {
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
makePendingClaudeProvider,
|
||||
probeClaudeCapabilities,
|
||||
} from "../Layers/ClaudeProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -57,7 +58,6 @@ import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "
|
||||
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
@@ -82,14 +82,15 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -120,8 +121,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -186,14 +187,13 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Claude provider snapshot.",
|
||||
detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -22,22 +22,22 @@
|
||||
* @module provider/Drivers/CodexDriver
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.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";
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
@@ -74,14 +73,15 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
* registered driver and the runtime satisfies them once.
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
/**
|
||||
* Stamp instance identity onto a `ServerProvider` snapshot produced by the
|
||||
@@ -117,8 +117,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
const continuationIdentity = codexContinuationIdentity(homeLayout);
|
||||
@@ -134,7 +134,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to materialize the Codex shadow home.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -186,14 +186,13 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Codex provider snapshot.",
|
||||
detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -12,17 +12,17 @@
|
||||
* @module provider/Drivers/CursorDriver
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
checkCursorProviderStatus,
|
||||
enrichCursorSnapshot,
|
||||
} from "../Layers/CursorProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -53,7 +53,6 @@ import {
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -65,14 +64,15 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -104,8 +104,8 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -157,15 +157,14 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Cursor provider snapshot.",
|
||||
detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
checkGrokProviderStatus,
|
||||
enrichGrokSnapshot,
|
||||
} from "../Layers/GrokProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
@@ -49,14 +48,15 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
);
|
||||
|
||||
export type GrokDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -86,8 +86,8 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -134,14 +134,13 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
publishSnapshot,
|
||||
httpClient,
|
||||
}),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the Grok provider snapshot.",
|
||||
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -13,27 +13,27 @@
|
||||
* @module provider/Drivers/OpenCodeDriver
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
|
||||
import {
|
||||
checkOpenCodeProviderStatus,
|
||||
makePendingOpenCodeProvider,
|
||||
} from "../Layers/OpenCodeProvider.ts";
|
||||
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import { OpenCodeRuntime } from "../opencodeRuntime.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
@@ -55,7 +55,6 @@ import {
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
@@ -78,15 +77,16 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime.OpenCodeRuntime
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers.ProviderEventLoggers
|
||||
| ServerConfig.ServerConfig
|
||||
| ServerSettings.ServerSettingsService;
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig
|
||||
| ServerSettingsService;
|
||||
|
||||
const withInstanceIdentity =
|
||||
(input: {
|
||||
@@ -114,11 +114,11 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
driverKind: DRIVER_KIND,
|
||||
@@ -147,10 +147,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
effectiveConfig,
|
||||
serverConfig.cwd,
|
||||
processEnv,
|
||||
).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
|
||||
);
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
|
||||
@@ -169,7 +166,6 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
},
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
@@ -177,7 +173,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
new ProviderDriverError({
|
||||
driver: DRIVER_KIND,
|
||||
instanceId,
|
||||
detail: "Failed to build the OpenCode provider snapshot.",
|
||||
detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -64,7 +64,7 @@ export class ProviderAdapterRequestError extends Schema.TaggedErrorClass<Provide
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter request failed (${this.provider}) for ${this.method}.`;
|
||||
return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,13 +76,12 @@ export class ProviderAdapterProcessError extends Schema.TaggedErrorClass<Provide
|
||||
{
|
||||
provider: Schema.String,
|
||||
threadId: Schema.String,
|
||||
stage: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider adapter process failed (${this.provider}) during ${this.stage} for thread ${this.threadId}.`;
|
||||
return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,8 +171,6 @@ export class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<Provid
|
||||
}
|
||||
}
|
||||
|
||||
export const isProviderSessionNotFoundError = Schema.is(ProviderSessionNotFoundError);
|
||||
|
||||
/**
|
||||
* ProviderSessionDirectoryPersistenceError - Session directory persistence failure.
|
||||
*/
|
||||
|
||||
@@ -327,7 +327,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, ProviderAdapterProcessError);
|
||||
assert.equal(error.stage, "session-start");
|
||||
assert.equal(error.detail, "Failed to start Claude runtime session.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notMatch(error.message, /credential material/u);
|
||||
|
||||
@@ -1354,6 +1354,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
|
||||
const createQuery =
|
||||
options?.createQuery ??
|
||||
@@ -1387,7 +1389,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
|
||||
|
||||
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
|
||||
const logNativeSdkMessage = Effect.fnUntraced(function* (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
) {
|
||||
@@ -2893,7 +2895,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: context.session.threadId,
|
||||
stage: "runtime-stream",
|
||||
detail: "Claude runtime stream failed.",
|
||||
cause,
|
||||
}),
|
||||
@@ -2906,7 +2907,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: context.session.threadId,
|
||||
stage: "runtime-event",
|
||||
detail: "Failed to process Claude runtime event.",
|
||||
cause,
|
||||
}),
|
||||
@@ -2994,7 +2994,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: context.session.threadId,
|
||||
stage: "runtime-query-close",
|
||||
detail: "Failed to close Claude runtime query.",
|
||||
cause,
|
||||
}),
|
||||
@@ -3518,7 +3517,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start Claude runtime session.",
|
||||
cause,
|
||||
}),
|
||||
@@ -3847,6 +3845,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
|
||||
),
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -34,11 +34,11 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
type CodexSessionRuntimeOptions,
|
||||
type CodexSessionRuntimeSendTurnInput,
|
||||
@@ -211,17 +211,14 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
|
||||
};
|
||||
}
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(
|
||||
ProviderSessionDirectory.ProviderSessionDirectory,
|
||||
{
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
},
|
||||
);
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const validationRuntimeFactory = makeRuntimeFactory();
|
||||
const validationLayer = it.layer(
|
||||
@@ -235,7 +232,7 @@ const validationLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -304,7 +301,7 @@ const sessionErrorLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -376,7 +373,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -430,7 +427,7 @@ const lifecycleLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -1103,7 +1100,7 @@ const scopedLifecycleLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -1147,7 +1144,7 @@ const scopedFailureLayer = it.layer(
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
@@ -1199,7 +1196,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -116,7 +116,7 @@ function mapCodexRuntimeError(
|
||||
return new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method,
|
||||
detail: "Codex runtime request failed.",
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
@@ -1432,8 +1432,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-runtime-create",
|
||||
detail: "Failed to create Codex runtime session.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -1462,8 +1461,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start Codex runtime session.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -1510,7 +1508,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "turn/start",
|
||||
detail: "Failed to read attachment file.",
|
||||
detail: `Failed to read attachment file: ${cause.message}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -1639,7 +1637,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
),
|
||||
);
|
||||
|
||||
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
|
||||
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
|
||||
if (!nativeEventLogger) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as Config from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -319,7 +319,7 @@ export function makeCursorAdapter(
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(Config.ServerConfig);
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
@@ -564,8 +564,7 @@ export function makeCursorAdapter(
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start the Cursor ACP session process.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -980,7 +979,7 @@ export function makeCursorAdapter(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Failed to read attachment '${attachment.id}'.`,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings } from "@t3tools/contracts";
|
||||
@@ -24,7 +25,11 @@ import {
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const runNode = <A, E>(
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
>,
|
||||
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
const cursorAcpDiscoveryFailedMessage = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
|
||||
const cursorCliCommandMissingMessage = [
|
||||
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
].join(" ");
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
discoveryWarning: cursorAcpDiscoveryFailedMessage,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
});
|
||||
|
||||
describe("checkCursorProviderStatus", () => {
|
||||
it("reports the install docs when the Cursor CLI command is missing", async () => {
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus({
|
||||
enabled: true,
|
||||
binaryPath: missingCursorBinaryPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: cursorCliCommandMissingMessage,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the injected environment to ACP model discovery", async () => {
|
||||
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
|
||||
|
||||
const provider = await Effect.runPromise(
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus(
|
||||
{
|
||||
enabled: true,
|
||||
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
|
||||
...process.env,
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
},
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
),
|
||||
);
|
||||
|
||||
expect(provider.models.map((model) => model.slug)).toEqual([
|
||||
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await runNode(makeMockAgentWrapper());
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
const models = await runNode(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
makeExitLogFixture("cursor-provider-exit-log-"),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
await runNode(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
}),
|
||||
);
|
||||
|
||||
const exitLog = await runNode(waitForFileContent(exitLogPath));
|
||||
|
||||
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
|
||||
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Cursor CLI command \`${binaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildCursorProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly cursorSettings: CursorSettings;
|
||||
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
|
||||
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
|
||||
: "Failed to execute Cursor Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
yield* Effect.logWarning("Cursor ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
|
||||
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
|
||||
@@ -5,11 +5,14 @@ import * as NodePath from "node:path";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
@@ -148,6 +151,100 @@ describe("EventNdjsonLogger", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("shares one thread writer across native and canonical streams", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
|
||||
const native = store.logger("native");
|
||||
const canonical = store.logger("canonical");
|
||||
const threadId = ThreadId.make("thread-shared");
|
||||
|
||||
yield* native.write({ id: "native-event" }, threadId);
|
||||
yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-shared.log"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "NTIVE", payload: '{"id":"native-event"}' },
|
||||
{
|
||||
stream: "CANON",
|
||||
payload: '{"type":"item.completed","id":"canonical-event"}',
|
||||
},
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("flushes an active batch without a permanent polling loop", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const threadPath = NodePath.join(tempDir, "thread-batched.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 });
|
||||
yield* store
|
||||
.logger("native")
|
||||
.write({ id: "batched-event" }, ThreadId.make("thread-batched"));
|
||||
|
||||
assert.equal(NodeFS.existsSync(threadPath), false);
|
||||
yield* TestClock.adjust(1_000);
|
||||
assert.equal(NodeFS.existsSync(threadPath), true);
|
||||
yield* store.close();
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops transient canonical events before serialization", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
|
||||
try {
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
|
||||
const canonical = store.logger("canonical");
|
||||
const native = store.logger("native");
|
||||
const threadId = ThreadId.make("thread-filtered");
|
||||
const circularDelta: Record<string, unknown> = { type: "content.delta" };
|
||||
circularDelta["self"] = circularDelta;
|
||||
|
||||
yield* canonical.write(circularDelta, threadId);
|
||||
yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
|
||||
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
|
||||
yield* store.close();
|
||||
|
||||
const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-filtered.log"), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(parseLogLine);
|
||||
|
||||
assert.deepEqual(
|
||||
lines.map(({ stream, payload }) => ({ stream, payload })),
|
||||
[
|
||||
{ stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
|
||||
{ stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent first writes for the same segment", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
@@ -196,19 +293,19 @@ describe("EventNdjsonLogger", () => {
|
||||
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxBytes: 120,
|
||||
maxFiles: 2,
|
||||
batchWindowMs: 0,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
const native = store.logger("native");
|
||||
const canonical = store.logger("canonical");
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const logger = index % 2 === 0 ? native : canonical;
|
||||
yield* logger.write(
|
||||
{
|
||||
type: "session.started",
|
||||
threadId: "provider-thread-rotate",
|
||||
id: `evt-${index}`,
|
||||
payload: "x".repeat(40),
|
||||
@@ -216,7 +313,7 @@ describe("EventNdjsonLogger", () => {
|
||||
ThreadId.make("thread-rotate"),
|
||||
);
|
||||
}
|
||||
yield* logger.close();
|
||||
yield* store.close();
|
||||
|
||||
const fileStem = "thread-rotate.log";
|
||||
const matchingFiles = NodeFS.readdirSync(tempDir)
|
||||
@@ -240,4 +337,71 @@ describe("EventNdjsonLogger", () => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("enforces aggregate age and byte retention on startup", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "events.log");
|
||||
const expiredPath = NodePath.join(tempDir, "expired.log");
|
||||
const oldPath = NodePath.join(tempDir, "old.log");
|
||||
const newPath = NodePath.join(tempDir, "new.log");
|
||||
const ignoredPath = NodePath.join(tempDir, "ignored.txt");
|
||||
|
||||
try {
|
||||
yield* TestClock.setTime(1_800_000_000_000);
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
for (const filePath of [expiredPath, oldPath, newPath, ignoredPath]) {
|
||||
NodeFS.writeFileSync(filePath, "x".repeat(40));
|
||||
}
|
||||
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
|
||||
NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
|
||||
NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
|
||||
|
||||
const store = yield* makeEventNdjsonLogStore(basePath, {
|
||||
maxAgeMs: 10_000,
|
||||
maxTotalBytes: 60,
|
||||
});
|
||||
yield* store.close();
|
||||
|
||||
assert.equal(NodeFS.existsSync(expiredPath), false);
|
||||
assert.equal(NodeFS.existsSync(oldPath), false);
|
||||
assert.equal(NodeFS.existsSync(newPath), true);
|
||||
assert.equal(NodeFS.existsSync(ignoredPath), true);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports logical provider log writes to resource attribution", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
|
||||
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
|
||||
|
||||
try {
|
||||
const attribution = yield* ResourceAttribution.make();
|
||||
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||
stream: "native",
|
||||
batchWindowMs: 0,
|
||||
attribution,
|
||||
});
|
||||
assert.notEqual(logger, undefined);
|
||||
if (!logger) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* logger.write({ id: "attributed-event" }, ThreadId.make("thread-attribution"));
|
||||
yield* logger.close();
|
||||
|
||||
const snapshot = yield* attribution.snapshot;
|
||||
assert.equal(snapshot.entries.length, 1);
|
||||
assert.equal(snapshot.entries[0]?.component, "provider-event-log");
|
||||
assert.equal(snapshot.entries[0]?.operation, "native.append");
|
||||
assert.equal(snapshot.entries[0]?.count, 1);
|
||||
assert.isAbove(snapshot.entries[0]?.logicalWriteBytes ?? 0, 0);
|
||||
} finally {
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
/**
|
||||
* Provider event logger helper.
|
||||
* Best-effort provider event logging with one shared writer per thread.
|
||||
*
|
||||
* Best-effort writer for observability logs. Each record is formatted as a
|
||||
* single effect-style text line in a thread-scoped file. Failures are
|
||||
* downgraded to warnings so provider runtime behavior is unaffected.
|
||||
* Native and canonical views share batching, rotation, and retention state so
|
||||
* they cannot race while appending to the same thread-scoped file.
|
||||
*/
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
@@ -12,45 +11,149 @@ import * as NodePath from "node:path";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { errorTag } from "@t3tools/shared/observability";
|
||||
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 Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||
import type { ResourceAttributionShape } from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
|
||||
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const MEBIBYTE = 1024 * 1024;
|
||||
const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
|
||||
const DEFAULT_MAX_FILES = 10;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 1_000;
|
||||
const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
|
||||
const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
|
||||
const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
|
||||
const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
|
||||
const DEFAULT_MAX_BUFFERED_RECORDS = 512;
|
||||
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||
const LOG_SCOPE = "provider-observability";
|
||||
const PROVIDER_LOG_FILE_PATTERN = /\.log(?:\.\d+)?$/u;
|
||||
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
const transientCanonicalEventTypes = new Set([
|
||||
"content.delta",
|
||||
"hook.progress",
|
||||
"item.updated",
|
||||
"task.progress",
|
||||
"thread.realtime.audio.delta",
|
||||
"tool.progress",
|
||||
"turn.proposed.delta",
|
||||
]);
|
||||
|
||||
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||
|
||||
export interface EventNdjsonLogger {
|
||||
readonly filePath: string;
|
||||
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void, never, never>;
|
||||
close: () => Effect.Effect<void, never, never>;
|
||||
readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||
readonly close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLoggerOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
export interface EventNdjsonLogStore {
|
||||
readonly filePath: string;
|
||||
readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
|
||||
readonly close: () => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export interface EventNdjsonLogStoreOptions {
|
||||
readonly maxBytes?: number;
|
||||
readonly maxFiles?: number;
|
||||
readonly batchWindowMs?: number;
|
||||
readonly maxTotalBytes?: number;
|
||||
readonly maxAgeMs?: number;
|
||||
readonly retentionCheckIntervalMs?: number;
|
||||
readonly maxBufferedBytes?: number;
|
||||
readonly maxBufferedRecords?: number;
|
||||
readonly attribution?: ResourceAttributionShape;
|
||||
}
|
||||
|
||||
interface ThreadWriter {
|
||||
writeMessage: (message: string) => Effect.Effect<void>;
|
||||
close: () => Effect.Effect<void>;
|
||||
export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
|
||||
readonly stream: EventNdjsonStream;
|
||||
}
|
||||
|
||||
interface LoggerState {
|
||||
readonly threadWriters: Map<string, ThreadWriter>;
|
||||
readonly failedSegments: Set<string>;
|
||||
export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
|
||||
"EventNdjsonLogConfigurationError",
|
||||
{
|
||||
filePath: Schema.String,
|
||||
option: Schema.String,
|
||||
value: Schema.Number,
|
||||
minimum: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
|
||||
"EventNdjsonLogDirectoryError",
|
||||
{
|
||||
directory: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create provider event log directory '${this.directory}'`;
|
||||
}
|
||||
}
|
||||
|
||||
export type EventNdjsonLogStoreError =
|
||||
| EventNdjsonLogConfigurationError
|
||||
| EventNdjsonLogDirectoryError;
|
||||
|
||||
interface ResolvedOptions {
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly retentionCheckIntervalMs: number;
|
||||
readonly maxBufferedBytes: number;
|
||||
readonly maxBufferedRecords: number;
|
||||
readonly attribution: ResourceAttributionShape | undefined;
|
||||
}
|
||||
|
||||
interface PendingRecord {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly threadSegment: string;
|
||||
readonly line: string;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
interface StoreState {
|
||||
readonly pending: ReadonlyArray<PendingRecord>;
|
||||
readonly pendingBytes: number;
|
||||
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
|
||||
readonly failedSegments: ReadonlySet<string>;
|
||||
readonly flushScheduled: boolean;
|
||||
readonly closed: boolean;
|
||||
readonly lastRetentionAt: number;
|
||||
}
|
||||
|
||||
interface AttributionSummary {
|
||||
readonly stream: EventNdjsonStream;
|
||||
readonly count: number;
|
||||
readonly logicalWriteBytes: number;
|
||||
}
|
||||
|
||||
interface FileOperationFailure {
|
||||
readonly filePath: string;
|
||||
readonly cause: unknown;
|
||||
}
|
||||
|
||||
interface RetentionResult {
|
||||
readonly failures: ReadonlyArray<FileOperationFailure>;
|
||||
}
|
||||
|
||||
interface DrainResult {
|
||||
readonly attributions: ReadonlyArray<AttributionSummary>;
|
||||
readonly failures: ReadonlyArray<FileOperationFailure>;
|
||||
}
|
||||
|
||||
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||
@@ -62,34 +165,249 @@ function resolveThreadSegment(raw: string | null | undefined): string {
|
||||
return normalized ?? GLOBAL_THREAD_SEGMENT;
|
||||
}
|
||||
|
||||
function formatLoggerMessage(message: unknown): string {
|
||||
if (Array.isArray(message)) {
|
||||
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
|
||||
}
|
||||
return typeof message === "string" ? message : String(message);
|
||||
}
|
||||
|
||||
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
|
||||
return Logger.make(
|
||||
({ date, message }) =>
|
||||
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
switch (stream) {
|
||||
case "native":
|
||||
return "NTIVE";
|
||||
case "canonical":
|
||||
case "orchestration":
|
||||
default:
|
||||
return "CANON";
|
||||
}
|
||||
return stream === "native" ? "NTIVE" : "CANON";
|
||||
}
|
||||
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
|
||||
if (stream !== "canonical" || typeof event !== "object" || event === null) {
|
||||
return true;
|
||||
}
|
||||
const type = Reflect.get(event, "type");
|
||||
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
|
||||
}
|
||||
|
||||
function writeBatchedMessages(
|
||||
sink: RotatingFileSink,
|
||||
records: ReadonlyArray<PendingRecord>,
|
||||
maxBytes: number,
|
||||
): void {
|
||||
let pendingLines: Array<string> = [];
|
||||
let pendingBytes = 0;
|
||||
|
||||
const flush = () => {
|
||||
if (pendingLines.length === 0) return;
|
||||
sink.write(pendingLines.join(""));
|
||||
pendingLines = [];
|
||||
pendingBytes = 0;
|
||||
};
|
||||
|
||||
for (const record of records) {
|
||||
if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
|
||||
flush();
|
||||
}
|
||||
pendingLines.push(record.line);
|
||||
pendingBytes += record.bytes;
|
||||
if (pendingBytes >= maxBytes) {
|
||||
flush();
|
||||
}
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
function enforceRetention(input: {
|
||||
readonly directory: string;
|
||||
readonly maxTotalBytes: number;
|
||||
readonly maxAgeMs: number;
|
||||
readonly activeFilePaths: ReadonlySet<string>;
|
||||
readonly now: number;
|
||||
}): RetentionResult {
|
||||
const failures: Array<FileOperationFailure> = [];
|
||||
const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
|
||||
|
||||
let entries: ReadonlyArray<NodeFS.Dirent>;
|
||||
try {
|
||||
entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
|
||||
} catch (cause) {
|
||||
return { failures: [{ filePath: input.directory, cause }] };
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !PROVIDER_LOG_FILE_PATTERN.test(entry.name)) continue;
|
||||
const filePath = NodePath.join(input.directory, entry.name);
|
||||
try {
|
||||
const stat = NodeFS.statSync(filePath);
|
||||
files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
|
||||
} catch (cause) {
|
||||
failures.push({ filePath, cause });
|
||||
}
|
||||
}
|
||||
|
||||
let totalBytes = files.reduce((total, file) => total + file.size, 0);
|
||||
const remove = (file: (typeof files)[number]) => {
|
||||
if (input.activeFilePaths.has(file.filePath)) return false;
|
||||
try {
|
||||
NodeFS.rmSync(file.filePath, { force: true });
|
||||
totalBytes -= file.size;
|
||||
return true;
|
||||
} catch (cause) {
|
||||
failures.push({ filePath: file.filePath, cause });
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const retained = files.filter((file) => {
|
||||
if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
|
||||
return !remove(file);
|
||||
});
|
||||
|
||||
for (const file of retained.toSorted(
|
||||
(left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
|
||||
)) {
|
||||
if (totalBytes <= input.maxTotalBytes) break;
|
||||
remove(file);
|
||||
}
|
||||
|
||||
return { failures };
|
||||
}
|
||||
|
||||
function validateOption(input: {
|
||||
readonly filePath: string;
|
||||
readonly option: string;
|
||||
readonly value: number;
|
||||
readonly minimum: number;
|
||||
}): EventNdjsonLogConfigurationError | undefined {
|
||||
if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
|
||||
return new EventNdjsonLogConfigurationError(input);
|
||||
}
|
||||
|
||||
function resolveOptions(
|
||||
filePath: string,
|
||||
options: EventNdjsonLogStoreOptions,
|
||||
): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {
|
||||
const resolved = {
|
||||
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
||||
maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
|
||||
batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
|
||||
maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
|
||||
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
|
||||
retentionCheckIntervalMs:
|
||||
options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
|
||||
maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,
|
||||
maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
|
||||
attribution: options.attribution,
|
||||
} satisfies ResolvedOptions;
|
||||
|
||||
const validations = [
|
||||
["maxBytes", resolved.maxBytes, 1],
|
||||
["maxFiles", resolved.maxFiles, 1],
|
||||
["batchWindowMs", resolved.batchWindowMs, 0],
|
||||
["maxTotalBytes", resolved.maxTotalBytes, 1],
|
||||
["maxAgeMs", resolved.maxAgeMs, 1],
|
||||
["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
|
||||
["maxBufferedBytes", resolved.maxBufferedBytes, 1],
|
||||
["maxBufferedRecords", resolved.maxBufferedRecords, 1],
|
||||
] as const;
|
||||
|
||||
for (const [option, value, minimum] of validations) {
|
||||
const error = validateOption({ filePath, option, value, minimum });
|
||||
if (error) return Effect.fail(error);
|
||||
}
|
||||
return Effect.succeed(resolved);
|
||||
}
|
||||
|
||||
function drainPending(input: {
|
||||
readonly directory: string;
|
||||
readonly options: ResolvedOptions;
|
||||
readonly state: StoreState;
|
||||
readonly now: number;
|
||||
readonly timerFired: boolean;
|
||||
readonly close: boolean;
|
||||
}): readonly [DrainResult, StoreState] {
|
||||
if (input.state.closed) {
|
||||
return [{ attributions: [], failures: [] }, input.state];
|
||||
}
|
||||
|
||||
const sinks = new Map(input.state.sinks);
|
||||
const failedSegments = new Set(input.state.failedSegments);
|
||||
const failures: Array<FileOperationFailure> = [];
|
||||
const attributionByStream = new Map<
|
||||
EventNdjsonStream,
|
||||
{ count: number; logicalWriteBytes: number }
|
||||
>();
|
||||
const recordsBySegment = new Map<string, Array<PendingRecord>>();
|
||||
|
||||
for (const record of input.state.pending) {
|
||||
const records = recordsBySegment.get(record.threadSegment) ?? [];
|
||||
records.push(record);
|
||||
recordsBySegment.set(record.threadSegment, records);
|
||||
}
|
||||
|
||||
for (const [threadSegment, records] of recordsBySegment) {
|
||||
if (failedSegments.has(threadSegment)) continue;
|
||||
const filePath = NodePath.join(input.directory, `${threadSegment}.log`);
|
||||
let sink = sinks.get(threadSegment);
|
||||
if (!sink) {
|
||||
try {
|
||||
sink = new RotatingFileSink({
|
||||
filePath,
|
||||
maxBytes: input.options.maxBytes,
|
||||
maxFiles: input.options.maxFiles,
|
||||
throwOnError: true,
|
||||
});
|
||||
sinks.set(threadSegment, sink);
|
||||
} catch (cause) {
|
||||
failedSegments.add(threadSegment);
|
||||
failures.push({ filePath, cause });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
writeBatchedMessages(sink, records, input.options.maxBytes);
|
||||
for (const record of records) {
|
||||
const current = attributionByStream.get(record.stream) ?? {
|
||||
count: 0,
|
||||
logicalWriteBytes: 0,
|
||||
};
|
||||
attributionByStream.set(record.stream, {
|
||||
count: current.count + 1,
|
||||
logicalWriteBytes: current.logicalWriteBytes + record.bytes,
|
||||
});
|
||||
}
|
||||
} catch (cause) {
|
||||
failedSegments.add(threadSegment);
|
||||
failures.push({ filePath, cause });
|
||||
}
|
||||
}
|
||||
|
||||
const retentionDue =
|
||||
input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
|
||||
const retention = retentionDue
|
||||
? enforceRetention({
|
||||
directory: input.directory,
|
||||
maxTotalBytes: input.options.maxTotalBytes,
|
||||
maxAgeMs: input.options.maxAgeMs,
|
||||
activeFilePaths: new Set(
|
||||
Array.from(sinks.keys(), (threadSegment) =>
|
||||
NodePath.join(input.directory, `${threadSegment}.log`),
|
||||
),
|
||||
),
|
||||
now: input.now,
|
||||
})
|
||||
: { failures: [] };
|
||||
|
||||
return [
|
||||
{
|
||||
attributions: Array.from(attributionByStream, ([stream, value]) => ({
|
||||
stream,
|
||||
...value,
|
||||
})),
|
||||
failures: [...failures, ...retention.failures],
|
||||
},
|
||||
{
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks,
|
||||
failedSegments,
|
||||
flushScheduled: input.timerFired ? false : input.state.flushScheduled,
|
||||
closed: input.close,
|
||||
lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
|
||||
return yield* encodeUnknownJsonString(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning("failed to serialize provider event log record", {
|
||||
@@ -99,188 +417,169 @@ const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
errorTag: errorTag(sinkResult.error),
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
errorTag: errorTag(flushResult.error),
|
||||
});
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
|
||||
export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
options: EventNdjsonLogStoreOptions = {},
|
||||
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
|
||||
const resolved = yield* resolveOptions(filePath, options);
|
||||
const directory = NodePath.dirname(filePath);
|
||||
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
yield* Effect.try({
|
||||
try: () => NodeFS.mkdirSync(directory, { recursive: true }),
|
||||
catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
errorTag: errorTag(directoryReady.error),
|
||||
|
||||
const initializedAt = yield* Clock.currentTimeMillis;
|
||||
const initialRetention = yield* Effect.sync(() =>
|
||||
enforceRetention({
|
||||
directory,
|
||||
maxTotalBytes: resolved.maxTotalBytes,
|
||||
maxAgeMs: resolved.maxAgeMs,
|
||||
activeFilePaths: new Set(),
|
||||
now: initializedAt,
|
||||
}),
|
||||
);
|
||||
for (const failure of initialRetention.failures) {
|
||||
yield* logWarning("provider event log retention failed", {
|
||||
filePath: failure.filePath,
|
||||
errorTag: errorTag(failure.cause),
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const stateRef = yield* SynchronizedRef.make<LoggerState>({
|
||||
threadWriters: new Map(),
|
||||
const stateRef = yield* SynchronizedRef.make<StoreState>({
|
||||
pending: [],
|
||||
pendingBytes: 0,
|
||||
sinks: new Map(),
|
||||
failedSegments: new Set(),
|
||||
flushScheduled: false,
|
||||
closed: false,
|
||||
lastRetentionAt: initializedAt,
|
||||
});
|
||||
const timerScope = yield* Scope.make();
|
||||
|
||||
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
|
||||
threadSegment: string,
|
||||
): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
|
||||
if (state.failedSegments.has(threadSegment)) {
|
||||
return Effect.succeed([undefined, state] as const);
|
||||
}
|
||||
|
||||
const existing = state.threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return Effect.succeed([existing, state] as const);
|
||||
}
|
||||
|
||||
return makeThreadWriter({
|
||||
filePath: NodePath.join(NodePath.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
}).pipe(
|
||||
Effect.map((writer) => {
|
||||
if (!writer) {
|
||||
const nextFailedSegments = new Set(state.failedSegments);
|
||||
nextFailedSegments.add(threadSegment);
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
...state,
|
||||
failedSegments: nextFailedSegments,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
const nextThreadWriters = new Map(state.threadWriters);
|
||||
nextThreadWriters.set(threadSegment, writer);
|
||||
return [
|
||||
writer,
|
||||
{
|
||||
...state,
|
||||
threadWriters: nextThreadWriters,
|
||||
},
|
||||
] as const;
|
||||
const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
|
||||
const startedAt = yield* Clock.currentTimeMillis;
|
||||
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.sync(() =>
|
||||
drainPending({
|
||||
directory,
|
||||
options: resolved,
|
||||
state,
|
||||
now: startedAt,
|
||||
timerFired,
|
||||
close,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
for (const failure of result.failures) {
|
||||
yield* logWarning("provider event log write or retention failed", {
|
||||
filePath: failure.filePath,
|
||||
errorTag: errorTag(failure.cause),
|
||||
});
|
||||
}
|
||||
|
||||
if (resolved.attribution && result.attributions.length > 0) {
|
||||
const completedAt = yield* Clock.currentTimeMillis;
|
||||
const durationMs = Math.max(0, completedAt - startedAt);
|
||||
const totalBytes = result.attributions.reduce(
|
||||
(total, entry) => total + entry.logicalWriteBytes,
|
||||
0,
|
||||
);
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
result.attributions,
|
||||
(entry) =>
|
||||
resolved.attribution?.record({
|
||||
component: "provider-event-log",
|
||||
operation: `${entry.stream}.append`,
|
||||
logicalWriteBytes: entry.logicalWriteBytes,
|
||||
count: entry.count,
|
||||
durationMs:
|
||||
totalBytes === 0
|
||||
? 0
|
||||
: Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
|
||||
}) ?? Effect.void,
|
||||
{ discard: true },
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
|
||||
const close = Effect.fn("close")(function* () {
|
||||
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
|
||||
Effect.gen(function* () {
|
||||
for (const writer of state.threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
|
||||
return [
|
||||
undefined,
|
||||
{
|
||||
threadWriters: new Map<string, ThreadWriter>(),
|
||||
failedSegments: new Set<string>(),
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
const scheduleFlush = Effect.fnUntraced(function* () {
|
||||
yield* Effect.forkIn(
|
||||
Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
|
||||
timerScope,
|
||||
{ startImmediately: true },
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write,
|
||||
close,
|
||||
} satisfies EventNdjsonLogger;
|
||||
const close = Effect.fnUntraced(function* () {
|
||||
yield* flush(false, true);
|
||||
yield* Scope.close(timerScope, Exit.void);
|
||||
});
|
||||
|
||||
const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
|
||||
const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
|
||||
const existing = loggerViews.get(stream);
|
||||
if (existing) return existing;
|
||||
|
||||
const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
|
||||
if (!shouldPersist(stream, event)) return;
|
||||
const payload = yield* serializeEvent(event);
|
||||
if (payload === undefined) return;
|
||||
|
||||
const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
|
||||
const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
|
||||
const bytes = Buffer.byteLength(line);
|
||||
const action = yield* SynchronizedRef.modify(stateRef, (state) => {
|
||||
if (state.closed) {
|
||||
return [{ flush: false, schedule: false }, state] as const;
|
||||
}
|
||||
const pending = [
|
||||
...state.pending,
|
||||
{ stream, threadSegment: resolveThreadSegment(threadId), line, bytes },
|
||||
];
|
||||
const pendingBytes = state.pendingBytes + bytes;
|
||||
const flush =
|
||||
resolved.batchWindowMs === 0 ||
|
||||
pending.length >= resolved.maxBufferedRecords ||
|
||||
pendingBytes >= resolved.maxBufferedBytes;
|
||||
const schedule = !flush && !state.flushScheduled;
|
||||
return [
|
||||
{ flush, schedule },
|
||||
{
|
||||
...state,
|
||||
pending,
|
||||
pendingBytes,
|
||||
flushScheduled: state.flushScheduled || schedule,
|
||||
},
|
||||
] as const;
|
||||
});
|
||||
|
||||
if (action.flush) {
|
||||
yield* flush(false, false);
|
||||
} else if (action.schedule) {
|
||||
yield* scheduleFlush();
|
||||
}
|
||||
});
|
||||
|
||||
const view = { filePath, write, close } satisfies EventNdjsonLogger;
|
||||
loggerViews.set(stream, view);
|
||||
return view;
|
||||
};
|
||||
|
||||
return { filePath, logger, close } satisfies EventNdjsonLogStore;
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning(error.message, { error }).pipe(
|
||||
Effect.as<EventNdjsonLogStore | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
return store?.logger(options.stream);
|
||||
});
|
||||
@@ -32,7 +32,7 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as Config from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -176,7 +176,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(Config.ServerConfig);
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
@@ -408,8 +408,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start the Grok ACP session process.",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -737,7 +736,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Failed to read attachment '${attachment.id}'.`,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -20,11 +20,15 @@ import {
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import * as Config from "../../config.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as ProviderSessionDirectory from "../ProviderSessionDirectory.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
makeOpenCodeAdapter,
|
||||
@@ -75,7 +79,7 @@ const runtimeMock = {
|
||||
},
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
@@ -163,12 +167,10 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
})(),
|
||||
}),
|
||||
},
|
||||
}) as unknown as ReturnType<
|
||||
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
|
||||
>,
|
||||
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||
cause: null,
|
||||
@@ -176,17 +178,14 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
),
|
||||
};
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(
|
||||
ProviderSessionDirectory.ProviderSessionDirectory,
|
||||
{
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
},
|
||||
);
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
// The adapter now receives its settings as a plain argument (the old design
|
||||
// read from `ServerSettingsService` internally). The test-only
|
||||
@@ -204,10 +203,10 @@ const OpenCodeAdapterTestLayer = Layer.effect(
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
@@ -335,11 +334,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings),
|
||||
).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
|
||||
),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -369,8 +366,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const promptFailure = new Error("prompt failed");
|
||||
runtimeMock.state.promptAsyncError = promptFailure;
|
||||
runtimeMock.state.promptAsyncError = new Error("prompt failed");
|
||||
const error = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-send-turn-failure"),
|
||||
@@ -387,17 +383,15 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
if (error._tag !== "ProviderAdapterRequestError") {
|
||||
throw new Error("Unexpected error type");
|
||||
}
|
||||
NodeAssert.equal(error.detail, "OpenCode SDK request failed.");
|
||||
NodeAssert.equal(error.detail, "prompt failed");
|
||||
NodeAssert.equal(
|
||||
error.message,
|
||||
"Provider adapter request failed (opencode) for session.promptAsync.",
|
||||
"Provider adapter request failed (opencode) for session.promptAsync: prompt failed",
|
||||
);
|
||||
NodeAssert.ok(OpenCodeRuntime.isOpenCodeRuntimeError(error.cause));
|
||||
NodeAssert.strictEqual(error.cause.cause, promptFailure);
|
||||
NodeAssert.equal(sessions.length, 1);
|
||||
NodeAssert.equal(sessions[0]?.status, "ready");
|
||||
NodeAssert.equal(sessions[0]?.activeTurnId, undefined);
|
||||
NodeAssert.equal(sessions[0]?.lastError, "OpenCode SDK request failed.");
|
||||
NodeAssert.equal(sessions[0]?.lastError, "prompt failed");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -486,9 +480,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -533,9 +527,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -575,9 +569,9 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
OpenCodeAdapter,
|
||||
makeOpenCodeAdapter(openCodeAdapterTestSettings, { instanceId }),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -798,12 +792,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
nativeEventLogger,
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
|
||||
),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
@@ -882,12 +874,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
nativeEventLogger,
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
|
||||
),
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
|
||||
@@ -25,7 +25,7 @@ import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import {
|
||||
@@ -36,7 +36,19 @@ import {
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import {
|
||||
buildOpenCodePermissionRules,
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
openCodeQuestionId,
|
||||
openCodeRuntimeErrorDetail,
|
||||
parseOpenCodeModelSlug,
|
||||
runOpenCodeSdk,
|
||||
toOpenCodeFileParts,
|
||||
toOpenCodePermissionReply,
|
||||
toOpenCodeQuestionAnswers,
|
||||
type OpenCodeServerConnection,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("opencode");
|
||||
@@ -56,7 +68,7 @@ type OpenCodeSubscribedEvent =
|
||||
interface OpenCodeSessionContext {
|
||||
session: ProviderSession;
|
||||
readonly client: OpencodeClient;
|
||||
readonly server: OpenCodeRuntime.OpenCodeServerConnection;
|
||||
readonly server: OpenCodeServerConnection;
|
||||
readonly directory: string;
|
||||
readonly openCodeSessionId: string;
|
||||
readonly pendingPermissions: Map<string, PermissionRequest>;
|
||||
@@ -96,16 +108,30 @@ export interface OpenCodeAdapterLiveOptions {
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
/**
|
||||
* Map a tagged OpenCodeRuntimeError produced by {@link OpenCodeRuntime.runOpenCodeSdk} into
|
||||
* Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into
|
||||
* the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call
|
||||
* sites pipe through this in `Effect.mapError` so they never build the error
|
||||
* shape by hand.
|
||||
*/
|
||||
const toRequestError = (cause: OpenCodeRuntime.OpenCodeRuntimeError): ProviderAdapterRequestError =>
|
||||
const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: cause.operation,
|
||||
detail: "OpenCode SDK request failed.",
|
||||
detail: cause.detail,
|
||||
cause: cause.cause,
|
||||
});
|
||||
|
||||
/**
|
||||
* Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The
|
||||
* typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}),
|
||||
* in which case we preserve its `detail`; otherwise we fall back to
|
||||
* {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.).
|
||||
*/
|
||||
const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
});
|
||||
|
||||
@@ -227,7 +253,7 @@ function ensureSessionContext(
|
||||
|
||||
function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
|
||||
return request.questions.map((question, index) => ({
|
||||
id: OpenCodeRuntime.openCodeQuestionId(index, question),
|
||||
id: openCodeQuestionId(index, question),
|
||||
header: question.header,
|
||||
question: question.question,
|
||||
options: question.options.map((option) => ({
|
||||
@@ -387,7 +413,7 @@ const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (
|
||||
// Best-effort remote abort. The scope close below tears down the local
|
||||
// handles (event-pump fiber, server-exit fiber, event-subscribe fetch),
|
||||
// but we still want to tell OpenCode that this session is done.
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.ignore({ log: true }));
|
||||
|
||||
@@ -404,8 +430,8 @@ export function makeOpenCodeAdapter(
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode");
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
@@ -543,7 +569,7 @@ export function makeOpenCodeAdapter(
|
||||
// Inline the teardown that `stopOpenCodeContext` would do; we can't
|
||||
// delegate to it because our `getAndSet` above already flipped the
|
||||
// one-shot guard, so the call would no-op.
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.ignore({ log: true }));
|
||||
yield* Scope.close(context.sessionScope, Exit.void);
|
||||
@@ -815,7 +841,7 @@ export function makeOpenCodeAdapter(
|
||||
context.pendingQuestions.delete(event.properties.requestID);
|
||||
const answers = Object.fromEntries(
|
||||
(request?.questions ?? []).map((question, index) => [
|
||||
OpenCodeRuntime.openCodeQuestionId(index, question),
|
||||
openCodeQuestionId(index, question),
|
||||
event.properties.answers[index]?.join(", ") ?? "",
|
||||
]),
|
||||
);
|
||||
@@ -949,18 +975,20 @@ export function makeOpenCodeAdapter(
|
||||
// Fibers forked into `context.sessionScope` are interrupted
|
||||
// automatically when the scope closes — no bookkeeping required.
|
||||
yield* Effect.flatMap(
|
||||
OpenCodeRuntime.runOpenCodeSdk("event.subscribe", () =>
|
||||
runOpenCodeSdk("event.subscribe", () =>
|
||||
context.client.event.subscribe(undefined, {
|
||||
signal: eventsAbortController.signal,
|
||||
}),
|
||||
),
|
||||
(subscription) =>
|
||||
Stream.fromAsyncIterable(subscription.stream, (cause) =>
|
||||
OpenCodeRuntime.OpenCodeRuntimeError.fromCause({
|
||||
operation: "event.subscribe",
|
||||
detail: "OpenCode event subscription failed.",
|
||||
cause,
|
||||
}),
|
||||
Stream.fromAsyncIterable(
|
||||
subscription.stream,
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "event.subscribe",
|
||||
detail: openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),
|
||||
).pipe(
|
||||
Effect.exit,
|
||||
@@ -974,7 +1002,7 @@ export function makeOpenCodeAdapter(
|
||||
if (Exit.isFailure(exit)) {
|
||||
yield* emitUnexpectedExit(
|
||||
context,
|
||||
OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(Cause.squash(exit.cause)),
|
||||
openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),
|
||||
);
|
||||
}
|
||||
}),
|
||||
@@ -1028,7 +1056,7 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
if (mcpSession && !server.external) {
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
|
||||
yield* runOpenCodeSdk("mcp.add", () =>
|
||||
client.mcp.add({
|
||||
name: "t3-code",
|
||||
config: {
|
||||
@@ -1042,14 +1070,14 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
);
|
||||
}
|
||||
const openCodeSession = yield* OpenCodeRuntime.runOpenCodeSdk("session.create", () =>
|
||||
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
|
||||
client.session.create({
|
||||
title: `T3 Code ${input.threadId}`,
|
||||
permission: OpenCodeRuntime.buildOpenCodePermissionRules(input.runtimeMode),
|
||||
permission: buildOpenCodePermissionRules(input.runtimeMode),
|
||||
}),
|
||||
);
|
||||
if (!openCodeSession.data) {
|
||||
return yield* new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "session.create",
|
||||
detail: "OpenCode session.create returned no session payload.",
|
||||
});
|
||||
@@ -1064,14 +1092,7 @@ export function makeOpenCodeAdapter(
|
||||
);
|
||||
if (Exit.isFailure(startedExit)) {
|
||||
yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);
|
||||
const cause = Cause.squash(startedExit.cause);
|
||||
return yield* new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
stage: "session-start",
|
||||
detail: "Failed to start OpenCode runtime session.",
|
||||
cause,
|
||||
});
|
||||
return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));
|
||||
}
|
||||
return startedExit.value;
|
||||
});
|
||||
@@ -1082,7 +1103,7 @@ export function makeOpenCodeAdapter(
|
||||
if (raceWinner) {
|
||||
// Another call won the race – clean up the session we just created
|
||||
// (including the remote SDK session) and return the existing one.
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
started.client.session.abort({
|
||||
sessionID: started.openCodeSession.id,
|
||||
}),
|
||||
@@ -1164,7 +1185,7 @@ export function makeOpenCodeAdapter(
|
||||
issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`,
|
||||
});
|
||||
}
|
||||
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(modelSelection?.model);
|
||||
const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);
|
||||
if (!parsedModel) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
@@ -1174,7 +1195,7 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
|
||||
const text = input.input?.trim();
|
||||
const fileParts = OpenCodeRuntime.toOpenCodeFileParts({
|
||||
const fileParts = toOpenCodeFileParts({
|
||||
attachments: input.attachments,
|
||||
resolveAttachmentPath: (attachment) =>
|
||||
resolveAttachmentPath({
|
||||
@@ -1217,7 +1238,7 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
}
|
||||
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.promptAsync", () =>
|
||||
yield* runOpenCodeSdk("session.promptAsync", () =>
|
||||
context.client.session.promptAsync({
|
||||
sessionID: context.openCodeSessionId,
|
||||
model: parsedModel,
|
||||
@@ -1271,7 +1292,7 @@ export function makeOpenCodeAdapter(
|
||||
const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
function* (threadId, turnId) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.abort", () =>
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
context.client.session.abort({ sessionID: context.openCodeSessionId }),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
if (turnId ?? context.activeTurnId) {
|
||||
@@ -1301,10 +1322,10 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
}
|
||||
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("permission.reply", () =>
|
||||
yield* runOpenCodeSdk("permission.reply", () =>
|
||||
context.client.permission.reply({
|
||||
requestID: requestId,
|
||||
reply: OpenCodeRuntime.toOpenCodePermissionReply(decision),
|
||||
reply: toOpenCodePermissionReply(decision),
|
||||
}),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
});
|
||||
@@ -1322,10 +1343,10 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
}
|
||||
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("question.reply", () =>
|
||||
yield* runOpenCodeSdk("question.reply", () =>
|
||||
context.client.question.reply({
|
||||
requestID: requestId,
|
||||
answers: OpenCodeRuntime.toOpenCodeQuestionAnswers(request, answers),
|
||||
answers: toOpenCodeQuestionAnswers(request, answers),
|
||||
}),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
});
|
||||
@@ -1365,7 +1386,7 @@ export function makeOpenCodeAdapter(
|
||||
const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(
|
||||
function* (threadId) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const messages = yield* OpenCodeRuntime.runOpenCodeSdk("session.messages", () =>
|
||||
const messages = yield* runOpenCodeSdk("session.messages", () =>
|
||||
context.client.session.messages({
|
||||
sessionID: context.openCodeSessionId,
|
||||
}),
|
||||
@@ -1391,7 +1412,7 @@ export function makeOpenCodeAdapter(
|
||||
const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
|
||||
function* (threadId, numTurns) {
|
||||
const context = ensureSessionContext(sessions, threadId);
|
||||
const messages = yield* OpenCodeRuntime.runOpenCodeSdk("session.messages", () =>
|
||||
const messages = yield* runOpenCodeSdk("session.messages", () =>
|
||||
context.client.session.messages({
|
||||
sessionID: context.openCodeSessionId,
|
||||
}),
|
||||
@@ -1402,7 +1423,7 @@ export function makeOpenCodeAdapter(
|
||||
);
|
||||
const targetIndex = assistantMessages.length - numTurns - 1;
|
||||
const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;
|
||||
yield* OpenCodeRuntime.runOpenCodeSdk("session.revert", () =>
|
||||
yield* runOpenCodeSdk("session.revert", () =>
|
||||
context.client.session.revert({
|
||||
sessionID: context.openCodeSessionId,
|
||||
...(target ? { messageID: target.info.id } : {}),
|
||||
|
||||
@@ -8,10 +8,14 @@ import * as Schema from "effect/Schema";
|
||||
import { beforeEach } from "vite-plus/test";
|
||||
|
||||
import { OpenCodeSettings } from "@t3tools/contracts";
|
||||
import * as Config from "../../config.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import { checkOpenCodeProviderStatus, OpenCodeProbeError } from "./OpenCodeProvider.ts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
|
||||
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
|
||||
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
|
||||
@@ -48,7 +52,7 @@ const runtimeMock = {
|
||||
},
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.succeed({
|
||||
url: "http://127.0.0.1:4301",
|
||||
@@ -72,7 +76,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
runOpenCodeCommand: () =>
|
||||
runtimeMock.state.runVersionError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: runtimeMock.state.runVersionError.message,
|
||||
cause: runtimeMock.state.runVersionError,
|
||||
@@ -80,27 +84,25 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
|
||||
)
|
||||
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: () =>
|
||||
({}) as unknown as ReturnType<
|
||||
OpenCodeRuntime.OpenCodeRuntime["Service"]["createOpenCodeSdkClient"]
|
||||
>,
|
||||
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
runtimeMock.state.inventoryError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: runtimeMock.state.inventoryError.message,
|
||||
cause: runtimeMock.state.inventoryError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeRuntime.OpenCodeInventory),
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const testLayer = Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
|
||||
Layer.provideMerge(Config.ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
@@ -114,24 +116,6 @@ const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSe
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("structures OpenCode probe failures without deriving messages from causes", () => {
|
||||
const cause = new Error("401 Unauthorized");
|
||||
const runtimeError = new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
});
|
||||
const probeError = OpenCodeProbeError.fromCause("load-inventory")(runtimeError);
|
||||
const versionProbeError = OpenCodeProbeError.fromCause("probe-version")(runtimeError);
|
||||
|
||||
NodeAssert.equal(probeError.operation, "load-inventory");
|
||||
NodeAssert.equal(probeError.detail, "401 Unauthorized");
|
||||
NodeAssert.strictEqual(probeError.cause, runtimeError);
|
||||
NodeAssert.strictEqual(runtimeError.cause, cause);
|
||||
NodeAssert.equal(probeError.message, "OpenCode probe failed during load-inventory.");
|
||||
NodeAssert.equal(versionProbeError.message, "OpenCode probe failed during probe-version.");
|
||||
});
|
||||
|
||||
it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
it.effect("shows a codex-style missing binary message", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -228,7 +212,7 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
|
||||
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(
|
||||
makeOpenCodeSettings({
|
||||
serverUrl: "http://url-user:[email protected]:9999/private?token=secret#fragment",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
}),
|
||||
process.cwd(),
|
||||
@@ -262,28 +246,6 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
|
||||
snapshot.message,
|
||||
"Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
|
||||
);
|
||||
NodeAssert.doesNotMatch(
|
||||
snapshot.message ?? "",
|
||||
/url-user|url-password|private|token|secret|fragment/,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps IPv6 brackets in configured server diagnostics", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("fetch failed: connect ECONNREFUSED ::1:9999");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(
|
||||
makeOpenCodeSettings({
|
||||
serverUrl: "http://[::1]:9999/private",
|
||||
serverPassword: "secret-password",
|
||||
}),
|
||||
process.cwd(),
|
||||
);
|
||||
|
||||
NodeAssert.equal(
|
||||
snapshot.message,
|
||||
"Couldn't reach the configured OpenCode server at http://[::1]:9999. Check that the server is running and the URL is correct.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -5,9 +5,9 @@ import {
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
@@ -18,7 +18,11 @@ import {
|
||||
providerModelsFromSettings,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
openCodeRuntimeErrorDetail,
|
||||
type OpenCodeInventory,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("opencode");
|
||||
@@ -28,29 +32,10 @@ const OPENCODE_PRESENTATION = {
|
||||
} as const;
|
||||
const MINIMUM_OPENCODE_VERSION = "1.14.19";
|
||||
|
||||
export class OpenCodeProbeError extends Schema.TaggedErrorClass<OpenCodeProbeError>()(
|
||||
"OpenCodeProbeError",
|
||||
{
|
||||
operation: Schema.Literals(["probe-version", "load-inventory"]),
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode probe failed during ${this.operation}.`;
|
||||
}
|
||||
|
||||
static fromCause(operation: "probe-version" | "load-inventory") {
|
||||
return (cause: unknown): OpenCodeProbeError =>
|
||||
new OpenCodeProbeError({
|
||||
operation,
|
||||
detail: OpenCodeRuntime.OpenCodeRuntimeError.detailFromCause(cause),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const isOpenCodeProbeError = Schema.is(OpenCodeProbeError);
|
||||
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
|
||||
readonly cause: unknown;
|
||||
readonly detail: string;
|
||||
}> {}
|
||||
|
||||
function normalizeProbeMessage(message: string): string | undefined {
|
||||
const trimmed = message.trim();
|
||||
@@ -67,7 +52,7 @@ function normalizeProbeMessage(message: string): string | undefined {
|
||||
}
|
||||
|
||||
function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
if (isOpenCodeProbeError(cause)) {
|
||||
if (cause instanceof OpenCodeProbeError) {
|
||||
return normalizeProbeMessage(cause.detail);
|
||||
}
|
||||
|
||||
@@ -78,15 +63,6 @@ function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
return normalizeProbeMessage(cause.message);
|
||||
}
|
||||
|
||||
function openCodeServerDisplayTarget(input: string): string | undefined {
|
||||
try {
|
||||
const url = new URL(input);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function formatOpenCodeProbeError(input: {
|
||||
readonly cause: unknown;
|
||||
readonly isExternalServer: boolean;
|
||||
@@ -117,13 +93,9 @@ function formatOpenCodeProbeError(input: {
|
||||
lower.includes("timeout") ||
|
||||
lower.includes("socket hang up")
|
||||
) {
|
||||
const serverTarget = openCodeServerDisplayTarget(input.serverUrl);
|
||||
return {
|
||||
installed: true,
|
||||
message:
|
||||
serverTarget === undefined
|
||||
? "Couldn't reach the configured OpenCode server. Check that the server is running and the URL is correct."
|
||||
: `Couldn't reach the configured OpenCode server at ${serverTarget}. Check that the server is running and the URL is correct.`,
|
||||
message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -247,9 +219,7 @@ function openCodeCapabilitiesForModel(input: {
|
||||
});
|
||||
}
|
||||
|
||||
function flattenOpenCodeModels(
|
||||
input: OpenCodeRuntime.OpenCodeInventory,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
@@ -332,18 +302,20 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
openCodeSettings: OpenCodeSettings,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime.OpenCodeRuntime> {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const customModels = openCodeSettings.customModels;
|
||||
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
|
||||
|
||||
const buildFailureSnapshot = (
|
||||
failure: { readonly installed: boolean; readonly message: string },
|
||||
version: string | null,
|
||||
) =>
|
||||
buildServerProvider({
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: openCodeSettings.enabled,
|
||||
checkedAt,
|
||||
@@ -361,16 +333,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) =>
|
||||
buildFailureSnapshot(
|
||||
formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
}),
|
||||
version,
|
||||
);
|
||||
};
|
||||
|
||||
if (!openCodeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
@@ -404,7 +367,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
args: ["--version"],
|
||||
environment: resolvedEnvironment,
|
||||
})
|
||||
.pipe(Effect.mapError(OpenCodeProbeError.fromCause("probe-version"))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
@@ -412,11 +379,10 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
|
||||
if (!version) {
|
||||
return buildFailureSnapshot(
|
||||
{
|
||||
installed: true,
|
||||
message: `Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
},
|
||||
return fallback(
|
||||
new Error(
|
||||
`Unable to determine OpenCode version from \`opencode --version\` output. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
),
|
||||
null,
|
||||
);
|
||||
}
|
||||
@@ -459,7 +425,11 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.mapError(OpenCodeProbeError.fromCause("load-inventory"))),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
|
||||
+20
-16
@@ -10,15 +10,16 @@ import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { ClaudeAdapterShape } from "./Services/ClaudeAdapter.ts";
|
||||
import type { CodexAdapterShape } from "./Services/CodexAdapter.ts";
|
||||
import type { CursorAdapterShape } from "./Services/CursorAdapter.ts";
|
||||
import type { OpenCodeAdapterShape } from "./Services/OpenCodeAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "./ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import type * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import type * as ClaudeAdapter from "../Services/ClaudeAdapter.ts";
|
||||
import type * as CodexAdapter from "../Services/CodexAdapter.ts";
|
||||
import type * as CursorAdapter from "../Services/CursorAdapter.ts";
|
||||
import type * as OpenCodeAdapter from "../Services/OpenCodeAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type * as TextGeneration from "../../textGeneration/TextGeneration.ts";
|
||||
import * as ProviderAdapterRegistryLayer from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
@@ -26,7 +27,7 @@ const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
|
||||
const fakeCodexAdapter: CodexAdapterShape = {
|
||||
const fakeCodexAdapter: CodexAdapter.CodexAdapterShape = {
|
||||
provider: CODEX_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -43,7 +44,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
|
||||
provider: CLAUDE_AGENT_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -60,7 +61,7 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
|
||||
provider: OPENCODE_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -77,7 +78,7 @@ const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
|
||||
provider: CURSOR_DRIVER,
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
@@ -94,7 +95,7 @@ const fakeCursorAdapter: CursorAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
// ProviderAdapterRegistry is a facade over ProviderInstanceRegistry —
|
||||
// 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
|
||||
@@ -146,11 +147,14 @@ const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.Provide
|
||||
});
|
||||
|
||||
const layer = Layer.mergeAll(
|
||||
Layer.provide(ProviderAdapterRegistry.layer, fakeInstanceRegistryLayer),
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLayer.ProviderAdapterRegistryLive,
|
||||
fakeInstanceRegistryLayer,
|
||||
),
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
it.layer(layer)("ProviderAdapterRegistry", (it) => {
|
||||
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
|
||||
it("resolves adapters and routing metadata from provider instances", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* 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";
|
||||
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry;
|
||||
|
||||
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
|
||||
registry.getInstance(instanceId).pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(
|
||||
new ProviderUnsupportedError({
|
||||
provider: instanceId,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(instance.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 };
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* ProviderEventLoggers — single observability service that owns the shared
|
||||
* provider event log store and exposes its two runtime views:
|
||||
*
|
||||
* - `native` — provider-protocol events as the SDK emits them, written
|
||||
* from inside each `<X>Adapter` factory.
|
||||
* - `canonical` — runtime events after `ProviderService` has normalized
|
||||
* them onto `ProviderRuntimeEvent`.
|
||||
*
|
||||
* Why a service tag and not constructor options?
|
||||
*
|
||||
* - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),
|
||||
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
|
||||
* call site where we can hand an `EventNdjsonLogger` in by hand.
|
||||
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
|
||||
* must share one underlying log store — opening N writers against the
|
||||
* same rotating file would race the rotation logic. Owning the loggers on
|
||||
* a single tag keeps that invariant intact.
|
||||
* - Tests can swap one (or both) loggers with in-memory recorders by
|
||||
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
|
||||
* juggling per-Layer option threading.
|
||||
*
|
||||
* Both fields are optional because observability must not prevent startup.
|
||||
*
|
||||
* @module provider/Layers/ProviderEventLoggers
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as ResourceAttribution from "../../resourceTelemetry/ResourceAttribution.ts";
|
||||
import * as EventNdjsonLogger from "./EventNdjsonLogger.ts";
|
||||
|
||||
export interface ProviderEventLoggersShape {
|
||||
readonly native: EventNdjsonLogger.EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger.EventNdjsonLogger | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared logger pair for native + canonical provider event streams.
|
||||
*
|
||||
* Service value is intentionally a struct of two optional loggers rather
|
||||
* than two parallel tags. Construction site is one place
|
||||
* (`layer`); consumers (drivers, `ProviderService`) read one tag and pluck the
|
||||
* field they need.
|
||||
*/
|
||||
export class ProviderEventLoggers extends Context.Service<
|
||||
ProviderEventLoggers,
|
||||
ProviderEventLoggersShape
|
||||
>()("t3/provider/Layers/ProviderEventLoggers") {}
|
||||
|
||||
/**
|
||||
* Constant value used by tests / boot layers that want to opt out of native
|
||||
* + canonical logging entirely. Keeps the tag non-optional in the type
|
||||
* system while letting the runtime treat absence as a no-op.
|
||||
*/
|
||||
export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
|
||||
native: undefined,
|
||||
canonical: undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds both stream views over one shared store. Setup failures are logged
|
||||
* and downgraded to the no-op service so diagnostics never block startup.
|
||||
*/
|
||||
export const make = Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const attribution = yield* ResourceAttribution.ResourceAttribution;
|
||||
const store = yield* EventNdjsonLogger.makeEventNdjsonLogStore(providerEventLogPath, {
|
||||
attribution,
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(error.message, { error }).pipe(
|
||||
Effect.annotateLogs({ scope: "provider-observability" }),
|
||||
Effect.as<EventNdjsonLogger.EventNdjsonLogStore | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (!store) {
|
||||
return ProviderEventLoggers.of(NoOpProviderEventLoggers);
|
||||
}
|
||||
|
||||
yield* Effect.addFinalizer(() => store.close());
|
||||
return ProviderEventLoggers.of({
|
||||
native: store.logger("native"),
|
||||
canonical: store.logger("canonical"),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderEventLoggers, make);
|
||||
@@ -29,7 +29,7 @@
|
||||
* ----------
|
||||
* On layer build we:
|
||||
* 1. Read the current `ServerSettings` once and use it to seed the
|
||||
* registry's initial state via `ProviderInstanceRegistry.mutableLayer`.
|
||||
* registry's initial state via `ProviderInstanceRegistryMutableLayer`.
|
||||
* 2. Fork a daemon fiber (lifetime tied to the layer's scope) that
|
||||
* subscribes to `ServerSettingsService.streamChanges` and calls
|
||||
* `ProviderInstanceRegistryMutator.reconcile` on every emission.
|
||||
@@ -51,9 +51,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ServerSettingsModule from "../../serverSettings.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts";
|
||||
import * as ProviderInstanceRegistry from "../ProviderInstanceRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts";
|
||||
import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
/**
|
||||
* Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.
|
||||
@@ -114,8 +116,8 @@ export const deriveProviderInstanceConfigMap = (
|
||||
*/
|
||||
const SettingsWatcherLive = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const mutator = yield* ProviderInstanceRegistry.ProviderInstanceRegistryMutator;
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const mutator = yield* ProviderInstanceRegistryMutator;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
yield* serverSettings.streamChanges.pipe(
|
||||
Stream.runForEach((next) =>
|
||||
mutator
|
||||
@@ -136,7 +138,7 @@ const SettingsWatcherLive = Layer.effectDiscard(
|
||||
* sync with subsequent `streamChanges` emissions.
|
||||
*
|
||||
* The Layer's two halves:
|
||||
* - `ProviderInstanceRegistry.mutableLayer` produces the registry +
|
||||
* - `ProviderInstanceRegistryMutableLayer` produces the registry +
|
||||
* mutator from the initial config map. Its scope owns every
|
||||
* per-instance child scope created during reconcile.
|
||||
* - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber
|
||||
@@ -148,12 +150,12 @@ const SettingsWatcherLive = Layer.effectDiscard(
|
||||
* it, so the visibility leak is harmless in practice.
|
||||
*/
|
||||
export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
ProviderInstanceRegistry,
|
||||
never,
|
||||
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
|
||||
BuiltInDriversEnv | ServerSettingsService
|
||||
> = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
@@ -162,15 +164,11 @@ export const ProviderInstanceRegistryHydrationLive: Layer.Layer<
|
||||
? ({} as ProviderInstanceConfigMap)
|
||||
: deriveProviderInstanceConfigMap(initialSettings);
|
||||
|
||||
const mutableLayer = ProviderInstanceRegistry.mutableLayer({
|
||||
const mutableLayer = ProviderInstanceRegistryMutableLayer({
|
||||
drivers: BUILT_IN_DRIVERS,
|
||||
configMap: initialConfigMap,
|
||||
});
|
||||
|
||||
return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));
|
||||
}),
|
||||
) as Layer.Layer<
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
never,
|
||||
BuiltInDriversEnv | ServerSettingsModule.ServerSettingsService
|
||||
>;
|
||||
) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;
|
||||
+63
-38
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Multi-instance validation slices for `ProviderInstanceRegistry`.
|
||||
* Multi-instance validation slices for `ProviderInstanceRegistryLive`.
|
||||
*
|
||||
* Two axes of the driver/registry refactor are exercised here:
|
||||
*
|
||||
@@ -34,21 +34,23 @@ import {
|
||||
type ProviderInstanceConfigMap,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as Config from "../config.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import { ClaudeDriver } from "./Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "./Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "./Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "./Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver } from "./Drivers/OpenCodeDriver.ts";
|
||||
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
import { CursorDriver } from "../Drivers/CursorDriver.ts";
|
||||
import { GrokDriver } from "../Drivers/GrokDriver.ts";
|
||||
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -57,6 +59,37 @@ const TestHttpClientLive = Layer.succeed(
|
||||
),
|
||||
);
|
||||
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -99,24 +132,20 @@ const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSetti
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
// `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
|
||||
// directory. `Layer.merge` just unions requirements, so we have to push
|
||||
// `NodeServices.layer` through `Layer.provideMerge` to satisfy that
|
||||
// dependency while still surfacing NodeServices to the test body (the
|
||||
// codex driver's `create` yields `ChildProcessSpawner` directly).
|
||||
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
|
||||
const testLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
|
||||
@@ -148,7 +177,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* ProviderInstanceRegistry.make({
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver],
|
||||
configMap,
|
||||
});
|
||||
@@ -214,7 +243,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* ProviderInstanceRegistry.make({
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver],
|
||||
configMap,
|
||||
});
|
||||
@@ -234,32 +263,28 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("ProviderInstanceRegistry — all drivers slice", () => {
|
||||
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
|
||||
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
|
||||
// at construction time, so we wire `OpenCodeRuntime.layer` into the stack.
|
||||
// `OpenCodeRuntime.layer` bundles its own `NetService.layer` via
|
||||
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
|
||||
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
|
||||
// `Layer.provide`, so the only external requirement it still exposes is
|
||||
// `ChildProcessSpawner` — resolved here by piping it through
|
||||
// `provideMerge(NodeServices.layer)`.
|
||||
//
|
||||
// The nested `provideMerge`s read bottom-up: `NodeServices.layer`
|
||||
// provides `OpenCodeRuntime.layer`'s deps while keeping its own outputs
|
||||
// provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
|
||||
// surfaced; that merged layer then provides `ServerConfig.layerTest`'s
|
||||
// `FileSystem` dep while keeping everything else surfaced to the test.
|
||||
const infraLayer = OpenCodeRuntime.layer.pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const testLayer = Config.ServerConfig.layerTest(process.cwd(), {
|
||||
const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
|
||||
const testLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
ProviderEventLoggers.ProviderEventLoggers,
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
it.live("boots one instance of every shipped driver from a single config map", () =>
|
||||
@@ -312,7 +337,7 @@ describe("ProviderInstanceRegistry — all drivers slice", () => {
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* ProviderInstanceRegistry.make({
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
|
||||
configMap,
|
||||
});
|
||||
+26
-97
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* ProviderInstanceRegistry — runtime implementation of
|
||||
* ProviderInstanceRegistryLive — runtime implementation of
|
||||
* `ProviderInstanceRegistry` plus its sibling mutator.
|
||||
*
|
||||
* Materializes every entry in a `ProviderInstanceConfigMap`:
|
||||
@@ -30,7 +30,7 @@
|
||||
* tears every instance down in reverse order; closing a single instance
|
||||
* (via `reconcile` removing it) leaves the rest untouched.
|
||||
*
|
||||
* @module provider/ProviderInstanceRegistry
|
||||
* @module provider/Layers/ProviderInstanceRegistryLive
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
@@ -48,86 +48,19 @@ import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { buildUnavailableProviderSnapshot } from "./unavailableProviderSnapshot.ts";
|
||||
import type { AnyProviderDriver, ProviderInstance } from "./ProviderDriver.ts";
|
||||
|
||||
export class ProviderInstanceRegistry extends Context.Service<
|
||||
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
|
||||
import {
|
||||
ProviderInstanceRegistry,
|
||||
{
|
||||
/**
|
||||
* Look up one instance by id. Returns `undefined` (not `Option`) when the
|
||||
* id is unknown; callers branch on absence and emit the appropriate domain
|
||||
* error.
|
||||
*/
|
||||
readonly getInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstance | undefined>;
|
||||
|
||||
/**
|
||||
* Every available (driver-registered, successfully created) instance, in
|
||||
* stable settings-author order.
|
||||
*/
|
||||
readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
|
||||
|
||||
/**
|
||||
* Wire-shape shadow snapshots for instances whose driver is unknown to this
|
||||
* build or whose config failed to decode. Suitable for merging directly
|
||||
* into `ProviderRegistry` output.
|
||||
*/
|
||||
readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Push notification stream emitted whenever the registry's contents change.
|
||||
* The payload is `void` because consumers always re-pull `listInstances`
|
||||
* and `listUnavailable` together.
|
||||
*
|
||||
* `Stream.fromPubSub` defers `PubSub.subscribe` until the stream starts
|
||||
* running, so forking a consumer races the next publish. Hot-reload
|
||||
* consumers that cannot miss a publish should use `subscribeChanges`
|
||||
* instead, which acquires the subscription synchronously before the
|
||||
* consumer loop is forked.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
|
||||
/**
|
||||
* Acquire a scoped subscription to the change channel synchronously in the
|
||||
* caller's fiber. Consumers typically `yield*` this in the same fiber that
|
||||
* forks their consumer loop, then drain it with `PubSub.take` or
|
||||
* `Stream.fromSubscription`. Because the subscription is registered before
|
||||
* this effect returns, no subsequent publish can land in a gap.
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
>()("t3/provider/ProviderInstanceRegistry") {}
|
||||
|
||||
/**
|
||||
* Internal mutation boundary used only by registry hydration.
|
||||
*
|
||||
* `reconcile` diffs by instance id, closes removed or replaced child scopes
|
||||
* before creating replacements, materializes additions in fresh child scopes,
|
||||
* and publishes one change tick after the batch. Reapplying an unchanged map
|
||||
* is a no-op.
|
||||
*/
|
||||
export class ProviderInstanceRegistryMutator extends Context.Service<
|
||||
type ProviderInstanceRegistryShape,
|
||||
} from "../Services/ProviderInstanceRegistry.ts";
|
||||
import {
|
||||
ProviderInstanceRegistryMutator,
|
||||
{
|
||||
/**
|
||||
* Bring the live registry in line with the supplied config map. The
|
||||
* operation closes removed or replaced scopes before creating replacements
|
||||
* and publishes a single change tick after the batch. Reapplying an
|
||||
* unchanged map is a no-op.
|
||||
*
|
||||
* The effect never fails: individual driver creation failures become
|
||||
* unavailable shadow snapshots, keeping settings-watcher loops alive when
|
||||
* one entry is invalid.
|
||||
*/
|
||||
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/provider/ProviderInstanceRegistry/ProviderInstanceRegistryMutator") {}
|
||||
type ProviderInstanceRegistryMutatorShape,
|
||||
} from "../Services/ProviderInstanceRegistryMutator.ts";
|
||||
import type { AnyProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
|
||||
/**
|
||||
* Live registry entry: the materialized `ProviderInstance` + the fresh
|
||||
@@ -160,8 +93,6 @@ interface RegistryState {
|
||||
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
|
||||
Equal.equals(a, b);
|
||||
|
||||
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
|
||||
|
||||
const decodedConfigEnabled = (config: unknown): boolean | undefined => {
|
||||
if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) {
|
||||
return undefined;
|
||||
@@ -206,13 +137,12 @@ const buildEntry = <R>(input: {
|
||||
const decoder = Schema.decodeUnknownEffect(driver.configSchema);
|
||||
const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
|
||||
if (decodeResult._tag === "Failure") {
|
||||
const cause = decodeResult.failure;
|
||||
const detail = formatSchemaIssue(cause.issue);
|
||||
const issue = decodeResult.failure;
|
||||
const detail = issue.message ?? String(issue);
|
||||
yield* Effect.logError("Failed to decode provider instance config", {
|
||||
instanceId: rawInstanceId,
|
||||
driver: entry.driver,
|
||||
detail,
|
||||
cause,
|
||||
});
|
||||
return {
|
||||
kind: "unavailable" as const,
|
||||
@@ -250,7 +180,6 @@ const buildEntry = <R>(input: {
|
||||
instanceId: rawInstanceId,
|
||||
driver: entry.driver,
|
||||
detail: createResult.failure.detail,
|
||||
cause: createResult.failure,
|
||||
});
|
||||
yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
|
||||
return {
|
||||
@@ -386,9 +315,9 @@ const makeReconcile = <R>(input: {
|
||||
* Build the registry's runtime state from a concrete configMap. Returns a
|
||||
* record containing:
|
||||
*
|
||||
* - `registry`: the read-only `ProviderInstanceRegistry["Service"]` to expose
|
||||
* - `registry`: the read-only `ProviderInstanceRegistryShape` to expose
|
||||
* under `ProviderInstanceRegistry`.
|
||||
* - `mutator`: the `ProviderInstanceRegistryMutator["Service"]` to expose
|
||||
* - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose
|
||||
* under `ProviderInstanceRegistryMutator`.
|
||||
* - `reconcile`: the raw reconcile function, provided for convenience so
|
||||
* boot-time layers can hydrate an initial map before publishing the
|
||||
@@ -398,13 +327,13 @@ const makeReconcile = <R>(input: {
|
||||
* created during `reconcile`. Closing that scope closes every live
|
||||
* instance.
|
||||
*/
|
||||
export const make = <R>(input: {
|
||||
export const makeProviderInstanceRegistry = <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
}): Effect.Effect<
|
||||
{
|
||||
readonly registry: ProviderInstanceRegistry["Service"];
|
||||
readonly mutator: ProviderInstanceRegistryMutator["Service"];
|
||||
readonly registry: ProviderInstanceRegistryShape;
|
||||
readonly mutator: ProviderInstanceRegistryMutatorShape;
|
||||
},
|
||||
never,
|
||||
R | Scope.Scope
|
||||
@@ -433,14 +362,14 @@ export const make = <R>(input: {
|
||||
|
||||
const state: RegistryState = { entries, unavailable, changes };
|
||||
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
|
||||
const reconcile: ProviderInstanceRegistryMutator["Service"]["reconcile"] = (configMap) =>
|
||||
const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
|
||||
reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
|
||||
|
||||
// Hydrate the initial configMap synchronously so callers can read
|
||||
// `listInstances` immediately after this effect completes.
|
||||
yield* reconcile(input.configMap);
|
||||
|
||||
const registry = ProviderInstanceRegistry.of({
|
||||
const registry: ProviderInstanceRegistryShape = {
|
||||
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
|
||||
listInstances: Ref.get(entries).pipe(
|
||||
Effect.map(
|
||||
@@ -466,9 +395,9 @@ export const make = <R>(input: {
|
||||
get subscribeChanges() {
|
||||
return PubSub.subscribe(changes);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const mutator = ProviderInstanceRegistryMutator.of({ reconcile });
|
||||
const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };
|
||||
|
||||
return { registry, mutator };
|
||||
});
|
||||
@@ -480,15 +409,15 @@ export const make = <R>(input: {
|
||||
* wiring up the settings watcher.
|
||||
*
|
||||
* Only exposes the public registry tag — hot-reload consumers should use
|
||||
* `mutableLayer` (below) or the hydration layer.
|
||||
* `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.
|
||||
*/
|
||||
export const layer = <R>(input: {
|
||||
export const ProviderInstanceRegistryLayer = <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
}): Layer.Layer<ProviderInstanceRegistry, never, R> =>
|
||||
Layer.effect(
|
||||
ProviderInstanceRegistry,
|
||||
make(input).pipe(Effect.map((built) => built.registry)),
|
||||
makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),
|
||||
) as Layer.Layer<ProviderInstanceRegistry, never, R>;
|
||||
|
||||
/**
|
||||
@@ -497,12 +426,12 @@ export const layer = <R>(input: {
|
||||
* changes. Tests that exercise the mutator directly can pair this Layer
|
||||
* with a test-local `ServerSettingsService`.
|
||||
*/
|
||||
export const mutableLayer = <R>(input: {
|
||||
export const ProviderInstanceRegistryMutableLayer = <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>
|
||||
Layer.effectContext(
|
||||
make(input).pipe(
|
||||
makeProviderInstanceRegistry(input).pipe(
|
||||
Effect.map(({ registry, mutator }) =>
|
||||
Context.make(ProviderInstanceRegistry, registry).pipe(
|
||||
Context.add(ProviderInstanceRegistryMutator, mutator),
|
||||
+88
-154
@@ -1,8 +1,8 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
@@ -25,32 +25,32 @@ import {
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as HttpClient from "effect/unstable/http/HttpClient";
|
||||
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import {
|
||||
checkCodexProviderStatus,
|
||||
type CodexAppServerProviderSnapshot,
|
||||
} from "./Layers/CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./Layers/ClaudeProvider.ts";
|
||||
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
|
||||
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import * as OpenCodeRuntime from "../opencodeRuntime.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./Layers/ProviderInstanceRegistryHydration.ts";
|
||||
import * as ProviderRegistry from "./ProviderRegistry.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerSettingsModule from "../serverSettings.ts";
|
||||
import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts";
|
||||
import {
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "./ProviderDriver.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
mergeProviderSnapshots,
|
||||
ProviderRegistryLive,
|
||||
selectProvidersByKind,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import * as ServerConfig from "../../config.ts";
|
||||
import * as ServerSettingsModule from "../../serverSettings.ts";
|
||||
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
|
||||
import * as ProviderRegistry from "../Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
const decodeServerSettings = Schema.decodeSync(ServerSettings);
|
||||
const encodeServerSettings = Schema.encodeSync(ServerSettings);
|
||||
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
|
||||
@@ -66,6 +66,7 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
@@ -74,6 +75,35 @@ const TestHttpClientLive = Layer.succeed(
|
||||
),
|
||||
);
|
||||
|
||||
const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
reportClientActivity: () => Effect.void,
|
||||
removeRpcClient: () => Effect.void,
|
||||
reportHostPowerState: () => Effect.void,
|
||||
snapshot: Effect.succeed({
|
||||
hostPower: {
|
||||
source: "unknown",
|
||||
idle: "unknown",
|
||||
idleSeconds: null,
|
||||
locked: "unknown",
|
||||
suspended: false,
|
||||
onBattery: "unknown",
|
||||
lowPowerMode: "unknown",
|
||||
thermalState: "unknown",
|
||||
stale: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
},
|
||||
leases: [],
|
||||
activeForegroundLeaseCount: 0,
|
||||
activeScopeKeys: [],
|
||||
shouldRunOpportunisticWork: true,
|
||||
updatedAt: TEST_EPOCH,
|
||||
}),
|
||||
streamChanges: Stream.empty,
|
||||
hasDemand: () => Effect.succeed(true),
|
||||
shouldRunScopeWork: () => Effect.succeed(true),
|
||||
shouldRunOpportunisticWork: Effect.succeed(true),
|
||||
});
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -473,7 +503,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
});
|
||||
|
||||
describe("ProviderRegistry", () => {
|
||||
describe("ProviderRegistryLive", () => {
|
||||
it("treats equal provider snapshots as unchanged", () => {
|
||||
const providers = [
|
||||
{
|
||||
@@ -504,7 +534,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
assert.strictEqual(ProviderRegistry.haveProvidersChanged(providers, [...providers]), false);
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it("preserves previously discovered provider models when a refresh returns none", () => {
|
||||
@@ -542,10 +572,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(
|
||||
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
|
||||
[...previousProvider.models],
|
||||
);
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it("fills missing capabilities from the previous provider snapshot", () => {
|
||||
@@ -592,10 +621,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(
|
||||
ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
|
||||
[...previousProvider.models],
|
||||
);
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("does not run provider probes during layer construction", () =>
|
||||
@@ -654,10 +682,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-background-refresh-",
|
||||
}),
|
||||
),
|
||||
@@ -722,10 +750,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
const mergedProviders = ProviderRegistry.mergeProviderSnapshots(previousProviders, [
|
||||
refreshedCursor,
|
||||
]);
|
||||
const persistedProviders = ProviderRegistry.selectProvidersByKind(
|
||||
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
|
||||
const persistedProviders = selectProvidersByKind(
|
||||
mergedProviders,
|
||||
new Set([ProviderDriverKind.make("cursor")]),
|
||||
);
|
||||
@@ -811,13 +837,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -854,105 +881,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("only keeps hydrated cache state while the boot snapshot is still initial", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
const fallbackProvider = {
|
||||
instanceId: codexInstanceId,
|
||||
driver: codexDriver,
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-04-29T10:01:00.000Z",
|
||||
version: null,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
message: "Codex provider status has not been checked in this session yet.",
|
||||
} as const satisfies ServerProvider;
|
||||
const cachedProvider = {
|
||||
...fallbackProvider,
|
||||
status: "ready",
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-29T10:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
message: "Loaded from the provider status cache.",
|
||||
} as const satisfies ServerProvider;
|
||||
const loadProviders = (snapshotState: "initial" | "live") =>
|
||||
Effect.gen(function* () {
|
||||
const instance = {
|
||||
instanceId: codexInstanceId,
|
||||
driverKind: codexDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: codexDriver,
|
||||
continuationKey: "codex:instance:codex",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(fallbackProvider),
|
||||
isInitialSnapshot: () => snapshotState === "initial",
|
||||
refresh: Effect.succeed(fallbackProvider),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
{
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
},
|
||||
);
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: `t3-provider-registry-cache-${snapshotState}-`,
|
||||
});
|
||||
const configLayer = ServerConfig.layerTest(process.cwd(), baseDir);
|
||||
const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(configLayer));
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: codexInstanceId,
|
||||
});
|
||||
yield* writeProviderStatusCache({ filePath, provider: cachedProvider });
|
||||
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.fresh(
|
||||
ProviderRegistry.layer.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(configLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
return yield* ProviderRegistry.ProviderRegistry.pipe(
|
||||
Effect.flatMap((registry) => registry.getProviders),
|
||||
Effect.provide(runtimeServices),
|
||||
);
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* loadProviders("initial"), [cachedProvider]);
|
||||
assert.deepStrictEqual(yield* loadProviders("live"), [fallbackProvider]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
@@ -1007,13 +935,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-refresh-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -1114,13 +1043,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistry.layer.pipe(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-sync-failure-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
@@ -1207,13 +1137,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1224,7 +1154,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
// outer `NodeServices.layer` on `it.layer(...)` and will
|
||||
// genuinely spawn a subprocess. The missing-binary ENOENT is
|
||||
@@ -1299,13 +1230,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1316,7 +1247,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
|
||||
ChildProcessSpawner.make((command) => {
|
||||
spawnedCommands.push((command as { readonly command: string }).command);
|
||||
@@ -1324,6 +1255,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1420,13 +1352,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1437,8 +1369,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
@@ -1481,13 +1414,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
let cursorSpawned = false;
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistry.layer.pipe(
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
@@ -1498,7 +1431,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
ProviderEventLoggers.NoOpProviderEventLoggers,
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(OpenCodeRuntime.layer),
|
||||
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "agent") {
|
||||
@@ -0,0 +1,698 @@
|
||||
/**
|
||||
* ProviderRegistryLive — aggregates per-instance snapshot streams into a
|
||||
* single materialized list.
|
||||
*
|
||||
* Historically this Layer composed four per-kind Live Layers
|
||||
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
|
||||
* `ServerProviderShape`. Those Lives were deleted during the driver /
|
||||
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
|
||||
* bundled onto the `ProviderInstance` the registry produces.
|
||||
*
|
||||
* Each configured instance (including multi-instance setups like
|
||||
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
|
||||
* keyed by `instanceId`. Instances whose driver is unavailable or whose
|
||||
* config failed to decode are merged from `instanceRegistry.listUnavailable`
|
||||
* as shadow snapshots so the UI can render their exact unavailable reason.
|
||||
*
|
||||
* Cache paths on disk are now keyed by `instanceId`. Because
|
||||
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
|
||||
* `<kind>.json` files remain the on-disk location for that driver's default
|
||||
* instance. Identity-less legacy cache contents are ignored and replaced by
|
||||
* the first live refresh.
|
||||
*
|
||||
* @module ProviderRegistryLive
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
isCachedProviderCorrelated,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
const loadProviders = (
|
||||
providerSources: ReadonlyArray<ProviderSnapshotSource>,
|
||||
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
|
||||
Effect.forEach(
|
||||
providerSources,
|
||||
(providerSource) =>
|
||||
providerSource.getSnapshot.pipe(
|
||||
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
const mergeProviderModels = (
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
if (nextModels.length === 0 && previousModels.length > 0) {
|
||||
return previousModels;
|
||||
}
|
||||
|
||||
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
|
||||
const mergedModels = nextModels.map((model) => {
|
||||
const previousModel = previousBySlug.get(model.slug);
|
||||
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
|
||||
return model;
|
||||
}
|
||||
return {
|
||||
...model,
|
||||
capabilities: previousModel.capabilities,
|
||||
};
|
||||
});
|
||||
const nextSlugs = new Set(nextModels.map((model) => model.slug));
|
||||
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshot = (
|
||||
previousProvider: ServerProvider | undefined,
|
||||
nextProvider: ServerProvider,
|
||||
): ServerProvider =>
|
||||
!previousProvider
|
||||
? nextProvider
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
const correlateSnapshotWithSource = (
|
||||
source: ProviderSnapshotSource,
|
||||
snapshot: ServerProvider,
|
||||
): Effect.Effect<ServerProvider> => {
|
||||
if (snapshot.instanceId !== source.instanceId) {
|
||||
return Effect.die(
|
||||
new Error(
|
||||
`Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (snapshot.driver !== source.driverKind) {
|
||||
return Effect.die(
|
||||
new Error(
|
||||
`Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(snapshot);
|
||||
};
|
||||
|
||||
/**
|
||||
* Key a snapshot for aggregation and persistence. Snapshot sources
|
||||
* must be correlated by instance id before reaching this map; missing
|
||||
* identities are defects, not runtime routing fallbacks.
|
||||
*/
|
||||
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
|
||||
return provider.instanceId;
|
||||
};
|
||||
|
||||
// Project a live `ProviderInstance` into the aggregator's consumption
|
||||
// shape. Each call re-captures the instance's `snapshot` closures, so
|
||||
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
|
||||
// its settings changed), a fresh source rides the new PubSub instead
|
||||
// of a closed one.
|
||||
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
getSnapshot: instance.snapshot.getSnapshot,
|
||||
refresh: instance.snapshot.refresh,
|
||||
streamChanges: instance.snapshot.streamChanges,
|
||||
});
|
||||
|
||||
export const ProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const instanceRegistry = yield* ProviderInstanceRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
|
||||
// coalesced updates across every instance.
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
|
||||
// Boot-only: hydrate `providersRef` from the on-disk per-instance
|
||||
// cache so the UI has something to render during the first refresh.
|
||||
// Instances added post-boot skip this path; their first entry in
|
||||
// `providersRef` comes from the reactive `syncLiveSources` pass
|
||||
// below.
|
||||
const bootInstances = yield* instanceRegistry.listInstances;
|
||||
const bootSources = bootInstances.map(buildSnapshotSource);
|
||||
const fallbackProviders = yield* loadProviders(bootSources);
|
||||
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
|
||||
for (let index = 0; index < fallbackProviders.length; index++) {
|
||||
const provider = fallbackProviders[index];
|
||||
const source = bootSources[index];
|
||||
if (provider === undefined || source === undefined) {
|
||||
continue;
|
||||
}
|
||||
fallbackByInstance.set(source.instanceId, provider);
|
||||
}
|
||||
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
bootSources,
|
||||
(source) =>
|
||||
Effect.gen(function* () {
|
||||
// One cache file per configured instance. For the default
|
||||
// instance of a built-in kind the path equals `<kind>.json` —
|
||||
// identical to the legacy filename. We still require the cache
|
||||
// payload to carry matching instance id + driver kind; old
|
||||
// identity-less payloads are discarded and the awaited refresh
|
||||
// below repopulates the cache.
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: source.instanceId,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
const fallbackProvider = fallbackByInstance.get(source.instanceId);
|
||||
if (fallbackProvider === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return yield* readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.flatMap((cachedProvider) => {
|
||||
if (cachedProvider === undefined) {
|
||||
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
const correlation = {
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
} as const;
|
||||
if (!isCachedProviderCorrelated(correlation)) {
|
||||
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
|
||||
path: filePath,
|
||||
instanceId: source.instanceId,
|
||||
cachedInstanceId: cachedProvider.instanceId ?? null,
|
||||
driver: source.driverKind,
|
||||
cachedDriver: cachedProvider.driver ?? null,
|
||||
}).pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
return Effect.succeed(hydrateCachedProvider(correlation));
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
// reference is used for identity equality so "no-op" reconciles
|
||||
// (settings unchanged) skip re-subscribing + re-probing.
|
||||
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(
|
||||
new Map(),
|
||||
);
|
||||
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
|
||||
// interleave two passes clobbering each other's fiber bookkeeping.
|
||||
const syncSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
|
||||
liveSubsRef,
|
||||
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
|
||||
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
Effect.gen(function* () {
|
||||
// Persist every instance — the file name is the instance id, so
|
||||
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
|
||||
// get their own cache. We resolve the path fresh so snapshots
|
||||
// produced by newly-added instances post-boot still land on disk
|
||||
// without the aggregator holding a stale `cachePathByInstance`
|
||||
// entry.
|
||||
const key = snapshotInstanceKey(provider);
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: key,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
yield* writeProviderStatusCache({ filePath, provider }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
readonly persist?: boolean;
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
? provider
|
||||
: mergeProviderSnapshot(mergedProviders.get(key), provider),
|
||||
);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
return yield* providerSource.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) =>
|
||||
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshAll = Effect.fn("refreshAll")(function* () {
|
||||
const sources = yield* getLiveSources;
|
||||
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
|
||||
if (provider === undefined) {
|
||||
return yield* refreshAll();
|
||||
}
|
||||
// Kind-scoped refreshes target the default instance for that driver.
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(provider);
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find(
|
||||
(candidate) => candidate.instanceId === defaultInstanceId,
|
||||
);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const refreshInstance = Effect.fn("refreshInstance")(function* (
|
||||
instanceId: ProviderInstanceId,
|
||||
) {
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
* - subscribe to each newly-added or rebuilt instance's
|
||||
* `streamChanges` (so periodic + enrichment refreshes land in
|
||||
* `providersRef`);
|
||||
* - read each newly-added/rebuilt instance's current snapshot after
|
||||
* subscribing, closing the race with its independently-running
|
||||
* background startup probe;
|
||||
* - prune `providersRef` of instances that no longer exist.
|
||||
*
|
||||
* Provider refreshes are owned by each managed provider and never run
|
||||
* on this layer's construction path. Consumers see cached or pending
|
||||
* snapshots immediately, then receive live probe results through the
|
||||
* already-attached change stream.
|
||||
*
|
||||
* Per-instance subscription fibers are not tracked explicitly. When
|
||||
* a rebuilt instance's old child scope closes, its PubSub shuts
|
||||
* down and our `Stream.runForEach` fiber exits naturally.
|
||||
*/
|
||||
const syncLiveSources = syncSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const instances = yield* instanceRegistry.listInstances;
|
||||
const unavailableProviders = yield* instanceRegistry.listUnavailable;
|
||||
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
|
||||
instances.map((instance) => [instance.instanceId, instance] as const),
|
||||
);
|
||||
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
|
||||
for (const provider of unavailableProviders) {
|
||||
knownInstanceIds.add(snapshotInstanceKey(provider));
|
||||
}
|
||||
const previousSubs = yield* Ref.get(liveSubsRef);
|
||||
|
||||
// Carry over subscriptions for instances whose identity is
|
||||
// unchanged (reconcile treated them as no-op). Instances that
|
||||
// disappeared, or were rebuilt with a different reference,
|
||||
// fall through to the "newly-added" branch below.
|
||||
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
|
||||
for (const [instanceId, previousInstance] of previousSubs) {
|
||||
const nextInstance = nextByInstance.get(instanceId);
|
||||
if (nextInstance !== undefined && nextInstance === previousInstance) {
|
||||
carriedOver.set(instanceId, previousInstance);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect new/rebuilt instances in `nextByInstance` insertion
|
||||
// order (which preserves settings-author order).
|
||||
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
|
||||
for (const [instanceId, instance] of nextByInstance) {
|
||||
if (carriedOver.has(instanceId)) {
|
||||
continue;
|
||||
}
|
||||
newlyAdded.push([instanceId, instance] as const);
|
||||
}
|
||||
|
||||
// Fork long-lived subscriptions to each new/rebuilt instance's
|
||||
// change stream before reading its current snapshot. If the
|
||||
// driver's own initial probe finishes during this sync, either
|
||||
// the current read or the active subscriber observes the result.
|
||||
for (const [, instance] of newlyAdded) {
|
||||
const source = buildSnapshotSource(instance);
|
||||
yield* Stream.runForEach(source.streamChanges, (provider) =>
|
||||
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// Snapshot current state without starting a probe. Managed providers
|
||||
// launch their startup refresh independently, so this closes the
|
||||
// subscription race without putting external work on the registry
|
||||
// or HTTP server construction path.
|
||||
yield* Effect.forEach(
|
||||
newlyAdded,
|
||||
([, instance]) =>
|
||||
Effect.gen(function* () {
|
||||
const source = buildSnapshotSource(instance);
|
||||
const provider = yield* source.getSnapshot;
|
||||
yield* correlateSnapshotWithSource(source, provider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
);
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
yield* upsertProviders(unavailableProviders, {
|
||||
persist: false,
|
||||
replace: true,
|
||||
});
|
||||
|
||||
const nextSubs = new Map(carriedOver);
|
||||
for (const [instanceId, instance] of newlyAdded) {
|
||||
nextSubs.set(instanceId, instance);
|
||||
}
|
||||
yield* Ref.set(liveSubsRef, nextSubs);
|
||||
|
||||
// Drop aggregator state for instances that have disappeared —
|
||||
// otherwise the UI would keep rendering ghosts.
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const providers = orderProviderSnapshots(
|
||||
previousProviders.filter((provider) =>
|
||||
knownInstanceIds.has(snapshotInstanceKey(provider)),
|
||||
),
|
||||
);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.logError(
|
||||
"provider registry instance sync failed; keeping subscription alive",
|
||||
{
|
||||
cause: Cause.pretty(cause),
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
// Seed `providersRef` with the boot-time fallback snapshots so
|
||||
// consumers calling `getProviders` immediately after layer build see
|
||||
// a populated list — even before the first `syncLiveSources` refresh
|
||||
// resolves. Cached snapshots (already in `providersRef`) merge with
|
||||
// these via `upsertProviders` so on-disk state wins where present
|
||||
// and pending fallbacks fill the gaps.
|
||||
yield* upsertProviders(fallbackProviders, { publish: false });
|
||||
// Subscribe to registry mutations BEFORE running the initial sync.
|
||||
// `subscribeChanges` acquires the dequeue synchronously in this
|
||||
// fibre; the subscription is active the instant this `yield*`
|
||||
// returns. Forking the consumer loop later cannot lose a publish
|
||||
// because no publish can reach a not-yet-subscribed dequeue.
|
||||
//
|
||||
// (Contrast with the pre-fix code that did
|
||||
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
|
||||
// `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,
|
||||
// and `forkScoped` only schedules the fibre — so a reconcile that
|
||||
// published between "fibre scheduled" and "fibre starts running"
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
// Subscribe to registry mutations BEFORE running the initial sync.
|
||||
// `subscribeChanges` acquires the `PubSub.Subscription` synchronously
|
||||
// in this fibre; the subscription is registered with the PubSub the
|
||||
// instant this `yield*` returns, so any subsequent publish is
|
||||
// buffered in the subscription regardless of when the consumer
|
||||
// fibre below actually starts running.
|
||||
//
|
||||
// (Contrast with the pre-fix code that did
|
||||
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
|
||||
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
|
||||
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
|
||||
// schedules the consumer fibre — so a reconcile that published
|
||||
// between "fibre scheduled" and "fibre starts running + subscribes"
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
const instanceChanges = yield* instanceRegistry.subscribeChanges;
|
||||
// Initial sync attaches subscriptions and snapshots current state for
|
||||
// every instance present at boot. Provider probes are already running in
|
||||
// their managed background fibers and never block this layer.
|
||||
yield* syncLiveSources;
|
||||
// React to registry mutations — instance added / removed / rebuilt.
|
||||
// `Stream.fromSubscription` builds a stream over the pre-acquired
|
||||
// subscription rather than subscribing on stream start, which is
|
||||
// what closes the race.
|
||||
yield* Stream.runForEach(
|
||||
Stream.fromSubscription(instanceChanges),
|
||||
() => syncLiveSourcesAndContinue,
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
|
||||
cause: Cause.Cause<unknown>,
|
||||
) {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
return yield* Ref.get(providersRef);
|
||||
});
|
||||
|
||||
return {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderDriverKind) =>
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
);
|
||||
+38
-84
@@ -30,7 +30,6 @@ import * as Metric from "effect/Metric";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
@@ -42,27 +41,23 @@ import {
|
||||
ProviderUnsupportedError,
|
||||
ProviderValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "./ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
} from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "../Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
|
||||
import { makeProviderServiceLive } from "./ProviderService.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
|
||||
import { makeAdapterRegistryMock } from "./testUtils/providerAdapterRegistryMock.ts";
|
||||
|
||||
// Several tests build two ProviderService instances in one scope to simulate a
|
||||
// process restart. Construct a fresh Layer for each build so Layer memoization
|
||||
// cannot reuse the first service instance.
|
||||
const makeFreshProviderServiceLayer = (options?: ProviderService.ProviderServiceOptions) =>
|
||||
Layer.effect(ProviderService.ProviderService, ProviderService.make(options));
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import * as ServerSettings from "../../serverSettings.ts";
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
|
||||
|
||||
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
|
||||
@@ -289,11 +284,11 @@ function makeProviderServiceLayer() {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
makeFreshProviderServiceLayer().pipe(
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -342,11 +337,9 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = Layer.mergeAll(
|
||||
makeFreshProviderServiceLayer().pipe(
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -404,10 +397,8 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -488,10 +479,10 @@ it.effect(
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(serverSettingsLayer),
|
||||
@@ -560,10 +551,8 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -607,10 +596,8 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const providerLayer = makeFreshProviderServiceLayer({
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive({
|
||||
canonicalEventLogger: {
|
||||
filePath: "memory://provider-canonical-events",
|
||||
write: (event, threadId) => {
|
||||
@@ -669,9 +656,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
@@ -682,7 +667,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
});
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
const providerLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
@@ -743,10 +728,10 @@ it.effect(
|
||||
[ProviderDriverKind.make("codex")]: firstCodex.adapter,
|
||||
});
|
||||
|
||||
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
@@ -802,10 +787,10 @@ it.effect(
|
||||
const secondRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: secondCodex.adapter,
|
||||
});
|
||||
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
@@ -1086,18 +1071,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
|
||||
const exit = yield* Effect.exit(provider.listSessions());
|
||||
assert.equal(Exit.hasDies(exit), true);
|
||||
const defect = Exit.findDefect(exit);
|
||||
assert.equal(Result.isSuccess(defect), true);
|
||||
if (Result.isSuccess(defect)) {
|
||||
assert.instanceOf(defect.success, ProviderService.ProviderSessionBindingCorrelationError);
|
||||
assert.deepInclude(defect.success, {
|
||||
threadId,
|
||||
sessionProvider: ProviderDriverKind.make("codex"),
|
||||
bindingProvider: ProviderDriverKind.make("claudeAgent"),
|
||||
sessionInstanceId: codexInstanceId,
|
||||
bindingInstanceId: claudeAgentInstanceId,
|
||||
});
|
||||
}
|
||||
yield* directory.upsert({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
@@ -1325,10 +1298,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const firstRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
|
||||
});
|
||||
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
@@ -1363,10 +1336,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const secondRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
|
||||
});
|
||||
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
@@ -1431,10 +1404,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const firstRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter,
|
||||
});
|
||||
const firstDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const firstProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry),
|
||||
),
|
||||
@@ -1464,10 +1437,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const secondRegistry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter,
|
||||
});
|
||||
const secondDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const secondProviderLayer = makeFreshProviderServiceLayer().pipe(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry),
|
||||
),
|
||||
@@ -1810,25 +1783,6 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
|
||||
const validation = makeProviderServiceLayer();
|
||||
validation.layer("ProviderServiceLive validation", (it) => {
|
||||
it.effect("rejects whitespace-only turns without attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
|
||||
validation.codex.sendTurn.mockClear();
|
||||
const failure = yield* provider
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-whitespace-only"),
|
||||
input: " \n\t ",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(failure, ProviderValidationError);
|
||||
assert.equal(failure.operation, "ProviderService.sendTurn");
|
||||
assert.equal(validation.codex.sendTurn.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects session starts without an explicit provider instance id", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
+225
-326
@@ -1,15 +1,13 @@
|
||||
/**
|
||||
* ProviderService - Cross-provider session and turn service.
|
||||
* ProviderServiceLive - Cross-provider orchestration layer.
|
||||
*
|
||||
* Routes validated transport/API calls to provider adapters through
|
||||
* `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a
|
||||
* unified provider event stream for subscribers.
|
||||
*
|
||||
* It does not implement provider protocol details (adapter concern).
|
||||
* Uses Effect `Context.Service` for dependency injection and returns typed
|
||||
* domain errors for validation, session, codex, and checkpoint workflows.
|
||||
*
|
||||
* @module ProviderService
|
||||
* @module ProviderServiceLive
|
||||
*/
|
||||
import {
|
||||
ModelSelection,
|
||||
@@ -21,13 +19,12 @@ import {
|
||||
ProviderSendTurnInput,
|
||||
ProviderSessionStartInput,
|
||||
ProviderStopSessionInput,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -47,141 +44,17 @@ import {
|
||||
providerTurnsTotal,
|
||||
providerTurnMetricAttributes,
|
||||
withMetrics,
|
||||
} from "../observability/Metrics.ts";
|
||||
import {
|
||||
type ProviderAdapterError,
|
||||
type ProviderServiceError,
|
||||
ProviderValidationError,
|
||||
} from "./Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterCapabilities,
|
||||
ProviderAdapterShape,
|
||||
} from "./Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts";
|
||||
} from "../../observability/Metrics.ts";
|
||||
import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
|
||||
import * as ProviderService from "../Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts";
|
||||
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
|
||||
import {
|
||||
clearAllMcpProviderSessions,
|
||||
clearMcpProviderSession,
|
||||
setMcpProviderSession,
|
||||
} from "../mcp/McpProviderSession.ts";
|
||||
import {
|
||||
issueActiveMcpCredential,
|
||||
revokeActiveMcpThread,
|
||||
revokeAllActiveMcpCredentials,
|
||||
} from "../mcp/McpSessionRegistry.ts";
|
||||
|
||||
export class ProviderBindingInstanceIdMissingError extends Schema.TaggedErrorClass<ProviderBindingInstanceIdMissingError>()(
|
||||
"ProviderBindingInstanceIdMissingError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
provider: Schema.optional(ProviderDriverKind),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const provider = this.provider === undefined ? "" : ` for provider '${this.provider}'`;
|
||||
return `Provider binding is missing an instance id${provider} in ${this.operation}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderRuntimeEventCorrelationError extends Schema.TaggedErrorClass<ProviderRuntimeEventCorrelationError>()(
|
||||
"ProviderRuntimeEventCorrelationError",
|
||||
{
|
||||
sourceInstanceId: ProviderInstanceId,
|
||||
sourceProvider: ProviderDriverKind,
|
||||
eventInstanceId: Schema.optional(ProviderInstanceId),
|
||||
eventProvider: ProviderDriverKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const eventInstanceId = this.eventInstanceId ?? "unattributed";
|
||||
return `Provider runtime event correlation failed for source instance '${this.sourceInstanceId}' (${this.sourceProvider}) and emitted instance '${eventInstanceId}' (${this.eventProvider}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderSessionBindingCorrelationError extends Schema.TaggedErrorClass<ProviderSessionBindingCorrelationError>()(
|
||||
"ProviderSessionBindingCorrelationError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
sessionProvider: ProviderDriverKind,
|
||||
bindingProvider: ProviderDriverKind,
|
||||
sessionInstanceId: ProviderInstanceId,
|
||||
bindingInstanceId: ProviderInstanceId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Active provider session and persisted binding disagree for thread '${this.threadId}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderService extends Context.Service<
|
||||
ProviderService,
|
||||
{
|
||||
/** Start a provider session. */
|
||||
readonly startSession: (
|
||||
threadId: ThreadId,
|
||||
input: ProviderSessionStartInput,
|
||||
) => Effect.Effect<ProviderSession, ProviderServiceError>;
|
||||
|
||||
/** Send a turn through the adapter bound to the session. */
|
||||
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 structured provider 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>;
|
||||
|
||||
/** Read routing metadata for a configured provider instance. */
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderAdapterRegistry.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>;
|
||||
}
|
||||
>()("t3/provider/ProviderService") {}
|
||||
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
/**
|
||||
@@ -189,15 +62,30 @@ const isModelSelection = Schema.is(ModelSelection);
|
||||
* from `ProviderEventLoggers`. Production wiring leaves this undefined and
|
||||
* reads the logger off the tag.
|
||||
*/
|
||||
export interface ProviderServiceOptions {
|
||||
export interface ProviderServiceLiveOptions {
|
||||
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
|
||||
ProviderService.ProviderService["Service"][Name];
|
||||
|
||||
const ProviderRollbackConversationInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
numTurns: NonNegativeInt,
|
||||
});
|
||||
|
||||
function toValidationError(
|
||||
operation: string,
|
||||
issue: string,
|
||||
cause?: unknown,
|
||||
): ProviderValidationError {
|
||||
return new ProviderValidationError({
|
||||
operation,
|
||||
issue,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const decodeInputOrValidationError = <S extends Schema.Top>(input: {
|
||||
readonly operation: string;
|
||||
readonly schema: S;
|
||||
@@ -284,10 +172,11 @@ const dieOnMissingBindingInstanceId = (
|
||||
if (payload.providerInstanceId !== undefined) {
|
||||
return payload.providerInstanceId;
|
||||
}
|
||||
throw new ProviderBindingInstanceIdMissingError({
|
||||
operation,
|
||||
...(payload.provider === undefined ? {} : { provider: payload.provider }),
|
||||
});
|
||||
throw new Error(
|
||||
payload.provider
|
||||
? `${operation}: provider instance id is required for provider '${payload.provider}'.`
|
||||
: `${operation}: provider instance id is required.`,
|
||||
);
|
||||
};
|
||||
|
||||
const correlateRuntimeEventWithInstance = (
|
||||
@@ -297,23 +186,22 @@ const correlateRuntimeEventWithInstance = (
|
||||
},
|
||||
event: ProviderRuntimeEvent,
|
||||
): ProviderRuntimeEvent => {
|
||||
if (
|
||||
event.provider !== source.provider ||
|
||||
(event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId)
|
||||
) {
|
||||
throw new ProviderRuntimeEventCorrelationError({
|
||||
sourceInstanceId: source.instanceId,
|
||||
sourceProvider: source.provider,
|
||||
...(event.providerInstanceId === undefined
|
||||
? {}
|
||||
: { eventInstanceId: event.providerInstanceId }),
|
||||
eventProvider: event.provider,
|
||||
});
|
||||
if (event.provider !== source.provider) {
|
||||
throw new Error(
|
||||
`ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,
|
||||
);
|
||||
}
|
||||
if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {
|
||||
throw new Error(
|
||||
`ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,
|
||||
);
|
||||
}
|
||||
return { ...event, providerInstanceId: source.instanceId };
|
||||
};
|
||||
|
||||
export const make = Effect.fn("ProviderService.make")(function* (options?: ProviderServiceOptions) {
|
||||
const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
options?: ProviderServiceLiveOptions,
|
||||
) {
|
||||
const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
|
||||
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
|
||||
// Options-provided logger wins (test overrides); otherwise we take whatever
|
||||
@@ -327,14 +215,16 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
|
||||
issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
|
||||
McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
|
||||
Effect.tap((credential) =>
|
||||
credential ? Effect.sync(() => setMcpProviderSession(credential.config)) : Effect.void,
|
||||
credential
|
||||
? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
const clearMcpSession = (threadId: ThreadId) =>
|
||||
revokeActiveMcpThread(threadId).pipe(
|
||||
Effect.tap(() => Effect.sync(() => clearMcpProviderSession(threadId))),
|
||||
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
|
||||
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
|
||||
);
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
@@ -358,12 +248,12 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
payload.providerInstanceId !== undefined
|
||||
? Effect.succeed(payload.providerInstanceId)
|
||||
: Effect.fail(
|
||||
new ProviderValidationError({
|
||||
toValidationError(
|
||||
operation,
|
||||
issue: payload.provider
|
||||
payload.provider
|
||||
? `Provider instance id is required for provider '${payload.provider}'.`
|
||||
: "Provider instance id is required.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const upsertSessionBinding = (
|
||||
@@ -498,10 +388,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
}
|
||||
|
||||
if (!hasResumeCursor) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
@@ -521,10 +411,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
.pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));
|
||||
if (resumed.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(input.binding.threadId);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(
|
||||
@@ -555,10 +445,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
const bindingOption = yield* directory.getBinding(input.threadId);
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (!binding) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: input.operation,
|
||||
issue: `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
);
|
||||
}
|
||||
const instanceId = yield* requireBindingInstanceId(input.operation, binding);
|
||||
const adapter = yield* registry.getByInstance(instanceId);
|
||||
@@ -629,7 +519,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
);
|
||||
});
|
||||
|
||||
const startSession: ProviderService["Service"]["startSession"] = Effect.fn("startSession")(
|
||||
const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")(
|
||||
function* (threadId, rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
@@ -653,10 +543,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
const resolvedProvider = instanceInfo.driverKind;
|
||||
metricProvider = resolvedProvider;
|
||||
if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,
|
||||
);
|
||||
}
|
||||
const input = {
|
||||
...parsed,
|
||||
@@ -664,10 +554,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
provider: resolvedProvider,
|
||||
};
|
||||
if (!instanceInfo.enabled) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,
|
||||
);
|
||||
}
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
@@ -712,10 +602,10 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
yield* clearMcpSession(threadId);
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
issue: `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
});
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
);
|
||||
}
|
||||
const sessionWithInstance = {
|
||||
...session,
|
||||
@@ -752,84 +642,82 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const sendTurn: ProviderService["Service"]["sendTurn"] = Effect.fn("sendTurn")(
|
||||
function* (rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
attachments: parsed.attachments ?? [],
|
||||
};
|
||||
if (!input.input?.trim() && input.attachments.length === 0) {
|
||||
return yield* new ProviderValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
issue: "Either input text or at least one attachment is required",
|
||||
});
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "send-turn",
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.interaction_mode": input.interactionMode,
|
||||
"provider.attachment_count": input.attachments.length,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
let metricModel = input.modelSelection?.model;
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
metricModel = input.modelSelection?.model;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.kind": routed.adapter.provider,
|
||||
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
providerInstanceId: routed.instanceId,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: yield* nowIso,
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
timer: providerTurnDuration,
|
||||
attributes: () =>
|
||||
providerTurnMetricAttributes({
|
||||
provider: metricProvider,
|
||||
model: metricModel,
|
||||
extra: {
|
||||
operation: "send",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
const input = {
|
||||
...parsed,
|
||||
attachments: parsed.attachments ?? [],
|
||||
};
|
||||
if (!input.input && input.attachments.length === 0) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.sendTurn",
|
||||
"Either input text or at least one attachment is required",
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "send-turn",
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.interaction_mode": input.interactionMode,
|
||||
"provider.attachment_count": input.attachments.length,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
let metricModel = input.modelSelection?.model;
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
metricModel = input.modelSelection?.model;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.kind": routed.adapter.provider,
|
||||
...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}),
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
providerInstanceId: routed.instanceId,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: yield* nowIso,
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
timer: providerTurnDuration,
|
||||
attributes: () =>
|
||||
providerTurnMetricAttributes({
|
||||
provider: metricProvider,
|
||||
model: metricModel,
|
||||
extra: {
|
||||
operation: "send",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderService["Service"]["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.interruptTurn",
|
||||
@@ -866,45 +754,45 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const respondToRequest: ProviderService["Service"]["respondToRequest"] = Effect.fn(
|
||||
"respondToRequest",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
schema: ProviderRespondToRequestInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
schema: ProviderRespondToRequestInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "respond-to-request",
|
||||
"provider.kind": routed.adapter.provider,
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.request_id": input.requestId,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
yield* analytics.record("provider.request.responded", {
|
||||
provider: routed.adapter.provider,
|
||||
decision: input.decision,
|
||||
});
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
outcomeAttributes: () =>
|
||||
providerMetricAttributes(metricProvider, {
|
||||
operation: "approval-response",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
let metricProvider = "unknown";
|
||||
return yield* Effect.gen(function* () {
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
});
|
||||
metricProvider = routed.adapter.provider;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"provider.operation": "respond-to-request",
|
||||
"provider.kind": routed.adapter.provider,
|
||||
"provider.thread_id": input.threadId,
|
||||
"provider.request_id": input.requestId,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
yield* analytics.record("provider.request.responded", {
|
||||
provider: routed.adapter.provider,
|
||||
decision: input.decision,
|
||||
});
|
||||
}).pipe(
|
||||
withMetrics({
|
||||
counter: providerTurnsTotal,
|
||||
outcomeAttributes: () =>
|
||||
providerMetricAttributes(metricProvider, {
|
||||
operation: "approval-response",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const respondToUserInput: ProviderService["Service"]["respondToUserInput"] = Effect.fn(
|
||||
const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn(
|
||||
"respondToUserInput",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
@@ -938,7 +826,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
);
|
||||
});
|
||||
|
||||
const stopSession: ProviderService["Service"]["stopSession"] = Effect.fn("stopSession")(
|
||||
const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.stopSession",
|
||||
@@ -986,7 +874,7 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const listSessions: ProviderService["Service"]["listSessions"] = Effect.fn("listSessions")(
|
||||
const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")(
|
||||
function* () {
|
||||
const currentAdapters = yield* getAdapterEntries;
|
||||
const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
|
||||
@@ -1047,18 +935,18 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
"ProviderService.listSessions",
|
||||
binding,
|
||||
);
|
||||
if (
|
||||
binding.provider !== session.provider ||
|
||||
overrides.providerInstanceId !== session.providerInstanceId
|
||||
) {
|
||||
if (binding.provider !== session.provider) {
|
||||
return yield* Effect.die(
|
||||
new ProviderSessionBindingCorrelationError({
|
||||
threadId: session.threadId,
|
||||
sessionProvider: session.provider,
|
||||
bindingProvider: binding.provider,
|
||||
sessionInstanceId: session.providerInstanceId,
|
||||
bindingInstanceId: overrides.providerInstanceId,
|
||||
}),
|
||||
new Error(
|
||||
`ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (overrides.providerInstanceId !== session.providerInstanceId) {
|
||||
return yield* Effect.die(
|
||||
new Error(
|
||||
`ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
@@ -1073,13 +961,13 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
},
|
||||
);
|
||||
|
||||
const getCapabilities: ProviderService["Service"]["getCapabilities"] = (instanceId) =>
|
||||
const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) =>
|
||||
registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));
|
||||
|
||||
const getInstanceInfo: ProviderService["Service"]["getInstanceInfo"] = (instanceId) =>
|
||||
const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
|
||||
registry.getInstanceInfo(instanceId);
|
||||
|
||||
const rollbackConversation: ProviderService["Service"]["rollbackConversation"] = Effect.fn(
|
||||
const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
|
||||
"rollbackConversation",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
@@ -1142,8 +1030,8 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* revokeAllActiveMcpCredentials();
|
||||
clearAllMcpProviderSessions();
|
||||
yield* McpSessionRegistry.revokeAllActiveMcpCredentials();
|
||||
McpProviderSession.clearAllMcpProviderSessions();
|
||||
const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));
|
||||
yield* Effect.forEach(bindings, (binding) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1172,11 +1060,15 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
runStopAll().pipe(
|
||||
Effect.catchCause((cause) => Effect.logWarning("failed to stop provider service", { cause })),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to stop provider service", {
|
||||
errorTag: causeErrorTag(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return ProviderService.of({
|
||||
return {
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
@@ -1190,10 +1082,17 @@ export const make = Effect.fn("ProviderService.make")(function* (options?: Provi
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
|
||||
// independently receive all runtime events.
|
||||
get streamEvents(): ProviderService["Service"]["streamEvents"] {
|
||||
get streamEvents(): ProviderServiceMethod<"streamEvents"> {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
});
|
||||
} satisfies ProviderService.ProviderService["Service"];
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderService, make());
|
||||
export const ProviderServiceLive = Layer.effect(
|
||||
ProviderService.ProviderService,
|
||||
makeProviderService(),
|
||||
);
|
||||
|
||||
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
|
||||
return Layer.effect(ProviderService.ProviderService, makeProviderService(options));
|
||||
}
|
||||
+11
-22
@@ -15,16 +15,16 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
|
||||
import { isProviderSessionNotFoundError } from "./Errors.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
} 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,
|
||||
ProviderSessionDirectory.layer.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
NodeServices.layer,
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const initialThreadId = ThreadId.make("thread-1");
|
||||
@@ -77,20 +77,9 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
assert.deepEqual(threadIds, [nextThreadId]);
|
||||
}));
|
||||
|
||||
it("reports a missing provider binding as a domain not-found error", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
const error = yield* directory.getProvider(threadId).pipe(Effect.flip);
|
||||
|
||||
assert(isProviderSessionNotFoundError(error));
|
||||
assert.equal(error.threadId, threadId);
|
||||
}));
|
||||
|
||||
it("persists runtime fields and merges payload updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const threadId = ThreadId.make("thread-runtime");
|
||||
@@ -135,7 +124,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
it("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const olderThreadId = ThreadId.make("thread-runtime-older");
|
||||
@@ -209,7 +198,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.make("thread-provider-change");
|
||||
|
||||
@@ -247,7 +236,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
const threadId = ThreadId.make("thread-restart");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
@@ -255,7 +244,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const provider = yield* directory.getProvider(threadId);
|
||||
assert.equal(provider, "codex");
|
||||
@@ -0,0 +1,201 @@
|
||||
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);
|
||||
}
|
||||
+26
-41
@@ -17,13 +17,14 @@ import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as 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 * as ProviderSessionReaper from "./ProviderSessionReaper.ts";
|
||||
import * as ProviderService from "./ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
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"),
|
||||
@@ -116,8 +117,7 @@ function makeReadModel(
|
||||
|
||||
describe("ProviderSessionReaper", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
| ProviderSessionReaper.ProviderSessionReaper
|
||||
| ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
@@ -137,19 +137,19 @@ describe("ProviderSessionReaper", () => {
|
||||
readonly readModel: ReturnType<typeof makeReadModel>;
|
||||
readonly stopSessionImplementation?: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
}) => ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>;
|
||||
}) => ReturnType<ProviderServiceShape["stopSession"]>;
|
||||
}) {
|
||||
const stoppedThreadIds = new Set<ThreadId>();
|
||||
const stopSession = vi.fn<ProviderService.ProviderService["Service"]["stopSession"]>(
|
||||
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
|
||||
(request) =>
|
||||
(input.stopSessionImplementation
|
||||
? input.stopSessionImplementation(request)
|
||||
: Effect.sync(() => {
|
||||
stoppedThreadIds.add(request.threadId);
|
||||
})) as ReturnType<ProviderService.ProviderService["Service"]["stopSession"]>,
|
||||
})) as ReturnType<ProviderServiceShape["stopSession"]>,
|
||||
);
|
||||
|
||||
const providerService: ProviderService.ProviderService["Service"] = {
|
||||
const providerService: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
@@ -178,21 +178,18 @@ describe("ProviderSessionReaper", () => {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectory.layer.pipe(
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(runtimeRepositoryLayer),
|
||||
);
|
||||
const layer = Layer.effect(
|
||||
ProviderSessionReaper.ProviderSessionReaper,
|
||||
ProviderSessionReaper.make({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}),
|
||||
).pipe(
|
||||
const layer = makeProviderSessionReaperLive({
|
||||
inactivityThresholdMs: 1_000,
|
||||
sweepIntervalMs: 60_000,
|
||||
}).pipe(
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
Layer.provideMerge(runtimeRepositoryLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService.ProviderService, providerService)),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
@@ -260,9 +257,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
@@ -312,9 +307,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
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);
|
||||
@@ -363,9 +356,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
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);
|
||||
@@ -414,9 +405,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
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);
|
||||
@@ -502,9 +491,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
@@ -587,9 +574,7 @@ describe("ProviderSessionReaper", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const reaper = await runtime!.runPromise(
|
||||
Effect.service(ProviderSessionReaper.ProviderSessionReaper),
|
||||
);
|
||||
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
|
||||
|
||||
+25
-22
@@ -1,37 +1,31 @@
|
||||
import * as Context from "effect/Context";
|
||||
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 type * as Scope from "effect/Scope";
|
||||
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ProviderService from "./ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./ProviderSessionDirectory.ts";
|
||||
|
||||
export class ProviderSessionReaper extends Context.Service<
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
ProviderSessionReaper,
|
||||
{
|
||||
/** Start the background provider session reaper within the provided scope. */
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
>()("t3/provider/ProviderSessionReaper") {}
|
||||
type ProviderSessionReaperShape,
|
||||
} from "../Services/ProviderSessionReaper.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 ProviderSessionReaperOptions {
|
||||
export interface ProviderSessionReaperLiveOptions {
|
||||
readonly inactivityThresholdMs?: number;
|
||||
readonly sweepIntervalMs?: number;
|
||||
}
|
||||
|
||||
export const make = (options?: ProviderSessionReaperOptions) =>
|
||||
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const inactivityThresholdMs = Math.max(
|
||||
1,
|
||||
@@ -109,15 +103,19 @@ export const make = (options?: ProviderSessionReaperOptions) =>
|
||||
}
|
||||
});
|
||||
|
||||
const start: ProviderSessionReaper["Service"]["start"] = () =>
|
||||
const start: ProviderSessionReaperShape["start"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
sweep.pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-failed", { error }),
|
||||
Effect.logWarning("provider.session.reaper.sweep-failed", {
|
||||
error,
|
||||
}),
|
||||
),
|
||||
Effect.catchDefect((defect: unknown) =>
|
||||
Effect.logWarning("provider.session.reaper.sweep-defect", { defect }),
|
||||
Effect.logWarning("provider.session.reaper.sweep-defect", {
|
||||
defect,
|
||||
}),
|
||||
),
|
||||
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
|
||||
),
|
||||
@@ -129,7 +127,12 @@ export const make = (options?: ProviderSessionReaperOptions) =>
|
||||
});
|
||||
});
|
||||
|
||||
return ProviderSessionReaper.of({ start });
|
||||
return {
|
||||
start,
|
||||
} satisfies ProviderSessionReaperShape;
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderSessionReaper, make());
|
||||
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
|
||||
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
|
||||
|
||||
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
|
||||
@@ -1,167 +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.
|
||||
* - `listProviders` — legacy kind-keyed routing for default instances
|
||||
* (`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.
|
||||
*
|
||||
* Adapter lookups are resolved dynamically through `ProviderInstanceRegistry`.
|
||||
* Settings-driven hot reload is therefore visible immediately without
|
||||
* rebuilding this facade.
|
||||
*
|
||||
* @module ProviderAdapterRegistry
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import type * as PubSub from "effect/PubSub";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderUnsupportedError, type ProviderAdapterError } from "./Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
|
||||
import type { ProviderContinuationIdentity } from "./ProviderDriver.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
|
||||
export interface ProviderInstanceRoutingInfo {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly driverKind: ProviderDriverKind;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly enabled: boolean;
|
||||
readonly continuationIdentity: ProviderContinuationIdentity;
|
||||
}
|
||||
|
||||
export class ProviderAdapterRegistry extends Context.Service<
|
||||
ProviderAdapterRegistry,
|
||||
{
|
||||
/**
|
||||
* 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>;
|
||||
|
||||
/** Resolve routing metadata for a specific live provider instance. */
|
||||
readonly getInstanceInfo: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
|
||||
|
||||
/**
|
||||
* List all live instance ids. Excludes unavailable/shadow instances because
|
||||
* callers of this method want something they can pass to `getByInstance`.
|
||||
*/
|
||||
readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;
|
||||
|
||||
/**
|
||||
* List provider kinds whose default instance is currently registered.
|
||||
*
|
||||
* @deprecated Prefer `listInstances`. Retained for migration-era call sites
|
||||
* that iterate providers to build UI or metrics.
|
||||
*/
|
||||
readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;
|
||||
|
||||
/**
|
||||
* Change notification stream mirroring
|
||||
* `ProviderInstanceRegistry.streamChanges`. Emits one `void` tick whenever
|
||||
* the set of live instances changes. Consumers that fan out
|
||||
* `adapter.streamEvents` per instance re-pull `listInstances` on each tick
|
||||
* and fork subscriptions for instances they have not 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>;
|
||||
}
|
||||
>()("t3/provider/ProviderAdapterRegistry") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
|
||||
|
||||
const getByInstance: ProviderAdapterRegistry["Service"]["getByInstance"] = (instanceId) =>
|
||||
registry
|
||||
.getInstance(instanceId)
|
||||
.pipe(
|
||||
Effect.flatMap((instance) =>
|
||||
instance === undefined
|
||||
? Effect.fail(new ProviderUnsupportedError({ provider: instanceId }))
|
||||
: Effect.succeed(instance.adapter),
|
||||
),
|
||||
);
|
||||
|
||||
const getInstanceInfo: ProviderAdapterRegistry["Service"]["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: ProviderAdapterRegistry["Service"]["listInstances"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
|
||||
);
|
||||
|
||||
const listProviders: ProviderAdapterRegistry["Service"]["listProviders"] = () =>
|
||||
registry.listInstances.pipe(
|
||||
Effect.map((instances) => {
|
||||
const kinds = new Set<ProviderDriverKind>();
|
||||
for (const instance of instances) {
|
||||
if (instance.instanceId === defaultInstanceIdForDriver(instance.driverKind)) {
|
||||
// Only default instances appear through this legacy view; custom
|
||||
// instances such as `codex_personal` have no driver-kind identity.
|
||||
kinds.add(instance.driverKind);
|
||||
}
|
||||
}
|
||||
return Array.from(kinds);
|
||||
}),
|
||||
);
|
||||
|
||||
return ProviderAdapterRegistry.of({
|
||||
getByInstance,
|
||||
getInstanceInfo,
|
||||
listInstances,
|
||||
listProviders,
|
||||
// The facade owns no state; the instance registry already coalesces
|
||||
// add, remove, and rebuild notifications into a single change channel.
|
||||
streamChanges: registry.streamChanges,
|
||||
subscribeChanges: registry.subscribeChanges,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderAdapterRegistry, make);
|
||||
@@ -1,79 +0,0 @@
|
||||
/**
|
||||
* ProviderEventLoggers — single observability service that owns the two
|
||||
* shared NDJSON streams the provider runtime writes:
|
||||
*
|
||||
* - `native` — provider-protocol events as the SDK emits them, written
|
||||
* from inside each `<X>Adapter` factory.
|
||||
* - `canonical` — runtime events after `ProviderService` has normalized
|
||||
* them onto `ProviderRuntimeEvent`.
|
||||
*
|
||||
* Why a service tag and not constructor options?
|
||||
*
|
||||
* - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),
|
||||
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
|
||||
* call site where we can hand an `EventNdjsonLogger` in by hand.
|
||||
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
|
||||
* should share one underlying log writer per stream — opening N writers
|
||||
* against the same rotating file would race the rotation logic. Owning
|
||||
* the loggers on a single tag keeps that invariant intact.
|
||||
* - Tests can swap one (or both) loggers with in-memory recorders by
|
||||
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
|
||||
* juggling per-Layer option threading.
|
||||
*
|
||||
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
|
||||
* the target directory cannot be created; we forward that as `undefined`
|
||||
* rather than failing the boot Layer, matching the previous best-effort
|
||||
* behavior of `server.ts`.
|
||||
*
|
||||
* @module provider/ProviderEventLoggers
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Config from "../config.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./Layers/EventNdjsonLogger.ts";
|
||||
|
||||
/**
|
||||
* Shared logger pair for native + canonical provider event streams.
|
||||
*
|
||||
* Service value is intentionally a struct of two optional loggers rather
|
||||
* than two parallel tags. Construction site is one place
|
||||
* (`layer`); consumers (drivers, `ProviderService`) read
|
||||
* one tag and pluck the field they need.
|
||||
*/
|
||||
export class ProviderEventLoggers extends Context.Service<
|
||||
ProviderEventLoggers,
|
||||
{
|
||||
readonly native: EventNdjsonLogger | undefined;
|
||||
readonly canonical: EventNdjsonLogger | undefined;
|
||||
}
|
||||
>()("t3/provider/ProviderEventLoggers") {}
|
||||
|
||||
/**
|
||||
* Constant value used by tests / boot layers that want to opt out of native
|
||||
* + canonical logging entirely. Keeps the tag non-optional in the type
|
||||
* system while letting the runtime treat absence as a no-op.
|
||||
*/
|
||||
export const NoOpProviderEventLoggers: ProviderEventLoggers["Service"] = {
|
||||
native: undefined,
|
||||
canonical: undefined,
|
||||
};
|
||||
|
||||
/**
|
||||
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
|
||||
* If the directory create fails for either stream, the corresponding field
|
||||
* is `undefined` and writes from that stream become no-ops downstream.
|
||||
*/
|
||||
export const make = Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* Config.ServerConfig;
|
||||
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "native",
|
||||
});
|
||||
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
stream: "canonical",
|
||||
});
|
||||
return ProviderEventLoggers.of({ native, canonical });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderEventLoggers, make);
|
||||
@@ -1,769 +0,0 @@
|
||||
/**
|
||||
* ProviderRegistry aggregates per-instance snapshot streams into a
|
||||
* single materialized list.
|
||||
*
|
||||
* Historically this Layer composed four per-kind Live Layers
|
||||
* (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a
|
||||
* `ServerProviderShape`. Those Lives were deleted during the driver /
|
||||
* instance refactor — every driver now carries its `snapshot: ServerProviderShape`
|
||||
* bundled onto the `ProviderInstance` the registry produces.
|
||||
*
|
||||
* Each configured instance (including multi-instance setups like
|
||||
* `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,
|
||||
* keyed by `instanceId`. Instances whose driver is unavailable or whose
|
||||
* config failed to decode are merged from `instanceRegistry.listUnavailable`
|
||||
* as shadow snapshots so the UI can render their exact unavailable reason.
|
||||
*
|
||||
* Cache paths on disk are now keyed by `instanceId`. Because
|
||||
* `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing
|
||||
* `<kind>.json` files remain the on-disk location for that driver's default
|
||||
* instance. Identity-less legacy cache contents are ignored and replaced by
|
||||
* the first live refresh.
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as Config from "../config.ts";
|
||||
import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
isCachedProviderCorrelated,
|
||||
orderProviderSnapshots,
|
||||
readProviderStatusCache,
|
||||
resolveProviderStatusCachePath,
|
||||
writeProviderStatusCache,
|
||||
} from "./providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "./ProviderDriver.ts";
|
||||
import {
|
||||
makeManualOnlyProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "./builtInProviderCatalog.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export class ProviderSnapshotCorrelationError extends Schema.TaggedErrorClass<ProviderSnapshotCorrelationError>()(
|
||||
"ProviderSnapshotCorrelationError",
|
||||
{
|
||||
sourceInstanceId: ProviderInstanceId,
|
||||
snapshotInstanceId: ProviderInstanceId,
|
||||
sourceDriver: ProviderDriverKind,
|
||||
snapshotDriver: ProviderDriverKind,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Provider snapshot correlation failed for source instance '${this.sourceInstanceId}' (${this.sourceDriver}) and emitted instance '${this.snapshotInstanceId}' (${this.snapshotDriver}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProviderRegistry extends Context.Service<
|
||||
ProviderRegistry,
|
||||
{
|
||||
/**
|
||||
* Read the latest provider snapshots for every configured instance.
|
||||
* Multiple snapshots may share the same driver kind and disambiguate via
|
||||
* `instanceId`.
|
||||
*/
|
||||
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh all providers, or the default instance of the specified kind
|
||||
* when supplied.
|
||||
*
|
||||
* Retained for compatibility with legacy call sites such as the WS refresh
|
||||
* RPC and orchestration metrics.
|
||||
*
|
||||
* @deprecated Prefer `refreshInstance` for new call sites.
|
||||
*/
|
||||
readonly refresh: (
|
||||
provider?: ProviderDriverKind,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh one configured instance. Unknown ids resolve to the current
|
||||
* cached list, matching the legacy `refresh` behavior so transport layers
|
||||
* do not have to special-case unknown ids.
|
||||
*/
|
||||
readonly refreshInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve maintenance capabilities for one live provider instance,
|
||||
* falling back to manual-only capabilities when it is unavailable.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance. This
|
||||
* state is never persisted. Today only update actions are projected onto
|
||||
* `ServerProvider.updateState`; install/auth actions can extend this map
|
||||
* without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates, one emission per aggregated change.
|
||||
* The array contains the full current state.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
|
||||
}
|
||||
>()("t3/provider/ProviderRegistry") {}
|
||||
|
||||
const loadProviders = (
|
||||
providerSources: ReadonlyArray<ProviderSnapshotSource>,
|
||||
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
|
||||
Effect.forEach(
|
||||
providerSources,
|
||||
(providerSource) =>
|
||||
providerSource.getSnapshot.pipe(
|
||||
Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
const mergeProviderModels = (
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
if (nextModels.length === 0 && previousModels.length > 0) {
|
||||
return previousModels;
|
||||
}
|
||||
|
||||
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
|
||||
const mergedModels = nextModels.map((model) => {
|
||||
const previousModel = previousBySlug.get(model.slug);
|
||||
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
|
||||
return model;
|
||||
}
|
||||
return {
|
||||
...model,
|
||||
capabilities: previousModel.capabilities,
|
||||
};
|
||||
});
|
||||
const nextSlugs = new Set(nextModels.map((model) => model.slug));
|
||||
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshot = (
|
||||
previousProvider: ServerProvider | undefined,
|
||||
nextProvider: ServerProvider,
|
||||
): ServerProvider =>
|
||||
!previousProvider
|
||||
? nextProvider
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
const correlateSnapshotWithSource = (
|
||||
source: ProviderSnapshotSource,
|
||||
snapshot: ServerProvider,
|
||||
): Effect.Effect<ServerProvider> => {
|
||||
if (snapshot.instanceId !== source.instanceId || snapshot.driver !== source.driverKind) {
|
||||
return Effect.die(
|
||||
new ProviderSnapshotCorrelationError({
|
||||
sourceInstanceId: source.instanceId,
|
||||
snapshotInstanceId: snapshot.instanceId,
|
||||
sourceDriver: source.driverKind,
|
||||
snapshotDriver: snapshot.driver,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.succeed(snapshot);
|
||||
};
|
||||
|
||||
/**
|
||||
* Key a snapshot for aggregation and persistence. Snapshot sources
|
||||
* must be correlated by instance id before reaching this map; missing
|
||||
* identities are defects, not runtime routing fallbacks.
|
||||
*/
|
||||
const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {
|
||||
return provider.instanceId;
|
||||
};
|
||||
|
||||
// Project a live `ProviderInstance` into the aggregator's consumption
|
||||
// shape. Each call re-captures the instance's `snapshot` closures, so
|
||||
// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because
|
||||
// its settings changed), a fresh source rides the new PubSub instead
|
||||
// of a closed one.
|
||||
const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({
|
||||
instanceId: instance.instanceId,
|
||||
driverKind: instance.driverKind,
|
||||
getSnapshot: instance.snapshot.getSnapshot,
|
||||
...(instance.snapshot.isInitialSnapshot === undefined
|
||||
? {}
|
||||
: { isInitialSnapshot: instance.snapshot.isInitialSnapshot }),
|
||||
refresh: instance.snapshot.refresh,
|
||||
streamChanges: instance.snapshot.streamChanges,
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
|
||||
const config = yield* Config.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
// Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for
|
||||
// coalesced updates across every instance.
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
|
||||
// Boot-only: hydrate `providersRef` from the on-disk per-instance
|
||||
// cache so the UI has something to render during the first refresh.
|
||||
// Instances added post-boot skip this path; their first entry in
|
||||
// `providersRef` comes from the reactive `syncLiveSources` pass
|
||||
// below.
|
||||
const bootInstances = yield* instanceRegistry.listInstances;
|
||||
const bootSources = bootInstances.map(buildSnapshotSource);
|
||||
const fallbackProviders = yield* loadProviders(bootSources);
|
||||
const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();
|
||||
for (let index = 0; index < fallbackProviders.length; index++) {
|
||||
const provider = fallbackProviders[index];
|
||||
const source = bootSources[index];
|
||||
if (provider === undefined || source === undefined) {
|
||||
continue;
|
||||
}
|
||||
fallbackByInstance.set(source.instanceId, provider);
|
||||
}
|
||||
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
bootSources,
|
||||
(source) =>
|
||||
Effect.gen(function* () {
|
||||
// One cache file per configured instance. For the default
|
||||
// instance of a built-in kind the path equals `<kind>.json` —
|
||||
// identical to the legacy filename. We still require the cache
|
||||
// payload to carry matching instance id + driver kind; old
|
||||
// identity-less payloads are discarded and the awaited refresh
|
||||
// below repopulates the cache.
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: source.instanceId,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
const fallbackProvider = fallbackByInstance.get(source.instanceId);
|
||||
if (fallbackProvider === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return yield* readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.flatMap((cachedProvider) => {
|
||||
if (cachedProvider === undefined) {
|
||||
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
const correlation = {
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
} as const;
|
||||
if (!isCachedProviderCorrelated(correlation)) {
|
||||
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
|
||||
path: filePath,
|
||||
instanceId: source.instanceId,
|
||||
cachedInstanceId: cachedProvider.instanceId ?? null,
|
||||
driver: source.driverKind,
|
||||
cachedDriver: cachedProvider.driver ?? null,
|
||||
}).pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
return Effect.succeed(hydrateCachedProvider(correlation));
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.map((providers) =>
|
||||
orderProviderSnapshots(
|
||||
providers.filter((provider): provider is ServerProvider => provider !== undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cachedInstanceIds = new Set(cachedProviders.map(snapshotInstanceKey));
|
||||
const bootInstancesById = new Map(
|
||||
bootInstances.map((instance) => [instance.instanceId, instance] as const),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
// reference is used for identity equality so "no-op" reconciles
|
||||
// (settings unchanged) skip re-subscribing + re-probing.
|
||||
const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(new Map());
|
||||
// Serialize `syncLiveSources` so a rapid burst of reconciles doesn't
|
||||
// interleave two passes clobbering each other's fiber bookkeeping.
|
||||
const syncSemaphore = yield* Semaphore.make(1);
|
||||
|
||||
const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(
|
||||
liveSubsRef,
|
||||
).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
|
||||
|
||||
const persistProvider = (provider: ServerProvider) =>
|
||||
Effect.gen(function* () {
|
||||
// Persist every instance — the file name is the instance id, so
|
||||
// multi-instance setups (e.g. `codex_personal`, `codex_work`) each
|
||||
// get their own cache. We resolve the path fresh so snapshots
|
||||
// produced by newly-added instances post-boot still land on disk
|
||||
// without the aggregator holding a stale `cachePathByInstance`
|
||||
// entry.
|
||||
const key = snapshotInstanceKey(provider);
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: key,
|
||||
}).pipe(Effect.provideService(Path.Path, path));
|
||||
yield* writeProviderStatusCache({ filePath, provider }).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.ignore,
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
readonly persist?: boolean;
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
? provider
|
||||
: mergeProviderSnapshot(mergedProviders.get(key), provider),
|
||||
);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
}
|
||||
if (options?.publish !== false) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
|
||||
const syncProvider = Effect.fn("syncProvider")(function* (
|
||||
provider: ServerProvider,
|
||||
options?: {
|
||||
readonly publish?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
return yield* providerSource.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) =>
|
||||
correlateSnapshotWithSource(providerSource, nextProvider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshAll = Effect.fn("refreshAll")(function* () {
|
||||
const sources = yield* getLiveSources;
|
||||
return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
}).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderDriverKind) {
|
||||
if (provider === undefined) {
|
||||
return yield* refreshAll();
|
||||
}
|
||||
// Kind-scoped refreshes target the default instance for that driver.
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(provider);
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find((candidate) => candidate.instanceId === defaultInstanceId);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const refreshInstance = Effect.fn("refreshInstance")(function* (instanceId: ProviderInstanceId) {
|
||||
const sources = yield* getLiveSources;
|
||||
const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
* - subscribe to each newly-added or rebuilt instance's
|
||||
* `streamChanges` (so periodic + enrichment refreshes land in
|
||||
* `providersRef`);
|
||||
* - read each newly-added/rebuilt instance's current snapshot after
|
||||
* subscribing, closing the race with its independently-running
|
||||
* background startup probe;
|
||||
* - prune `providersRef` of instances that no longer exist.
|
||||
*
|
||||
* Provider refreshes are owned by each managed provider and never run
|
||||
* on this layer's construction path. Consumers see cached or pending
|
||||
* snapshots immediately, then receive live probe results through the
|
||||
* already-attached change stream.
|
||||
*
|
||||
* Per-instance subscription fibers are not tracked explicitly. When
|
||||
* a rebuilt instance's old child scope closes, its PubSub shuts
|
||||
* down and our `Stream.runForEach` fiber exits naturally.
|
||||
*/
|
||||
const syncLiveSources = syncSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const instances = yield* instanceRegistry.listInstances;
|
||||
const unavailableProviders = yield* instanceRegistry.listUnavailable;
|
||||
const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(
|
||||
instances.map((instance) => [instance.instanceId, instance] as const),
|
||||
);
|
||||
const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());
|
||||
for (const provider of unavailableProviders) {
|
||||
knownInstanceIds.add(snapshotInstanceKey(provider));
|
||||
}
|
||||
const previousSubs = yield* Ref.get(liveSubsRef);
|
||||
|
||||
// Carry over subscriptions for instances whose identity is
|
||||
// unchanged (reconcile treated them as no-op). Instances that
|
||||
// disappeared, or were rebuilt with a different reference,
|
||||
// fall through to the "newly-added" branch below.
|
||||
const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();
|
||||
for (const [instanceId, previousInstance] of previousSubs) {
|
||||
const nextInstance = nextByInstance.get(instanceId);
|
||||
if (nextInstance !== undefined && nextInstance === previousInstance) {
|
||||
carriedOver.set(instanceId, previousInstance);
|
||||
}
|
||||
}
|
||||
|
||||
// Collect new/rebuilt instances in `nextByInstance` insertion
|
||||
// order (which preserves settings-author order).
|
||||
const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];
|
||||
for (const [instanceId, instance] of nextByInstance) {
|
||||
if (carriedOver.has(instanceId)) {
|
||||
continue;
|
||||
}
|
||||
newlyAdded.push([instanceId, instance] as const);
|
||||
}
|
||||
|
||||
// Fork long-lived subscriptions to each new/rebuilt instance's
|
||||
// change stream before reading its current snapshot. If the
|
||||
// driver's own initial probe finishes during this sync, either
|
||||
// the current read or the active subscriber observes the result.
|
||||
for (const [, instance] of newlyAdded) {
|
||||
const source = buildSnapshotSource(instance);
|
||||
yield* Stream.runForEach(source.streamChanges, (provider) =>
|
||||
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// Snapshot current state without starting a probe. Managed providers
|
||||
// launch their startup refresh independently, so this closes the
|
||||
// subscription race without putting external work on the registry
|
||||
// or HTTP server construction path.
|
||||
yield* Effect.forEach(
|
||||
newlyAdded,
|
||||
([instanceId, instance]) =>
|
||||
Effect.gen(function* () {
|
||||
const source = buildSnapshotSource(instance);
|
||||
const provider = yield* source.getSnapshot;
|
||||
// Keep hydrated cache state only while the original boot instance
|
||||
// still exposes its explicitly-marked initial snapshot. Comparing
|
||||
// snapshot values is insufficient: the first probe may have
|
||||
// completed before registry construction, making the boot-time
|
||||
// fallback a real live result that must replace stale disk state.
|
||||
if (
|
||||
cachedInstanceIds.has(instanceId) &&
|
||||
bootInstancesById.get(instanceId) === instance &&
|
||||
source.isInitialSnapshot?.(provider) === true
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider));
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
yield* upsertProviders(unavailableProviders, {
|
||||
persist: false,
|
||||
replace: true,
|
||||
});
|
||||
|
||||
const nextSubs = new Map(carriedOver);
|
||||
for (const [instanceId, instance] of newlyAdded) {
|
||||
nextSubs.set(instanceId, instance);
|
||||
}
|
||||
yield* Ref.set(liveSubsRef, nextSubs);
|
||||
|
||||
// Drop aggregator state for instances that have disappeared —
|
||||
// otherwise the UI would keep rendering ghosts.
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const providers = orderProviderSnapshots(
|
||||
previousProviders.filter((provider) =>
|
||||
knownInstanceIds.has(snapshotInstanceKey(provider)),
|
||||
),
|
||||
);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
},
|
||||
);
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.interrupt;
|
||||
}
|
||||
return Effect.logError("provider registry instance sync failed; keeping subscription alive", {
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
// Cached snapshots are already in `providersRef`; only seed instances
|
||||
// without cache entries so pending fallbacks cannot overwrite hydrated
|
||||
// status while the managed provider's first probe is still running.
|
||||
yield* upsertProviders(
|
||||
fallbackProviders.filter((provider) => !cachedInstanceIds.has(snapshotInstanceKey(provider))),
|
||||
{ publish: false },
|
||||
);
|
||||
// Subscribe to registry mutations BEFORE running the initial sync.
|
||||
// `subscribeChanges` acquires the `PubSub.Subscription` synchronously
|
||||
// in this fibre; the subscription is registered with the PubSub the
|
||||
// instant this `yield*` returns, so any subsequent publish is
|
||||
// buffered in the subscription regardless of when the consumer
|
||||
// fibre below actually starts running.
|
||||
//
|
||||
// (Contrast with the pre-fix code that did
|
||||
// `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.
|
||||
// `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,
|
||||
// which defers `PubSub.subscribe` to stream start. `forkScoped` only
|
||||
// schedules the consumer fibre — so a reconcile that published
|
||||
// between "fibre scheduled" and "fibre starts running + subscribes"
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
const instanceChanges = yield* instanceRegistry.subscribeChanges;
|
||||
// Initial sync attaches subscriptions and snapshots current state for
|
||||
// every instance present at boot. Provider probes are already running in
|
||||
// their managed background fibers and never block this layer.
|
||||
yield* syncLiveSources;
|
||||
// React to registry mutations — instance added / removed / rebuilt.
|
||||
// `Stream.fromSubscription` builds a stream over the pre-acquired
|
||||
// subscription rather than subscribing on stream start, which is
|
||||
// what closes the race.
|
||||
yield* Stream.runForEach(
|
||||
Stream.fromSubscription(instanceChanges),
|
||||
() => syncLiveSourcesAndContinue,
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const recoverRefreshFailure = Effect.fn("recoverRefreshFailure")(function* (
|
||||
cause: Cause.Cause<unknown>,
|
||||
) {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return yield* Effect.interrupt;
|
||||
}
|
||||
yield* Effect.logError("provider registry refresh failed; preserving cached providers", {
|
||||
cause,
|
||||
});
|
||||
return yield* Ref.get(providersRef);
|
||||
});
|
||||
|
||||
return ProviderRegistry.of({
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (provider?: ProviderDriverKind) =>
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderRegistry, make);
|
||||
@@ -1,283 +0,0 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ProviderSessionRuntimeStatus,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
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 {
|
||||
ProviderSessionDirectoryPersistenceError,
|
||||
ProviderSessionNotFoundError,
|
||||
ProviderValidationError,
|
||||
} from "./Errors.ts";
|
||||
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.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
|
||||
| ProviderSessionNotFoundError;
|
||||
|
||||
export type ProviderSessionDirectoryWriteError =
|
||||
| ProviderValidationError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export class ProviderSessionDirectory extends Context.Service<
|
||||
ProviderSessionDirectory,
|
||||
{
|
||||
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>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
readonly listThreadIds: () => Effect.Effect<
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
readonly listBindings: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderRuntimeBindingWithMetadata>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
>;
|
||||
}
|
||||
>()("t3/provider/ProviderSessionDirectory") {}
|
||||
|
||||
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
|
||||
|
||||
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: rows written before provider instances had a
|
||||
// nullable id. Promote them here so runtime routing never has to
|
||||
// infer an instance from its 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,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
|
||||
const getBinding: ProviderSessionDirectory["Service"]["getBinding"] = (threadId) =>
|
||||
repository.getByThreadId({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getBinding:getByThreadId",
|
||||
detail: "Failed to read the persisted provider session binding.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((runtime) =>
|
||||
Option.match(runtime, {
|
||||
onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),
|
||||
onSome: (value) =>
|
||||
toRuntimeBinding(value, "ProviderSessionDirectory.getBinding").pipe(
|
||||
Effect.map(Option.some),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const upsert: ProviderSessionDirectory["Service"]["upsert"] = Effect.fn(
|
||||
"ProviderSessionDirectory.upsert",
|
||||
)(function* (binding) {
|
||||
const existing = yield* repository.getByThreadId({ threadId: binding.threadId }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.upsert:getByThreadId",
|
||||
detail: "Failed to read the existing provider session binding before upsert.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.upsert:upsert",
|
||||
detail: "Failed to persist the provider session binding.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const getProvider: ProviderSessionDirectory["Service"]["getProvider"] = (threadId) =>
|
||||
getBinding(threadId).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: (value) => Effect.succeed(value.provider),
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new ProviderSessionNotFoundError({
|
||||
threadId,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectory["Service"]["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.listThreadIds:list",
|
||||
detail: "Failed to list persisted provider session bindings.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((rows) => rows.map((row) => row.threadId)),
|
||||
);
|
||||
|
||||
const listBindings: ProviderSessionDirectory["Service"]["listBindings"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.listBindings:list",
|
||||
detail: "Failed to list persisted provider session bindings.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(
|
||||
rows,
|
||||
(row) => toRuntimeBinding(row, "ProviderSessionDirectory.listBindings"),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return ProviderSessionDirectory.of({
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
listThreadIds,
|
||||
listBindings,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderSessionDirectory, make);
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* 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") {}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* ProviderInstanceRegistry — the single Effect service in the new model.
|
||||
*
|
||||
* Owns a `Map<ProviderInstanceId, ProviderInstance>` produced by running
|
||||
* registered driver factories against `ServerSettings.providerInstances`.
|
||||
* The registry watches settings; when an instance's config changes (or
|
||||
* the entry disappears), the registry tears down the affected instance's
|
||||
* scope and rebuilds — that's the entire hot-reload story.
|
||||
*
|
||||
* What rest-of-server reads from here:
|
||||
* - `getInstance(instanceId)` — for routing turn/session calls.
|
||||
* - `listInstances` — for snapshot aggregation in `ProviderRegistry`.
|
||||
* - `listUnavailable` — `ServerProvider` shadows for instances whose
|
||||
* driver is not registered in this build (rollback / fork tolerance).
|
||||
* - `streamChanges` — coalesced "registry mutated" pings so consumers
|
||||
* can re-pull lists or re-broadcast.
|
||||
*
|
||||
* @module provider/Services/ProviderInstanceRegistry
|
||||
*/
|
||||
import type { ProviderInstanceId, ServerProvider } 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 { ProviderInstance } from "../ProviderDriver.ts";
|
||||
|
||||
export interface ProviderInstanceRegistryShape {
|
||||
/**
|
||||
* Look up one instance by id. Returns `undefined` (not Option) when the
|
||||
* id is unknown — callers branch on falsy and emit
|
||||
* `ProviderInstanceNotFoundError`.
|
||||
*/
|
||||
readonly getInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ProviderInstance | undefined>;
|
||||
/**
|
||||
* Every available (driver-registered, successfully created) instance,
|
||||
* in stable settings-author order.
|
||||
*/
|
||||
readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;
|
||||
/**
|
||||
* Wire-shape shadow snapshots for instances whose driver is unknown to
|
||||
* this build (or whose config failed to decode). Suitable for merging
|
||||
* directly into `ProviderRegistry` output.
|
||||
*/
|
||||
readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
/**
|
||||
* Push notification stream emitted whenever the registry's contents
|
||||
* change — instance added, removed, or rebuilt. The payload is `void`
|
||||
* because consumers always want to re-pull `listInstances` /
|
||||
* `listUnavailable` together.
|
||||
*
|
||||
* NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the
|
||||
* stream starts running, forking a consumer via
|
||||
* `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next
|
||||
* publish — the forked fiber may not have subscribed yet when the
|
||||
* publish lands. Hot-reload consumers that must not miss a publish
|
||||
* should use `subscribeChanges` below instead, which acquires the
|
||||
* subscription synchronously in the caller's fiber before the consumer
|
||||
* loop is forked.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<void>;
|
||||
/**
|
||||
* Acquire a subscription to the registry's change channel synchronously
|
||||
* in the caller's fiber. Returns a `PubSub.Subscription<void>` whose
|
||||
* lifetime is scoped to the provided `Scope` (the subscription is
|
||||
* released when the scope closes). Consumers typically `yield*` this
|
||||
* in the same fiber that forks their consumer loop, then drain with
|
||||
* `PubSub.take(subscription)` inside `Effect.forever`. Because the
|
||||
* subscription is registered with the PubSub before this `yield*`
|
||||
* returns, no subsequent publish can land in a gap.
|
||||
*
|
||||
* This exists because the `ProviderInstanceRegistry` publishes on a
|
||||
* PubSub and `Stream.fromPubSub` defers subscription until the stream
|
||||
* starts executing — a consumer that `forkScoped`s the stream
|
||||
* consumption can miss a publish that lands in the narrow window
|
||||
* between "fiber scheduled" and "fiber starts running".
|
||||
*/
|
||||
readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
export class ProviderInstanceRegistry extends Context.Service<
|
||||
ProviderInstanceRegistry,
|
||||
ProviderInstanceRegistryShape
|
||||
>()("t3/provider/Services/ProviderInstanceRegistry") {}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* ProviderInstanceRegistryMutator — internal handle used by the hydration
|
||||
* layer to reconcile the live registry with a fresh
|
||||
* `ProviderInstanceConfigMap`.
|
||||
*
|
||||
* Kept separate from the public `ProviderInstanceRegistry` service tag so
|
||||
* downstream consumers (drivers, reactors, `ProviderService`) can only read
|
||||
* from the registry. Only the hydration layer — which watches
|
||||
* `ServerSettingsService.streamChanges` and applies diffs — imports this
|
||||
* tag.
|
||||
*
|
||||
* The mutator exposes a single entry point, `reconcile(configMap)`, which:
|
||||
*
|
||||
* 1. Diffs the incoming map against the live one keyed by instance id.
|
||||
* 2. Closes the per-instance `Scope` of every removed or replaced entry
|
||||
* (tearing down adapter processes, refresh fibres, temp files) BEFORE
|
||||
* creating the replacement — `reconcile` guarantees "at most one live
|
||||
* instance per id" at all times.
|
||||
* 3. Opens a fresh child `Scope` for every added or replaced entry, runs
|
||||
* the driver's `create`, and stores the resulting `ProviderInstance`
|
||||
* plus its scope.
|
||||
* 4. Publishes one `void` tick on the registry's `streamChanges` PubSub at
|
||||
* the end of the batch — consumers re-pull `listInstances` /
|
||||
* `listUnavailable`.
|
||||
*
|
||||
* `reconcile` is idempotent: calling it with an unchanged config map is a
|
||||
* no-op (no scope churn, no pubsub emission).
|
||||
*
|
||||
* @module provider/Services/ProviderInstanceRegistryMutator
|
||||
*/
|
||||
import type { ProviderInstanceConfigMap } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export interface ProviderInstanceRegistryMutatorShape {
|
||||
/**
|
||||
* Bring the live registry in line with the supplied config map. See
|
||||
* module docs for the add / remove / replace semantics.
|
||||
*
|
||||
* The effect never fails: individual driver `create` failures are
|
||||
* captured as "unavailable" shadow snapshots inside the registry, the
|
||||
* same way boot-time failures are handled by
|
||||
* `makeProviderInstanceRegistry`. This keeps settings-watcher loops from
|
||||
* erroring out on a single bad entry.
|
||||
*/
|
||||
readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class ProviderInstanceRegistryMutator extends Context.Service<
|
||||
ProviderInstanceRegistryMutator,
|
||||
ProviderInstanceRegistryMutatorShape
|
||||
>()("t3/provider/Services/ProviderInstanceRegistryMutator") {}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* ProviderRegistry - Provider snapshot service.
|
||||
*
|
||||
* Owns provider install/auth/version/model snapshots and exposes the latest
|
||||
* provider state to transport layers.
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ServerProvider,
|
||||
ServerProviderUpdateState,
|
||||
} 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 { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
* Read the latest provider snapshots for every configured instance.
|
||||
* Multiple snapshots may share the same `provider` kind (multiple
|
||||
* instances of the same driver) and disambiguate via `instanceId`.
|
||||
*/
|
||||
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh all providers, or the default instance of the specified
|
||||
* kind when supplied.
|
||||
*
|
||||
* Retained for back-compat with legacy call sites (WS refresh RPC,
|
||||
* orchestration metrics). New code should prefer `refreshInstance`.
|
||||
*
|
||||
* @deprecated prefer `refreshInstance` for new call sites.
|
||||
*/
|
||||
readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Refresh the specific configured instance. Returns the updated snapshot
|
||||
* list. When the instance id is unknown the call resolves with the
|
||||
* currently cached list (no error) — matching the legacy `refresh` shim
|
||||
* behaviour so transport layers don't have to special-case unknowns.
|
||||
*/
|
||||
readonly refreshInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance.
|
||||
* This state is never persisted to disk. Today only update actions are
|
||||
* projected onto `ServerProvider.updateState`; install/auth actions can
|
||||
* extend this action map without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates — one emission per aggregated
|
||||
* change. The array contains the full current state.
|
||||
*/
|
||||
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
|
||||
}
|
||||
|
||||
export class ProviderRegistry extends Context.Service<ProviderRegistry, ProviderRegistryShape>()(
|
||||
"t3/provider/Services/ProviderRegistry",
|
||||
) {}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 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",
|
||||
) {}
|
||||
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user