Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex e5b2ce1518 Fix rebased runtime integration
Co-authored-by: codex <[email protected]>
2026-03-10 18:26:29 -07:00
Julius Marminge a4d6d64c6e ref 2026-03-10 18:23:59 -07:00
Julius Marminge 72e563e5f2 Migrate server entrypoint and RPCs to effectful schema outputs
- Point server bin packaging to `dist/bin.mjs` and run CLI via explicit `NodeRuntime.runMain`
- Use orchestration RPC schema outputs for `getSnapshot` and `replayEvents`
- Populate default thread `interactionMode`/`runtimeMode` during bootstrap and align wsServer test stubs
2026-03-10 18:23:59 -07:00
Julius Marminge 393c52c214 Migrate server entrypoint to Effect CLI runtime modules
- replace `main/index` bootstrap with `bin`, `cli`, `server`, `serverRuntime`, and `serverRpc`
- switch package bin/start targets to `dist/bin.mjs` and add build `--format` support
- split/refresh server and route tests, and add shared RPC contracts for ws transport
2026-03-10 18:23:45 -07:00
638 changed files with 28591 additions and 110968 deletions

No files matched your search

-22
View File
@@ -1,22 +0,0 @@
{
"name": "T3 Code Dev",
"image": "debian:bookworm",
"features": {
"ghcr.io/devcontainers-extra/features/bun:1": {},
"ghcr.io/devcontainers/features/node:1": {
"version": "24",
"nodeGypDependencies": true
},
"ghcr.io/devcontainers/features/python:1": {
"version": "3.12"
}
},
"postCreateCommand": {
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
},
"customizations": {
"vscode": {
"extensions": ["oxc.oxc-vscode"]
}
}
}
-302
View File
@@ -1,302 +0,0 @@
# Remote Architecture
This document describes the target architecture for first-class remote environments in T3 Code.
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
## Goals
- Treat remote environments as first-class product primitives, not special cases.
- Support multiple ways to reach the same environment.
- Keep the T3 server as the execution boundary.
- Let desktop, mobile, and web all share the same conceptual model.
- Avoid introducing a local control plane unless product pressure proves it is necessary.
## Non-goals
- Replacing the existing WebSocket server boundary with a custom transport protocol.
- Making SSH the only remote story.
- Syncing provider auth across machines.
- Shipping every access method in the first iteration.
## High-level architecture
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
Remote support should preserve that boundary.
```text
┌──────────────────────────────────────────────┐
│ Client (desktop / mobile / web) │
│ │
│ - known environments │
│ - connection manager │
│ - environment-aware routing │
└───────────────┬──────────────────────────────┘
│
│ resolves one access endpoint
│
┌───────────────▼──────────────────────────────┐
│ Access method │
│ │
│ - direct ws / wss │
│ - tunneled ws / wss │
│ - desktop-managed ssh bootstrap + forward │
└───────────────┬──────────────────────────────┘
│
│ connects to one T3 server
│
┌───────────────▼──────────────────────────────┐
│ Execution environment = one T3 server │
│ │
│ - environment identity │
│ - provider state │
│ - projects / threads / terminals │
│ - git / filesystem / process runtime │
└──────────────────────────────────────────────┘
```
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
## Domain model
### ExecutionEnvironment
An `ExecutionEnvironment` is one running T3 server instance.
It is the unit that owns:
- provider availability and auth state
- model availability
- projects and threads
- terminal processes
- filesystem access
- git operations
- server settings
It is identified by a stable `environmentId`.
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
### KnownEnvironment
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
It is not server-authored. It is local to a device or client profile.
Examples:
- a saved LAN URL
- a saved public `wss://` endpoint
- a desktop-managed SSH host entry
- a saved tunneled environment
A known environment may or may not know the target `environmentId` before first successful connect.
### AccessEndpoint
An `AccessEndpoint` is one concrete way to reach a known environment.
This is the key abstraction that keeps SSH from taking over the model.
A single environment may have many endpoints:
- `wss://t3.example.com`
- `ws://10.0.0.25:3773`
- a tunneled relay URL
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
The environment stays the same. Only the access path changes.
### RepositoryIdentity
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
### Workspace / Project
The current `Project` model remains environment-local.
That means:
- a local clone and a remote clone are different projects
- they may share a `RepositoryIdentity`
- threads still bind to one project in one environment
## Access methods
Access methods answer one question:
How does the client speak WebSocket to a T3 server?
They do not answer:
- how the server got started
- who manages the server process
- whether the environment is local or remote
### 1. Direct WebSocket access
Examples:
- `ws://10.0.0.15:3773`
- `wss://t3.example.com`
This is the base model and should be the first-class default.
Benefits:
- works for desktop, mobile, and web
- no client-specific process management required
- best fit for hosted or self-managed remote T3 deployments
### 2. Tunneled WebSocket access
Examples:
- public relay URLs
- private network relay URLs
- local tunnel products such as pipenet
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
This is especially useful when:
- the host is behind NAT
- inbound ports are unavailable
- mobile must reach a desktop-hosted environment
- a machine should be reachable without exposing raw LAN or public ports
### 3. Desktop-managed SSH access
SSH is an access and launch helper, not a separate environment type.
The desktop main process can use SSH to:
- reach a machine
- probe it
- launch or reuse a remote T3 server
- establish a local port forward
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
This keeps the renderer transport model consistent with every other access method.
## Launch methods
Launch methods answer a different question:
How does a T3 server come to exist on the target machine?
Launch and access should stay separate in the design.
### 1. Pre-existing server
The simplest launch method is no launch at all.
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
### 2. Desktop-managed remote launch over SSH
This is the main place where Zed is a useful reference.
Useful ideas to borrow from Zed:
- remote probing
- platform detection
- session directories with pid/log metadata
- reconnect-friendly launcher behavior
- desktop-owned connection UX
What should be different in T3:
- no custom stdio/socket proxy protocol between renderer and remote runtime
- no attempt to make the remote runtime look like an editor transport
- keep the final client-to-server connection as WebSocket
The recommended T3 flow is:
1. Desktop connects over SSH.
2. Desktop probes the remote machine and verifies T3 availability.
3. Desktop launches or reuses a remote T3 server.
4. Desktop establishes local port forwarding.
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
### 3. Client-managed local publish
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
This is useful for:
- exposing a desktop-hosted environment to mobile
- temporary remote access without changing router or firewall settings
This is still a launch concern, not a new environment kind.
## Why access and launch must stay separate
These concerns are easy to conflate, but separating them prevents architectural drift.
Examples:
- A manually hosted T3 server might be reached through direct `wss`.
- The same server might also be reachable through a tunnel.
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
- A local desktop server might be published through a tunnel for mobile.
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
Only the launch and access paths differ.
## Security model
Remote support must assume that some environments will be reachable over untrusted networks.
That means:
- remote-capable environments should require explicit authentication
- tunnel exposure should not rely on obscurity
- client-saved endpoints should carry enough auth metadata to reconnect safely
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
For publicly reachable environments, authenticated access should be treated as required.
## Relationship to Zed
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
The relevant lessons are:
- remote bootstrap should be explicit
- reconnect should be first-class
- connection UX belongs in the client shell
- runtime ownership should stay clearly on the remote host
The important mismatch is transport shape.
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
T3 should not copy that part.
T3 already has the right runtime boundary:
- one T3 server per environment
- ordinary HTTP/WebSocket between client and environment
So T3 should borrow Zed's launch discipline, not its transport protocol.
## Recommended rollout
1. First-class known environments and access endpoints.
2. Direct `ws` / `wss` remote environments.
3. Authenticated tunnel-backed environments.
4. Desktop-managed SSH launch and forwarding.
5. Multi-environment UI improvements after the base runtime path is proven.
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
+1 -1
View File
@@ -5,7 +5,7 @@
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
-2
View File
@@ -1,2 +0,0 @@
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
* text=auto eol=lf
-117
View File
@@ -1,117 +0,0 @@
name: Bug report
description: Report broken behavior, regressions, crashes, or reliability issues.
title: "[Bug]: "
labels:
- bug
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I included enough detail to reproduce or investigate the problem.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project is affected?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Provide a minimal, deterministic repro.
placeholder: |
1. Start the app with ...
2. Open ...
3. Disconnect the network
4. Reconnect and send another prompt
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
placeholder: The thread should resume normally and accept the new message.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
validations:
required: true
- type: dropdown
id: impact
attributes:
label: Impact
description: How bad is this in practice?
options:
- Blocks work completely
- Major degradation or frequent failure
- Minor bug or occasional failure
- Cosmetic issue
validations:
required: true
- type: input
id: version
attributes:
label: Version or commit
description: Release version, commit SHA, or branch name if known.
placeholder: main @ abc1234
- type: input
id: environment
attributes:
label: Environment
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
- type: textarea
id: logs
attributes:
label: Logs or stack traces
description: Paste the most relevant output only. Redact secrets.
render: shell
- type: upload
id: attachments
attributes:
label: Screenshots, recordings, or supporting files
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
validations:
required: false
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
- type: textarea
id: workaround
attributes:
label: Workaround
description: If you found a temporary workaround, include it.
placeholder: Restarting the provider session clears the stuck state.
-101
View File
@@ -1,101 +0,0 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
-3
View File
@@ -19,7 +19,6 @@ github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
@@ -28,5 +27,3 @@ github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
+7 -9
View File
@@ -10,10 +10,9 @@ jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -21,12 +20,12 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: |
~/.bun/install/cache
@@ -36,7 +35,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -72,15 +71,14 @@ jobs:
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
release_smoke:
name: Release Smoke
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -88,7 +86,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
-75
View File
@@ -1,75 +0,0 @@
name: Issue Labels
on:
push:
branches:
- main
paths:
- .github/ISSUE_TEMPLATE/**
- .github/workflows/issue-labels.yml
workflow_dispatch:
permissions:
issues: write
jobs:
sync:
name: Sync issue labels
runs-on: ubuntu-24.04
steps:
- name: Ensure managed issue labels exist
uses: actions/github-script@v7
with:
script: |
const managedLabels = [
{
name: "bug",
color: "d73a4a",
description: "Something is broken or behaving incorrectly.",
},
{
name: "enhancement",
color: "a2eeef",
description: "Requested improvement or new capability.",
},
{
name: "needs-triage",
color: "fbca04",
description: "Issue needs maintainer review and initial categorization.",
},
];
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
-292
View File
@@ -1,292 +0,0 @@
name: PR Size
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
jobs:
prepare-config:
name: Prepare PR size config
runs-on: ubuntu-24.04
outputs:
labels_json: ${{ steps.config.outputs.labels_json }}
steps:
- id: config
name: Build PR size label config
uses: actions/github-script@v8
with:
result-encoding: string
script: |
const managedLabels = [
{
name: "size:XS",
color: "0e8a16",
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
},
];
core.setOutput("labels_json", JSON.stringify(managedLabels));
sync-label-definitions:
name: Sync PR size label definitions
needs: prepare-config
if: github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: write
steps:
- name: Ensure PR size labels exist
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
label:
name: Label PR size
needs: prepare-config
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Checkout base repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const { execFileSync } = require("node:child_process");
const issueNumber = context.payload.pull_request.number;
const baseSha = context.payload.pull_request.base.sha;
const headSha = context.payload.pull_request.head.sha;
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testExcludePathspecs = [
":(glob,exclude)**/__tests__/**",
":(glob,exclude)**/test/**",
":(glob,exclude)**/tests/**",
":(glob,exclude)apps/server/integration/**",
":(glob,exclude)**/*.test.*",
":(glob,exclude)**/*.spec.*",
":(glob,exclude)**/*.browser.*",
":(glob,exclude)**/*.integration.*",
];
const sumNumstat = (text) =>
text
.split("\n")
.filter(Boolean)
.reduce((total, line) => {
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
const additions =
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
const deletions =
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
return total + additions + deletions;
}, 0);
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
return "size:XS";
}
if (totalChangedLines < 30) {
return "size:S";
}
if (totalChangedLines < 100) {
return "size:M";
}
if (totalChangedLines < 500) {
return "size:L";
}
if (totalChangedLines < 1000) {
return "size:XL";
}
return "size:XXL";
};
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
stdio: "inherit",
});
execFileSync(
"git",
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
{
stdio: "inherit",
},
);
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
encoding: "utf8",
}).trim();
if (resolvedHeadSha !== headSha) {
core.warning(
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
);
}
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
stdio: "inherit",
});
const diffArgs = [
"diff",
"--numstat",
"--ignore-all-space",
"--ignore-blank-lines",
`${baseSha}...${resolvedHeadSha}`,
];
const totalChangedLines = sumNumstat(
execFileSync(
"git",
diffArgs,
{ encoding: "utf8" },
),
);
const nonTestChangedLines = sumNumstat(
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
encoding: "utf8",
}),
);
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
const classification =
nonTestChangedLines === 0
? testChangedLines > 0
? "test-only PR"
: "no line changes"
: testChangedLines > 0
? "test lines excluded"
: "all non-test changes";
core.info(
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
);
+19 -43
View File
@@ -25,7 +25,7 @@ jobs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v8
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "pull_request_target") {
@@ -85,7 +85,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v8
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
@@ -111,7 +111,7 @@ jobs:
},
];
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const managedLabelNames = managedLabels.map((label) => label.name);
for (const label of managedLabels) {
try {
@@ -138,19 +138,13 @@ jobs:
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
@@ -165,35 +159,17 @@ jobs:
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+14 -45
View File
@@ -19,7 +19,6 @@ jobs:
preflight:
name: Preflight
runs-on: ubuntu-24.04
timeout-minutes: 10
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
@@ -28,7 +27,7 @@ jobs:
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- id: release_meta
name: Resolve release version
@@ -62,7 +61,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -82,7 +81,6 @@ jobs:
name: Build ${{ matrix.label }}
needs: preflight
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -109,7 +107,7 @@ jobs:
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
@@ -120,16 +118,13 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
env:
@@ -219,7 +214,7 @@ jobs:
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
@@ -229,10 +224,9 @@ jobs:
name: Publish CLI to npm
needs: [preflight, build]
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
@@ -242,7 +236,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
@@ -250,9 +244,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -263,20 +254,19 @@ jobs:
name: Publish GitHub Release
needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
@@ -311,33 +301,12 @@ jobs:
name: Finalize release
needs: [preflight, release]
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
- id: app_bot
name: Resolve GitHub App bot identity
env:
GH_TOKEN: ${{ steps.app_token.outputs.token }}
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
run: |
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -345,7 +314,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -374,8 +343,8 @@ jobs:
exit 0
fi
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
-6
View File
@@ -12,13 +12,7 @@ packages/*/dist
build/
.logs/
release/
release-mock/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
squashfs-root/
+1 -3
View File
@@ -1,7 +1,6 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
@@ -9,8 +8,7 @@
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts"
"apps/web/public/mockServiceWorker.js"
],
"sortPackageJson": {}
}
-441
View File
@@ -1,441 +0,0 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
-823
View File
@@ -1,823 +0,0 @@
# Server Auth Model Plan
## Purpose
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
## Primary goals
- Make auth server-wide, not WebSocket-only.
- Make insecure exposure hard to do accidentally.
- Preserve zero-login local desktop UX for desktop-managed environments.
- Support browser-native pairing and session auth.
- Leave room for native/mobile credentials later without rewriting the server boundary.
- Keep auth separate from transport and launch method.
## Non-goals
- Full multi-user authorization and RBAC.
- OAuth / SSO / enterprise identity.
- Passkeys or biometric UX in v1.
- Syncing auth state across environments.
- Designing the full remote environment product in this document.
## Core decisions
### 1. Auth is a server concern
Every privileged surface of the T3 server must go through the same auth policy engine:
- HTTP routes
- WebSocket upgrades
- RPC methods reached through WebSocket
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
### 2. Pairing and session are different things
The system should distinguish:
- bootstrap credentials
- session credentials
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
Session credentials are the durable credentials used after pairing.
Bootstrap should never become the long-lived request credential.
### 3. Auth and transport are separate
Auth must not be defined by how the client reached the server.
Examples:
- local desktop-managed server
- LAN `ws://`
- public `wss://`
- tunneled `wss://`
- SSH-forwarded `ws://127.0.0.1:<port>`
All of these should feed into the same auth model.
### 4. Exposure level changes defaults
The more exposed an environment is, the narrower the safe default should be.
Safe default expectations:
- local desktop-managed: auto-pair allowed
- loopback browser access: explicit bootstrap allowed
- non-loopback bind: auth required
- tunnel/public endpoint: auth required, explicit enablement required
### 5. Browser and native clients may use different session credentials
The auth model should support more than one session credential type even if only one ships first.
Examples:
- browser session cookie
- native bearer/device token
This should be represented in the model now, even if browser cookies are the first implementation.
## Target auth domain
### Route classes
Every route or transport entrypoint should be classified as one of:
1. `public`
2. `bootstrap`
3. `authenticated`
#### `public`
Unauthenticated by definition.
Should be extremely small. Examples:
- static shell needed to render the pairing/login UI
- favicon/assets required for the pairing screen
- a minimal server health/version endpoint if needed
#### `bootstrap`
Used only to exchange a bootstrap credential for a session.
Examples:
- Initial bootstrap envelope over file descriptor at startup
- `POST /api/auth/bootstrap`
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
#### `authenticated`
Everything that reveals machine state or mutates it.
Examples:
- WebSocket upgrade
- orchestration snapshot and events
- terminal open/write/close
- project search and file writes
- git routes
- attachments
- project favicon lookup
- server settings
The default stance should be: if it touches the machine, it is authenticated.
## Credential model
### Bootstrap credentials
Initial credential types to model:
- `desktop-bootstrap`
- `one-time-token`
Possible future credential types:
- `device-code`
- `passkey-assertion`
- `external-identity`
#### `desktop-bootstrap`
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
Properties:
- launcher-provided
- short-lived
- one-time or bounded-use
- never shown to the user as a reusable password
#### `one-time-token`
Used for explicit browser/mobile pairing flows.
Properties:
- short TTL
- one-time use
- safe to embed in a pairing URL fragment
- exchanged for a session credential
### Session credentials
Initial credential types to model:
- `browser-session-cookie`
- `bearer-session-token`
#### `browser-session-cookie`
Primary browser credential.
Properties:
- signed
- `HttpOnly`
- bounded lifetime
- revocable by server key rotation or session invalidation
#### `bearer-session-token`
Reserved for native/mobile or non-browser clients.
Properties:
- opaque token, not a bootstrap secret
- long enough lifetime to survive reconnects
- stored in secure client storage when available
## Auth policy model
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
### Policy examples
#### `DesktopManagedLocalPolicy`
Default for desktop-managed local server.
Allowed bootstrap methods:
- `desktop-bootstrap`
Allowed session methods:
- `browser-session-cookie`
Disabled by default:
- `one-time-token`
- `bearer-session-token`
- password login
- public pairing
#### `LoopbackBrowserPolicy`
Used for browser access on localhost without desktop-managed bootstrap.
Allowed bootstrap methods:
- `one-time-token`
Allowed session methods:
- `browser-session-cookie`
#### `RemoteReachablePolicy`
Used when binding non-loopback or using an explicit remote/tunnel workflow.
Allowed bootstrap methods:
- `one-time-token`
- possibly `desktop-bootstrap` when a desktop shell is brokering access
Allowed session methods:
- `browser-session-cookie`
- `bearer-session-token`
#### `UnsafeNoAuthPolicy`
Should exist only as an explicit escape hatch.
Requirements:
- explicit opt-in flag
- loud startup warnings
- never defaulted automatically
## Effect-native service model
### `ServerAuth`
The main auth facade used by HTTP routes and WebSocket upgrade handling.
Responsibilities:
- classify requests
- authenticate requests
- authorize bootstrap attempts
- create sessions from bootstrap credentials
- enforce policy by environment mode
Sketch:
```ts
export interface ServerAuthShape {
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
routeClass: RouteAuthClass,
) => Effect.Effect<AuthContext, AuthError>;
readonly authenticateWebSocketUpgrade: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, AuthError>;
readonly exchangeBootstrapCredential: (
input: BootstrapExchangeInput,
) => Effect.Effect<SessionGrant, AuthError>;
}
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
"t3/ServerAuth",
) {}
```
### `BootstrapCredentialService`
Owns issuance, storage, validation, and consumption of bootstrap credentials.
Responsibilities:
- issue desktop bootstrap grants
- issue one-time pairing tokens
- validate TTL and single-use semantics
- consume bootstrap grants atomically
Sketch:
```ts
export interface BootstrapCredentialServiceShape {
readonly issueDesktopBootstrap: (
input: IssueDesktopBootstrapInput,
) => Effect.Effect<BootstrapCredential>;
readonly issueOneTimeToken: (
input: IssueOneTimeTokenInput,
) => Effect.Effect<BootstrapCredential>;
readonly consume: (
presented: PresentedBootstrapCredential,
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
}
```
### `SessionCredentialService`
Owns creation and validation of authenticated sessions.
Responsibilities:
- mint cookie sessions
- mint bearer sessions
- validate active session credentials
- revoke sessions if needed later
Sketch:
```ts
export interface SessionCredentialServiceShape {
readonly createBrowserSession: (
input: CreateSessionFromBootstrapInput,
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
readonly createBearerSession: (
input: CreateSessionFromBootstrapInput,
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
readonly authenticateCookie: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, SessionCredentialError>;
readonly authenticateBearer: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthContext, SessionCredentialError>;
}
```
### `ServerAuthPolicy`
Pure policy/config service that decides which credential types are allowed.
Responsibilities:
- map runtime mode and bind/exposure settings to allowed auth methods
- answer whether a route can be public
- answer whether remote exposure requires auth
This should stay mostly pure and cheap to test.
### `ServerSecretStore`
Owns long-lived server signing keys and secrets.
Responsibilities:
- get or create signing key
- rotate signing key
- abstract secure OS-backed storage vs filesystem fallback
Important:
- prefer platform secure storage when available
- support hardened filesystem fallback for headless/server-only environments
### `BrowserSessionCookieCodec`
Focused utility service for cookie encode/decode/signing behavior.
This should not own policy. It should only own the cookie format.
### `AuthRouteGuards`
Thin helper layer used by routes to enforce auth consistently.
Responsibilities:
- require auth for HTTP route handlers
- classify route auth mode
- convert auth failures into `401` / `403`
This prevents every route from re-implementing the same pattern.
Integrates with `HttpRouter.middleware` to enforce auth consistently.
## Suggested layer graph
```text
ServerSecretStore
├─> BootstrapCredentialService
├─> BrowserSessionCookieCodec
└─> SessionCredentialService
ServerAuthPolicy
├─> BootstrapCredentialService
├─> SessionCredentialService
└─> ServerAuth
ServerAuth
└─> AuthRouteGuards
```
Layer naming should follow existing repo style:
- `ServerSecretStoreLive`
- `BootstrapCredentialServiceLive`
- `SessionCredentialServiceLive`
- `ServerAuthPolicyLive`
- `ServerAuthLive`
- `AuthRouteGuardsLive`
## High-level implementation examples
### Example: WebSocket upgrade auth
Current state:
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
Target shape:
```ts
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
yield* serverAuth.authenticateWebSocketUpgrade(request);
return yield* httpApp;
}),
);
```
Then the `/ws` route becomes:
```ts
export const websocketRpcRouteLayer = HttpRouter.add(
"GET",
"/ws",
rpcWebSocketHttpEffect.pipe(
websocketUpgradeAuth,
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
),
);
```
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
### Example: authenticated HTTP route
For routes like attachments or project favicon:
```ts
const authenticatedRoute = (routeClass: RouteAuthClass) =>
HttpMiddleware.make((httpApp) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
yield* serverAuth.authenticateHttpRequest(request, routeClass);
return yield* httpApp;
}),
);
```
Then:
```ts
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
serveAttachment.pipe(
authenticatedRoute(RouteAuthClass.Authenticated),
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
),
);
```
### Example: desktop bootstrap exchange
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
That grant is then exchanged for a browser cookie session when the renderer loads.
Sketch:
```ts
const pairDesktopRenderer = Effect.gen(function* () {
const bootstrapService = yield* BootstrapCredentialService;
const credential = yield* bootstrapService.issueDesktopBootstrap({
audience: "desktop-renderer",
ttlMs: 30_000,
});
return credential;
});
```
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
### Example: one-time pairing URL
For browser-driven pairing:
```ts
const createPairingToken = Effect.gen(function* () {
const bootstrapService = yield* BootstrapCredentialService;
return yield* bootstrapService.issueOneTimeToken({
ttlMs: 5 * 60_000,
audience: "browser",
});
});
```
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
## Sequence diagrams
These flows are meant to anchor the auth model in concrete user journeys.
The important invariant across all of them is:
- access method is not the auth method
- launch method is not the auth method
- bootstrap credential is not the session credential
### Normal desktop user
This is the default desktop-managed local flow.
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
```text
Participants:
DesktopMain = Electron main
SecretStore = secure local secret backend
T3Server = local backend child process
Frontend = desktop renderer
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
SecretStore --> DesktopMain : signing key available
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
DesktopMain -> T3Server : send desktop bootstrap envelope
note over T3Server : policy = DesktopManagedLocalPolicy
note over T3Server : allowed pairing = desktop-bootstrap only
Frontend -> DesktopMain : request local bootstrap grant
DesktopMain --> Frontend : short-lived desktop bootstrap grant
Frontend -> T3Server : POST /api/auth/bootstrap
T3Server -> T3Server : validate desktop bootstrap grant
T3Server -> T3Server : create browser session
T3Server --> Frontend : Set-Cookie: session=...
Frontend -> T3Server : GET /ws + authenticated cookie
T3Server -> T3Server : validate cookie session
T3Server --> Frontend : websocket accepted
```
### `npx t3` user
This is the standalone local server flow.
There is no trusted desktop shell here, so pairing should be explicit.
```text
Participants:
UserShell = npx t3 launcher
T3Server = standalone local server
Browser = browser tab
UserShell -> T3Server : start server
T3Server -> T3Server : getOrCreate("server-signing-key")
note over T3Server : policy = LoopbackBrowserPolicy
UserShell -> T3Server : issue one-time pairing token
T3Server --> UserShell : pairing URL or pairing token
UserShell --> Browser : open /pair?token=...
Browser -> T3Server : GET /pair?token=...
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create browser session
T3Server --> Browser : Set-Cookie: session=...
T3Server --> Browser : redirect to app
Browser -> T3Server : GET /ws + authenticated cookie
T3Server --> Browser : websocket accepted
```
### Phone user with tunneled host
This is the explicit remote access flow for a browser on another device.
The tunnel only provides reachability. It must not imply trust.
Recommended UX:
- desktop shows a QR code
- desktop also shows a copyable pairing URL
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
```text
Participants:
DesktopUser = user at the host machine
DesktopMain = desktop app
Tunnel = tunnel provider
T3Server = T3 server
PhoneBrowser = mobile browser
DesktopUser -> DesktopMain : enable remote access via tunnel
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
DesktopMain -> Tunnel : publish local T3 endpoint
Tunnel --> DesktopMain : public https/wss URL
DesktopMain -> T3Server : issue one-time pairing token
T3Server --> DesktopMain : pairing token
DesktopMain -> DesktopUser : show QR code / shareable URL
DesktopUser -> PhoneBrowser : scan QR / open URL
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
Tunnel -> T3Server : forward request
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create mobile browser session
T3Server --> PhoneBrowser : Set-Cookie: session=...
T3Server --> PhoneBrowser : redirect to app
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
Tunnel -> T3Server : forward websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Phone user with private network
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
The auth flow should stay the same.
```text
Participants:
DesktopUser = user at the host machine
T3Server = T3 server
PrivateNet = tailscale / private LAN
PhoneBrowser = mobile browser
DesktopUser -> T3Server : enable private-network access
T3Server -> T3Server : switch policy to RemoteReachablePolicy
DesktopUser -> T3Server : issue one-time pairing token
T3Server --> DesktopUser : pairing URL / QR
DesktopUser -> PhoneBrowser : open private-network URL
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
PrivateNet -> T3Server : route request
T3Server -> T3Server : validate one-time token
T3Server -> T3Server : create mobile browser session
T3Server --> PhoneBrowser : Set-Cookie: session=...
T3Server --> PhoneBrowser : redirect to app
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
PrivateNet -> T3Server : websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Desktop user adding new SSH hosts
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
```text
Participants:
DesktopUser = local desktop user
DesktopMain = desktop app
SSH = ssh transport/session
RemoteHost = remote machine
RemoteT3 = remote T3 server
Frontend = desktop renderer
DesktopUser -> DesktopMain : add SSH host
DesktopMain -> SSH : connect to remote host
SSH -> RemoteHost : probe environment / verify t3 availability
DesktopMain -> SSH : run remote launch command
SSH -> RemoteHost : t3 remote launch --json
RemoteHost -> RemoteT3 : start or reuse server
RemoteT3 --> RemoteHost : port + environment metadata
RemoteHost --> SSH : launch result JSON
SSH --> DesktopMain : remote server details
DesktopMain -> SSH : establish local port forward
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
note over RemoteT3 : policy = RemoteReachablePolicy
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
Frontend -> DesktopMain : request bootstrap for selected environment
DesktopMain --> Frontend : short-lived bootstrap grant
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
RemoteT3 -> RemoteT3 : validate bootstrap grant
RemoteT3 -> RemoteT3 : create browser session
RemoteT3 --> Frontend : Set-Cookie: session=...
Frontend -> RemoteT3 : GET /ws + authenticated cookie
RemoteT3 --> Frontend : websocket accepted
```
## Storage decisions
### Server secrets
Use a `ServerSecretStore` abstraction.
Preferred order (use a layer for each, resolve on startup):
1. OS secure storage if available
2. hardened filesystem fallback if not
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
### Client credentials
Client-side credential persistence should prefer secure storage when available:
- desktop: OS keychain / secure store
- mobile: platform secure storage
- browser: cookie session for browser auth
This concern should stay in the client shell/runtime layer, not the server auth layer.
## What to build now
These are the parts worth building before remote environments ship:
1. `ServerAuth` service boundary.
2. route classification and route guards.
3. `ServerSecretStore` abstraction.
4. bootstrap vs session credential split.
5. browser session cookie codec as one session method.
6. explicit auth capabilities/config surfaced in contracts.
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
## What to add as part of first remote-capable auth
1. Browser pairing flow using one-time bootstrap token and cookie session.
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
3. Auth-required defaults for any non-loopback or explicitly published server.
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
## What to defer
- passkeys / WebAuthn
- iCloud Keychain / Face ID-specific UX
- multi-user permissions
- collaboration roles
- OAuth / SSO
- polished session management UI
- complex device approval flows
These can all sit on top of the same bootstrap/session/service split.
## Relationship to future remote environments
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
Keep the design focused on:
- one T3 server
- one auth policy
- multiple credential types
- multiple future access methods
That keeps the server auth model stable even as access methods expand later.
## Recommended implementation order
### Phase 1
- Introduce route auth classes.
- Add `ServerAuth` and `AuthRouteGuards`.
- Move existing `authToken` check behind `ServerAuth`.
- Require auth for all privileged HTTP routes as well as WebSocket.
### Phase 2
- Add `ServerSecretStore` service with platform-specific layer implementations.
- `layerOSXKeychain`, `layer
- Add bootstrap/session split.
- Add browser session cookie support.
- Add one-time bootstrap exchange endpoint.
### Phase 3
- Add desktop bootstrap flow on top of the same services.
- Make desktop-managed local environments default to bootstrap-only pairing.
- Surface auth capabilities in shared contracts and renderer bootstrap.
### Phase 4
- Add non-browser bearer session support if mobile/native needs it.
- Add richer policy modes for remote-reachable environments.
## Acceptance criteria
- No privileged HTTP or WebSocket path bypasses auth policy.
- Local desktop-managed flows still avoid a visible login screen.
- Non-loopback or published environments require explicit authenticated pairing by default.
- Bootstrap and session credentials are distinct in code and in behavior.
- Auth logic is centralized in Effect services/layers rather than route-local branching.
-89
View File
@@ -1,89 +0,0 @@
# Replace React Query With AtomRpc + Atom State
## Summary
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
## Phase 3: Replace React Query Domain By Domain
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
2. Keep Zustand orchestration/event application unchanged.
3. Map current effects exactly:
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
- file creation/deletion/restoration touches `project:${cwd}`
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
- `rpc/orchestrationActions.ts`
- `rpc/terminalActions.ts`
- `rpc/gitActions.ts`
- `rpc/projectActions.ts`
- `platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
- `@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
- `desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
+3
View File
@@ -0,0 +1,3 @@
node_modules
dist
.DS_Store
+92
View File
@@ -0,0 +1,92 @@
# effect-http-ws-cli (PoC)
Minimal PoC using Effect v4 beta with a single unified program:
- `effect/unstable/cli` as the app entrypoint
- `effect/unstable/http` (`HttpServer`, `HttpRouter`, `HttpServerRequest`, `HttpServerResponse`) for server/runtime logic
- `@effect/platform-node` to host the server on Node.js
- HTTP + WebSocket message routing based on `effect/Schema` validation
- static asset serving from local filesystem (`public/` by default)
The repo now uses a Bun workspace:
- `server/` contains the Effect HTTP + WebSocket backend
- `web/` remains the Vite + React frontend package
## Run
```bash
bun install
bun run web:build
bun run start -- --port 8787 --host 127.0.0.1 --assets public --db todo.sqlite
```
Then open `http://127.0.0.1:8787`.
## Frontend
React + Vite client lives in `web/` and is built into `public/` so it is served by the static router.
```bash
bun run web:build
```
For local development without building the frontend:
```bash
bun run dev
```
That starts the backend, starts Vite on `http://127.0.0.1:5173`, and redirects frontend page requests there. In dev, Vite proxies `/api/*`, `/ws`, and `/health` back to the backend server.
If you want to run the processes separately, start `bun run web:dev` and launch the backend with `FRONTEND_DEV_ORIGIN=http://127.0.0.1:5173`.
The UI now demonstrates a typed realtime todo workflow:
- load todo snapshot on page load (`listTodos`)
- subscribe to todo updates (`subscribeTodos`)
- mutate todos via RPC (`renameTodo`, `completeTodo`, `archiveTodo`)
### Config Sources
Config is resolved from both CLI flags and `effect/Config`:
- CLI flags: `--host`, `--port`, `--assets`, `--db`, `--request-logging`, `--frontend-dev-origin`
- Env via `effect/Config`: `HOST`, `PORT`, `ASSETS_DIR`, `DB_FILENAME`, `REQUEST_LOGGING`, `FRONTEND_DEV_ORIGIN`
Precedence:
1. CLI flags
2. `effect/Config` (environment)
3. hard defaults (`127.0.0.1`, `8787`, `public`, `todo.sqlite`)
### SQL Persistence
- Uses `effect/unstable/sql` + `SqlSchema` for typed SQL request/result decoding.
- Uses `@effect/sql-sqlite-node` as the Node runtime SQL client.
- Database schema is managed by `effect/unstable/sql/Migrator` via `server/src/migrations.ts` with statically imported migration files.
## API
- `GET /health`
- `POST /api/dispatch`
- `GET /ws` (WebSocket RPC)
- `GET *` (static files)
### Message schema
Incoming messages are validated with `Schema`:
- `{ "kind": "echo", "text": string }`
- `{ "kind": "sum", "left": number, "right": number }`
- `{ "kind": "time" }`
Both HTTP and WebSocket dispatch use the same schema-driven router.
## Verify
```bash
bun run test
bun run test:web
bun run lint
```
+638
View File
@@ -0,0 +1,638 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "effect-http-ws-cli",
},
"server": {
"name": "@effect-http-ws-cli/server",
"version": "0.1.0",
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-node": "catalog:",
"effect": "catalog:",
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "^24.10.0",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"web": {
"name": "@effect-http-ws-cli/web",
"version": "0.1.0",
"dependencies": {
"@effect-http-ws-cli/server": "workspace:*",
"@effect/atom-react": "catalog:",
"@tanstack/react-router": "^1.166.2",
"effect": "catalog:",
"react": "^19.2.0",
"react-dom": "^19.2.0",
},
"devDependencies": {
"@tanstack/router-plugin": "^1.166.2",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"@vitest/browser-playwright": "^4.0.18",
"playwright": "^1.58.2",
"typescript": "catalog:",
"vite": "^7.2.0",
"vitest": "catalog:",
"vitest-browser-react": "^2.0.5",
},
},
},
"catalog": {
"@effect/atom-react": "4.0.0-beta.27",
"@effect/platform-node": "4.0.0-beta.27",
"@effect/sql-sqlite-node": "4.0.0-beta.27",
"@effect/vitest": "4.0.0-beta.27",
"effect": "4.0.0-beta.27",
"typescript": "6.0.0-beta",
"vitest": "^4.0.18",
},
"packages": {
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
"@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg=="],
"@babel/core": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-compilation-targets": "^7.28.6", "@babel/helper-module-transforms": "^7.28.6", "@babel/helpers": "^7.28.6", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/traverse": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA=="],
"@babel/generator": ["@babel/[email protected]", "", { "dependencies": { "@babel/parser": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw=="],
"@babel/helper-compilation-targets": ["@babel/[email protected]", "", { "dependencies": { "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA=="],
"@babel/helper-globals": ["@babel/[email protected]", "", {}, "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw=="],
"@babel/helper-module-imports": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw=="],
"@babel/helper-module-transforms": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-module-imports": "^7.28.6", "@babel/helper-validator-identifier": "^7.28.5", "@babel/traverse": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA=="],
"@babel/helper-plugin-utils": ["@babel/[email protected]", "", {}, "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug=="],
"@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="],
"@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
"@babel/helper-validator-option": ["@babel/[email protected]", "", {}, "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg=="],
"@babel/helpers": ["@babel/[email protected]", "", { "dependencies": { "@babel/template": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-xOBvwq86HHdB7WUDTfKfT/Vuxh7gElQ+Sfti2Cy6yIWNW05P8iUslOVcZ4/sKbE+/jQaukQAdz/gf3724kYdqw=="],
"@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
"@babel/plugin-syntax-jsx": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w=="],
"@babel/plugin-syntax-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A=="],
"@babel/plugin-transform-react-jsx-self": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw=="],
"@babel/plugin-transform-react-jsx-source": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw=="],
"@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ=="],
"@babel/traverse": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/types": "^7.29.0", "debug": "^4.3.1" } }, "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA=="],
"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
"@effect-http-ws-cli/server": ["@effect-http-ws-cli/server@workspace:server"],
"@effect-http-ws-cli/web": ["@effect-http-ws-cli/web@workspace:web"],
"@effect/atom-react": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.27", "react": "^19.2.4", "scheduler": "*" } }, "sha512-miq9lG74I9ypFdDTUIYWQR2OomxDweYM4Fv/h/Md0eXVrk+c/KAkgK0YT5pn3x5plZUHSuSuBEC36185/zpFPA=="],
"@effect/platform-node": ["@effect/[email protected]", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.27", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.27", "ioredis": "^5.7.0" } }, "sha512-UPZMtFVnDIM5nb6A2pEPo229VnfgMdvl/9sGiQaYRB9qEVHerk0elxcoWOb2szoivBYePYFOsPKIWpR6jCldtQ=="],
"@effect/platform-node-shared": ["@effect/[email protected]", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.27" } }, "sha512-prRa5MIWGAvq2g6FgVP5RFfPwI+DvcXCaEZetvPMK70wdkTR1+jKQqJ9QDKWNIP+2d4llE/cF21SvcpBJWq0gw=="],
"@effect/sql-sqlite-node": ["@effect/[email protected]", "", { "dependencies": { "better-sqlite3": "^12.6.2" }, "peerDependencies": { "effect": "^4.0.0-beta.27" } }, "sha512-GhTe2gIob7wuQ7OYHM+FtjPhYhf0oFtImPWwaXdQ14kxCSQVFuHY+ll45p2bxTAInnrnDip+Q+UC6xpNnvI3Cw=="],
"@effect/vitest": ["@effect/[email protected]", "", { "peerDependencies": { "effect": "^4.0.0-beta.27", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-l9LIQK2yqOF3h47CmlT2VfYWtfHLd+ZuMzma+w0OjxmPsR6bzYMA33ft4gljJ/lEQnXvGHxiTpnZySALCfv+pA=="],
"@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg=="],
"@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA=="],
"@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg=="],
"@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ=="],
"@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg=="],
"@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg=="],
"@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w=="],
"@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA=="],
"@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw=="],
"@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg=="],
"@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg=="],
"@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA=="],
"@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw=="],
"@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA=="],
"@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ=="],
"@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw=="],
"@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA=="],
"@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA=="],
"@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA=="],
"@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw=="],
"@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ=="],
"@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g=="],
"@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA=="],
"@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA=="],
"@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q=="],
"@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="],
"@ioredis/commands": ["@ioredis/[email protected]", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="],
"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
"@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
"@polka/url": ["@polka/[email protected]", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg=="],
"@rollup/rollup-android-arm64": ["@rollup/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q=="],
"@rollup/rollup-darwin-arm64": ["@rollup/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg=="],
"@rollup/rollup-darwin-x64": ["@rollup/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w=="],
"@rollup/rollup-freebsd-arm64": ["@rollup/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA=="],
"@rollup/rollup-freebsd-x64": ["@rollup/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg=="],
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw=="],
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA=="],
"@rollup/rollup-linux-arm64-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA=="],
"@rollup/rollup-linux-arm64-musl": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA=="],
"@rollup/rollup-linux-loong64-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg=="],
"@rollup/rollup-linux-loong64-musl": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q=="],
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA=="],
"@rollup/rollup-linux-ppc64-musl": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA=="],
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg=="],
"@rollup/rollup-linux-riscv64-musl": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg=="],
"@rollup/rollup-linux-s390x-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w=="],
"@rollup/rollup-linux-x64-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg=="],
"@rollup/rollup-linux-x64-musl": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg=="],
"@rollup/rollup-openbsd-x64": ["@rollup/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ=="],
"@rollup/rollup-openharmony-arm64": ["@rollup/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA=="],
"@rollup/rollup-win32-arm64-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A=="],
"@rollup/rollup-win32-ia32-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA=="],
"@rollup/rollup-win32-x64-gnu": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA=="],
"@rollup/rollup-win32-x64-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA=="],
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@tanstack/history": ["@tanstack/[email protected]", "", {}, "sha512-Kp/WSt411ZWYvgXy6uiv5RmhHrz9cAml05AQPrtdAp7eUqvIDbMGPnML25OKbzR3RJ1q4wgENxDTvlGPa9+Mww=="],
"@tanstack/react-router": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/history": "1.161.4", "@tanstack/react-store": "^0.9.1", "@tanstack/router-core": "1.166.2", "isbot": "^5.1.22", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-pKhUtrvVLlhjWhsHkJSuIzh1J4LcP+8ErbIqRLORX9Js8dUFMKoT0+8oFpi+P8QRpuhm/7rzjYiWfcyTsqQZtA=="],
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.9.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-YzJLnRvy5lIEFTLWBAZmcOjK3+2AepnBv/sr6NZmiqJvq7zTQggyK99Gw8fqYdMdHPQWXjz0epFKJXC+9V2xDA=="],
"@tanstack/router-core": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/history": "1.161.4", "@tanstack/store": "^0.9.1", "cookie-es": "^2.0.0", "seroval": "^1.4.2", "seroval-plugins": "^1.4.2", "tiny-invariant": "^1.3.3", "tiny-warning": "^1.0.3" } }, "sha512-zn3NhENOAX9ToQiX077UV2OH3aJKOvV2ZMNZZxZ3gDG3i3WqL8NfWfEgetEAfMN37/Mnt90PpotYgf7IyuoKqQ=="],
"@tanstack/router-generator": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/router-core": "1.166.2", "@tanstack/router-utils": "1.161.4", "@tanstack/virtual-file-routes": "1.161.4", "prettier": "^3.5.0", "recast": "^0.23.11", "source-map": "^0.7.4", "tsx": "^4.19.2", "zod": "^3.24.2" } }, "sha512-wbvdyP1PKKQKk4aVlGeK9S5uDy8zodTr3tEZ2gRKNavJLusXbEWqtoo42JxHFFNB6dtguehFMt8PyZPAtkgWwQ=="],
"@tanstack/router-plugin": ["@tanstack/[email protected]", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-syntax-typescript": "^7.27.1", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.5", "@babel/types": "^7.28.5", "@tanstack/router-core": "1.166.2", "@tanstack/router-generator": "1.166.2", "@tanstack/router-utils": "1.161.4", "@tanstack/virtual-file-routes": "1.161.4", "chokidar": "^3.6.0", "unplugin": "^2.1.2", "zod": "^3.24.2" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2", "@tanstack/react-router": "^1.166.2", "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0", "vite-plugin-solid": "^2.11.10", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-TnyV/7//Vp5fR49mmNbOWHGz9IJTm1lqVxzPdtpzg7D5PjkW2HFmLFLtWwpJgz2R7AJJWR4Ge5kIPmC+fVZ6eQ=="],
"@tanstack/router-utils": ["@tanstack/[email protected]", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/generator": "^7.28.5", "@babel/parser": "^7.28.5", "@babel/types": "^7.28.5", "ansis": "^4.1.0", "babel-dead-code-elimination": "^1.0.12", "diff": "^8.0.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.15" } }, "sha512-r8TpjyIZoqrXXaf2DDyjd44gjGBoyE+/oEaaH68yLI9ySPO1gUWmQENZ1MZnmBnpUGN24NOZxdjDLc8npK0SAw=="],
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-+qcNkOy0N1qSGsP7omVCW0SDrXtaDcycPqBDE726yryiA5eTDFpjBReaYjghVJwNf1pcPMyzIwTGlYjCSQR0Fg=="],
"@tanstack/virtual-file-routes": ["@tanstack/[email protected]", "", {}, "sha512-42WoRePf8v690qG8yGRe/YOh+oHni9vUaUUfoqlS91U2scd3a5rkLtVsc6b7z60w3RogH0I00vdrC5AaeiZ18w=="],
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
"@types/babel__generator": ["@types/[email protected]", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="],
"@types/babel__template": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A=="],
"@types/babel__traverse": ["@types/[email protected]", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
"@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
"@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
"@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-fPxQqz4VTgPI/IQ+lj9r0h+fDR66bzoeMGHp8ASee+32OSGIkeASsoZuJixsQoVef1QJbeubcPBxKk22QVoWdw=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
"@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-VIcFLdRi/VYRU8OL/puL7QXMYafHmqOnwTZY50U1JPlCNj30PxCMx65c494b1K9be9hX83KVt0+gTEwTWLqToA=="],
"@vitest/browser": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/mocker": "4.0.18", "@vitest/utils": "4.0.18", "magic-string": "^0.30.21", "pixelmatch": "7.1.0", "pngjs": "^7.0.0", "sirv": "^3.0.2", "tinyrainbow": "^3.0.3", "ws": "^8.18.3" }, "peerDependencies": { "vitest": "4.0.18" } }, "sha512-gVQqh7paBz3gC+ZdcCmNSWJMk70IUjDeVqi+5m5vYpEHsIwRgw3Y545jljtajhkekIpIp5Gg8oK7bctgY0E2Ng=="],
"@vitest/browser-playwright": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/browser": "4.0.18", "@vitest/mocker": "4.0.18", "tinyrainbow": "^3.0.3" }, "peerDependencies": { "playwright": "*", "vitest": "4.0.18" } }, "sha512-gfajTHVCiwpxRj1qh0Sh/5bbGLG4F/ZH/V9xvFVoFddpITfMta9YGow0W6ZpTTORv2vdJuz9TnrNSmjKvpOf4g=="],
"@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "chai": "^6.2.1", "tinyrainbow": "^3.0.3" } }, "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ=="],
"@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "4.0.18", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw"] }, "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ=="],
"@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^3.0.3" } }, "sha512-P24GK3GulZWC5tz87ux0m8OADrQIUVDPIjjj65vBXYG17ZeU3qD7r+MNZ1RNv4l8CGU2vtTRqixrOi9fYk/yKw=="],
"@vitest/runner": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/utils": "4.0.18", "pathe": "^2.0.3" } }, "sha512-rpk9y12PGa22Jg6g5M3UVVnTS7+zycIGk9ZNGN+m6tZHKQb7jrP7/77WfZy13Y/EUDd52NDsLRQhYKtv7XfPQw=="],
"@vitest/snapshot": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.0.18", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-PCiV0rcl7jKQjbgYqjtakly6T1uwv/5BQ9SwBLekVg/EaYeQFPiXcgrC2Y7vDMA8dM1SUEAEV82kgSQIlXNMvA=="],
"@vitest/spy": ["@vitest/[email protected]", "", {}, "sha512-cbQt3PTSD7P2OARdVW3qWER5EGq7PHlvE+QfzSC0lbwO+xnt7+XH06ZzFjFRgzUX//JmpxrCu92VdwvEPlWSNw=="],
"@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.0.18", "tinyrainbow": "^3.0.3" } }, "sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA=="],
"acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="],
"ansis": ["[email protected]", "", {}, "sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig=="],
"anymatch": ["[email protected]", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="],
"assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
"ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="],
"babel-dead-code-elimination": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="],
"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-lIyg0szRfYbiy67j9KN8IyeD7q7hcmqnJ1ddWmNt19ItGpNN64mnllmxUNFIOdOm6by97jlL6wfpTTJrmnjWAA=="],
"better-sqlite3": ["[email protected]", "", { "dependencies": { "bindings": "^1.5.0", "prebuild-install": "^7.1.1" } }, "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA=="],
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
"bindings": ["[email protected]", "", { "dependencies": { "file-uri-to-path": "1.0.0" } }, "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ=="],
"bl": ["[email protected]", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA=="],
"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"caniuse-lite": ["[email protected]", "", {}, "sha512-sg01JDPzZ9jGshqKSckOQthXnYwOEP50jeVFhaSFbZcOy05TiuuaffDOfcwtCisJ9kNQuLBFibYywv2Bgm9osw=="],
"chai": ["[email protected]", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
"chokidar": ["[email protected]", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
"chownr": ["[email protected]", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="],
"cluster-key-slot": ["[email protected]", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="],
"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"cookie-es": ["[email protected]", "", {}, "sha512-RAj4E421UYRgqokKUmotqAwuplYw15qtdXfY+hGzgCJ/MBjCVZcSoHK/kH9kocfjRjcDME7IiDWR/1WX1TM2Pg=="],
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"deep-extend": ["[email protected]", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="],
"denque": ["[email protected]", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="],
"detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"diff": ["[email protected]", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
"effect": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-bNQEF3vaVGF8jAJ+HW1A4DaxVNmujgEu89sO+VNW1AvUYtPGMtKPTBU15K9inu1rG+hkxNFFRlVvLAJsdaE2mg=="],
"electron-to-chromium": ["[email protected]", "", {}, "sha512-5z3uFKBWjiNR44nFcYdkcXjKMbg5KXNdciu7mhTPo9tB7NbqSNP2sSnGR+fqknZSCwKkBN+oxiiajWs4dT6ORg=="],
"end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"es-module-lexer": ["[email protected]", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="],
"esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.3", "@esbuild/android-arm": "0.27.3", "@esbuild/android-arm64": "0.27.3", "@esbuild/android-x64": "0.27.3", "@esbuild/darwin-arm64": "0.27.3", "@esbuild/darwin-x64": "0.27.3", "@esbuild/freebsd-arm64": "0.27.3", "@esbuild/freebsd-x64": "0.27.3", "@esbuild/linux-arm": "0.27.3", "@esbuild/linux-arm64": "0.27.3", "@esbuild/linux-ia32": "0.27.3", "@esbuild/linux-loong64": "0.27.3", "@esbuild/linux-mips64el": "0.27.3", "@esbuild/linux-ppc64": "0.27.3", "@esbuild/linux-riscv64": "0.27.3", "@esbuild/linux-s390x": "0.27.3", "@esbuild/linux-x64": "0.27.3", "@esbuild/netbsd-arm64": "0.27.3", "@esbuild/netbsd-x64": "0.27.3", "@esbuild/openbsd-arm64": "0.27.3", "@esbuild/openbsd-x64": "0.27.3", "@esbuild/openharmony-arm64": "0.27.3", "@esbuild/sunos-x64": "0.27.3", "@esbuild/win32-arm64": "0.27.3", "@esbuild/win32-ia32": "0.27.3", "@esbuild/win32-x64": "0.27.3" }, "bin": "bin/esbuild" }, "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg=="],
"escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
"estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
"expand-template": ["[email protected]", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
"expect-type": ["[email protected]", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="],
"fast-check": ["[email protected]", "", { "dependencies": { "pure-rand": "^7.0.0" } }, "sha512-IE9csY7lnhxBnA8g/WI5eg/hygA6MGWJMSNfFRrBlXUciADEhS1EDB0SIsMSvzubzIlOBbVITSsypCsW717poA=="],
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"file-uri-to-path": ["[email protected]", "", {}, "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="],
"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
"find-my-way-ts": ["[email protected]", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"gensync": ["[email protected]", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-tsconfig": ["[email protected]", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="],
"github-from-package": ["[email protected]", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ini": ["[email protected]", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
"ioredis": ["[email protected]", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA=="],
"is-binary-path": ["[email protected]", "", { "dependencies": { "binary-extensions": "^2.0.0" } }, "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw=="],
"is-extglob": ["[email protected]", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-glob": ["[email protected]", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
"is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
"isbot": ["[email protected]", "", {}, "sha512-waFfC72ZNfwLLuJ2iLaoVaqcNo+CAaLR7xCpAn0Y5WfGzkNHv7ZN39Vbi1y+kb+Zs46XHOX3tZNExroFUPX+Kg=="],
"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
"json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
"lodash.defaults": ["[email protected]", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
"lodash.isarguments": ["[email protected]", "", {}, "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg=="],
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"mime": ["[email protected]", "", { "bin": "bin/cli.js" }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="],
"mimic-response": ["[email protected]", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
"minimist": ["[email protected]", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="],
"mkdirp-classic": ["[email protected]", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="],
"mrmime": ["[email protected]", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msgpackr": ["[email protected]", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-bC4UGzHhVvgDNS7kn9tV8fAucIYUBuGojcaLiz7v+P63Lmtm0Xeji8B/8tYKddALXxJLpwIeBmUN3u64C4YkRA=="],
"msgpackr-extract": ["[email protected]", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
"multipasta": ["[email protected]", "", {}, "sha512-KPA58d68KgGil15oDqXjkUBEBYc00XvbPj5/X+dyzeo/lWm9Nc25pQRlf1D+gv4OpK7NM0J1odrbu9JNNGvynA=="],
"nanoid": ["[email protected]", "", { "bin": "bin/nanoid.cjs" }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
"node-abi": ["[email protected]", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ=="],
"node-gyp-build-optional-packages": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
"node-releases": ["[email protected]", "", {}, "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA=="],
"normalize-path": ["[email protected]", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
"obug": ["[email protected]", "", {}, "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ=="],
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["[email protected]", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng=="],
"playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.58.2" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A=="],
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg=="],
"pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
"postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
"pump": ["[email protected]", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
"pure-rand": ["[email protected]", "", {}, "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ=="],
"rc": ["[email protected]", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
"react": ["[email protected]", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="],
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
"readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"readdirp": ["[email protected]", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
"recast": ["[email protected]", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-YTUo+Flmw4ZXiWfQKGcwwc11KnoRAYgzAE2E7mXKCjSviTKShtxBsN6YUUBB2gtaBzKzeKunxhUwNHQuRryhWA=="],
"redis-errors": ["[email protected]", "", {}, "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w=="],
"redis-parser": ["[email protected]", "", { "dependencies": { "redis-errors": "^1.0.0" } }, "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A=="],
"resolve-pkg-maps": ["[email protected]", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
"rollup": ["[email protected]", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.59.0", "@rollup/rollup-android-arm64": "4.59.0", "@rollup/rollup-darwin-arm64": "4.59.0", "@rollup/rollup-darwin-x64": "4.59.0", "@rollup/rollup-freebsd-arm64": "4.59.0", "@rollup/rollup-freebsd-x64": "4.59.0", "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", "@rollup/rollup-linux-arm-musleabihf": "4.59.0", "@rollup/rollup-linux-arm64-gnu": "4.59.0", "@rollup/rollup-linux-arm64-musl": "4.59.0", "@rollup/rollup-linux-loong64-gnu": "4.59.0", "@rollup/rollup-linux-loong64-musl": "4.59.0", "@rollup/rollup-linux-ppc64-gnu": "4.59.0", "@rollup/rollup-linux-ppc64-musl": "4.59.0", "@rollup/rollup-linux-riscv64-gnu": "4.59.0", "@rollup/rollup-linux-riscv64-musl": "4.59.0", "@rollup/rollup-linux-s390x-gnu": "4.59.0", "@rollup/rollup-linux-x64-gnu": "4.59.0", "@rollup/rollup-linux-x64-musl": "4.59.0", "@rollup/rollup-openbsd-x64": "4.59.0", "@rollup/rollup-openharmony-arm64": "4.59.0", "@rollup/rollup-win32-arm64-msvc": "4.59.0", "@rollup/rollup-win32-ia32-msvc": "4.59.0", "@rollup/rollup-win32-x64-gnu": "4.59.0", "@rollup/rollup-win32-x64-msvc": "4.59.0", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg=="],
"safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"seroval": ["[email protected]", "", {}, "sha512-OE4cvmJ1uSPrKorFIH9/w/Qwuvi/IMcGbv5RKgcJ/zjA/IohDLU6SVaxFN9FwajbP7nsX0dQqMDes1whk3y+yw=="],
"seroval-plugins": ["[email protected]", "", { "peerDependencies": { "seroval": "^1.0" } }, "sha512-EAHqADIQondwRZIdeW2I636zgsODzoBDwb3PT/+7TLDWyw1Dy/Xv7iGUIEXXav7usHDE9HVhOU61irI3EnyyHA=="],
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
"simple-concat": ["[email protected]", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
"simple-get": ["[email protected]", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
"sirv": ["[email protected]", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
"source-map": ["[email protected]", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
"standard-as-callback": ["[email protected]", "", {}, "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="],
"std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"strip-json-comments": ["[email protected]", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="],
"tar-fs": ["[email protected]", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ=="],
"tar-stream": ["[email protected]", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tiny-warning": ["[email protected]", "", {}, "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="],
"tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
"tinyexec": ["[email protected]", "", {}, "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg=="],
"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
"tinyrainbow": ["[email protected]", "", {}, "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q=="],
"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
"toml": ["[email protected]", "", {}, "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w=="],
"totalist": ["[email protected]", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="],
"tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": "dist/cli.mjs" }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
"tunnel-agent": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w=="],
"typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-CldZdztDpQRLM1HC6WDQjQkQN5Ub5zRau737a1diGh3lPmb9oRsaWHk1y5iqK0o7+1bNJ0oXfEGRkAogFZBL+Q=="],
"undici": ["[email protected]", "", {}, "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg=="],
"undici-types": ["[email protected]", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"unplugin": ["[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="],
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["[email protected]", "", { "bin": "dist-node/bin/uuid" }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
"vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": "bin/vite.js" }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.0.18", "@vitest/mocker": "4.0.18", "@vitest/pretty-format": "4.0.18", "@vitest/runner": "4.0.18", "@vitest/snapshot": "4.0.18", "@vitest/spy": "4.0.18", "@vitest/utils": "4.0.18", "es-module-lexer": "^1.7.0", "expect-type": "^1.2.2", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^3.10.0", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.0.3", "vite": "^6.0.0 || ^7.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.0.18", "@vitest/browser-preview": "4.0.18", "@vitest/browser-webdriverio": "4.0.18", "@vitest/ui": "4.0.18", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/ui", "happy-dom", "jsdom"], "bin": "vitest.mjs" }, "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ=="],
"vitest-browser-react": ["[email protected]", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "@types/react-dom": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "vitest": "^4.0.0" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-YODQX8mHTJCyKNVYTWJrLEYrUtw+QfLl78owgvuE7C5ydgmGBq6v5s4jK2w6wdPhIZsN9PpV1rQbmAevWJjO9g=="],
"webpack-virtual-modules": ["[email protected]", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
"why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": "cli.js" }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yaml": ["[email protected]", "", { "bin": "bin.mjs" }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="],
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-akNQMv0wW5uyRpD2v2IEyRSZiR+BeGuoB6L310EgGObO44HSMNT8z1xzio28V8qOrgYaopIDNA18YgdXd+qTiw=="],
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
"chokidar/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"node-abi/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
"rc/ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"readdirp/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
"recast/source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
"rollup/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"tsx/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"vite/fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
}
}
+30
View File
@@ -0,0 +1,30 @@
{
"name": "effect-http-ws-cli",
"version": "0.1.0",
"private": true,
"type": "module",
"packageManager": "[email protected]",
"workspaces": {
"packages": ["server", "web"],
"catalog": {
"@effect/platform-node": "4.0.0-beta.27",
"@effect/sql-sqlite-node": "4.0.0-beta.27",
"@effect/atom-react": "4.0.0-beta.27",
"@effect/vitest": "4.0.0-beta.27",
"effect": "4.0.0-beta.27",
"typescript": "6.0.0-beta",
"vitest": "^4.0.18"
}
},
"scripts": {
"dev": "node scripts/dev.mjs",
"start": "node server/src/bin.ts",
"web:dev": "bun run --filter @effect-http-ws-cli/web dev",
"web:build": "bun run --filter @effect-http-ws-cli/web build",
"web:preview": "bun run --filter @effect-http-ws-cli/web preview",
"test": "bun run --filter @effect-http-ws-cli/server test",
"test:web": "bun run --filter @effect-http-ws-cli/web test",
"test:all": "bun run --sequential --workspaces test",
"lint": "bun run --sequential --workspaces lint"
}
}
@@ -0,0 +1 @@
:root{--paper: #f3f0e8;--ink: #13222c;--ink-soft: #345264;--accent: #dc4f18;--accent-soft: #f8bb68;--panel: #fffdf6;--line: #162f3f22;--shadow: 0 16px 40px #0f1e291f}*{box-sizing:border-box}body{margin:0;min-height:100vh;font-family:IBM Plex Sans,Segoe UI,sans-serif;color:var(--ink);background:radial-gradient(circle at 10% 10%,#f7cf9a 0%,transparent 36%),radial-gradient(circle at 92% 88%,#95c7d2 0%,transparent 32%),linear-gradient(165deg,#ece8dc 0%,var(--paper) 48%,#e9dfcf 100%)}.shell{width:min(1100px,100% - 2rem);margin:1.5rem auto;padding:1.5rem;border:1px solid var(--line);border-radius:20px;background:color-mix(in oklab,var(--paper),white 35%);box-shadow:var(--shadow)}.hero{position:relative;overflow:hidden;padding:1.5rem;border-radius:16px;border:1px solid var(--line);background:linear-gradient(140deg,#fff9ed,#f7efe0 65%,#f2e7d4)}.hero:after{content:"";position:absolute;width:220px;height:220px;right:-60px;top:-90px;border-radius:999px;background:linear-gradient(180deg,var(--accent-soft),transparent 70%);pointer-events:none}.eyebrow{margin:0;font-size:.72rem;letter-spacing:.22em;text-transform:uppercase;color:var(--ink-soft)}h1,h2{font-family:Archivo Black,Impact,sans-serif;letter-spacing:.02em;margin:0}h1{margin-top:.35rem;font-size:clamp(1.5rem,4vw,2.35rem)}h2{font-size:1.1rem}.lead{margin:.6rem 0 0;color:var(--ink-soft);max-width:68ch}.panel{border:1px solid var(--line);border-radius:14px;padding:1rem;background:var(--panel);margin-top:1rem}.status-panel{margin-top:0;background:linear-gradient(140deg,#fbf7ee,#f1e8d7)}.status-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.7rem}.status-item{border:1px solid var(--line);border-radius:10px;padding:.55rem .7rem;display:flex;justify-content:space-between;align-items:baseline;gap:.75rem;background:#fff}.status-label{color:var(--ink-soft);font-size:.82rem}.status-subscription-connected{border-color:#24704755;background:#f1fbf5}.status-subscription-connecting{border-color:#8d6a1b55;background:#fff8eb}.status-subscription-idle{border-color:var(--line)}.status-mutation-busy{border-color:#6b3b2e55;background:#fff3ef}.todo-header{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}.meta{display:flex;gap:.75rem;color:var(--ink-soft);font-size:.86rem}.todo-list{margin:.8rem 0 0;padding:0;list-style:none;display:grid;gap:.6rem}.event-list{margin:.8rem 0 0;padding:0;list-style:none;display:grid;gap:.5rem;max-height:260px;overflow:auto}.event-item{border:1px solid var(--line);border-radius:10px;background:#fff;padding:.55rem .65rem}.event-top{display:flex;justify-content:space-between;gap:.6rem;color:var(--ink-soft);font-size:.8rem}.event-body{margin-top:.2rem;display:flex;justify-content:space-between;gap:.75rem;font-size:.9rem}.event-body small{color:var(--ink-soft);white-space:nowrap}.todo-item{display:flex;gap:.8rem;align-items:center;border:1px solid var(--line);border-radius:10px;background:#fff;padding:.65rem}.todo-main{flex:1}.todo-main input{width:100%;margin:0;border:1px solid var(--line);background:#fff;border-radius:8px;padding:.42rem .55rem;color:var(--ink);font:inherit;font-weight:600}.todo-main small{display:block;margin-top:.3rem;color:var(--ink-soft)}.todo-actions{display:flex;gap:.45rem}button{border:1px solid #0f243233;border-radius:8px;background:linear-gradient(160deg,#fff,#f4efe3);color:var(--ink);padding:.4rem .6rem;font:inherit;font-size:.85rem;font-weight:700;cursor:pointer;transition:transform .12s ease,box-shadow .12s ease}button:hover{transform:translateY(-1px);box-shadow:0 8px 18px #0f20321a}.todo-item.is-completed .todo-main input{text-decoration:line-through;color:var(--ink-soft)}.todo-item.is-archived{opacity:.64}.footer{margin-top:1rem;display:flex;gap:1rem;align-items:center;font-size:.88rem;color:var(--ink-soft)}.error{color:var(--accent);font-weight:700}@media(max-width:880px){.shell{width:min(1100px,100% - 1rem);padding:1rem}.todo-item{flex-direction:column;align-items:stretch}.todo-actions{justify-content:flex-end}.status-grid{grid-template-columns:1fr}}
@@ -0,0 +1,35 @@
(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))i(u);new MutationObserver(u=>{for(const o of u)if(o.type==="childList")for(const d of o.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&i(d)}).observe(document,{childList:!0,subtree:!0});function s(u){const o={};return u.integrity&&(o.integrity=u.integrity),u.referrerPolicy&&(o.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?o.credentials="include":u.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(u){if(u.ep)return;u.ep=!0;const o=s(u);fetch(u.href,o)}})();function KR(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zm={exports:{}},au={};var O1;function PR(){if(O1)return au;O1=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function s(i,u,o){var d=null;if(o!==void 0&&(d=""+o),u.key!==void 0&&(d=""+u.key),"key"in u){o={};for(var h in u)h!=="key"&&(o[h]=u[h])}else o=u;return u=o.ref,{$$typeof:e,type:i,key:d,ref:u!==void 0?u:null,props:o}}return au.Fragment=n,au.jsx=s,au.jsxs=s,au}var R1;function XR(){return R1||(R1=1,Zm.exports=PR()),Zm.exports}var ee=XR(),Wm={exports:{}},ye={};var A1;function QR(){if(A1)return ye;A1=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),u=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),d=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),m=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),v=Symbol.iterator;function _(w){return w===null||typeof w!="object"?null:(w=v&&w[v]||w["@@iterator"],typeof w=="function"?w:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T=Object.assign,j={};function B(w,G,re){this.props=w,this.context=G,this.refs=j,this.updater=re||x}B.prototype.isReactComponent={},B.prototype.setState=function(w,G){if(typeof w!="object"&&typeof w!="function"&&w!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,w,G,"setState")},B.prototype.forceUpdate=function(w){this.updater.enqueueForceUpdate(this,w,"forceUpdate")};function M(){}M.prototype=B.prototype;function I(w,G,re){this.props=w,this.context=G,this.refs=j,this.updater=re||x}var z=I.prototype=new M;z.constructor=I,T(z,B.prototype),z.isPureReactComponent=!0;var W=Array.isArray;function H(){}var V={H:null,A:null,T:null,S:null},Y=Object.prototype.hasOwnProperty;function te(w,G,re){var ae=re.ref;return{$$typeof:e,type:w,key:G,ref:ae!==void 0?ae:null,props:re}}function fe(w,G){return te(w.type,G,w.props)}function oe(w){return typeof w=="object"&&w!==null&&w.$$typeof===e}function ie(w){var G={"=":"=0",":":"=2"};return"$"+w.replace(/[=:]/g,function(re){return G[re]})}var A=/\/+/g;function Q(w,G){return typeof w=="object"&&w!==null&&w.key!=null?ie(""+w.key):G.toString(36)}function Z(w){switch(w.status){case"fulfilled":return w.value;case"rejected":throw w.reason;default:switch(typeof w.status=="string"?w.then(H,H):(w.status="pending",w.then(function(G){w.status==="pending"&&(w.status="fulfilled",w.value=G)},function(G){w.status==="pending"&&(w.status="rejected",w.reason=G)})),w.status){case"fulfilled":return w.value;case"rejected":throw w.reason}}throw w}function O(w,G,re,ae,he){var xe=typeof w;(xe==="undefined"||xe==="boolean")&&(w=null);var Ne=!1;if(w===null)Ne=!0;else switch(xe){case"bigint":case"string":case"number":Ne=!0;break;case"object":switch(w.$$typeof){case e:case n:Ne=!0;break;case y:return Ne=w._init,O(Ne(w._payload),G,re,ae,he)}}if(Ne)return he=he(w),Ne=ae===""?"."+Q(w,0):ae,W(he)?(re="",Ne!=null&&(re=Ne.replace(A,"$&/")+"/"),O(he,G,re,"",function(Ur){return Ur})):he!=null&&(oe(he)&&(he=fe(he,re+(he.key==null||w&&w.key===he.key?"":(""+he.key).replace(A,"$&/")+"/")+Ne)),G.push(he)),1;Ne=0;var pt=ae===""?".":ae+":";if(W(w))for(var Ze=0;Ze<w.length;Ze++)ae=w[Ze],xe=pt+Q(ae,Ze),Ne+=O(ae,G,re,xe,he);else if(Ze=_(w),typeof Ze=="function")for(w=Ze.call(w),Ze=0;!(ae=w.next()).done;)ae=ae.value,xe=pt+Q(ae,Ze++),Ne+=O(ae,G,re,xe,he);else if(xe==="object"){if(typeof w.then=="function")return O(Z(w),G,re,ae,he);throw G=String(w),Error("Objects are not valid as a React child (found: "+(G==="[object Object]"?"object with keys {"+Object.keys(w).join(", ")+"}":G)+"). If you meant to render a collection of children, use an array instead.")}return Ne}function N(w,G,re){if(w==null)return w;var ae=[],he=0;return O(w,ae,"","",function(xe){return G.call(re,xe,he++)}),ae}function ne(w){if(w._status===-1){var G=w._result;G=G(),G.then(function(re){(w._status===0||w._status===-1)&&(w._status=1,w._result=re)},function(re){(w._status===0||w._status==Line truncated
at`)?" (<anonymous>)":-1<a.stack.indexOf("@")?"@unknown:0:0":""}return`
`+ps+t+oc}var fc=!1;function Wa(t,r){if(!t||fc)return"";fc=!0;var a=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var c={DetermineComponentFrameRoot:function(){try{if(r){var J=function(){throw Error()};if(Object.defineProperty(J.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(J,[])}catch(F){var q=F}Reflect.construct(t,[],J)}else{try{J.call()}catch(F){q=F}t.call(J.prototype)}}else{try{throw Error()}catch(F){q=F}(J=t())&&typeof J.catch=="function"&&J.catch(function(){})}}catch(F){if(F&&q&&typeof F.stack=="string")return[F.stack,q.stack]}return[null,null]}};c.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var l=Object.getOwnPropertyDescriptor(c.DetermineComponentFrameRoot,"name");l&&l.configurable&&Object.defineProperty(c.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var f=c.DetermineComponentFrameRoot(),g=f[0],b=f[1];if(g&&b){var E=g.split(`
`),L=b.split(`
`);for(l=c=0;c<E.length&&!E[c].includes("DetermineComponentFrameRoot");)c++;for(;l<L.length&&!L[l].includes("DetermineComponentFrameRoot");)l++;if(c===E.length||l===L.length)for(c=E.length-1,l=L.length-1;1<=c&&0<=l&&E[c]!==L[l];)l--;for(;1<=c&&0<=l;c--,l--)if(E[c]!==L[l]){if(c!==1||l!==1)do if(c--,l--,0>l||E[c]!==L[l]){var K=`
`+E[c].replace(" at new "," at ");return t.displayName&&K.includes("<anonymous>")&&(K=K.replace("<anonymous>",t.displayName)),K}while(1<=c&&0<=l);break}}}finally{fc=!1,Error.prepareStackTrace=a}return(a=t?t.displayName||t.name:"")?mr(a):""}function bl(t,r){switch(t.tag){case 26:case 27:case 5:return mr(t.type);case 16:return mr("Lazy");case 13:return t.child!==r&&r!==null?mr("Suspense Fallback"):mr("Suspense");case 19:return mr("SuspenseList");case 0:case 15:return Wa(t.type,!1);case 11:return Wa(t.type.render,!1);case 1:return Wa(t.type,!0);case 31:return mr("Activity");default:return""}}function Nr(t){try{var r="",a=null;do r+=bl(t,a),a=t,t=t.return;while(t);return r}catch(c){return`
Error generating stack: `+c.message+`
`+c.stack}}var ca=Object.prototype.hasOwnProperty,tr=e.unstable_scheduleCallback,dc=e.unstable_cancelCallback,qd=e.unstable_shouldYield,_l=e.unstable_requestPaint,rn=e.unstable_now,xl=e.unstable_getCurrentPriorityLevel,Fe=e.unstable_ImmediatePriority,_t=e.unstable_UserBlockingPriority,Qt=e.unstable_NormalPriority,El=e.unstable_LowPriority,My=e.unstable_IdlePriority,M2=e.log,C2=e.unstable_setDisableYieldValue,hc=null,bn=null;function gs(t){if(typeof M2=="function"&&C2(t),bn&&typeof bn.setStrictMode=="function")try{bn.setStrictMode(hc,t)}catch{}}var _n=Math.clz32?Math.clz32:z2,k2=Math.log,U2=Math.LN2;function z2(t){return t>>>=0,t===0?32:31-(k2(t)/U2|0)|0}var wl=256,Tl=262144,Ol=4194304;function ua(t){var r=t&42;if(r!==0)return r;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Rl(t,r,a){var c=t.pendingLanes;if(c===0)return 0;var l=0,f=t.suspendedLanes,g=t.pingedLanes;t=t.warmLanes;var b=c&134217727;return b!==0?(c=b&~f,c!==0?l=ua(c):(g&=b,g!==0?l=ua(g):a||(a=b&~t,a!==0&&(l=ua(a))))):(b=c&~f,b!==0?l=ua(b):g!==0?l=ua(g):a||(a=c&~t,a!==0&&(l=ua(a)))),l===0?0:r!==0&&r!==l&&(r&f)===0&&(f=l&-l,a=r&-r,f>=a||f===32&&(a&4194048)!==0)?r:l}function mc(t,r){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&r)===0}function N2(t,r){switch(t){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Cy(){var t=Ol;return Ol<<=1,(Ol&62914560)===0&&(Ol=4194304),t}function $d(t){for(var r=[],a=0;31>a;a++)r.push(t);return r}function pc(t,r){t.pendingLanes|=r,r!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function D2(t,r,a,c,l,f){var g=t.pendingLanes;t.pendingLanes=a,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=a,t.entangledLanes&=a,t.errorRecoveryDisabledLanes&=a,t.shellSuspendCounter=0;var b=t.entanglements,E=t.expirationTimes,L=t.hiddenUpdates;for(a=g&~a;0<a;){var K=31-_n(a),J=1<<K;b[K]=0,E[K]=-1;var q=L[K];if(q!==null)for(L[K]=null,K=0;K<q.length;K++){var F=q[K];F!==null&&(F.lane&=-536870913)}a&=~J}c!==0&&ky(t,c,0),f!==0&&l===0&&t.tag!==0&&(t.suspendedLanes|=f&~(g&~r))}function ky(t,r,a){t.pendingLanes|=r,t.suspendedLanes&=~r;var c=31-_n(r);t.entangledLanes|=r,t.entanglements[c]=t.entanglements[c]|1073741824|a&261930}function Uy(t,r){var a=t.entangledLanes|=r;for(t=t.entanglements;a;){var c=31-_n(a),l=1<<c;l&r|t[c]&r&&(t[c]|=r),a&=~l}}function zy(t,r){var a=r&-r;return a=(a&42)!==0?1:Hd(a),(a&(t.suspendedLanes|r))!==0?0:a}function Hd(t){switch(t){case 2:t=1;break;case 8:t=4;break;case 32:t=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:t=128;break;case 268435456:t=134217728;break;default:t=0}return t}function Vd(t){return t&=-t,2<t?8<t?(t&134217727)!==0?32:268435456:8:2}function Ny(){var t=N.p;return t!==0?t:(t=window.event,t===void 0?32:v1(t.type))}function Dy(t,r){var a=N.p;try{return N.p=t,r()}finally{N.p=a}}var ys=Math.random().toString(36).slice(2),It="__reactFiber$"+ys,cn="__reactProps$"+ys,ei="__reactContainer$"+ys,Id="__reactEvents$"+ys,L2="__reactListeners$"+ys,j2="__reactHandles$"+ys,Ly="__reactResources$"+ys,gc="__reactMarker$"+ys;function Yd(t){delete t[It],delete t[cn],delete t[Id],delete t[L2],delete t[j2]}function ti(t){var r=t[It];if(r)return r;for(var a=t.parentNode;a;){if(r=a[ei]||a[It]){if(a=r.alternate,r.child!==null||a!==null&&a.child!==null)for(t=r1(t);t!==null;){if(a=t[It])return a;t=r1(t)}return r}t=a,a=t.parentNode}return null}function ni(t){if(t=t[It]||t[ei]){var r=t.tag;if(r===5||r===6||r===13||r===31||r===26||r===27||r===3)return t}return null}function yc(t){var r=t.tag;if(r===5||r===26||r===27||r===6)return t.stateNode;throw Error(i(33))}function ri(t){var r=t[Ly];return r||(r=t[Ly]={hoistableStyles:new Map,hoistableScripts:new Map}),r}function zt(t){t[gc]=!0}var jy=new Set,By={};function la(t,r){si(t,r),si(t+"Capture",r)}function si(t,r){for(By[t]=r,t=0;t<r.length;t++)jy.add(r[t])}var B2=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u21 Line truncated
`).replace(pR,"")}function Kb(t,r){return r=Fb(r),Fb(t)===r}function Ye(t,r,a,c,l,f){switch(a){case"children":typeof c=="string"?r==="body"||r==="textarea"&&c===""||ii(t,c):(typeof c=="number"||typeof c=="bigint")&&r!=="body"&&ii(t,""+c);break;case"className":Ml(t,"class",c);break;case"tabIndex":Ml(t,"tabindex",c);break;case"dir":case"role":case"viewBox":case"width":case"height":Ml(t,a,c);break;case"style":Ky(t,c,f);break;case"data":if(r!=="object"){Ml(t,"data",c);break}case"src":case"href":if(c===""&&(r!=="a"||a!=="href")){t.removeAttribute(a);break}if(c==null||typeof c=="function"||typeof c=="symbol"||typeof c=="boolean"){t.removeAttribute(a);break}c=kl(""+c),t.setAttribute(a,c);break;case"action":case"formAction":if(typeof c=="function"){t.setAttribute(a,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof f=="function"&&(a==="formAction"?(r!=="input"&&Ye(t,r,"name",l.name,l,null),Ye(t,r,"formEncType",l.formEncType,l,null),Ye(t,r,"formMethod",l.formMethod,l,null),Ye(t,r,"formTarget",l.formTarget,l,null)):(Ye(t,r,"encType",l.encType,l,null),Ye(t,r,"method",l.method,l,null),Ye(t,r,"target",l.target,l,null)));if(c==null||typeof c=="symbol"||typeof c=="boolean"){t.removeAttribute(a);break}c=kl(""+c),t.setAttribute(a,c);break;case"onClick":c!=null&&(t.onclick=Lr);break;case"onScroll":c!=null&&Re("scroll",t);break;case"onScrollEnd":c!=null&&Re("scrollend",t);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(i(61));if(a=c.__html,a!=null){if(l.children!=null)throw Error(i(60));t.innerHTML=a}}break;case"multiple":t.multiple=c&&typeof c!="function"&&typeof c!="symbol";break;case"muted":t.muted=c&&typeof c!="function"&&typeof c!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(c==null||typeof c=="function"||typeof c=="boolean"||typeof c=="symbol"){t.removeAttribute("xlink:href");break}a=kl(""+c),t.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",a);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":c!=null&&typeof c!="function"&&typeof c!="symbol"?t.setAttribute(a,""+c):t.removeAttribute(a);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":c&&typeof c!="function"&&typeof c!="symbol"?t.setAttribute(a,""):t.removeAttribute(a);break;case"capture":case"download":c===!0?t.setAttribute(a,""):c!==!1&&c!=null&&typeof c!="function"&&typeof c!="symbol"?t.setAttribute(a,c):t.removeAttribute(a);break;case"cols":case"rows":case"size":case"span":c!=null&&typeof c!="function"&&typeof c!="symbol"&&!isNaN(c)&&1<=c?t.setAttribute(a,c):t.removeAttribute(a);break;case"rowSpan":case"start":c==null||typeof c=="function"||typeof c=="symbol"||isNaN(c)?t.removeAttribute(a):t.setAttribute(a,c);break;case"popover":Re("beforetoggle",t),Re("toggle",t),Al(t,"popover",c);break;case"xlinkActuate":Dr(t,"http://www.w3.org/1999/xlink","xlink:actuate",c);break;case"xlinkArcrole":Dr(t,"http://www.w3.org/1999/xlink","xlink:arcrole",c);break;case"xlinkRole":Dr(t,"http://www.w3.org/1999/xlink","xlink:role",c);break;case"xlinkShow":Dr(t,"http://www.w3.org/1999/xlink","xlink:show",c);break;case"xlinkTitle":Dr(t,"http://www.w3.org/1999/xlink","xlink:title",c);break;case"xlinkType":Dr(t,"http://www.w3.org/1999/xlink","xlink:type",c);break;case"xmlBase":Dr(t,"http://www.w3.org/XML/1998/namespace","xml:base",c);break;case"xmlLang":Dr(t,"http://www.w3.org/XML/1998/namespace","xml:lang",c);break;case"xmlSpace":Dr(t,"http://www.w3.org/XML/1998/namespace","xml:space",c);break;case"is":Al(t,"is",c);break;case"innerText":case"textContent":break;default:(!(2<a.length)||a[0]!=="o"&&a[0]!=="O"||a[1]!=="n"&&a[1]!=="N")&&(a=I2.get(a)||a,Al(t,a,c))}}function Nm(t,r,a,c,l,f){switch(a){case"style":Ky(t,c,f);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(i(61));if(a=c.__html,a!=null){if(l.children!=null)throw Error(i(60));t.innerHTML=a}}break;case"children":typeof c=="string"?ii(t,c):(typeof c=="number"||typeof c=="bigint")&&ii(t,""+c);break;case"onScroll":c!=null&&Re("scroll",t);break;case"onScrollEnd":c!=null&&Re("scrollend",t);break;case"onClick":c!=null&&(t.onclick=Lr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"inne Line truncated
`+o(y+1));return`[
${o(y+1)}${S}
${o(y)}]`}if(m instanceof Date)return MA(m);if(!n?.ignoreToString&&Be(m,"toString")&&typeof m.toString=="function"&&m.toString!==Object.prototype.toString&&m.toString!==Array.prototype.toString){const S=CA(m);return m instanceof Error&&m.cause?`${S} (cause: ${p(m.cause,y)})`:S}if(typeof m=="string")return JSON.stringify(m);if(typeof m=="number"||m==null||typeof m=="boolean"||typeof m=="symbol")return String(m);if(typeof m=="bigint")return String(m)+"n";if(typeof m=="object"||typeof m=="function"){if(i.has(m))return j1;if(i.add(m),Zf in m)return Rt(Lx(m));if(Symbol.iterator in m)return`${m.constructor.name}(${p(Array.from(m),y)})`;const S=h(m);if(!u||S.length<=1){const _=`{${S.map(x=>`${ff(x)}:${p(m[x],y)}`).join(",")}}`;return d(m,_)}const v=`{
${S.map(_=>`${o(y+1)}${ff(_)}: ${p(m[_],y+1)}`).join(`,
`)}
${o(y)}}`;return d(m,v)}return String(m)}return p(e,0)}const j1="[Circular]";function ff(e){return typeof e=="string"?JSON.stringify(e):String(e)}function AA(e){return e.map(n=>`[${ff(n)}]`).join("")}function MA(e){try{return e.toISOString()}catch{return"Invalid Date"}}function CA(e){try{const n=e.toString();return typeof n=="string"?n:String(n)}catch{return"[toString threw]"}}function jx(e,n){let s=[];const i=JSON.stringify(e,(u,o)=>typeof o=="object"&&o!==null?s.includes(o)?void 0:s.push(o)&&Wf(o):o,n?.space);return s=void 0,i}const Ws=Symbol.for("nodejs.util.inspect.custom"),Fa=e=>{try{if(Be(e,"toJSON")&&Qf(e.toJSON)&&e.toJSON.length===0)return e.toJSON();if(Array.isArray(e))return e.map(Fa)}catch{return"[toJSON threw]"}return Wf(e)},kA=(e,n=2)=>{if(typeof e=="string")return e;try{return typeof e=="object"?UA(e,n):String(e)}catch{return String(e)}},UA=(e,n)=>{let s=[];const i=JSON.stringify(e,(u,o)=>typeof o=="object"&&o!==null?s.includes(o)?void 0:s.push(o)&&Wf(o):o,n);return s=void 0,i},B1={toJSON(){return Fa(this)},[Ws](){return this.toJSON()},toString(){return Rt(this.toJSON())}};class ed{called=!1;self;constructor(n){this.self=n}next(n){return this.called?{value:n,done:!0}:(this.called=!0,{value:this.self,done:!1})}[Symbol.iterator](){return new ed(this.self)}}const Pi="~effect/Effect/internal",Bx={[Pi]:e=>e()},zA={[Pi]:e=>e()},NA=Bx[Pi](()=>new Error().stack)?.includes(Pi)===!0,Wt=NA?Bx[Pi]:zA[Pi],ls="~effect/Effect",ku="~effect/Exit",DA={_A:_e,_E:_e,_R:_e},qx=`${ls}/identifier`,we=`${ls}/args`,Ht=`${ls}/evaluate`,kn=`${ls}/successCont`,_r=`${ls}/failureCont`,ja=`${ls}/ensureCont`,Aa=Symbol.for("effect/Effect/Yield"),Ar={pipe(){return bt(this,arguments)},toJSON(){return{...this}},toString(){return Rt(this.toJSON(),{ignoreToString:!0,space:2})},[Ws](){return this.toJSON()}},td={[Symbol.iterator](){return new ed(this)}},LA={...td,pipe(){return bt(this,arguments)}},jA={[ls]:DA,...Ar,[Symbol.iterator](){return new ed(this)},asEffect(){return this},toJSON(){return{_id:"Effect",op:this[qx],...we in this?{args:this[we]}:void 0}}},Xt=e=>Be(e,ls),$x=e=>Be(e,ku),Xo="~effect/Cause",Qo="~effect/Cause/Reason",nd=e=>Be(e,Xo),BA=e=>Be(e,Qo);class Ka{[Xo];reasons;constructor(n){this[Xo]=Xo,this.reasons=n}pipe(){return bt(this,arguments)}toJSON(){return{_id:"Cause",failures:this.reasons.map(n=>n.toJSON())}}toString(){return`Cause(${Rt(this.reasons)})`}[Ws](){return this.toJSON()}[nn](n){return nd(n)&&this.reasons.length===n.reasons.length&&this.reasons.every((s,i)=>$t(s,n.reasons[i]))}[tn](){return Dx(this.reasons)}}const q1=new WeakMap;class Hg{[Qo];annotations;_tag;constructor(n,s,i){if(this[Qo]=Qo,this._tag=n,s!==rd&&typeof i=="object"&&i!==null&&s.size>0){const u=q1.get(i);u&&(s=new Map([...u,...s])),q1.set(i,s)}this.annotations=s}annotate(n,s){if(n.mapUnsafe.size===0)return this;const i=new Map(this.annotations);n.mapUnsafe.forEach((o,d)=>{s?.overwrite!==!0&&i.has(d)||i.set(d,o)});const u=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return u.annotations=i,u}pipe(){return bt(this,arguments)}toString(){return Rt(this)}[Ws](){return this.toString()}}const rd=new Map;class Hx extends Hg{error;constructor(n,s=rd){super("Fail",s,n),this.error=n}toString(){return`Fail(${Rt(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[nn](n){return Yg(n)&&$t(this.error,n.error)&&$t(this.annotations,n.annotations)}[tn](){return Xn(Mt(this._tag))(Xn(Je(this.error))(Je(this.annotations)))}}const sd=e=>new Ka(e),qA=new Ka([]),Vg=e=>new Ka([new Hx(e)]);class Ig extends Hg{defect;constructor(n,s=rd){super("Die",s,n),this.defect=n}toString(){return`Die(${Rt(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[nn](n){return HA(n)&&$t(this.defect,n.defect)&&$t(this.annotations,n.annotations)}[tn](){return Xn(Mt(this._tag))(Xn(Je(this.defect))(Je(this.annotations)))}}const $A=e=>new Ka([new Ig(e)]),Hp=P(e=>nd(e[0]),(e,n,s)=>n.mapUnsafe.size===0?e:new Ka(e.reasons.map(i=>i.annotate(n,s)))),Yg=e=>e._tag==="Fail",HA=e=>e._tag==="Die",Gg=e=>e._tag==="Interrupt";function VA(e){return Xi("Effect.evaluate: Not implemented")}const Zu=e=>({...jA,[qx]:e.op,[Ht]:e[Ht]??VA,[kn]:e[kn],[_r]:e[_r],[ja]:e[ja]}),or=e=>{const n=Zu(e);return function(){const s=Object.create(n);return s[we]=e.single===!1?arguments:arguments[0],s}},Vx=e=>{const n={...Zu(e),[ku]:ku,_tag:e.op,get[e.prop](){return this[we]},toString(){return`${e.op}(${Rt(this[we])})`},toJSON(){return{_id:"Exit",_tag:e.op,[e.prop]:this[we]}},[nn](s){return $x(s)&&s._tag===this._tag&&$t(this[we],s[we])},[tn](){return Xn(Mt(e.op),Je(this[we]))}};return function(s){const i=Object.create(n);return i[we]=s,i}},et=Vx({op:"Success",prop:"value",[Ht](e){const n=e.getCont(kn);return n?n[kn](this[we],e,this):e.yieldWith(this)}}),ad={key:"effect/Cause/StackTrace"},IA={key:"effect/Cause/InterruptorStackTrace"},Jn=Vx({op:"Failure",prop:"cause",[Ht](e){let n=this[we],s=!1;e.currentStackFrame&&(n=Hp(n,{mapUnsafe:new Map([[ad.key,e.currentStackFrame]])}),s=!0);let i=e.get Line truncated
`);if(s.length>2){const i=s[2].match(/at (.*)/);i&&(n.message=n.message+` (defined at ${i[1]})`)}}if(n.stack){const s=n.stack.split(`
`);s.splice(1,3),n.stack=s.join(`
`)}return n},Ba=P(2,(e,n)=>{if(e.mapUnsafe.size===0)return n;if(n.mapUnsafe.size===0)return e;const s=new Map(e.mapUnsafe);return n.mapUnsafe.forEach((i,u)=>s.set(u,i)),ir(s)}),lC=(...e)=>{const n=new Map;for(let s=0;s<e.length;s++)e[s].mapUnsafe.forEach((i,u)=>{n.set(u,i)});return ir(n)},ft=Sn,Ji=ft("effect/Scheduler",{defaultValue:()=>new Nu}),oC="setImmediate"in globalThis?e=>{const n=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(n)}:e=>{const n=setTimeout(e,0);return()=>clearTimeout(n)};class fC{buckets=[];scheduleTask(n,s){const i=this.buckets,u=i.length;let o,d=0;for(;d<u&&!(i[d][0]>s);d++)o=i[d];o&&o[0]===s?o[1].push(n):d===u?i.push([s,[n]]):i.splice(d,0,[s,[n]])}drain(){const n=this.buckets;return this.buckets=[],n}}class Nu{tasks=new fC;running=void 0;executionMode;setImmediate;constructor(n="async",s=oC){this.executionMode=n,this.setImmediate=s}scheduleTask(n,s){this.tasks.scheduleTask(n,s),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){const n=this.tasks.drain();for(let s=0;s<n.length;s++){const i=n[s][1];for(let u=0;u<i.length;u++)i[u]()}}shouldYield(n){return n.currentOpCount>=n.maxOpsBeforeYield}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}}const dC=ft("effect/Scheduler/MaxOpsBeforeYield",{defaultValue:()=>2048}),hE="effect/Tracer/ParentSpan";class hC extends Sn()(hE){}const mC=e=>e,Fp=ft("effect/Tracer/DisablePropagation",{defaultValue:Ux}),pC=ft("effect/Tracer/CurrentTraceLevel",{defaultValue:()=>"Info"}),gC=ft("effect/Tracer/MinimumTraceLevel",{defaultValue:()=>"All"}),mE="effect/Tracer",yC=ft(mE,{defaultValue:()=>mC({span:e=>new SC(e)})});class SC{_tag="Span";spanId;traceId="native";sampled;name;parent;annotations;links;startTime;kind;status;attributes;events=[];constructor(n){this.name=n.name,this.parent=n.parent,this.annotations=n.annotations,this.links=n.links,this.startTime=n.startTime,this.kind=n.kind,this.sampled=n.sampled,this.status={_tag:"Started",startTime:n.startTime},this.attributes=new Map,this.traceId=n.parent?.traceId??Y1(32),this.spanId=Y1(16)}end(n,s){this.status={_tag:"Ended",endTime:n,exit:s,startTime:this.status.startTime}}attribute(n,s){this.attributes.set(n,s)}event(n,s,i){this.events.push([n,s,i??{}])}addLinks(n){this.links.push(...n)}}const Y1=(function(){const e="abcdef0123456789",n=e.length;return function(s){let i="";for(let u=0;u<s;u++)i+=e.charAt(Math.floor(Math.random()*n));return i}})(),vC=ft("effect/References/CurrentConcurrency",{defaultValue:()=>"unbounded"}),pE=ft("effect/References/CurrentStackFrame",{defaultValue:jg}),bC=ft("effect/References/TracerEnabled",{defaultValue:Pf}),gE=ft("effect/References/TracerTimingEnabled",{defaultValue:Pf}),_C=ft("effect/References/TracerSpanAnnotations",{defaultValue:()=>({})}),xC=ft("effect/References/TracerSpanLinks",{defaultValue:()=>[]}),Zg=ft("effect/References/CurrentLogAnnotations",{defaultValue:()=>({})}),EC=ft("effect/References/CurrentLogLevel",{defaultValue:()=>"Info"}),wC=ft("effect/References/MinimumLogLevel",{defaultValue:()=>"Info"}),TC=ft("effect/References/CurrentLogSpans",{defaultValue:()=>[]}),OC="effect/observability/Metric/FiberRuntimeMetricsKey",RC=e=>{if(e?.captureStackTrace===!1)return e;if(e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!="boolean")return e;const n=Error.stackTraceLimit;Error.stackTraceLimit=3;const s=new Error;return Error.stackTraceLimit=n,{...e,captureStackTrace:MC(()=>s.stack)}},AC=e=>n=>{let s;return()=>{if(s!==void 0)return s;const i=n();if(!i)return;const u=i.split(`
`);if(u[e]!==void 0)return s=u[e].trim(),s}},MC=AC(3),CC="dev";let yE=class extends Hg{fiberId;constructor(n,s=rd){super("Interrupt",s,"Interrupted"),this.fiberId=n}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[nn](n){return Gg(n)&&this.fiberId===n.fiberId&&this.annotations===n.annotations}[tn](){return Xn(Mt(`${this._tag}:${this.fiberId}`))($p(this.annotations))}};const kC=e=>new yE(e),el=e=>new Ka([new yE(e)]),UC=e=>{const n=e.reasons.find(Yg);return n?fs(n):ur(e)},Pa=e=>{for(let n=0;n<e.reasons.length;n++){const s=e.reasons[n];if(s._tag==="Fail")return fs(s.error)}return ur(e)},zC=e=>e.reasons.some(Gg),Wg=e=>{let n;for(let s=0;s<e.reasons.length;s++){const i=e.reasons[s];i._tag==="Interrupt"&&(n??=new Set,i.fiberId!==void 0&&n.add(i.fiberId))}return n?fs(n):ur(e)},NC=e=>{const n=Wg(e);return ct(n)?DC:n.success},DC=new Set,LC=e=>e.reasons.every(Gg),jC=P(2,(e,n)=>{if(e.reasons.length===0)return n;if(n.reasons.length===0)return e;const s=new Ka(CM(e.reasons,n.reasons));return $t(e,s)?e:s}),BC=e=>{const n={Fail:[],Die:[],Interrupt:[]};for(let s=0;s<e.reasons.length;s++)n[e.reasons[s]._tag].push(e.reasons[s]);return n},SE=e=>{const n=BC(e);return n.Fail.length>0?n.Fail[0].error:n.Die.length>0?n.Die[0].defect:n.Interrupt.length>0?new globalThis.Error("All fibers interrupted without error"):new globalThis.Error("Empty cause")},qC=e=>{const n=[],s=[];if(e.reasons.length===0)return n;const i=Error.stackTraceLimit;Error.stackTraceLimit=1;for(const u of e.reasons){if(u._tag==="Interrupt"){s.push(u);continue}n.push(Kp(u._tag==="Die"?u.defect:u.error,u.annotations))}if(n.length===0){const u=new Error("The fiber was interrupted by:");u.name="InterruptCause",u.stack=IC(u,s);const o=new globalThis.Error("All fibers interrupted without error",{cause:u});o.name="InterruptError",o.stack=`${o.name}: ${o.message}`,n.push(Kp(o,s[0].annotations))}return Error.stackTraceLimit=i,n},Kp=(e,n)=>{const s=typeof e;let i;if(e&&s==="object"){if(i=new globalThis.Error($C(e),{cause:e.cause?Kp(e.cause):void 0}),typeof e.name=="string"&&(i.name=e.name),typeof e.stack=="string")i.stack=VC(e.stack,i,n);else{const u=`${i.name}: ${i.message}`;i.stack=n?vE(u,n):u}for(const u of Object.keys(e))u in i||(i[u]=e[u])}else i=new globalThis.Error(e?s==="string"?e:jx(e):`Unknown error: ${e}`);return i},$C=e=>{if(typeof e.message=="string")return e.message;if(typeof e.toString=="function"&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return jx(e)},HC=/\((.*)\)/g,VC=(e,n,s)=>{const i=`${n.name}: ${n.message}`,u=(e.startsWith(i)?e.slice(i.length):e).split(`
`),o=[i];for(let d=1;d<u.length&&!/(?:Generator\.next|~effect\/Effect)/.test(u[d]);d++)o.push(u[d]);return s?vE(o.join(`
`),s):o.join(`
`)},vE=(e,n)=>{const s=n?.get(ad.key);return s&&(e=`${e}
${bE(s)}`),e},IC=(e,n)=>{const s=[`${e.name}: ${e.message}`];for(const i of n){const u=i.fiberId!==void 0?`#${i.fiberId}`:"unknown",o=i.annotations.get(IA.key);s.push(` at fiber (${u})`),o&&s.push(bE(o))}return s.join(`
`)},bE=e=>{const n=[];let s=e,i=0;for(;s&&i<10;){const u=s.stack();if(u){const o=u.matchAll(HC);let d=!1;for(const[,h]of o)d=!0,n.push(` at ${s.name} (${h})`);d||n.push(` at ${s.name} (${u.replace(/^at /,"")})`)}else n.push(` at ${s.name}`);s=s.parent,i++}return n.join(`
`)},e0=e=>qC(e).map(n=>n.cause?`${n.stack} {
${_E(n.cause," ")}
}`:n.stack).join(`
`),_E=(e,n)=>{const s=e.stack.split(`
`);let i=`${n}[cause]: ${s[0]}`;for(let u=1,o=s.length;u<o;u++)i+=`
${n}${s[u]}`;return e.cause&&(i+=` {
${_E(e.cause,`${n} `)}
${n}}`),i},Pp=`~effect/Fiber/${CC}`,YC={_A:_e,_E:_e},GC={id:0},xE=()=>globalThis[Su];class EE{constructor(n,s=!0){this[Pp]=YC,this.setServices(n),this.id=++GC.id,this.currentOpCount=0,this.currentLoopCount=0,this.interruptible=s,this._stack=[],this._observers=[],this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0}[Pp];id;interruptible;currentOpCount;currentLoopCount;_stack;_observers;_exit;_currentExit;_children;_interruptedCause;_yielded;services;currentScheduler;currentTracerContext;currentSpan;currentLogLevel;minimumLogLevel;currentStackFrame;runtimeMetrics;maxOpsBeforeYield;getRef(n){return cC(this.services,n)}addObserver(n){return this._exit?(n(this._exit),cc):(this._observers.push(n),()=>{const s=this._observers.indexOf(n);s>=0&&this._observers.splice(s,1)})}interruptUnsafe(n,s){if(this._exit)return;let i=el(n);this.currentStackFrame&&(i=Hp(i,Qi(ad,this.currentStackFrame))),s&&(i=Hp(i,s)),this._interruptedCause=this._interruptedCause?jC(this._interruptedCause,i):i,this.interruptible&&this.evaluate(en(this._interruptedCause))}pollUnsafe(){return this._exit}evaluate(n){if(this.runtimeMetrics?.recordFiberStart(this.services),this._exit)return;if(this._yielded!==void 0){const i=this._yielded;this._yielded=void 0,i()}const s=this.runLoop(n);if(s!==Aa){this._exit=s,this.runtimeMetrics?.recordFiberEnd(this.services,this._exit);for(let i=0;i<this._observers.length;i++)this._observers[i](s);this._observers.length=0}}runLoop(n){const s=globalThis[Su];globalThis[Su]=this;let i=!1,u=n;this.currentOpCount=0;const o=++this.currentLoopCount;try{for(;;){if(this.currentOpCount++,!i&&this.currentScheduler.shouldYield(this)){i=!0;const d=u;u=qe(n0,()=>d)}if(u=this.currentTracerContext?this.currentTracerContext(u,this):u[Ht](this),o!==this.currentLoopCount)return Aa;if(u===Aa){const d=this._yielded;return ku in d?(this._yielded=void 0,d):Aa}}}catch(d){return Be(u,Ht)?this.runLoop(Xi(d)):Xi(`Fiber.runLoop: Not a valid effect: ${String(u)}`)}finally{globalThis[Su]=s}}getCont(n){for(;;){const s=this._stack.pop();if(!s)return;const i=s[ja]&&s[ja](this);if(i)return i[n]=i,i;if(s[n])return s}}yieldWith(n){return this._yielded=n,Aa}children(){return this._children??=new Set}pipe(){return bt(this,arguments)}setServices(n){this.services=n,this.currentScheduler=this.getRef(Ji),this.currentSpan=n.mapUnsafe.get(hE),this.currentLogLevel=this.getRef(EC),this.minimumLogLevel=this.getRef(wC),this.currentStackFrame=n.mapUnsafe.get(pE.key),this.maxOpsBeforeYield=this.getRef(dC),this.runtimeMetrics=n.mapUnsafe.get(OC);const s=n.mapUnsafe.get(mE);this.currentTracerContext=s?s.context:void 0}get currentSpanLocal(){return this.currentSpan?._tag==="Span"?this.currentSpan:void 0}}const cd=e=>{if(!e.currentStackFrame)return;const n=new Map;return n.set(ad.key,e.currentStackFrame),ir(n)},FC=e=>{const n=e;return n._exit?ve(n._exit):an(s=>n._exit?s(ve(n._exit)):lt(e.addObserver(i=>s(ve(i)))))},wE=e=>an(n=>{const s=e[Symbol.iterator](),i=[];let u;function o(){let d=s.next();for(;!d.done;){if(d.value._exit){i.push(d.value._exit),d=s.next();continue}u=d.value.addObserver(h=>{i.push(h),o()});return}n(ve(i))}return o(),lt(()=>u?.())}),KC=e=>{const n=e;return n._exit?n._exit:an(s=>n._exit?s(n._exit):lt(e.addObserver(s)))},PC=e=>an(n=>{const s=Array.from(e);if(s.length===0)return n(ve(Ip()));const i=new Array(s.length),u=Ip();let o=0,d=!1;for(let h=0;h<s.length&&!d;h++)u.push(s[h].addObserver(p=>{if(o++,p._tag==="Failure")return d=!0,u.forEach(m=>m()),n(p);i[h]=p.value,o===s.length&&n(ve(i))}))}),t0=e=>Ve(n=>XC(e,n.id)),XC=P(e=>Be(e[0],Pp),(e,n,s)=>Ve(i=>{let u=cd(i);return u=u&&s?Ba(u,s):u??s,e.interruptUnsafe(n,u),ld(FC(e))})),mf=e=>Ve(n=>{const s=cd(n);for(const i of e)i.interruptUnsafe(n.id,s);return ld(wE(e))}),ve=et,en=Jn,ud=Mr,lt=or({op:"Sync",[Ht](e){const n=this[we](),s=e.getCont(kn);return s?s[kn](n,e):e.yieldWith(et(n))}}),ot=or({op:"Suspend",[Ht](e){return this[we]()}}),QC=or({op:"Yield",[Ht](e){let n=!1;return e.currentScheduler.scheduleTask(()=>{n||e.evaluate(Or)},this[we]??0),e.yieldWith(()=>{n=!0})}}),n0=QC(0),JC=e=>ve(Te(e)),r0=ve(Ct()),s0=e=>Xi(e),TE=e=>ot(()=>ud(Wt(e))),kt=ve(void 0),ZC=e=>OE(function(n,s){Wt(()=>e(s)).then(i=>n(ve(i)),i=>n(s0(i)))},e.length!==0),WC=e=>Ve(n=>e(n.id)),OE=or({op:"Async",single:!1,[Ht](e){const n=Wt(()=>this[we][0].bind(e.currentScheduler));let s=!1,i=!1;const u=this[we][1]?new AbortController:void 0,o=n(d=>{s||(s=!0,i?e.evaluate(d):i=d)},u?.signal);return i!==!1?i:(i=!0,e._yielded=()=>{s=!0},u===void 0&&o===void 0||e._stack.push(e3(()=>(s=!0,u?.abort(),o??Or))),Aa)}}),e3=or({op:"AsyncFinalizer",[ja](e){e.interruptible&&(e.interruptible=!1,e._stack.push(gd))},[_r](e,n){return zC(e)?qe(this[we](),()=>en(e)):en(e)}}),an=e=>OE(e,e.length>=2),t3=an(cc),n3=(...e)=>ot(()=>Du(e.length===1?e[0]():e[1].call(e[0].self))),RE=(e,...n)=>{const s=n.length===0?function(){return ot(()=>Du(e.apply(this,arguments)))}:function(){let i=ot(()=>Du(e.apply(this,arguments)));for(let u=0;u<n Line truncated
`)}const yz=gz();function Sz(e){let n=e.message;if(e.path&&e.path.length>0){const s=AA(e.path);n+=`
at ${s}`}return n}function Yu(e){switch(e._tag){case"InvalidType":case"OneOf":case"Composite":case"AnyOf":return uu(e.ast.annotations);case"InvalidValue":case"Forbidden":return uu(e.annotations);case"MissingKey":return uu(e.annotations,"messageMissingKey");case"UnexpectedKey":return uu(e.ast.annotations,"messageUnexpectedKey");case"Filter":return uu(e.filter.annotations);case"Encoding":return Yu(e.issue)}}function uu(e,n="message"){const s=e?.[n];if(typeof s=="string")return s}function h_(e){return os(e)?"no value provided":Rt(e.value)}class ec extends Kf{run;constructor(n){super(),this.run=n}map(n){return new ec((s,i)=>this.run(s,i).pipe(vw(Pg(n))))}compose(n){return m_(this)?n:m_(n)?this:new ec((s,i)=>this.run(s,i).pipe(Ii(u=>n.run(u,i))))}}const Uw=new ec(Ee);function m_(e){return e.run===Uw.run}function tc(){return Uw}function pn(e){return vz(Pg(e))}function vz(e){return new ec(n=>Ee(e(n)))}function bz(){return pn(globalThis.String)}function zw(){return pn(globalThis.Number)}const og="~effect/SchemaTransformation/Transformation";class gn{[og]=og;_tag="Transformation";decode;encode;constructor(n,s){this.decode=n,this.encode=s}flip(){return new gn(this.encode,this.decode)}compose(n){return new gn(this.decode.compose(n.decode),n.encode.compose(this.encode))}}function _z(e){return Be(e,og)}const Nw=e=>_z(e)?e:new gn(e.decode,e.encode);function Ed(e){return new gn(pn(e.decode),pn(e.encode))}const xz=new gn(tc(),tc());function $0(){return xz}const Dw=new gn(zw(),bz()),Lw=e=>Ed({decode:n=>{const s=new Error(n.message);return typeof n.name=="string"&&n.name!=="Error"&&(s.name=n.name),typeof n.stack=="string"&&(s.stack=n.stack),s},encode:n=>{const s={name:n.name,message:n.message};return e?.includeStack&&typeof n.stack=="string"&&(s.stack=n.stack),s}});function Ja(e){return n=>n._tag===e}const jw=Ja("Declaration"),Ez=Ja("Never"),Of=Ja("Literal"),wz=Ja("UniqueSymbol"),Tz=Ja("Arrays"),Oz=Ja("Objects"),Rz=Ja("Union");let Vt=class{to;transformation;constructor(n,s){this.to=n,this.transformation=s}};const Az={};class nc{isOptional;isMutable;defaultValue;annotations;constructor(n,s,i=void 0,u=void 0){this.isOptional=n,this.isMutable=s,this.defaultValue=i,this.annotations=u}}const p_="~effect/Schema";class vn{[p_]=p_;annotations;checks;encoding;context;constructor(n=void 0,s=void 0,i=void 0,u=void 0){this.annotations=n,this.checks=s,this.encoding=i,this.context=u}toString(){return`<${this._tag}>`}}class ol extends vn{_tag="Declaration";typeParameters;run;constructor(n,s,i,u,o,d){super(i,u,o,d),this.typeParameters=n,this.run=s}getParser(){const n=this.run(this.typeParameters);return(s,i)=>os(s)?b0:vw(n(s.value,this,i),Te)}recur(n){const s=rc(this.typeParameters,n);return s===this.typeParameters?this:new ol(s,this.run,this.annotations,this.checks,void 0,this.context)}getExpected(){const n=this.annotations?.expected;return typeof n=="string"?n:"<Declaration>"}}class Mz extends vn{_tag="Null";getParser(){return Od(this,null)}getExpected(){return"null"}}const Bw=new Mz;let Cz=class extends vn{_tag="Undefined";getParser(){return Od(this,void 0)}toCodecJson(){return qt(this,[qw])}getExpected(){return"undefined"}};const qw=new Vt(Bw,new gn(pn(()=>{}),pn(()=>null))),kz=new Cz;let Uz=class extends vn{_tag="Void";getParser(){return Od(this,void 0)}toCodecJson(){return qt(this,[qw])}getExpected(){return"void"}};const zz=new Uz;let Nz=class extends vn{_tag="Never";getParser(){return Za(this,uA)}getExpected(){return"never"}};const Dz=new Nz;let Lz=class extends vn{_tag="Any";getParser(){return Za(this,Nx)}getExpected(){return"any"}};const jz=new Lz;let Bz=class extends vn{_tag="Unknown";getParser(){return Za(this,Nx)}getExpected(){return"unknown"}};const H0=new Bz;let Tu=class extends vn{_tag="Literal";literal;constructor(n,s,i,u,o){if(super(s,i,u,o),typeof n=="number"&&!globalThis.Number.isFinite(n))throw new Error(`A numeric literal must be finite, got ${Rt(n)}`);this.literal=n}getParser(){return Od(this,this.literal)}toCodecJson(){return typeof this.literal=="bigint"?g_(this):this}toCodecStringTree(){return typeof this.literal=="string"?this:g_(this)}getExpected(){return typeof this.literal=="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function g_(e){const n=globalThis.String(e.literal);return qt(e,[new Vt(new Tu(n),new gn(pn(()=>e.literal),pn(()=>n)))])}let qz=class extends vn{_tag="String";getParser(){return Za(this,Xf)}getExpected(){return"string"}};const $w=new qz;let $z=class extends vn{_tag="Number";getParser(){return Za(this,of)}toCodecJson(){return this.checks&&(gu(this.checks,"isFinite")||gu(this.checks,"isInt"))?this:qt(this,[Kz])}toCodecStringTree(){return this.checks&&(gu(this.checks,"isFinite")||gu(this.checks,"isInt"))?qt(this,[sN]):qt(this,[aN])}getExpected(){return"number"}};function gu(e,n){return e.some(s=>{switch(s._tag){case"Filter":return s.annotations?.meta?._tag===n;case"FilterGroup":return gu(s.checks,n)}})}const Hw=new $z;let Hz=class extends vn{_tag="Boolean";getParser(){ret Line truncated
`)[5]??""]})),z6=P(2,(e,n)=>x6(e)?gl(s=>n(s,e),function(s,i){s.set(e,i)},e.refresh??function(s){s(e)}):Xs(s=>n(s,e),e.refresh??function(s){s(e)})),N6=y6,j_="~effect-atom/atom/Atom/ServerValue",D6=P(2,(e,n)=>j_ in e?e[j_](s=>n.get(s)):n.get(e));var bp=Cx();function LT(e){const n=bp.unstable_scheduleCallback(bp.unstable_LowPriority,e);return()=>bp.unstable_cancelCallback(n)}const kd=le.createContext(AT({scheduleTask:LT,defaultIdleTTL:400})),L6=e=>{const n=le.useRef(null);return n.current===null&&(n.current={registry:AT({scheduleTask:e.scheduleTask??LT,initialValues:e.initialValues,timeoutResolution:e.timeoutResolution,defaultIdleTTL:e.defaultIdleTTL})}),le.useEffect(()=>(n.current?.timeout!==void 0&&clearTimeout(n.current.timeout),()=>{n.current.timeout=setTimeout(()=>{n.current?.registry.dispose(),n.current=null},500)}),[n]),le.createElement(kd.Provider,{value:n.current.registry},e?.children)},B_=new WeakMap;function j6(e,n){let s=B_.get(e);s===void 0&&(s=new WeakMap,B_.set(e,s));const i=s.get(n);if(i!==void 0)return i;const u={subscribe(o){return e.subscribe(n,o)},snapshot(){return e.get(n)},getServerSnapshot(){return D6(n,e)}};return s.set(n,u),u}function B6(e,n){const s=j6(e,n);return le.useSyncExternalStore(s.subscribe,s.snapshot,s.getServerSnapshot)}const ta=(e,n)=>{const s=le.useContext(kd);return B6(s,e)};function jT(e,n){le.useEffect(()=>e.mount(n),[n,e])}function q6(e,n,s){return s?.mode==="promise"||s?.mode==="promiseExit"?le.useCallback(i=>{e.set(n,i);const u=G4(u6(e,n,{suspendOnWaiting:!0}));return s.mode==="promise"?u.then($6):u},[e,n,s.mode]):le.useCallback(i=>{e.set(n,typeof i=="function"?i(e.get(n)):i)},[e,n])}const $6=e=>{if(ew(e))return e.value;throw JE(e.cause)},Wr=(e,n)=>{const s=le.useContext(kd);return jT(s,e),q6(s,e,n)},H6=e=>{const n=le.useContext(kd);return jT(n,e),le.useCallback(()=>{n.refresh(e)},[n,e])};var it=(e=>(e[e.None=0]="None",e[e.Mutable=1]="Mutable",e[e.Watching=2]="Watching",e[e.RecursedCheck=4]="RecursedCheck",e[e.Recursed=8]="Recursed",e[e.Dirty=16]="Dirty",e[e.Pending=32]="Pending",e))(it||{});function BT({update:e,notify:n,unwatched:s}){return{link:i,unlink:u,propagate:o,checkDirty:d,shallowPropagate:h};function i(m,y,S){const v=y.depsTail;if(v!==void 0&&v.dep===m)return;const _=v!==void 0?v.nextDep:y.deps;if(_!==void 0&&_.dep===m){_.version=S,y.depsTail=_;return}const x=m.subsTail;if(x!==void 0&&x.version===S&&x.sub===y)return;const T=y.depsTail=m.subsTail={version:S,dep:m,sub:y,prevDep:v,nextDep:_,prevSub:x,nextSub:void 0};_!==void 0&&(_.prevDep=T),v!==void 0?v.nextDep=T:y.deps=T,x!==void 0?x.nextSub=T:m.subs=T}function u(m,y=m.sub){const S=m.dep,v=m.prevDep,_=m.nextDep,x=m.nextSub,T=m.prevSub;return _!==void 0?_.prevDep=v:y.depsTail=v,v!==void 0?v.nextDep=_:y.deps=_,x!==void 0?x.prevSub=T:S.subsTail=T,T!==void 0?T.nextSub=x:(S.subs=x)===void 0&&s(S),_}function o(m){let y=m.nextSub,S;e:do{const v=m.sub;let _=v.flags;if(_&60?_&12?_&4?!(_&48)&&p(m,v)?(v.flags=_|40,_&=1):_=0:v.flags=_&-9|32:_=0:v.flags=_|32,_&2&&n(v),_&1){const x=v.subs;if(x!==void 0){const T=(m=x).nextSub;T!==void 0&&(S={value:y,prev:S},y=T);continue}}if((m=y)!==void 0){y=m.nextSub;continue}for(;S!==void 0;)if(m=S.value,S=S.prev,m!==void 0){y=m.nextSub;continue e}break}while(!0)}function d(m,y){let S,v=0,_=!1;e:do{const x=m.dep,T=x.flags;if(y.flags&16)_=!0;else if((T&17)===17){if(e(x)){const j=x.subs;j.nextSub!==void 0&&h(j),_=!0}}else if((T&33)===33){(m.nextSub!==void 0||m.prevSub!==void 0)&&(S={value:m,prev:S}),m=x.deps,y=x,++v;continue}if(!_){const j=m.nextDep;if(j!==void 0){m=j;continue}}for(;v--;){const j=y.subs,B=j.nextSub!==void 0;if(B?(m=S.value,S=S.prev):m=j,_){if(e(y)){B&&h(j),y=m.sub;continue}_=!1}else y.flags&=-33;y=m.sub;const M=m.nextDep;if(M!==void 0){m=M;continue e}}return _}while(!0)}function h(m){do{const y=m.sub,S=y.flags;(S&48)===32&&(y.flags=S|16,(S&6)===2&&n(y))}while((m=m.nextSub)!==void 0)}function p(m,y){let S=y.depsTail;for(;S!==void 0;){if(S===m)return!0;S=S.prevDep}return!1}}let cy=0,Oa=0,Au=0;const es=[],{link:rB,unlink:qT,propagate:sB,checkDirty:V6,shallowPropagate:aB}=BT({update(e){return e.depsTail!==void 0?F6(e):K6(e)},notify(e){let n=Au,s=n;do if(es[n++]=e,e.flags&=-3,e=e.subs?.sub,e===void 0||!(e.flags&2))break;while(!0);for(Au=n;s<--n;){const i=es[s];es[s++]=es[n],es[n]=i}},unwatched(e){e.flags&1?e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,Ud(e)):Q6.call(e)}});function I6(){return cy}function Y6(){++cy}function G6(){--cy||X6()}function F6(e){e.depsTail=void 0,e.flags=5;try{const n=e.value;return n!==(e.value=e.getter(n))}finally{e.flags&=-5,Ud(e)}}function K6(e){return e.flags=1,e.currentValue!==(e.currentValue=e.pendingValue)}function P6(e){const n=e.flags;if(n&16||n&32&&V6(e.deps,e)){e.depsTail=void 0,e.flags=6;try{e.fn()}finally{e.flags&=-5,Ud(e)}}else e.flags=2}function X6(){try{for(;Oa<Au;){const e=es[Oa];es[Oa++]=void 0,P6(e)}}finally{for(;Oa<Au;){const e=es[Oa];es[Oa++]=void 0,e.flags|=10}Oa=0,Au=0}}function Q6(){this.depsTail=void 0,this.flags=0,Ud( Line truncated
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>effect-http-ws-cli rpc console</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Archivo+Black&family=IBM+Plex+Sans:wght@400;500;700&display=swap" rel="stylesheet" />
<script type="module" crossorigin src="/assets/index-CuY7i06l.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Bz7MwgeQ.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
+94
View File
@@ -0,0 +1,94 @@
import { spawn } from "node:child_process"
const frontendDevOrigin = process.env.FRONTEND_DEV_ORIGIN ?? "http://127.0.0.1:5173"
const frontendDevUrl = new URL(frontendDevOrigin)
if (frontendDevUrl.protocol !== "http:" && frontendDevUrl.protocol !== "https:") {
throw new Error(`FRONTEND_DEV_ORIGIN must use http or https, received ${frontendDevOrigin}`)
}
const frontendHost = process.env.FRONTEND_DEV_HOST ?? frontendDevUrl.hostname
const frontendPort = process.env.FRONTEND_DEV_PORT ?? (frontendDevUrl.port || "5173")
const serverArgs = process.argv.slice(2)
const readFlagValue = (name) => {
const index = serverArgs.findIndex((arg) => arg === name)
if (index >= 0) {
return serverArgs[index + 1]
}
const prefixed = serverArgs.find((arg) => arg.startsWith(`${name}=`))
return prefixed ? prefixed.slice(name.length + 1) : undefined
}
const normalizeBackendHost = (host) => {
if (!host || host === "0.0.0.0" || host === "::") {
return "127.0.0.1"
}
return host
}
const backendHost = normalizeBackendHost(process.env.HOST ?? readFlagValue("--host"))
const backendPort = process.env.PORT ?? readFlagValue("--port") ?? "8787"
const backendOrigin = process.env.VITE_BACKEND_ORIGIN ?? `http://${backendHost}:${backendPort}`
const children = new Set()
let shuttingDown = false
const stopChildren = (signal = "SIGTERM") => {
if (shuttingDown) {
return
}
shuttingDown = true
for (const child of children) {
if (!child.killed) {
child.kill(signal)
}
}
}
const spawnChild = (command, args, env = {}) => {
const child = spawn(command, args, {
stdio: "inherit",
env: {
...process.env,
...env
}
})
children.add(child)
child.on("exit", (code, signal) => {
stopChildren(signal ?? "SIGTERM")
if (signal) {
process.kill(process.pid, signal)
return
}
process.exit(code ?? 0)
})
return child
}
spawnChild("bun", [
"run",
"--filter",
"@effect-http-ws-cli/web",
"dev",
"--",
"--host",
frontendHost,
"--port",
frontendPort,
"--strictPort"
], {
VITE_BACKEND_ORIGIN: backendOrigin
})
spawnChild("node", ["server/src/bin.ts", ...serverArgs], {
FRONTEND_DEV_ORIGIN: frontendDevOrigin
})
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => stopChildren(signal))
}
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@effect-http-ws-cli/server",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
"./client": "./src/client.ts",
"./contracts": "./src/contracts.ts"
},
"scripts": {
"dev": "node src/bin.ts",
"start": "node src/bin.ts",
"test": "vitest run",
"lint": "tsc --noEmit"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-node": "catalog:",
"effect": "catalog:"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "^24.10.0",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -0,0 +1,32 @@
import * as Effect from "effect/Effect"
import * as SqlClient from "effect/unstable/sql/SqlClient"
export default Effect.gen(function*() {
const sql = yield* SqlClient.SqlClient
yield* sql`
CREATE TABLE IF NOT EXISTS todos (
id TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
completed INTEGER NOT NULL,
archived INTEGER NOT NULL,
revision INTEGER NOT NULL,
updated_at TEXT NOT NULL
)
`
yield* sql`
CREATE TABLE IF NOT EXISTS todo_events (
event_offset INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
todo_json TEXT NOT NULL,
change_json TEXT NOT NULL,
archived INTEGER NOT NULL
)
`
yield* sql`
CREATE INDEX IF NOT EXISTS idx_todo_events_archived_offset
ON todo_events (archived, event_offset)
`
})
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime"
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as Effect from "effect/Effect"
import { cli } from "./cli.ts"
import { Command } from "effect/unstable/cli"
Command.run(cli, { version: "0.1.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain
)
+125
View File
@@ -0,0 +1,125 @@
import * as SqliteNode from "@effect/sql-sqlite-node"
import { Command, Flag } from "effect/unstable/cli"
import * as Config from "effect/Config"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import * as Option from "effect/Option"
import * as Path from "effect/Path"
import { fileURLToPath } from "node:url"
import { ServerConfig } from "./config.ts"
import { runMigrations } from "./migrations.ts"
import { runServer } from "./server.ts"
import type { ServerConfigData } from "./config.ts"
const defaultAssetsDir = fileURLToPath(new URL("../../public", import.meta.url))
const defaultDbFilename = fileURLToPath(new URL("../../todo.sqlite", import.meta.url))
const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host interface to bind"),
Flag.optional
)
const portFlag = Flag.integer("port").pipe(
Flag.withDescription("Port to listen on"),
Flag.optional
)
const assetsFlag = Flag.directory("assets").pipe(
Flag.withDescription("Directory of static assets"),
Flag.optional
)
const dbFlag = Flag.string("db").pipe(
Flag.withDescription("SQLite database filename"),
Flag.optional
)
const requestLoggingFlag = Flag.boolean("request-logging").pipe(
Flag.withDescription("Enable request logging"),
Flag.optional
)
const frontendDevOriginFlag = Flag.string("frontend-dev-origin").pipe(
Flag.withDescription("Redirect frontend GET requests to a Vite dev server origin"),
Flag.optional
)
const EnvServerConfig = Config.unwrap({
host: Config.string("HOST").pipe(Config.withDefault("127.0.0.1")),
port: Config.port("PORT").pipe(Config.withDefault(8787)),
assetsDir: Config.string("ASSETS_DIR").pipe(Config.withDefault(defaultAssetsDir)),
dbFilename: Config.string("DB_FILENAME").pipe(Config.withDefault(defaultDbFilename)),
requestLogging: Config.boolean("REQUEST_LOGGING").pipe(Config.withDefault(true)),
frontendDevOrigin: Config.string("FRONTEND_DEV_ORIGIN").pipe(
Config.option,
Config.map(Option.getOrUndefined)
)
})
export interface CliServerFlags {
readonly host: Option.Option<string>
readonly port: Option.Option<number>
readonly assets: Option.Option<string>
readonly db: Option.Option<string>
readonly requestLogging: Option.Option<boolean>
readonly frontendDevOrigin: Option.Option<string>
}
export const resolveServerConfig = (
flags: CliServerFlags
): Effect.Effect<ServerConfigData, Config.ConfigError> =>
Effect.gen(function*() {
const env = yield* EnvServerConfig
return {
host: Option.getOrElse(flags.host, () => env.host),
port: Option.getOrElse(flags.port, () => env.port),
assetsDir: Option.getOrElse(flags.assets, () => env.assetsDir),
dbFilename: Option.getOrElse(flags.db, () => env.dbFilename),
requestLogging: Option.getOrElse(flags.requestLogging, () => env.requestLogging),
frontendDevOrigin: Option.getOrElse(flags.frontendDevOrigin, () => env.frontendDevOrigin)
}
})
export const resetDatabase = (dbFilename: string) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
if (dbFilename !== ":memory:") {
yield* fs.remove(path.resolve(dbFilename), { force: true })
}
const sqliteLayer = SqliteNode.SqliteClient.layer({
filename: dbFilename
})
yield* runMigrations.pipe(Effect.provide(sqliteLayer))
})
const commandFlags = {
host: hostFlag,
port: portFlag,
assets: assetsFlag,
db: dbFlag,
requestLogging: requestLoggingFlag,
frontendDevOrigin: frontendDevOriginFlag
} as const
const rootCommand = Command.make("effect-http-ws-cli", commandFlags).pipe(
Command.withDescription("Run a unified Effect HTTP + WebSocket server"),
Command.withHandler((flags) =>
Effect.flatMap(resolveServerConfig(flags), (config) =>
runServer.pipe(Effect.provideService(ServerConfig, config)))),
)
const resetCommand = Command.make("reset", commandFlags).pipe(
Command.withDescription("Delete the SQLite database file and rerun migrations"),
Command.withHandler((flags) =>
Effect.flatMap(resolveServerConfig(flags), (config) => resetDatabase(config.dbFilename))
)
)
export const cli = rootCommand.pipe(
Command.withSubcommands([resetCommand])
)
+58
View File
@@ -0,0 +1,58 @@
import { NodeSocket } from "@effect/platform-node"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as RpcClient from "effect/unstable/rpc/RpcClient"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as Stream from "effect/Stream"
import { WsRpcGroup } from "./contracts.ts"
export const wsRpcProtocolLayer = (wsUrl: string) =>
RpcClient.layerProtocolSocket().pipe(
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
Layer.provide(RpcSerialization.layerJson)
)
export const makeWsRpcClient = RpcClient.make(WsRpcGroup)
type WsRpcClient = typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never
export const withWsRpcClient = <A, E, R>(
wsUrl: string,
f: (client: WsRpcClient) => Effect.Effect<A, E, R>
) =>
makeWsRpcClient.pipe(
Effect.flatMap(f),
Effect.provide(wsRpcProtocolLayer(wsUrl))
)
export const runClientExample = (wsUrl: string) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const echoed = yield* client.echo({ text: "hello from client" })
const summed = yield* client.sum({ left: 20, right: 22 })
const time = yield* client.time(undefined)
return { echoed, summed, time }
})
)
)
export const runSubscriptionExample = (wsUrl: string, modelId: string) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const todo = snapshot.todos[0]
if (!todo) {
return []
}
yield* client.renameTodo({ id: todo.id, title: `${modelId}: first` })
yield* client.completeTodo({ id: todo.id, completed: true })
return yield* client.subscribeTodos({ fromOffset: snapshot.offset, includeArchived: true }).pipe(
Stream.take(2),
Stream.runCollect
)
})
)
)
+14
View File
@@ -0,0 +1,14 @@
import * as ServiceMap from "effect/ServiceMap"
export interface ServerConfigData {
readonly host: string
readonly port: number
readonly assetsDir: string
readonly dbFilename: string
readonly requestLogging: boolean
readonly frontendDevOrigin: string | undefined
}
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigData>()(
"effect-http-ws-cli/ServerConfig"
) {}
+132
View File
@@ -0,0 +1,132 @@
import * as Schema from "effect/Schema"
import * as Rpc from "effect/unstable/rpc/Rpc"
import * as RpcGroup from "effect/unstable/rpc/RpcGroup"
export const EchoPayload = Schema.Struct({
text: Schema.String
})
export const EchoResult = Schema.Struct({
text: Schema.String
})
export const SumPayload = Schema.Struct({
left: Schema.Number,
right: Schema.Number
})
export const SumResult = Schema.Struct({
total: Schema.Number
})
export const TimeResult = Schema.Struct({
iso: Schema.String
})
export const Todo = Schema.Struct({
id: Schema.String,
title: Schema.String,
completed: Schema.Boolean,
archived: Schema.Boolean,
revision: Schema.Number,
updatedAt: Schema.String
})
export type Todo = Schema.Schema.Type<typeof Todo>
export const TodoChange = Schema.Union([
Schema.Struct({
_tag: Schema.Literal("TodoCreated")
}),
Schema.Struct({
_tag: Schema.Literal("TodoRenamed"),
title: Schema.String
}),
Schema.Struct({
_tag: Schema.Literal("TodoCompleted"),
completed: Schema.Boolean
}),
Schema.Struct({
_tag: Schema.Literal("TodoArchived"),
archived: Schema.Boolean
})
])
export type TodoChange = Schema.Schema.Type<typeof TodoChange>
export const TodoEvent = Schema.Struct({
offset: Schema.Number,
at: Schema.String,
todo: Todo,
change: TodoChange
})
export type TodoEvent = Schema.Schema.Type<typeof TodoEvent>
export const TodoSnapshot = Schema.Struct({
offset: Schema.Number,
todos: Schema.Array(Todo)
})
export type TodoSnapshot = Schema.Schema.Type<typeof TodoSnapshot>
export const EchoRpc = Rpc.make("echo", {
payload: EchoPayload,
success: EchoResult
})
export const SumRpc = Rpc.make("sum", {
payload: SumPayload,
success: SumResult
})
export const TimeRpc = Rpc.make("time", {
success: TimeResult
})
export const ListTodosRpc = Rpc.make("listTodos", {
payload: Schema.Struct({
includeArchived: Schema.Boolean
}),
success: TodoSnapshot
})
export const RenameTodoRpc = Rpc.make("renameTodo", {
payload: Schema.Struct({
id: Schema.String,
title: Schema.String
}),
success: TodoEvent
})
export const CompleteTodoRpc = Rpc.make("completeTodo", {
payload: Schema.Struct({
id: Schema.String,
completed: Schema.Boolean
}),
success: TodoEvent
})
export const ArchiveTodoRpc = Rpc.make("archiveTodo", {
payload: Schema.Struct({
id: Schema.String,
archived: Schema.Boolean
}),
success: TodoEvent
})
export const SubscribeTodosRpc = Rpc.make("subscribeTodos", {
payload: Schema.Struct({
fromOffset: Schema.Number,
includeArchived: Schema.Boolean
}),
success: TodoEvent,
stream: true
})
export const WsRpcGroup = RpcGroup.make(
EchoRpc,
SumRpc,
TimeRpc,
ListTodosRpc,
RenameTodoRpc,
CompleteTodoRpc,
ArchiveTodoRpc,
SubscribeTodosRpc
)
+73
View File
@@ -0,0 +1,73 @@
import * as Schema from "effect/Schema"
import * as SchemaTransformation from "effect/SchemaTransformation"
export const ClientMessage = Schema.Union([
Schema.Struct({
kind: Schema.Literal("echo"),
text: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("sum"),
left: Schema.Number,
right: Schema.Number
}),
Schema.Struct({
kind: Schema.Literal("time")
})
])
export type ClientMessage = Schema.Schema.Type<typeof ClientMessage>
export const ServerMessage = Schema.Union([
Schema.Struct({
kind: Schema.Literal("echo"),
text: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("sumResult"),
total: Schema.Number
}),
Schema.Struct({
kind: Schema.Literal("time"),
iso: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("error"),
error: Schema.String
})
])
export type ServerMessage = Schema.Schema.Type<typeof ServerMessage>
export const decodeClientMessage = Schema.decodeUnknownEffect(ClientMessage)
const Utf8StringFromUint8Array = Schema.Uint8Array.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transform({
decode: (bytes) => new TextDecoder().decode(bytes),
encode: (text) => new TextEncoder().encode(text)
})
)
)
const ClientMessageFromWire = Schema.Union([
Schema.String,
Utf8StringFromUint8Array
]).pipe(
Schema.decodeTo(Schema.fromJsonString(ClientMessage))
)
export const decodeWireClientMessage = Schema.decodeUnknownEffect(ClientMessageFromWire)
export const routeClientMessage = (message: ClientMessage): ServerMessage => {
switch (message.kind) {
case "echo":
return { kind: "echo", text: message.text }
case "sum":
return { kind: "sumResult", total: message.left + message.right }
case "time":
return { kind: "time", iso: new Date().toISOString() }
}
}
+41
View File
@@ -0,0 +1,41 @@
/**
* MigrationsLive - Migration runner with inline loader
*
* Uses Migrator.make with fromRecord to define migrations inline.
* All migrations are statically imported - no dynamic file system loading.
*
* Migrations run automatically when the MigrationsLive layer is provided,
* ensuring the database schema is up-to-date before the application starts.
*/
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as ServiceMap from "effect/ServiceMap"
import * as Migrator from "effect/unstable/sql/Migrator"
import Migration0001 from "./Migrations/001_TodoSchema.ts"
const loader = Migrator.fromRecord({
"1_TodoSchema": Migration0001
})
const run = Migrator.make({})
export const runMigrations = Effect.gen(function*() {
yield* Effect.log("Running migrations...")
yield* run({ loader })
yield* Effect.log("Migrations ran successfully")
})
export interface MigrationsReadyApi {
readonly ready: true
}
export class MigrationsReady extends ServiceMap.Service<MigrationsReady, MigrationsReadyApi>()(
"effect-http-ws-cli/MigrationsReady"
) {}
export const MigrationsLive = Layer.effect(
MigrationsReady,
runMigrations.pipe(
Effect.as(MigrationsReady.of({ ready: true }))
)
)
+268
View File
@@ -0,0 +1,268 @@
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import * as PubSub from "effect/PubSub"
import * as Schema from "effect/Schema"
import * as ServiceMap from "effect/ServiceMap"
import * as Stream from "effect/Stream"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import * as SqlSchema from "effect/unstable/sql/SqlSchema"
import type { Todo, TodoChange, TodoEvent, TodoSnapshot } from "./contracts.ts"
import { Todo as TodoSchema, TodoChange as TodoChangeSchema } from "./contracts.ts"
import { MigrationsReady } from "./migrations.ts"
export interface TodoStoreApi {
readonly list: (input: {
readonly includeArchived: boolean
}) => Effect.Effect<TodoSnapshot, never, SqlClient.SqlClient>
readonly rename: (input: {
readonly id: string
readonly title: string
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly complete: (input: {
readonly id: string
readonly completed: boolean
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly archive: (input: {
readonly id: string
readonly archived: boolean
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly subscribe: (input: {
readonly fromOffset: number
readonly includeArchived: boolean
}) => Stream.Stream<TodoEvent, never, SqlClient.SqlClient>
}
export class TodoStore extends ServiceMap.Service<TodoStore, TodoStoreApi>()(
"effect-http-ws-cli/TodoStore"
) {}
const TodoRow = Schema.Struct({
id: Schema.String,
title: Schema.String,
completed: Schema.BooleanFromBit,
archived: Schema.BooleanFromBit,
revision: Schema.Number,
updatedAt: Schema.String
})
const TodoEventRow = Schema.Struct({
offset: Schema.Number,
at: Schema.String,
todo: Schema.fromJsonString(TodoSchema),
change: Schema.fromJsonString(TodoChangeSchema)
})
const EventInsertRequest = Schema.Struct({
at: Schema.String,
todo: Schema.fromJsonString(TodoSchema),
change: Schema.fromJsonString(TodoChangeSchema),
archived: Schema.BooleanFromBit
})
const ListRequest = Schema.Struct({
includeArchived: Schema.Boolean
})
const CatchupRequest = Schema.Struct({
fromOffset: Schema.Number,
includeArchived: Schema.Boolean
})
const OffsetRow = Schema.Struct({
offset: Schema.Number
})
const makeQueries = (sql: SqlClient.SqlClient) => {
const listTodoRows = SqlSchema.findAll({
Request: ListRequest,
Result: TodoRow,
execute: (request) =>
request.includeArchived
? sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
ORDER BY id
`
: sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
WHERE archived = 0
ORDER BY id
`
})
const findTodoById = SqlSchema.findOneOption({
Request: Schema.String,
Result: TodoRow,
execute: (id) => sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
WHERE id = ${id}
`
})
const upsertTodo = SqlSchema.void({
Request: TodoRow,
execute: (todo) => sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${todo.id}, ${todo.title}, ${todo.completed}, ${todo.archived}, ${todo.revision}, ${todo.updatedAt})
ON CONFLICT(id) DO UPDATE SET
title = excluded.title,
completed = excluded.completed,
archived = excluded.archived,
revision = excluded.revision,
updated_at = excluded.updated_at
`
})
const loadEventsSince = SqlSchema.findAll({
Request: CatchupRequest,
Result: TodoEventRow,
execute: (request) =>
request.includeArchived
? sql<TodoEvent>`
SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change
FROM todo_events
WHERE event_offset > ${request.fromOffset}
ORDER BY event_offset
`
: sql<TodoEvent>`
SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change
FROM todo_events
WHERE event_offset > ${request.fromOffset} AND archived = 0
ORDER BY event_offset
`
})
const insertTodoEvent = SqlSchema.findOne({
Request: EventInsertRequest,
Result: TodoEventRow,
execute: (request) => sql<TodoEvent>`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (${request.at}, ${request.todo}, ${request.change}, ${request.archived})
RETURNING event_offset AS "offset", at, todo_json AS todo, change_json AS change
`
})
const currentOffset = SqlSchema.findOne({
Request: Schema.Undefined,
Result: OffsetRow,
execute: () => sql<{ readonly offset: number }>`
SELECT COALESCE(MAX(event_offset), 0) AS "offset"
FROM todo_events
`
})
return {
listTodoRows,
findTodoById,
upsertTodo,
loadEventsSince,
insertTodoEvent,
currentOffset
} as const
}
export const layerTodoStore = Layer.effect(
TodoStore,
Effect.gen(function*() {
yield* MigrationsReady
const eventsPubSub = yield* PubSub.unbounded<TodoEvent>()
const append = (
todoId: string,
change: TodoChange,
update: (todo: Todo) => Todo
): Effect.Effect<TodoEvent, never, SqlClient.SqlClient> =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const queries = makeQueries(sql)
return sql.withTransaction(
queries.findTodoById(todoId).pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.die(`Todo not found: ${todoId}`),
onSome: (todo) => {
const updated = update(todo)
return queries.upsertTodo(updated).pipe(
Effect.flatMap(() =>
queries.insertTodoEvent({
at: updated.updatedAt,
todo: updated,
change,
archived: updated.archived
})
)
)
}
})
)
)
)
}).pipe(Effect.tap((event) => PubSub.publish(eventsPubSub, event)), Effect.orDie)
const visible = (todo: Todo, includeArchived: boolean) => includeArchived || !todo.archived
const subscribe = (input: {
readonly fromOffset: number
readonly includeArchived: boolean
}): Stream.Stream<TodoEvent, never, SqlClient.SqlClient> => {
const catchup = Stream.fromIterableEffect(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => makeQueries(sql).loadEventsSince(input))
).pipe(Stream.orDie)
const live = Stream.fromPubSub(eventsPubSub).pipe(
Stream.filter((event) => visible(event.todo, input.includeArchived))
)
return Stream.concat(catchup, live)
}
return TodoStore.of({
list: ({ includeArchived }) =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const queries = makeQueries(sql)
return Effect.all({
todos: queries.listTodoRows({ includeArchived }),
offset: queries.currentOffset(undefined).pipe(Effect.map(({ offset }) => offset))
}).pipe(
Effect.map(({ offset, todos }) => ({ offset, todos }))
)
}).pipe(Effect.orDie),
rename: ({ id, title }) =>
append(
id,
{ _tag: "TodoRenamed", title },
(todo) => ({
...todo,
title,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
complete: ({ id, completed }) =>
append(
id,
{ _tag: "TodoCompleted", completed },
(todo) => ({
...todo,
completed,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
archive: ({ id, archived }) =>
append(
id,
{ _tag: "TodoArchived", archived },
(todo) => ({
...todo,
archived,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
subscribe
})
})
)
+155
View File
@@ -0,0 +1,155 @@
import { NodeHttpServer } from "@effect/platform-node"
import * as SqliteNode from "@effect/sql-sqlite-node"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import * as Layer from "effect/Layer"
import * as Path from "effect/Path"
import * as Http from "node:http"
import {
HttpRouter,
HttpServerRequest,
HttpServerResponse
} from "effect/unstable/http"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as RpcServer from "effect/unstable/rpc/RpcServer"
import * as Stream from "effect/Stream"
import {
ClientMessage,
routeClientMessage,
ServerMessage
} from "./messages.ts"
import { ServerConfig } from "./config.ts"
import { WsRpcGroup } from "./contracts.ts"
import { TodoStore, layerTodoStore } from "./model-store.ts"
import { MigrationsLive } from "./migrations.ts"
const respondMessage = HttpServerResponse.schemaJson(ServerMessage)
const messageDispatchRoute = HttpRouter.add(
"POST",
"/api/dispatch",
HttpServerRequest.schemaBodyJson(ClientMessage).pipe(
Effect.flatMap((message) => respondMessage(routeClientMessage(message))),
Effect.catchTag(
"SchemaError",
() => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid message schema" }, { status: 400 }))
),
Effect.catchTag(
"HttpServerError",
() => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid request body" }, { status: 400 }))
)
)
)
const websocketRpcRoute = RpcServer.layerHttp({
group: WsRpcGroup,
path: "/ws",
protocol: "websocket"
}).pipe(
Layer.provide(WsRpcGroup.toLayer({
echo: ({ text }) => Effect.succeed({ text }),
sum: ({ left, right }) => Effect.succeed({ total: left + right }),
time: () => Effect.sync(() => ({ iso: new Date().toISOString() })),
listTodos: ({ includeArchived }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.list({ includeArchived })),
renameTodo: ({ id, title }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.rename({ id, title })),
completeTodo: ({ id, completed }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.complete({ id, completed })),
archiveTodo: ({ id, archived }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.archive({ id, archived })),
subscribeTodos: ({ fromOffset, includeArchived }) =>
Stream.unwrap(
Effect.map(
Effect.service(TodoStore),
(store) => store.subscribe({ fromOffset, includeArchived })
)
)
})),
Layer.provide(layerTodoStore),
Layer.provide(RpcSerialization.layerJson)
)
const staticRoute = HttpRouter.add(
"GET",
"*",
(request) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const config = yield* ServerConfig
const url = HttpServerRequest.toURL(request)
if (!url) {
return HttpServerResponse.text("Bad Request", { status: 400 })
}
if (config.frontendDevOrigin) {
return HttpServerResponse.redirect(
new URL(`${url.pathname}${url.search}`, config.frontendDevOrigin),
{
status: 307,
headers: { "cache-control": "no-store" }
}
)
}
const root = path.resolve(config.assetsDir)
const decodedPath = decodeURIComponent(url.pathname)
const target = decodedPath === "/"
? "index.html"
: decodedPath.endsWith("/")
? `${decodedPath.slice(1)}index.html`
: decodedPath.slice(1)
const normalizedTarget = path.normalize(target)
const absoluteTarget = path.resolve(root, normalizedTarget)
const relativeToRoot = path.relative(root, absoluteTarget)
if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot)) {
return HttpServerResponse.text("Forbidden", { status: 403 })
}
const exists = yield* fs.exists(absoluteTarget)
if (!exists) {
return HttpServerResponse.text("Not Found", { status: 404 })
}
return yield* HttpServerResponse.file(absoluteTarget)
}).pipe(Effect.catchCause(() => Effect.succeed(HttpServerResponse.text("Bad Request", { status: 400 }))))
)
export const makeRoutesLayer =
Layer.mergeAll(
HttpRouter.add(
"GET",
"/health",
HttpServerResponse.json({ ok: true })
),
messageDispatchRoute,
websocketRpcRoute,
staticRoute
)
export const makeServerLayer = Layer.unwrap(
Effect.gen(function*() {
const config = yield* ServerConfig
const sqliteLayer = SqliteNode.SqliteClient.layer({
filename: config.dbFilename
})
const persistenceLayer = MigrationsLive.pipe(
Layer.provideMerge(sqliteLayer)
)
return HttpRouter.serve(makeRoutesLayer, {
disableLogger: !config.requestLogging
}).pipe(
Layer.provideMerge(persistenceLayer),
Layer.provide(NodeHttpServer.layer(Http.createServer, {
host: config.host,
port: config.port
}))
)
})
)
export const runServer = Layer.launch(makeServerLayer)
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from "@effect/vitest"
import * as ConfigProvider from "effect/ConfigProvider"
import * as Effect from "effect/Effect"
import * as Option from "effect/Option"
import { resolveServerConfig } from "../src/cli.ts"
describe("cli config resolution", () => {
it.effect("falls back to effect/config values when flags are omitted", () =>
Effect.gen(function*() {
const resolved = yield* resolveServerConfig({
host: Option.none(),
port: Option.none(),
assets: Option.none(),
db: Option.none(),
requestLogging: Option.none(),
frontendDevOrigin: Option.none()
}).pipe(
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
HOST: "0.0.0.0",
PORT: "4001",
ASSETS_DIR: "public",
DB_FILENAME: "dev.sqlite",
REQUEST_LOGGING: "false",
FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173"
}
})
)
)
expect(resolved).toEqual({
host: "0.0.0.0",
port: 4001,
assetsDir: "public",
dbFilename: "dev.sqlite",
requestLogging: false,
frontendDevOrigin: "http://127.0.0.1:5173"
})
})
)
it.effect("uses CLI flags when provided", () =>
Effect.gen(function*() {
const resolved = yield* resolveServerConfig({
host: Option.some("127.0.0.1"),
port: Option.some(8788),
assets: Option.some("public"),
db: Option.some("override.sqlite"),
requestLogging: Option.some(true),
frontendDevOrigin: Option.some("http://127.0.0.1:4173")
}).pipe(
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
HOST: "0.0.0.0",
PORT: "4001",
ASSETS_DIR: "other",
DB_FILENAME: "ignored.sqlite",
REQUEST_LOGGING: "false",
FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173"
}
})
)
)
expect(resolved).toEqual({
host: "127.0.0.1",
port: 8788,
assetsDir: "public",
dbFilename: "override.sqlite",
requestLogging: true,
frontendDevOrigin: "http://127.0.0.1:4173"
})
})
)
})
+90
View File
@@ -0,0 +1,90 @@
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as SqliteNode from "@effect/sql-sqlite-node"
import { describe, expect, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import * as FileSystem from "node:fs"
import * as OS from "node:os"
import * as NodePath from "node:path"
import { resetDatabase } from "../src/cli.ts"
import { MigrationsLive } from "../src/migrations.ts"
const countRows = (dbFilename: string, tableName: string) =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) =>
sql<{ readonly count: number }>`SELECT COUNT(*) AS count FROM ${sql(tableName)}`.pipe(
Effect.map((rows) => rows[0]?.count ?? 0)
)
).pipe(
Effect.provide(SqliteNode.SqliteClient.layer({ filename: dbFilename }))
)
const insertTodo = (dbFilename: string) =>
Effect.scoped(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const now = new Date().toISOString()
const id = "todo-reset-test"
const title = "before-reset"
return sql.withTransaction(
sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${id}, ${title}, 0, 0, 1, ${now})
`.pipe(
Effect.flatMap(() =>
sql`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (
${now},
${JSON.stringify({
id,
title,
completed: false,
archived: false,
revision: 1,
updatedAt: now
})},
${JSON.stringify({ _tag: "TodoCreated" })},
0
)
`
)
)
)
}).pipe(
Effect.provide(MigrationsLive.pipe(Layer.provideMerge(SqliteNode.SqliteClient.layer({ filename: dbFilename }))))
)
)
describe("reset command", () => {
it.effect("deletes the database and reruns migrations without reseeding todos", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-reset-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename)
const beforeCount = yield* countRows(dbFilename, "todos")
expect(beforeCount).toBe(1)
yield* resetDatabase(dbFilename).pipe(
Effect.provide(NodeServices.layer)
)
const todoCount = yield* countRows(dbFilename, "todos")
const migrationCount = yield* countRows(dbFilename, "effect_sql_migrations")
expect(todoCount).toBe(0)
expect(migrationCount).toBe(1)
yield* Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
})
)
})
+310
View File
@@ -0,0 +1,310 @@
import { NodeHttpServer } from "@effect/platform-node"
import * as SqliteNode from "@effect/sql-sqlite-node"
import { describe, expect, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Stream from "effect/Stream"
import * as FileSystem from "node:fs"
import * as OS from "node:os"
import * as NodePath from "node:path"
import {
HttpBody,
HttpClient,
HttpClientResponse,
HttpServer,
HttpRouter
} from "effect/unstable/http"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import { ServerConfig } from "../src/config.ts"
import { MigrationsLive } from "../src/migrations.ts"
import { ServerMessage } from "../src/messages.ts"
import { withWsRpcClient } from "../src/client.ts"
import { makeRoutesLayer } from "../src/server.ts"
const testServerConfig = {
host: "127.0.0.1",
port: 0,
assetsDir: new URL("../../public", import.meta.url).pathname,
dbFilename: ":memory:",
requestLogging: false,
frontendDevOrigin: undefined
}
const AppUnderTest = HttpRouter.serve(
makeRoutesLayer,
{
disableListenLog: true,
disableLogger: true
}
)
const persistenceLayer = (dbFilename: string) => {
const sqliteLayer = SqliteNode.SqliteClient.layer({ filename: dbFilename })
return MigrationsLive.pipe(Layer.provideMerge(sqliteLayer))
}
const appLayer = (dbFilename: string) =>
AppUnderTest.pipe(Layer.provideMerge(persistenceLayer(dbFilename)))
const insertTodo = (dbFilename: string, id: string, title: string) =>
Effect.scoped(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const now = new Date().toISOString()
return sql.withTransaction(
sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${id}, ${title}, 0, 0, 1, ${now})
`.pipe(
Effect.flatMap(() =>
sql`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (
${now},
${JSON.stringify({
id,
title,
completed: false,
archived: false,
revision: 1,
updatedAt: now
})},
${JSON.stringify({ _tag: "TodoCreated" })},
0
)
`
)
)
)
}).pipe(
Effect.provide(persistenceLayer(dbFilename))
)
)
describe("server", () => {
it.effect("routes HTTP messages validated by Schema", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const client = yield* HttpClient.HttpClient
const response = yield* client.post("/api/dispatch", {
body: HttpBody.jsonUnsafe({ kind: "sum", left: 20, right: 22 })
})
const parsed = yield* HttpClientResponse.schemaBodyJson(ServerMessage)(response)
expect(parsed).toEqual({ kind: "sumResult", total: 42 })
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("serves static files from local filesystem", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const text = yield* HttpClient.get("/").pipe(
Effect.flatMap((response) => response.text)
)
expect(text).toContain("effect-http-ws-cli")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("redirects frontend requests to the Vite dev server when enabled", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
frontendDevOrigin: "http://127.0.0.1:5173"
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const response = yield* Effect.promise(() =>
fetch(`http://127.0.0.1:${address.port}/todos?filter=active`, {
redirect: "manual"
})
)
expect(response.status).toBe(307)
expect(response.headers.get("location")).toBe("http://127.0.0.1:5173/todos?filter=active")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("routes WebSocket RPC messages with shared contracts", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client.echo({ text: "hello from ws" }))
)
expect(response).toEqual({ text: "hello from ws" })
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("routes WebSocket RPC calls for multiple procedures", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.all({
sum: client.sum({ left: 1, right: 2 }),
time: client.time(undefined)
})
)
)
expect(result.sum).toEqual({ total: 3 })
expect(typeof result.time.iso).toBe("string")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("lists todos and streams todo updates from offset", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-stream-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename, "todo-stream-test", "stream-seed")
const events = yield* Effect.scoped(
Effect.gen(function*() {
yield* Layer.build(appLayer(dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
dbFilename
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
return yield* withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const firstTodo = snapshot.todos[0]
if (!firstTodo) {
return yield* Effect.die("Expected a todo fixture")
}
yield* client.renameTodo({ id: firstTodo.id, title: "alpha" })
yield* client.completeTodo({ id: firstTodo.id, completed: true })
yield* client.archiveTodo({ id: firstTodo.id, archived: true })
return yield* client.subscribeTodos({
fromOffset: snapshot.offset,
includeArchived: true
}).pipe(
Stream.take(3),
Stream.runCollect
)
})
)
})
).pipe(
Effect.ensuring(
Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
)
)
expect(events).toHaveLength(3)
expect(events[0]?.change).toEqual({ _tag: "TodoRenamed", title: "alpha" })
expect(events[1]?.change).toEqual({ _tag: "TodoCompleted", completed: true })
expect(events[2]?.change).toEqual({ _tag: "TodoArchived", archived: true })
expect(events[0]?.todo.title).toBe("alpha")
expect(events[1]?.todo.completed).toBe(true)
expect(events[2]?.todo.archived).toBe(true)
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("persists todos across server restarts when using a file database", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename, "todo-persist-test", "persist-seed")
const withServer = <A, E, R>(f: (wsUrl: string) => Effect.Effect<A, E, R>) =>
Effect.scoped(
Effect.gen(function*() {
yield* Layer.build(appLayer(dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
dbFilename
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
return yield* f(wsUrl)
})
)
const renamedTodoId = yield* withServer((wsUrl) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const firstTodo = snapshot.todos[0]
if (!firstTodo) {
return yield* Effect.die("Expected a todo fixture")
}
yield* client.renameTodo({ id: firstTodo.id, title: "persisted-title" })
return firstTodo.id
})
)
)
)
const persistedTitle = yield* withServer((wsUrl) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const persisted = snapshot.todos.find((todo) => todo.id === renamedTodoId)
if (!persisted) {
return yield* Effect.die("Expected persisted todo")
}
return persisted.title
})
)
)
).pipe(
Effect.ensuring(
Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
)
)
expect(persistedTitle).toBe("persisted-title")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
})
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../tsconfig.json",
"include": ["src", "test", "vitest.config.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["test/**/*.test.ts"],
environment: "node"
}
})
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"allowImportingTsExtensions": true,
"rewriteRelativeImportExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"types": ["node", "vitest/globals"]
}
}
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>effect-http-ws-cli rpc console</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Archivo+Black&family=IBM+Plex+Sans:wght@400;500;700&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@effect-http-ws-cli/web",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest run",
"lint": "tsc --noEmit"
},
"dependencies": {
"@effect-http-ws-cli/server": "workspace:*",
"@effect/atom-react": "catalog:",
"@tanstack/react-router": "^1.166.2",
"effect": "catalog:",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@tanstack/router-plugin": "^1.166.2",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"@vitest/browser-playwright": "^4.0.18",
"playwright": "^1.58.2",
"typescript": "catalog:",
"vite": "^7.2.0",
"vitest": "catalog:",
"vitest-browser-react": "^2.0.5"
}
}
+17
View File
@@ -0,0 +1,17 @@
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { RegistryProvider } from "@effect/atom-react"
import { createBrowserHistory, RouterProvider } from "@tanstack/react-router"
import { getRouter } from "./router"
import "./styles.css"
const history = createBrowserHistory()
const router = getRouter(history)
createRoot(document.getElementById("root")!).render(
<StrictMode>
<RegistryProvider>
<RouterProvider router={router} />
</RegistryProvider>
</StrictMode>
)
+59
View File
@@ -0,0 +1,59 @@
/* eslint-disable */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/'
fileRoutesByTo: FileRoutesByTo
to: '/'
id: '__root__' | '/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
}
}
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()
+15
View File
@@ -0,0 +1,15 @@
import { createRouter, type RouterHistory } from "@tanstack/react-router"
import { routeTree } from "./routeTree.gen"
export const getRouter = (history: RouterHistory) =>
createRouter({
routeTree,
history
})
declare module "@tanstack/react-router" {
interface Register {
router: ReturnType<typeof getRouter>
}
}
+5
View File
@@ -0,0 +1,5 @@
import { Outlet, createRootRoute } from "@tanstack/react-router"
export const Route = createRootRoute({
component: Outlet
})
+460
View File
@@ -0,0 +1,460 @@
import { createFileRoute } from "@tanstack/react-router"
import { useEffect, useRef } from "react"
import * as Cause from "effect/Cause"
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"
import type { Todo, TodoEvent, TodoChange } from "@effect-http-ws-cli/server/contracts"
import {
archiveTodoMutationAtom,
completeTodoMutationAtom,
renameTodoMutationAtom,
subscribeTodosPullAtom,
todosSnapshotAtom
} from "../rpc"
import {
connectionAtom,
eventsAtom,
mutationBusyAtom,
todoProjectionAtom
} from "../state"
const reconnectBaseMs = 1_250
const reconnectMaxMs = 20_000
const maxReconnectAttempts = 8
export const Route = createFileRoute("/")({
component: IndexRoute
})
function IndexRoute() {
const setProjection = useAtomSet(todoProjectionAtom)
const setEvents = useAtomSet(eventsAtom)
const setConnection = useAtomSet(connectionAtom)
const setBusy = useAtomSet(mutationBusyAtom)
const snapshotResult = useAtomValue(todosSnapshotAtom)
const subscriptionPullResult = useAtomValue(subscribeTodosPullAtom)
const pullSubscription = useAtomSet(subscribeTodosPullAtom)
const refreshSubscription = useAtomRefresh(subscribeTodosPullAtom)
const seenOffsetsRef = useRef<Set<number>>(new Set())
const baselineOffsetRef = useRef(0)
const hasInitializedRef = useRef(false)
const hasStartedSubscriptionRef = useRef(false)
const brokenSubscriptionRef = useRef(false)
const reconnectAttemptsRef = useRef(0)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const clearReconnectTimer = () => {
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
}
}
const startSubscriptionPull = () => {
clearReconnectTimer()
if (!hasStartedSubscriptionRef.current) {
hasStartedSubscriptionRef.current = true
}
setConnection((current) => ({ ...current, subscriptionState: "connecting" }))
refreshSubscription()
pullSubscription(undefined)
}
const scheduleReconnect = (lastError: string) => {
brokenSubscriptionRef.current = true
reconnectAttemptsRef.current += 1
if (reconnectAttemptsRef.current > maxReconnectAttempts) {
setConnection((current) => ({
...current,
lastError,
subscriptionState: "idle"
}))
return
}
const delayMs = Math.min(
reconnectBaseMs * 2 ** Math.max(0, reconnectAttemptsRef.current - 1),
reconnectMaxMs
)
setConnection((current) => ({
...current,
lastError,
subscriptionState: "connecting"
}))
clearReconnectTimer()
reconnectTimerRef.current = setTimeout(() => {
reconnectTimerRef.current = null
startSubscriptionPull()
}, delayMs)
}
const addEvent = (event: TodoEvent): boolean => {
if (event.offset <= baselineOffsetRef.current) {
return false
}
if (seenOffsetsRef.current.has(event.offset)) {
return false
}
seenOffsetsRef.current.add(event.offset)
setEvents((events) => [...events, event])
return true
}
const applyEvent = (event: TodoEvent) => {
setProjection((current) => ({
...current,
lastOffset: Math.max(current.lastOffset, event.offset),
todos: sortTodos(
current.todos.some((todo) => todo.id === event.todo.id)
? current.todos.map((todo) => (todo.id === event.todo.id ? event.todo : todo))
: [...current.todos, event.todo]
),
titleDrafts: {
...current.titleDrafts,
[event.todo.id]: event.todo.title
}
}))
}
const applyTodoEvent = (event: TodoEvent) => {
const isNew = addEvent(event)
if (isNew) {
applyEvent(event)
}
}
useEffect(() => {
if (AsyncResult.isInitial(snapshotResult)) {
return
}
if (AsyncResult.isFailure(snapshotResult)) {
scheduleReconnect(Cause.pretty(snapshotResult.cause))
return
}
const snapshot = snapshotResult.value
setProjection({
todos: sortTodos(snapshot.todos),
lastOffset: snapshot.offset,
titleDrafts: Object.fromEntries(snapshot.todos.map((todo) => [todo.id, todo.title]))
})
if (!hasInitializedRef.current) {
hasInitializedRef.current = true
baselineOffsetRef.current = snapshot.offset
seenOffsetsRef.current = new Set()
setEvents([])
startSubscriptionPull()
}
}, [snapshotResult, setEvents, setProjection])
useEffect(() => {
if (!hasStartedSubscriptionRef.current) {
return
}
if (AsyncResult.isInitial(subscriptionPullResult)) {
setConnection((current) => ({
...current,
subscriptionState: subscriptionPullResult.waiting ? "connected" : "connecting"
}))
return
}
if (AsyncResult.isFailure(subscriptionPullResult)) {
scheduleReconnect(Cause.pretty(subscriptionPullResult.cause))
return
}
reconnectAttemptsRef.current = 0
brokenSubscriptionRef.current = false
setConnection((current) => ({
...current,
lastError: null,
subscriptionState: "connected"
}))
for (const event of subscriptionPullResult.value.items) {
applyTodoEvent(event)
}
if (!subscriptionPullResult.value.done && !subscriptionPullResult.waiting) {
pullSubscription(undefined)
}
}, [pullSubscription, setConnection, subscriptionPullResult])
useEffect(() => {
const reconnectOnFocus = () => {
if (document.visibilityState !== "visible") {
return
}
if (!brokenSubscriptionRef.current) {
return
}
reconnectAttemptsRef.current = 0
startSubscriptionPull()
}
window.addEventListener("focus", reconnectOnFocus)
document.addEventListener("visibilitychange", reconnectOnFocus)
return () => {
window.removeEventListener("focus", reconnectOnFocus)
document.removeEventListener("visibilitychange", reconnectOnFocus)
}
}, [setConnection])
useEffect(() => {
return () => {
clearReconnectTimer()
}
}, [])
const runMutation: MutationRunner = (label, run, onSuccess) => {
setBusy(label)
setConnection((current) => ({ ...current, lastError: null }))
void run().then(
(value) => {
onSuccess(value)
},
(error) => {
setConnection((current) => ({ ...current, lastError: Cause.pretty(error) }))
}
).finally(() => {
setBusy(null)
})
}
return (
<main className="shell">
<Status />
<section className="hero">
<p className="eyebrow">effect-http-ws-cli</p>
<h1>Realtime Todo Stream</h1>
<p className="lead">
Snapshot on load, then live updates over typed WebSocket RPC subscriptions.
</p>
</section>
<TodoPanel runMutation={runMutation} applyTodoEvent={applyTodoEvent} />
<EventList />
<Footer />
</main>
)
}
type MutationRunner = <A>(
label: string,
run: () => Promise<A>,
onSuccess: (value: A) => void
) => void
const sortTodos = (todos: ReadonlyArray<Todo>): ReadonlyArray<Todo> =>
[...todos].sort((a, b) => {
if (a.archived !== b.archived) return a.archived ? 1 : -1
if (a.completed !== b.completed) return a.completed ? 1 : -1
return a.id.localeCompare(b.id)
})
const describeChange = (change: TodoChange): string => {
switch (change._tag) {
case "TodoCreated":
return "created"
case "TodoRenamed":
return `renamed to "${change.title}"`
case "TodoCompleted":
return change.completed ? "completed" : "marked incomplete"
case "TodoArchived":
return change.archived ? "archived" : "unarchived"
}
}
const Status = () => {
const connection = useAtomValue(connectionAtom)
const busy = useAtomValue(mutationBusyAtom)
return (
<section className="panel status-panel">
<div className="status-grid">
<div className={`status-item status-subscription-${connection.subscriptionState}`}>
<span className="status-label">Subscription</span>
<strong>{connection.subscriptionState}</strong>
</div>
<div className={`status-item ${busy ? "status-mutation-busy" : "status-mutation-idle"}`}>
<span className="status-label">Mutation</span>
<strong>{busy ? busy : "idle"}</strong>
</div>
</div>
</section>
)
}
const TodoPanel = (props: {
readonly runMutation: MutationRunner
readonly applyTodoEvent: (event: TodoEvent) => void
}) => {
const projection = useAtomValue(todoProjectionAtom)
const connection = useAtomValue(connectionAtom)
const setProjection = useAtomSet(todoProjectionAtom)
const renameTodo = useAtomSet(renameTodoMutationAtom, { mode: "promise" })
const completeTodo = useAtomSet(completeTodoMutationAtom, { mode: "promise" })
const archiveTodo = useAtomSet(archiveTodoMutationAtom, { mode: "promise" })
return (
<section className="panel todo-panel">
<header className="todo-header">
<h2>Todos</h2>
<div className="meta">
<span>offset #{projection.lastOffset}</span>
<span>subscription: {connection.subscriptionState}</span>
</div>
</header>
<ul className="todo-list">
{projection.todos.map((todo) => (
<li
key={todo.id}
className={`todo-item${todo.completed ? " is-completed" : ""}${todo.archived ? " is-archived" : ""}`}
>
<div className="todo-main">
<input
value={projection.titleDrafts[todo.id] ?? todo.title}
onChange={(event) => {
setProjection((current) => ({
...current,
titleDrafts: {
...current.titleDrafts,
[todo.id]: event.target.value
}
}))
}}
/>
<small>
rev {todo.revision} · {new Date(todo.updatedAt).toLocaleTimeString()}
</small>
</div>
<div className="todo-actions">
<button
type="button"
onClick={() =>
props.runMutation(
`rename:${todo.id}`,
() =>
renameTodo({
payload: {
id: todo.id,
title: projection.titleDrafts[todo.id] ?? todo.title
}
}),
props.applyTodoEvent
)
}
>
Rename
</button>
<button
type="button"
onClick={() =>
props.runMutation(
`complete:${todo.id}`,
() =>
completeTodo({
payload: {
id: todo.id,
completed: !todo.completed
}
}),
props.applyTodoEvent
)
}
>
{todo.completed ? "Undo" : "Complete"}
</button>
<button
type="button"
onClick={() =>
props.runMutation(
`archive:${todo.id}`,
() =>
archiveTodo({
payload: {
id: todo.id,
archived: !todo.archived
}
}),
props.applyTodoEvent
)
}
>
{todo.archived ? "Unarchive" : "Archive"}
</button>
</div>
</li>
))}
</ul>
</section>
)
}
const EventList = () => {
const events = useAtomValue(eventsAtom)
return (
<section className="panel event-panel">
<header className="todo-header">
<h2>Events</h2>
<div className="meta">
<span>{events.length} total</span>
</div>
</header>
<ul className="event-list">
{[...events].reverse().map((event) => (
<li key={event.offset} className="event-item">
<div className="event-top">
<strong>#{event.offset}</strong>
<span>{new Date(event.at).toLocaleTimeString()}</span>
</div>
<div className="event-body">
<span>{event.todo.title}</span>
<small>{describeChange(event.change)}</small>
</div>
</li>
))}
</ul>
</section>
)
}
const Footer = () => {
const connection = useAtomValue(connectionAtom)
return (
<footer className="footer">
{connection.lastError ? <span className="error">{connection.lastError}</span> : <span>no errors</span>}
</footer>
)
}
+41
View File
@@ -0,0 +1,41 @@
import * as Layer from "effect/Layer"
import * as RpcClient from "effect/unstable/rpc/RpcClient"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as AtomRpc from "effect/unstable/reactivity/AtomRpc"
import * as Socket from "effect/unstable/socket/Socket"
import { WsRpcGroup } from "@effect-http-ws-cli/server/contracts"
const wsUrl = () => {
const protocol = window.location.protocol === "https:" ? "wss" : "ws"
return `${protocol}://${window.location.host}/ws`
}
const protocolLayer = RpcClient.layerProtocolSocket({
retryTransientErrors: true
}).pipe(
Layer.provide(Socket.layerWebSocket(wsUrl())),
Layer.provide(Socket.layerWebSocketConstructorGlobal),
Layer.provide(RpcSerialization.layerJson)
)
export class TodoRpcClient extends AtomRpc.Service<TodoRpcClient>()("TodoRpcClient", {
group: WsRpcGroup,
protocol: protocolLayer
}) {}
export const todosSnapshotAtom = TodoRpcClient.query(
"listTodos",
{ includeArchived: true }
)
export const subscribeTodosPullAtom = TodoRpcClient.query(
"subscribeTodos",
{
fromOffset: 0,
includeArchived: true
}
)
export const renameTodoMutationAtom = TodoRpcClient.mutation("renameTodo")
export const completeTodoMutationAtom = TodoRpcClient.mutation("completeTodo")
export const archiveTodoMutationAtom = TodoRpcClient.mutation("archiveTodo")
+34
View File
@@ -0,0 +1,34 @@
import * as Atom from "effect/unstable/reactivity/Atom"
import type { Todo, TodoEvent } from "@effect-http-ws-cli/server/contracts"
export type SubscriptionState = "connecting" | "connected" | "idle"
export interface TodoProjectionState {
readonly todos: ReadonlyArray<Todo>
readonly titleDrafts: Readonly<Record<string, string>>
readonly lastOffset: number
}
export interface ConnectionState {
readonly subscriptionState: SubscriptionState
readonly lastError: string | null
}
export const todoProjectionAtom = Atom.make<TodoProjectionState>({
todos: [],
titleDrafts: {},
lastOffset: 0
}).pipe(Atom.withLabel("todo-projection"))
export const eventsAtom = Atom.make<ReadonlyArray<TodoEvent>>([]).pipe(
Atom.withLabel("events")
)
export const connectionAtom = Atom.make<ConnectionState>({
subscriptionState: "idle",
lastError: null
}).pipe(Atom.withLabel("connection"))
export const mutationBusyAtom = Atom.make<string | null>(null).pipe(
Atom.withLabel("mutation-busy")
)
+298
View File
@@ -0,0 +1,298 @@
:root {
--paper: #f3f0e8;
--ink: #13222c;
--ink-soft: #345264;
--accent: #dc4f18;
--accent-soft: #f8bb68;
--panel: #fffdf6;
--line: #162f3f22;
--shadow: 0 16px 40px #0f1e291f;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
color: var(--ink);
background:
radial-gradient(circle at 10% 10%, #f7cf9a 0%, transparent 36%),
radial-gradient(circle at 92% 88%, #95c7d2 0%, transparent 32%),
linear-gradient(165deg, #ece8dc 0%, var(--paper) 48%, #e9dfcf 100%);
}
.shell {
width: min(1100px, 100% - 2rem);
margin: 1.5rem auto;
padding: 1.5rem;
border: 1px solid var(--line);
border-radius: 20px;
background: color-mix(in oklab, var(--paper), white 35%);
box-shadow: var(--shadow);
}
.hero {
position: relative;
overflow: hidden;
padding: 1.5rem;
border-radius: 16px;
border: 1px solid var(--line);
background: linear-gradient(140deg, #fff9ed 0%, #f7efe0 65%, #f2e7d4 100%);
}
.hero::after {
content: "";
position: absolute;
width: 220px;
height: 220px;
right: -60px;
top: -90px;
border-radius: 999px;
background: linear-gradient(180deg, var(--accent-soft), transparent 70%);
pointer-events: none;
}
.eyebrow {
margin: 0;
font-size: 0.72rem;
letter-spacing: 0.22em;
text-transform: uppercase;
color: var(--ink-soft);
}
h1,
h2 {
font-family: "Archivo Black", Impact, sans-serif;
letter-spacing: 0.02em;
margin: 0;
}
h1 {
margin-top: 0.35rem;
font-size: clamp(1.5rem, 4vw, 2.35rem);
}
h2 {
font-size: 1.1rem;
}
.lead {
margin: 0.6rem 0 0;
color: var(--ink-soft);
max-width: 68ch;
}
.panel {
border: 1px solid var(--line);
border-radius: 14px;
padding: 1rem;
background: var(--panel);
margin-top: 1rem;
}
.status-panel {
margin-top: 0;
background: linear-gradient(140deg, #fbf7ee, #f1e8d7);
}
.status-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.7rem;
}
.status-item {
border: 1px solid var(--line);
border-radius: 10px;
padding: 0.55rem 0.7rem;
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 0.75rem;
background: #fff;
}
.status-label {
color: var(--ink-soft);
font-size: 0.82rem;
}
.status-subscription-connected {
border-color: #24704755;
background: #f1fbf5;
}
.status-subscription-connecting {
border-color: #8d6a1b55;
background: #fff8eb;
}
.status-subscription-idle {
border-color: var(--line);
}
.status-mutation-busy {
border-color: #6b3b2e55;
background: #fff3ef;
}
.todo-header {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 1rem;
}
.meta {
display: flex;
gap: 0.75rem;
color: var(--ink-soft);
font-size: 0.86rem;
}
.todo-list {
margin: 0.8rem 0 0;
padding: 0;
list-style: none;
display: grid;
gap: 0.6rem;
}
.event-list {
margin: 0.8rem 0 0;
padding: 0;
list-style: none;
display: grid;
gap: 0.5rem;
max-height: 260px;
overflow: auto;
}
.event-item {
border: 1px solid var(--line);
border-radius: 10px;
background: #fff;
padding: 0.55rem 0.65rem;
}
.event-top {
display: flex;
justify-content: space-between;
gap: 0.6rem;
color: var(--ink-soft);
font-size: 0.8rem;
}
.event-body {
margin-top: 0.2rem;
display: flex;
justify-content: space-between;
gap: 0.75rem;
font-size: 0.9rem;
}
.event-body small {
color: var(--ink-soft);
white-space: nowrap;
}
.todo-item {
display: flex;
gap: 0.8rem;
align-items: center;
border: 1px solid var(--line);
border-radius: 10px;
background: #fff;
padding: 0.65rem;
}
.todo-main {
flex: 1;
}
.todo-main input {
width: 100%;
margin: 0;
border: 1px solid var(--line);
background: #fff;
border-radius: 8px;
padding: 0.42rem 0.55rem;
color: var(--ink);
font: inherit;
font-weight: 600;
}
.todo-main small {
display: block;
margin-top: 0.3rem;
color: var(--ink-soft);
}
.todo-actions {
display: flex;
gap: 0.45rem;
}
button {
border: 1px solid #0f243233;
border-radius: 8px;
background: linear-gradient(160deg, #fff, #f4efe3);
color: var(--ink);
padding: 0.4rem 0.6rem;
font: inherit;
font-size: 0.85rem;
font-weight: 700;
cursor: pointer;
transition: transform 120ms ease, box-shadow 120ms ease;
}
button:hover {
transform: translateY(-1px);
box-shadow: 0 8px 18px #0f20321a;
}
.todo-item.is-completed .todo-main input {
text-decoration: line-through;
color: var(--ink-soft);
}
.todo-item.is-archived {
opacity: 0.64;
}
.footer {
margin-top: 1rem;
display: flex;
gap: 1rem;
align-items: center;
font-size: 0.88rem;
color: var(--ink-soft);
}
.error {
color: var(--accent);
font-weight: 700;
}
@media (max-width: 880px) {
.shell {
width: min(1100px, 100% - 1rem);
padding: 1rem;
}
.todo-item {
flex-direction: column;
align-items: stretch;
}
.todo-actions {
justify-content: flex-end;
}
.status-grid {
grid-template-columns: 1fr;
}
}
+74
View File
@@ -0,0 +1,74 @@
import * as React from "react"
import { RegistryProvider } from "@effect/atom-react"
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"
import * as Atom from "effect/unstable/reactivity/Atom"
import { describe, expect, it, vi } from "vitest"
import { render } from "vitest-browser-react"
import { createMemoryHistory, RouterProvider } from "@tanstack/react-router"
import { getRouter } from "../src/router"
vi.mock("../src/rpc.ts", () => {
const initialSnapshot = AsyncResult.success({
offset: 42,
todos: [
{
id: "todo-1",
title: "Harness Todo",
completed: false,
archived: false,
revision: 1,
updatedAt: "2026-03-05T00:00:00.000Z"
}
]
})
const noopSubscription = AsyncResult.initial<{
readonly done: boolean
readonly items: ReadonlyArray<unknown>
}>(true)
const mutationResult = AsyncResult.success({
offset: 43,
at: "2026-03-05T00:00:01.000Z",
todo: {
id: "todo-1",
title: "Harness Todo",
completed: false,
archived: false,
revision: 1,
updatedAt: "2026-03-05T00:00:01.000Z"
},
change: { _tag: "TodoRenamed", title: "Harness Todo" as const }
})
return {
todosSnapshotAtom: Atom.make(initialSnapshot),
subscribeTodosPullAtom: Atom.writable(
() => noopSubscription,
() => {
// no-op: smoke test doesn't exercise stream pulling
}
),
renameTodoMutationAtom: Atom.make(mutationResult),
completeTodoMutationAtom: Atom.make(mutationResult),
archiveTodoMutationAtom: Atom.make(mutationResult)
}
})
describe("web app harness", () => {
it("renders App in browser mode", async () => {
const history = createMemoryHistory()
const router = getRouter(history)
const screen = await render(
<RegistryProvider>
<RouterProvider router={router} />
</RegistryProvider>
)
await expect.element(screen.getByRole("heading", { name: "Realtime Todo Stream" })).toBeVisible()
await expect.element(screen.getByRole("heading", { name: "Todos" })).toBeVisible()
await expect.element(screen.getByRole("textbox")).toHaveValue("Harness Todo")
})
})
+17
View File
@@ -0,0 +1,17 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts", "vitest.config.ts"]
}
+30
View File
@@ -0,0 +1,30 @@
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
import { TanStackRouterVite } from "@tanstack/router-plugin/vite"
const backendOrigin = process.env.VITE_BACKEND_ORIGIN ?? "http://127.0.0.1:8787"
export default defineConfig({
plugins: [TanStackRouterVite(), react()],
server: {
proxy: {
"/api": {
target: backendOrigin,
changeOrigin: true
},
"/health": {
target: backendOrigin,
changeOrigin: true
},
"/ws": {
target: backendOrigin,
changeOrigin: true,
ws: true
}
}
},
build: {
outDir: "../public",
emptyOutDir: true
}
})
+31
View File
@@ -0,0 +1,31 @@
import { playwright } from "@vitest/browser-playwright"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vitest/config"
export default defineConfig({
plugins: [react()],
optimizeDeps: {
include: [
"react",
"react-dom",
"react/jsx-dev-runtime",
"@tanstack/react-router",
"@effect/atom-react",
"vitest-browser-react",
"effect/unstable/reactivity/Atom",
"effect/unstable/reactivity/AsyncResult"
]
},
test: {
include: ["test/**/*.browser.test.tsx"],
browser: {
enabled: true,
provider: playwright(),
instances: [
{
browser: "chromium"
}
]
}
}
})
+2 -2
View File
@@ -7,7 +7,7 @@
## Project Snapshot
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
+1 -1
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
PRs are automatically labeled with a `vouch:*` trust status.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
+1 -1
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
+5 -31
View File
@@ -1,43 +1,19 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
## Installation
## How to use
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
```bash
npx t3
```
### Desktop app
You can also just install the desktop app. It's cooler.
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
## Some notes
@@ -45,8 +21,6 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+41 -63
View File
@@ -1,87 +1,65 @@
# Remote Access
# Remote Access Setup
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
## Recommended Setup
## CLI ↔ Env option map
Use a trusted private network that meshes your devices together, such as a tailnet.
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
That gives you:
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ---------------------------------- |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
- a stable address to connect to
- transport security at the network layer
- less exposure than opening the server to the public internet
> TIP: Use the `--help` flag to see all available options and their descriptions.
## Enabling Network Access
## Security First
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
- Always set `--auth-token` before exposing the server outside localhost.
- Treat the token like a password.
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
### Option 1: Desktop App
## 1) Build + run server for remote access
If you are already running the desktop app and want to make it reachable from other devices:
1. Open **Settings** → **Connections**.
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
4. Use **Create Link** to generate a pairing link you can share with another device.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
Run the server with `t3 serve`.
Remote access should use the built web app (not local Vite redirect mode).
```bash
npx t3 serve --host "$(tailscale ip -4)"
bun run build
TOKEN="$(openssl rand -hex 24)"
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
```
`t3 serve` starts the server without opening a browser and prints:
Then open on your phone:
- a connection string
- a pairing token
- a pairing URL
- a QR code for the pairing URL
`http://<your-machine-ip>:3773`
From there, connect from another device in either of these ways:
Example:
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
`http://192.168.1.42:3773`
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
Notes:
> Note
> The GUIs do not currently support adding projects on remote environments.
> For now, use `t3 project ...` on the server machine instead.
> Full GUI support for remote project management is coming soon.
- `--host 0.0.0.0` listens on all IPv4 interfaces.
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
- Ensure your OS firewall allows inbound TCP on the selected port.
## How Pairing Works
## 2) Tailnet / Tailscale access
The remote device does not need a long-lived secret up front.
If you use Tailscale, you can bind directly to your Tailnet address.
Instead:
```bash
TAILNET_IP="$(tailscale ip -4)"
TOKEN="$(openssl rand -hex 24)"
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
```
1. `t3 serve` issues a one-time owner pairing token.
2. The remote device exchanges that token with the server.
3. The server creates an authenticated session for that device.
Open from any device in your tailnet:
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
`http://<tailnet-ip>:3773`
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
Typical uses:
- issue additional pairing credentials
- inspect active sessions
- revoke old pairing links or sessions
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
## Security Notes
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.15",
"version": "0.0.9",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -24,7 +24,8 @@
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
"vitest": "catalog:",
"wait-on": "^8.0.2"
},
"productName": "T3 Code (Alpha)"
}
+13 -23
View File
@@ -1,39 +1,27 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
if (!devServerUrl) {
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
}
const devServer = new URL(devServerUrl);
const port = Number.parseInt(devServer.port, 10);
if (!Number.isInteger(port) || port <= 0) {
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
}
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/bin.mjs",
"../server/dist/index.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
tcpHost: devServer.hostname,
tcpPort: port,
await waitOn({
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
});
const childEnv = { ...process.env };
@@ -72,7 +60,10 @@ function startApp() {
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
{
cwd: desktopDir,
env: childEnv,
env: {
...childEnv,
VITE_DEV_SERVER_URL: devServerUrl,
},
stdio: "inherit",
},
);
@@ -89,13 +80,12 @@ function startApp() {
}
});
app.once("exit", (code, signal) => {
app.once("exit", () => {
if (currentApp === app) {
currentApp = null;
}
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
if (!shuttingDown && !expectedExits.has(app)) {
scheduleRestart();
}
});
+1 -1
View File
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const APP_BUNDLE_ID = "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
-119
View File
@@ -1,119 +0,0 @@
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await FileSystem.access(filePath);
return true;
} catch {
return false;
}
}
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = Net.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
if (settled) {
return;
}
settled = true;
socket.removeAllListeners();
socket.destroy();
resolveReady(ready);
};
socket.once("connect", () => {
finish(true);
});
socket.once("timeout", () => {
finish(false);
});
socket.once("error", () => {
finish(false);
});
socket.setTimeout(connectTimeoutMs);
});
}
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
}
let tcpReady = false;
for (const host of tcpHosts) {
tcpReady = await tcpPortIsReady({
host,
port: tcpPort,
connectTimeoutMs,
});
if (tcpReady) {
break;
}
}
return {
pendingFiles,
tcpReady,
};
}
export async function waitForResources({
baseDir,
files = [],
intervalMs = 100,
timeoutMs = 120_000,
tcpHost,
tcpPort,
connectTimeoutMs = 500,
}) {
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
throw new TypeError("waitForResources requires a positive integer tcpPort");
}
const startedAt = Date.now();
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
while (true) {
const { pendingFiles, tcpReady } = await resolvePendingResources({
baseDir,
files,
tcpPort,
tcpHosts,
connectTimeoutMs,
});
if (pendingFiles.length === 0 && tcpReady) {
return;
}
if (Date.now() - startedAt >= timeoutMs) {
const pendingResources = [];
if (!tcpReady) {
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
}
for (const filePath of pendingFiles) {
pendingResources.push(`file:${filePath}`);
}
throw new Error(
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
);
}
await Timers.setTimeout(intervalMs);
}
}
-56
View File
@@ -1,56 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3773);
expect(canListenOnHost).toHaveBeenCalledTimes(1);
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
});
it("increments sequentially until it finds an available port", async () => {
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3775);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3774, "127.0.0.1"],
[3775, "127.0.0.1"],
]);
});
it("fails when the scan range is exhausted", async () => {
const canListenOnHost = vi.fn(async () => false);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 65534,
maxPort: 65535,
canListenOnHost,
}),
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
expect(canListenOnHost.mock.calls).toEqual([
[65534, "127.0.0.1"],
[65535, "127.0.0.1"],
]);
});
});
-53
View File
@@ -1,53 +0,0 @@
import * as Effect from "effect/Effect";
import { NetService } from "@t3tools/shared/Net";
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
export interface ResolveDesktopBackendPortOptions {
readonly host: string;
readonly startPort?: number;
readonly maxPort?: number;
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
}
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
Effect.service(NetService).pipe(
Effect.flatMap((net) => net.canListenOnHost(port, host)),
Effect.provide(NetService.layer),
Effect.runPromise,
);
const isValidPort = (port: number): boolean =>
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
export async function resolveDesktopBackendPort({
host,
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
maxPort = MAX_TCP_PORT,
canListenOnHost = defaultCanListenOnHost,
}: ResolveDesktopBackendPortOptions): Promise<number> {
if (!isValidPort(startPort)) {
throw new Error(`Invalid desktop backend start port: ${startPort}`);
}
if (!isValidPort(maxPort)) {
throw new Error(`Invalid desktop backend max port: ${maxPort}`);
}
if (maxPort < startPort) {
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
}
// Keep desktop startup predictable across app restarts by probing upward from
// the same preferred port instead of picking a fresh ephemeral port.
for (let port = startPort; port <= maxPort; port += 1) {
if (await canListenOnHost(port, host)) {
return port;
}
}
throw new Error(
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
);
}
-83
View File
@@ -1,83 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
BackendReadinessAbortedError,
isBackendReadinessAborted,
waitForHttpReady,
} from "./backendReadiness";
describe("waitForHttpReady", () => {
it("returns once the backend reports a successful session endpoint", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response(null, { status: 503 }))
.mockResolvedValueOnce(new Response(null, { status: 200 }));
await waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 1_000,
intervalMs: 0,
});
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it("retries after a readiness request stalls past the per-request timeout", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockImplementationOnce(
(_input, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener(
"abort",
() => {
reject(new Error("request timed out"));
},
{ once: true },
);
}) as ReturnType<typeof fetch>,
)
.mockResolvedValueOnce(new Response(null, { status: 200 }));
await waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 100,
intervalMs: 0,
requestTimeoutMs: 1,
});
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it("aborts an in-flight readiness wait", async () => {
const controller = new AbortController();
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
() =>
new Promise((_resolve, reject) => {
controller.signal.addEventListener(
"abort",
() => {
reject(new BackendReadinessAbortedError());
},
{ once: true },
);
}) as ReturnType<typeof fetch>,
);
const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
fetchImpl,
timeoutMs: 1_000,
intervalMs: 0,
signal: controller.signal,
});
controller.abort();
await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
});
it("recognizes aborted readiness errors", () => {
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
});
});
-103
View File
@@ -1,103 +0,0 @@
export interface WaitForHttpReadyOptions {
readonly timeoutMs?: number;
readonly intervalMs?: number;
readonly requestTimeoutMs?: number;
readonly fetchImpl?: typeof fetch;
readonly signal?: AbortSignal;
}
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_INTERVAL_MS = 100;
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
export class BackendReadinessAbortedError extends Error {
constructor() {
super("Backend readiness wait was aborted.");
this.name = "BackendReadinessAbortedError";
}
}
function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
resolve();
}, ms);
const onAbort = () => {
cleanup();
reject(new BackendReadinessAbortedError());
};
const cleanup = () => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
};
if (signal?.aborted) {
cleanup();
reject(new BackendReadinessAbortedError());
return;
}
signal?.addEventListener("abort", onAbort, { once: true });
});
}
export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
return error instanceof BackendReadinessAbortedError;
}
export async function waitForHttpReady(
baseUrl: string,
options?: WaitForHttpReadyOptions,
): Promise<void> {
const fetchImpl = options?.fetchImpl ?? fetch;
const signal = options?.signal;
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const deadline = Date.now() + timeoutMs;
for (;;) {
if (signal?.aborted) {
throw new BackendReadinessAbortedError();
}
const requestController = new AbortController();
const requestTimeout = setTimeout(() => {
requestController.abort();
}, requestTimeoutMs);
const abortRequest = () => {
requestController.abort();
};
signal?.addEventListener("abort", abortRequest, { once: true });
try {
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
redirect: "manual",
signal: requestController.signal,
});
if (response.ok) {
return;
}
} catch (error) {
if (isBackendReadinessAborted(error)) {
throw error;
}
if (signal?.aborted) {
throw new BackendReadinessAbortedError();
}
// Retry until the backend becomes reachable or the deadline expires.
} finally {
clearTimeout(requestTimeout);
signal?.removeEventListener("abort", abortRequest);
}
if (Date.now() >= deadline) {
throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
}
await delay(intervalMs, signal);
}
}
-234
View File
@@ -1,234 +0,0 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
EnvironmentId,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
readClientSettings,
readSavedEnvironmentRegistry,
readSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempPath(fileName: string): string {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
tempDirectories.push(directory);
return path.join(directory, fileName);
}
function makeSecretStorage(available: boolean): DesktopSecretStorage {
return {
isEncryptionAvailable: () => available,
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
decryptString: (value) => {
const decoded = value.toString("utf8");
if (!decoded.startsWith("enc:")) {
throw new Error("invalid secret");
}
return decoded.slice("enc:".length);
},
};
}
const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
};
describe("clientPersistence", () => {
it("persists and reloads client settings", () => {
const settingsPath = makeTempPath("client-settings.json");
writeClientSettings(settingsPath, clientSettings);
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
});
it("persists and reloads saved environment metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
});
it("persists encrypted saved environment secrets when encryption is available", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
}),
).toBe(true);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
records: [
{
...savedRegistryRecord,
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
},
],
});
});
it("preserves existing secrets when encryption is unavailable", () => {
const registryPath = makeTempPath("saved-environments.json");
const availableSecretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: availableSecretStorage,
});
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
secretStorage: makeSecretStorage(false),
}),
).toBe(false);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: availableSecretStorage,
}),
).toBe("bearer-token");
});
it("removes saved environment secrets", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
});
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBeNull();
});
it("treats malformed secrets documents as empty", () => {
const registryPath = makeTempPath("saved-environments.json");
fs.writeFileSync(registryPath, "{}\n", "utf8");
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: makeSecretStorage(true),
}),
).toBeNull();
expect(() =>
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
}),
).not.toThrow();
});
it("returns false when writing a secret without metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: makeSecretStorage(true),
}),
).toBe(false);
});
it("preserves encrypted secrets when metadata is rewritten", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
});
});
-216
View File
@@ -1,216 +0,0 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
}
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
readonly encryptedBearerToken?: string;
}
interface SavedEnvironmentRegistryDocument {
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
}
export interface DesktopSecretStorage {
readonly isEncryptionAvailable: () => boolean;
readonly encryptString: (value: string) => Buffer;
readonly decryptString: (value: Buffer) => string;
}
function readJsonFile<T>(filePath: string): T | null {
try {
if (!FS.existsSync(filePath)) {
return null;
}
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
} catch {
return null;
}
}
function writeJsonFile(filePath: string, value: unknown): void {
const directory = Path.dirname(filePath);
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
FS.mkdirSync(directory, { recursive: true });
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
FS.renameSync(tempPath, filePath);
}
function isPersistedSavedEnvironmentStorageRecord(
value: unknown,
): value is PersistedSavedEnvironmentStorageRecord {
return (
Predicate.isObject(value) &&
typeof value.environmentId === "string" &&
typeof value.label === "string" &&
typeof value.httpBaseUrl === "string" &&
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
if (!Predicate.isObject(parsed)) {
return { records: [] };
}
return {
records: Array.isArray(parsed.records)
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
: [],
};
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
}
export function readSavedEnvironmentRegistry(
registryPath: string,
): readonly PersistedSavedEnvironmentRecord[] {
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
toPersistedSavedEnvironmentRecord(record),
);
}
export function writeSavedEnvironmentRegistry(
registryPath: string,
records: readonly PersistedSavedEnvironmentRecord[],
): void {
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
const encryptedBearerTokenById = new Map(
currentDocument.records.flatMap((record) =>
record.encryptedBearerToken
? [[record.environmentId, record.encryptedBearerToken] as const]
: [],
),
);
writeJsonFile(registryPath, {
records: records.map((record) => {
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
return encryptedBearerToken
? {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
}
: record;
}),
} satisfies SavedEnvironmentRegistryDocument);
}
export function readSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secretStorage: DesktopSecretStorage;
}): string | null {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
const encoded = document.records.find(
(record) => record.environmentId === input.environmentId,
)?.encryptedBearerToken;
if (!encoded) {
return null;
}
if (!input.secretStorage.isEncryptionAvailable()) {
return null;
}
try {
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
} catch {
return null;
}
}
export function writeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secret: string;
readonly secretStorage: DesktopSecretStorage;
}): boolean {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (!input.secretStorage.isEncryptionAvailable()) {
return false;
}
let found = false;
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
found = true;
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
}
export function removeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
}): void {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (
!document.records.some(
(record) =>
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
} satisfies SavedEnvironmentRegistryDocument);
}
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
-64
View File
@@ -1,64 +0,0 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
writeDesktopSettings,
} from "./desktopSettings";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
function makeSettingsPath() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
tempDirectories.push(directory);
return path.join(directory, "desktop-settings.json");
}
describe("desktopSettings", () => {
it("returns defaults when no settings file exists", () => {
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
it("persists and reloads the configured server exposure mode", () => {
const settingsPath = makeSettingsPath();
writeDesktopSettings(settingsPath, {
serverExposureMode: "network-accessible",
});
expect(readDesktopSettings(settingsPath)).toEqual({
serverExposureMode: "network-accessible",
});
});
it("preserves the requested network-accessible preference across temporary fallback", () => {
expect(
setDesktopServerExposurePreference(
{
serverExposureMode: "local-only",
},
"network-accessible",
),
).toEqual({
serverExposureMode: "network-accessible",
});
});
it("falls back to defaults when the settings file is malformed", () => {
const settingsPath = makeSettingsPath();
fs.writeFileSync(settingsPath, "{not-json", "utf8");
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
});
});
-51
View File
@@ -1,51 +0,0 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
export interface DesktopSettings {
readonly serverExposureMode: DesktopServerExposureMode;
}
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
serverExposureMode: "local-only",
};
export function setDesktopServerExposurePreference(
settings: DesktopSettings,
requestedMode: DesktopServerExposureMode,
): DesktopSettings {
return settings.serverExposureMode === requestedMode
? settings
: {
...settings,
serverExposureMode: requestedMode,
};
}
export function readDesktopSettings(settingsPath: string): DesktopSettings {
try {
if (!FS.existsSync(settingsPath)) {
return DEFAULT_DESKTOP_SETTINGS;
}
const raw = FS.readFileSync(settingsPath, "utf8");
const parsed = JSON.parse(raw) as {
readonly serverExposureMode?: unknown;
};
return {
serverExposureMode:
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
};
} catch {
return DEFAULT_DESKTOP_SETTINGS;
}
}
export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
const directory = Path.dirname(settingsPath);
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
FS.mkdirSync(directory, { recursive: true });
FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
FS.renameSync(tempPath, settingsPath);
}
+15
View File
@@ -0,0 +1,15 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+62 -593
View File
File diff suppressed because it is too large. Load diff
+2 -32
View File
@@ -9,41 +9,12 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getLocalEnvironmentBootstrap: () => {
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
if (typeof result !== "object" || result === null) {
return null;
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
@@ -61,7 +32,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
-139
View File
@@ -1,139 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
describe("resolveLanAdvertisedHost", () => {
it("prefers an explicit host override", () => {
expect(
resolveLanAdvertisedHost(
{
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
"10.0.0.9",
),
).toBe("10.0.0.9");
});
it("returns the first usable non-internal IPv4 address", () => {
expect(
resolveLanAdvertisedHost(
{
lo0: [
{
address: "127.0.0.1",
family: "IPv4",
internal: true,
netmask: "255.0.0.0",
cidr: "127.0.0.1/8",
mac: "00:00:00:00:00:00",
},
],
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
undefined,
),
).toBe("192.168.1.44");
});
it("returns null when no usable network address is available", () => {
expect(
resolveLanAdvertisedHost(
{
lo0: [
{
address: "127.0.0.1",
family: "IPv4",
internal: true,
netmask: "255.0.0.0",
cidr: "127.0.0.1/8",
mac: "00:00:00:00:00:00",
},
],
},
undefined,
),
).toBeNull();
});
});
describe("resolveDesktopServerExposure", () => {
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
expect(
resolveDesktopServerExposure({
mode: "local-only",
port: 3773,
networkInterfaces: {},
}),
).toEqual({
mode: "local-only",
bindHost: "127.0.0.1",
localHttpUrl: "http://127.0.0.1:3773",
localWsUrl: "ws://127.0.0.1:3773",
endpointUrl: null,
advertisedHost: null,
});
});
it("binds to all interfaces in network-accessible mode", () => {
expect(
resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {
en0: [
{
address: "192.168.1.44",
family: "IPv4",
internal: false,
netmask: "255.255.255.0",
cidr: "192.168.1.44/24",
mac: "00:00:00:00:00:00",
},
],
},
}),
).toEqual({
mode: "network-accessible",
bindHost: "0.0.0.0",
localHttpUrl: "http://127.0.0.1:3773",
localWsUrl: "ws://127.0.0.1:3773",
endpointUrl: "http://192.168.1.44:3773",
advertisedHost: "192.168.1.44",
});
});
it("stays network-accessible even when no LAN address is currently detectable", () => {
expect(
resolveDesktopServerExposure({
mode: "network-accessible",
port: 3773,
networkInterfaces: {},
}),
).toEqual({
mode: "network-accessible",
bindHost: "0.0.0.0",
localHttpUrl: "http://127.0.0.1:3773",
localWsUrl: "ws://127.0.0.1:3773",
endpointUrl: null,
advertisedHost: null,
});
});
});
-80
View File
@@ -1,80 +0,0 @@
import type { NetworkInterfaceInfo } from "node:os";
import type { DesktopServerExposureMode } from "@t3tools/contracts";
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
export interface DesktopServerExposure {
readonly mode: DesktopServerExposureMode;
readonly bindHost: string;
readonly localHttpUrl: string;
readonly localWsUrl: string;
readonly endpointUrl: string | null;
readonly advertisedHost: string | null;
}
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
};
const isUsableLanIpv4Address = (address: string): boolean =>
!address.startsWith("127.") && !address.startsWith("169.254.");
export function resolveLanAdvertisedHost(
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
explicitHost: string | undefined,
): string | null {
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
if (normalizedExplicitHost) {
return normalizedExplicitHost;
}
for (const interfaceAddresses of Object.values(networkInterfaces)) {
if (!interfaceAddresses) continue;
for (const address of interfaceAddresses) {
if (address.internal) continue;
if (address.family !== "IPv4") continue;
if (!isUsableLanIpv4Address(address.address)) continue;
return address.address;
}
}
return null;
}
export function resolveDesktopServerExposure(input: {
readonly mode: DesktopServerExposureMode;
readonly port: number;
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
readonly advertisedHostOverride?: string;
}): DesktopServerExposure {
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
if (input.mode === "local-only") {
return {
mode: input.mode,
bindHost: DESKTOP_LOOPBACK_HOST,
localHttpUrl,
localWsUrl,
endpointUrl: null,
advertisedHost: null,
};
}
const advertisedHost = resolveLanAdvertisedHost(
input.networkInterfaces,
input.advertisedHostOverride,
);
return {
mode: input.mode,
bindHost: DESKTOP_LAN_BIND_HOST,
localHttpUrl,
localWsUrl,
endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
advertisedHost,
};
}
@@ -1,105 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("does nothing outside macOS and linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/usr/local/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "win32",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
-36
View File
@@ -1,36 +0,0 @@
import {
readEnvironmentFromLoginShell,
resolveLoginShell,
ShellEnvironmentReader,
} from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
try {
const shell = resolveLoginShell(platform, env.SHELL);
if (!shell) return;
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
"PATH",
"SSH_AUTH_SOCK",
]);
if (shellEnvironment.PATH) {
env.PATH = shellEnvironment.PATH;
}
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
} catch {
// Keep inherited environment if shell lookup fails.
}
}
-29
View File
@@ -71,37 +71,10 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toContain("packaged production builds");
});
it("reports packaged local builds without an update feed as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: false,
}),
).toContain("no update feed");
});
it("allows packaged builds with an update feed", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toBeNull();
});
it("reports env-disabled auto updates", () => {
expect(
getAutoUpdateDisabledReason({
@@ -110,7 +83,6 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "darwin",
appImage: undefined,
disabledByEnv: true,
hasUpdateFeedConfig: true,
}),
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
});
@@ -123,7 +95,6 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "linux",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toContain("AppImage");
});
-4
View File
@@ -34,11 +34,7 @@ export function getAutoUpdateDisabledReason(args: {
platform: NodeJS.Platform;
appImage?: string | undefined;
disabledByEnv: boolean;
hasUpdateFeedConfig: boolean;
}): string | null {
if (!args.hasUpdateFeedConfig) {
return "Automatic updates are not available because no update feed is configured.";
}
if (args.isDevelopment || !args.isPackaged) {
return "Automatic updates are only available in packaged production builds.";
}
+2 -2
View File
@@ -10,10 +10,10 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
+4 -5
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import { RELEASES_URL } from "../lib/releases";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
@@ -18,11 +17,11 @@ import { RELEASES_URL } from "../lib/releases";
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
<a class="download-card" data-asset="arm64.dmg" href="#">
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
<a class="download-card" data-asset="x64.dmg" href="#">
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
@@ -36,7 +35,7 @@ import { RELEASES_URL } from "../lib/releases";
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
<a class="download-card" data-asset="x64.exe" href="#">
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
@@ -50,7 +49,7 @@ import { RELEASES_URL } from "../lib/releases";
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
<a class="download-card" data-asset="x86_64.AppImage" href="#">
<span class="card-arch">x86_64</span>
<span class="card-format">AppImage</span>
</a>
@@ -1,20 +1,20 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
@@ -24,9 +24,7 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
@@ -39,18 +37,16 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.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 { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
@@ -69,9 +65,7 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -81,16 +75,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
});
}
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
});
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
@@ -128,7 +120,7 @@ function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 40_000,
timeoutMs = 10_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
@@ -213,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
readonly realCodex?: boolean;
}
@@ -221,9 +213,7 @@ export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const sleep = (ms: number) => Effect.sleep(ms);
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
@@ -240,16 +230,13 @@ export const makeOrchestrationIntegrationHarness = (
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
});
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -274,7 +261,7 @@ export const makeOrchestrationIntegrationHarness = (
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
@@ -290,75 +277,41 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusTest,
RuntimeReceiptBusLive,
);
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
generateBranchName: () => Effect.succeed({ branch: null }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
streamStatus: () => Stream.empty,
}),
),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -392,13 +345,13 @@ export const makeOrchestrationIntegrationHarness = (
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
@@ -515,7 +468,13 @@ export const makeOrchestrationIntegrationHarness = (
}
});
yield* shutdown;
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
@@ -10,7 +10,6 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -178,7 +177,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +197,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
}
function nowIso(): string {
@@ -206,7 +205,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +215,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -5,13 +5,10 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
ModelSelection,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -28,7 +25,6 @@ import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -40,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
type IntegrationProvider = "codex";
function nowIso() {
return new Date().toISOString();
@@ -53,11 +49,13 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
timeoutMs = 3000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
@@ -70,7 +68,7 @@ function waitForSync<A>(
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* Effect.sleep(10);
yield* sleep(10);
}
});
}
@@ -91,7 +89,7 @@ function withHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
function withRealCodexHarness<A, E>(
@@ -101,14 +99,12 @@ function withRealCodexHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -116,10 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider,
model: defaultModel,
},
defaultModel: "gpt-5-codex",
createdAt,
});
@@ -129,10 +122,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider,
model: defaultModel,
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -146,7 +136,7 @@ const startTurn = (input: {
readonly commandId: string;
readonly messageId: string;
readonly text: string;
readonly modelSelection?: ModelSelection;
readonly provider?: IntegrationProvider;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
@@ -158,11 +148,7 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
...(input.modelSelection !== undefined
? {
modelSelection: input.modelSelection,
}
: {}),
...(input.provider !== undefined ? { provider: input.provider } : {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
@@ -265,10 +251,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
defaultModel: "gpt-5.3-codex",
createdAt,
});
@@ -278,10 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -902,435 +882,3 @@ it.live(
}),
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
@@ -1,6 +1,5 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
@@ -13,7 +12,6 @@ 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 { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -62,7 +60,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
@@ -86,7 +83,6 @@ const collectEventsDuring = <A, E, R>(
Effect.forkScoped,
);
yield* Effect.sleep("50 millis");
yield* action;
return yield* Effect.forEach(
@@ -105,6 +101,7 @@ const runTurn = (input: {
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.threadId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
@@ -116,7 +113,7 @@ const runTurn = (input: {
);
});
it.live("replays typed runtime fixture events", () =>
it.effect("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
@@ -149,7 +146,7 @@ it.live("replays typed runtime fixture events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("replays file-changing fixture turn events", () =>
it.effect("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -188,7 +185,7 @@ it.live("replays file-changing fixture turn events", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("runs multi-turn tool/approval flow", () =>
it.effect("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
@@ -242,7 +239,7 @@ it.live("runs multi-turn tool/approval flow", () =>
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("rolls back provider conversation state only", () =>
it.effect("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
+6 -7
View File
@@ -1,7 +1,6 @@
{
"name": "t3",
"version": "0.0.15",
"license": "MIT",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
@@ -19,18 +18,17 @@
"build": "node scripts/cli.ts build",
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"typecheck": "node scripts/typecheck.mjs",
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0"
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -40,11 +38,12 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
"node": "^22.13 || ^23.4 || >=24.10"
}
}
+6 -3
View File
@@ -121,6 +121,7 @@ const buildCmd = Command.make(
"build",
{
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
format: Flag.choice("format", ["esm", "cjs"]).pipe(Flag.withDefault("esm")),
},
(config) =>
Effect.gen(function* () {
@@ -137,7 +138,7 @@ const buildCmd = Command.make(
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun tsdown`,
})`bun tsdown --format ${config.format}`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
@@ -177,7 +178,7 @@ const publishCmd = Command.make(
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
@@ -195,8 +196,10 @@ const publishCmd = Command.make(
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
type: serverPackageJson.type,
bin: {
t3: "./dist/bin.mjs",
},
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
+42
View File
@@ -0,0 +1,42 @@
import { spawn } from "node:child_process";
import { createRequire } from "node:module";
import path from "node:path";
const require = createRequire(import.meta.url);
const tscPath = require.resolve("typescript/bin/tsc");
const cwd = path.resolve(import.meta.dirname, "..");
const child = spawn(process.execPath, [tscPath, "--noEmit"], {
cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
child.stdout.on("data", (chunk) => {
const text = chunk.toString();
output += text;
process.stdout.write(text);
});
child.stderr.on("data", (chunk) => {
const text = chunk.toString();
output += text;
process.stderr.write(text);
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
if (code === 0) {
process.exit(0);
return;
}
const hasTypeScriptErrors = /error TS\d+:/.test(output);
process.exit(hasTypeScriptErrors ? (code ?? 1) : 0);
});
+2 -2
View File
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
}
export function resolveAttachmentRelativePath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(input.attachmentsDir);
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
+8 -6
View File
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
+4 -4
View File
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
}
export function resolveAttachmentPath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
@@ -1,111 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
import { makeAuthControlPlane } from "./AuthControlPlane.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
);
const makeAuthControlPlaneLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
Layer.provideMerge(BootstrapCredentialServiceLive),
Layer.provideMerge(SessionCredentialServiceLive),
Layer.provideMerge(ServerSecretStoreLive),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provide(makeServerConfigLayer(overrides)),
);
it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
it.effect("creates, lists, and revokes client pairing links", () =>
Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const created = yield* authControlPlane.createPairingLink({
role: "client",
subject: "one-time-token",
label: "CI phone",
});
const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
const revoked = yield* authControlPlane.revokePairingLink(created.id);
const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
expect(created.role).toBe("client");
expect(created.credential.length).toBeGreaterThan(0);
expect(listedBeforeRevoke).toHaveLength(1);
expect(listedBeforeRevoke[0]?.id).toBe(created.id);
expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
expect(revoked).toBe(true);
expect(listedAfterRevoke).toHaveLength(0);
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
);
it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const sessionCredentials = yield* SessionCredentialService;
const issued = yield* authControlPlane.issueSession({
label: "deploy-bot",
});
const verified = yield* sessionCredentials.verify(issued.token);
const listedBeforeRevoke = yield* authControlPlane.listSessions();
const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
const listedAfterRevoke = yield* authControlPlane.listSessions();
expect(issued.method).toBe("bearer-session-token");
expect(issued.role).toBe("owner");
expect(issued.client.deviceType).toBe("bot");
expect(issued.client.label).toBe("deploy-bot");
expect(verified.sessionId).toBe(issued.sessionId);
expect(verified.role).toBe("owner");
expect(verified.method).toBe("bearer-session-token");
expect(listedBeforeRevoke).toHaveLength(1);
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
expect(revoked).toBe(true);
expect(listedAfterRevoke).toHaveLength(0);
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
);
it.effect("surfaces lastConnectedAt through the listed session view", () =>
Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const sessionCredentials = yield* SessionCredentialService;
const issued = yield* authControlPlane.issueSession({
label: "remote-ipad",
});
const beforeConnect = yield* authControlPlane.listSessions();
yield* sessionCredentials.markConnected(issued.sessionId);
const afterConnect = yield* authControlPlane.listSessions();
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
);
});
@@ -1,176 +0,0 @@
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
import { DateTime, Effect, Layer } from "effect";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
import {
AuthControlPlane,
AuthControlPlaneError,
AuthControlPlaneShape,
DEFAULT_SESSION_SUBJECT,
IssuedBearerSession,
IssuedPairingLink,
} from "../Services/AuthControlPlane.ts";
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
if (left.role !== right.role) {
return left.role === "owner" ? -1 : 1;
}
if (left.connected !== right.connected) {
return left.connected ? -1 : 1;
}
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
};
const toAuthControlPlaneError =
(message: string) =>
(cause: unknown): AuthControlPlaneError =>
new AuthControlPlaneError({
message,
cause,
});
export const makeAuthControlPlane = Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const sessions = yield* SessionCredentialService;
const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
Effect.gen(function* () {
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials.issueOneTimeToken({
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
...(input?.ttl ? { ttl: input.ttl } : {}),
...(input?.label ? { label: input.label } : {}),
});
return {
id: issued.id,
credential: issued.credential,
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
...(issued.label ? { label: issued.label } : {}),
createdAt: DateTime.toUtc(createdAt),
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedPairingLink;
}).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
Effect.map((pairingLinks) =>
pairingLinks
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
.map((pairingLink) =>
pairingLink.label
? ({
id: pairingLink.id,
credential: pairingLink.credential,
role: pairingLink.role,
subject: pairingLink.subject,
label: pairingLink.label,
createdAt: pairingLink.createdAt,
expiresAt: pairingLink.expiresAt,
} satisfies AuthPairingLink)
: ({
id: pairingLink.id,
credential: pairingLink.credential,
role: pairingLink.role,
subject: pairingLink.subject,
createdAt: pairingLink.createdAt,
expiresAt: pairingLink.expiresAt,
} satisfies AuthPairingLink),
)
.toSorted(
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
),
),
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
);
const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
bootstrapCredentials
.revoke(id)
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
sessions
.issue({
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
method: "bearer-session-token",
role: input?.role ?? "owner",
client: {
...(input?.label ? { label: input.label } : {}),
deviceType: "bot",
},
...(input?.ttl ? { ttl: input.ttl } : {}),
})
.pipe(
Effect.flatMap((issued) => {
if (issued.method !== "bearer-session-token") {
return Effect.fail(
new AuthControlPlaneError({
message: "CLI session issuance produced an unexpected session method.",
}),
);
}
return Effect.succeed({
sessionId: issued.sessionId,
token: issued.token,
method: "bearer-session-token" as const,
role: issued.role,
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
client: issued.client,
expiresAt: DateTime.toUtc(issued.expiresAt),
} satisfies IssuedBearerSession);
}),
Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
);
const listSessions: AuthControlPlaneShape["listSessions"] = () =>
sessions.listActive().pipe(
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
);
const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
sessions
.revoke(sessionId)
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
sessionId,
) =>
sessions
.revokeAllExcept(sessionId)
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
return {
createPairingLink,
listPairingLinks,
revokePairingLink,
issueSession,
listSessions,
revokeSession,
revokeOtherSessionsExcept,
} satisfies AuthControlPlaneShape;
});
export const AuthCoreLive = Layer.mergeAll(
BootstrapCredentialServiceLive,
SessionCredentialServiceLive,
);
export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
Layer.provideMerge(AuthRuntimeLive),
);
@@ -1,151 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const config = yield* ServerConfig;
return {
...config,
...overrides,
} satisfies ServerConfigShape;
}),
).pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
);
const makeBootstrapCredentialLayer = (
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
) =>
BootstrapCredentialServiceLive.pipe(
Layer.provide(SqlitePersistenceMemory),
Layer.provide(makeServerConfigLayer(overrides)),
);
it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
it.effect("issues pairing tokens in a short manual-entry format", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const issued = yield* bootstrapCredentials.issueOneTimeToken();
expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
const first = yield* bootstrapCredentials.consume(issued.credential);
const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
expect(first.method).toBe("one-time-token");
expect(first.role).toBe("client");
expect(first.subject).toBe("one-time-token");
expect(first.label).toBe("Julius iPhone");
expect(issued.label).toBe("Julius iPhone");
expect(second._tag).toBe("BootstrapCredentialError");
expect(second.message).toContain("Unknown bootstrap credential");
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
it.effect("atomically consumes a one-time token when multiple requests race", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const token = yield* bootstrapCredentials.issueOneTimeToken();
const results = yield* Effect.all(
Array.from({ length: 8 }, () =>
Effect.result(bootstrapCredentials.consume(token.credential)),
),
{
concurrency: "unbounded",
},
);
const successes = results.filter((result) => result._tag === "Success");
const failures = results.filter((result) => result._tag === "Failure");
expect(successes).toHaveLength(1);
expect(failures).toHaveLength(7);
for (const failure of failures) {
expect(failure.failure._tag).toBe("BootstrapCredentialError");
expect(failure.failure.message).toContain("Unknown bootstrap credential");
}
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
expect(first.method).toBe("desktop-bootstrap");
expect(first.role).toBe("owner");
expect(first.subject).toBe("desktop-bootstrap");
expect(second._tag).toBe("BootstrapCredentialError");
expect(second.status).toBe(401);
}).pipe(
Effect.provide(
makeBootstrapCredentialLayer({
desktopBootstrapToken: "desktop-bootstrap-token",
}),
),
),
);
it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
yield* TestClock.adjust(Duration.minutes(6));
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
expect(expired._tag).toBe("BootstrapCredentialError");
expect(expired.status).toBe(401);
expect(expired.message).toContain("Bootstrap credential expired");
}).pipe(
Effect.provide(
Layer.merge(
makeBootstrapCredentialLayer({
desktopBootstrapToken: "desktop-bootstrap-token",
}),
TestClock.layer(),
),
),
),
);
it.effect("lists and revokes active pairing links", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* BootstrapCredentialService;
const first = yield* bootstrapCredentials.issueOneTimeToken();
const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
const revoked = yield* bootstrapCredentials.revoke(first.id);
const activeAfterRevoke = yield* bootstrapCredentials.listActive();
const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
expect(revoked).toBe(true);
expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
expect(revokedConsume.message).toContain("no longer available");
expect(revokedConsume.status).toBe(401);
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
);
});
@@ -1,296 +0,0 @@
import type { AuthPairingLink } from "@t3tools/contracts";
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
import { Option } from "effect";
import { ServerConfig } from "../../config.ts";
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
import {
BootstrapCredentialError,
BootstrapCredentialService,
type BootstrapCredentialChange,
type BootstrapCredentialServiceShape,
type BootstrapGrant,
type IssuedBootstrapCredential,
} from "../Services/BootstrapCredentialService.ts";
interface StoredBootstrapGrant extends BootstrapGrant {
readonly remainingUses: number | "unbounded";
}
type ConsumeResult =
| {
readonly _tag: "error";
readonly reason: "not-found" | "expired";
readonly error: BootstrapCredentialError;
}
| {
readonly _tag: "success";
readonly grant: BootstrapGrant;
};
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const generatePairingToken = (): string => {
const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
};
export const makeBootstrapCredentialService = Effect.gen(function* () {
const config = yield* ServerConfig;
const pairingLinks = yield* AuthPairingLinkRepository;
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
const invalidBootstrapCredentialError = (message: string) =>
new BootstrapCredentialError({
message,
status: 401,
});
const internalBootstrapCredentialError = (message: string, cause: unknown) =>
new BootstrapCredentialError({
message,
status: 500,
cause,
});
const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
Ref.update(seededGrantsRef, (current) => {
const next = new Map(current);
next.set(credential, grant);
return next;
});
const emitUpsert = (pairingLink: AuthPairingLink) =>
PubSub.publish(changesPubSub, {
type: "pairingLinkUpserted",
pairingLink,
}).pipe(Effect.asVoid);
const emitRemoved = (id: string) =>
PubSub.publish(changesPubSub, {
type: "pairingLinkRemoved",
id,
}).pipe(Effect.asVoid);
if (config.desktopBootstrapToken) {
const now = yield* DateTime.now;
yield* seedGrant(config.desktopBootstrapToken, {
method: "desktop-bootstrap",
role: "owner",
subject: "desktop-bootstrap",
expiresAt: DateTime.add(now, {
milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
}),
remainingUses: 1,
});
}
const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
internalBootstrapCredentialError(message, cause);
const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const rows = yield* pairingLinks.listActive({ now });
return rows.map((row) =>
row.label
? ({
id: row.id,
credential: row.credential,
role: row.role,
subject: row.subject,
label: row.label,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
} satisfies AuthPairingLink)
: ({
id: row.id,
credential: row.credential,
role: row.role,
subject: row.subject,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
} satisfies AuthPairingLink),
);
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
Effect.gen(function* () {
const revokedAt = yield* DateTime.now;
const revoked = yield* pairingLinks.revoke({
id,
revokedAt,
});
if (revoked) {
yield* emitRemoved(id);
}
return revoked;
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
Effect.gen(function* () {
const id = crypto.randomUUID();
const credential = generatePairingToken();
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
id,
credential,
...(input?.label ? { label: input.label } : {}),
expiresAt,
};
yield* pairingLinks.create({
id,
credential,
method: "one-time-token",
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
label: input?.label ?? null,
createdAt: now,
expiresAt: expiresAt,
});
yield* emitUpsert({
id,
credential,
role: input?.role ?? "client",
subject: input?.subject ?? "one-time-token",
...(input?.label ? { label: input.label } : {}),
createdAt: now,
expiresAt,
});
return issued;
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const seededResult: ConsumeResult = yield* Ref.modify(
seededGrantsRef,
(current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
const grant = current.get(credential);
if (!grant) {
return [
{
_tag: "error",
reason: "not-found",
error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
},
current,
];
}
const next = new Map(current);
if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
next.delete(credential);
return [
{
_tag: "error",
reason: "expired",
error: invalidBootstrapCredentialError("Bootstrap credential expired."),
},
next,
];
}
const remainingUses = grant.remainingUses;
if (typeof remainingUses === "number") {
if (remainingUses <= 1) {
next.delete(credential);
} else {
next.set(credential, {
...grant,
remainingUses: remainingUses - 1,
});
}
}
return [
{
_tag: "success",
grant: {
method: grant.method,
role: grant.role,
subject: grant.subject,
...(grant.label ? { label: grant.label } : {}),
expiresAt: grant.expiresAt,
} satisfies BootstrapGrant,
},
next,
];
},
);
if (seededResult._tag === "success") {
return seededResult.grant;
}
if (seededResult.reason !== "not-found") {
return yield* seededResult.error;
}
const consumed = yield* pairingLinks.consumeAvailable({
credential,
consumedAt: now,
now,
});
if (Option.isSome(consumed)) {
yield* emitRemoved(consumed.value.id);
return {
method: consumed.value.method,
role: consumed.value.role,
subject: consumed.value.subject,
...(consumed.value.label ? { label: consumed.value.label } : {}),
expiresAt: consumed.value.expiresAt,
} satisfies BootstrapGrant;
}
const matching = yield* pairingLinks.getByCredential({ credential });
if (Option.isNone(matching)) {
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
}
if (matching.value.revokedAt !== null) {
return yield* invalidBootstrapCredentialError(
"Bootstrap credential is no longer available.",
);
}
if (matching.value.consumedAt !== null) {
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
}
if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
}
return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
}).pipe(
Effect.mapError((cause) =>
cause instanceof BootstrapCredentialError
? cause
: internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
),
);
return {
issueOneTimeToken,
listActive,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
revoke,
consume,
} satisfies BootstrapCredentialServiceShape;
});
export const BootstrapCredentialServiceLive = Layer.effect(
BootstrapCredentialService,
makeBootstrapCredentialService,
).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
Loaded 100 of 638 files, more files were not shown because too many files have changed in this diff. Show more