The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Make local development and checks dist-free. (#20)
debajyoti-truefoundry2291f4f37fa5
diff --git a/AGENTS.md b/AGENTS.mdindex 0cb196826..3ffbcac04 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,4 +1,6 @@- Workspace tasks MUST use `package.json` scripts; add a script when a missing workflow is repeatable like the existing commands, not ad hoc commands.+- Release wiring MUST keep dist-free host development, `pnpm smoke`, and packed CJS/ESM consumers working without changes in `tfy-llm-gateway`.+- Shared Postgres/Redis settings in `docker-compose.yml` and `docker-compose.dev.yml` (image versions, health checks, `env_file`) MUST stay synchronized; intentional differences (app services, data paths, project `name`, host ports, in-network `POSTGRES_HOST` / `REDIS_URL`) MUST stay explicit. `packages/server/.env` is the host-dev + secrets source; `docker-compose.yml` may read it but MUST override container connectivity so host-dev localhost values are not used inside the smoke-test stack.- Changes to types or schemas MUST keep `packages/harness`, `packages/frontend`, `packages/server`, and `patches` synchronized; they MUST NOT update only one affected layer.- TypeScript code MUST NOT use assertion escapes such as `as T`, `as unknown as T`, non-null `!`, or `as never` to silence type errors; implementations MUST use sound contracts, guards, or corrected types.- When catching an error and throwing another, the new error MUST set `{ cause: caught }` so the original failure is preserved for logs and debugging.diff --git a/Dockerfile b/Dockerfileindex 2ba0a69be..c8c501843 100644--- a/Dockerfile+++ b/Dockerfile@@ -15,10 +15,16 @@ ENV PATH="$PNPM_HOME:$PATH"RUN corepack enable && pnpm config set store-dir /pnpm/storeWORKDIR /app+# Native dependencies (for example better-sqlite3) compile in build stages.+FROM base AS build-base+RUN apt-get update \+ && apt-get install -y --no-install-recommends g++ make python3 \+ && rm -rf /var/lib/apt/lists/*+# ---------------------------------------------------------------------------# store: the pnpm store, from the lockfile only (stable when manifests churn).# ----------------------------------------------------------------------------FROM base AS store+FROM build-base AS storeCOPY pnpm-lock.yaml pnpm-workspace.yaml ./COPY patches patchesRUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm fetchdiff --git a/README.md b/README.mdindex ce56b021c..bd52f828f 100644--- a/README.md+++ b/README.md@@ -8,52 +8,61 @@ pnpm workspace with:| `@truefoundry/server` | [`packages/server`](packages/server) | HTTP server + UI host (private; depends on utils) || `frontend` | [`packages/frontend`](packages/frontend) | Private draft-only agent chat UI (not published) |-## Develop+## Development++The API and frontend run on the host with hot reload. Postgres and Redis run in Docker.++### One-time setup```bashpnpm install-pnpm build-pnpm test-pnpm typecheck+cp packages/server/.env.example packages/server/.env+cp -R packages/server/registry-example packages/server/registry```-Root `build` / `typecheck` (and CI) include utils, server, and frontend.+Fill in `MODEL_API_KEY` in `packages/server/.env`. The copied defaults already connect the host server to the Compose services.-## Run the server+### Day-to-day-Create the local environment and registry files from the tracked examples:+Terminal 1:```bash-cp packages/server/.env.example packages/server/.env-cp -R packages/server/registry-example packages/server/registry+pnpm dev:infra # Postgres + Redis (data in ./data/dev/postgres); Ctrl+C stops them```-Fill in `MODEL_API_KEY` in `packages/server/.env`, then start both dev servers:+Terminal 2:```bash-pnpm dev # API on :8790 and Vite on :3000, one terminal+pnpm dev # API on :8790 and Vite on :3000```-| Script | Runs |-| -------------------- | ------------------------------------------------------ |-| `pnpm dev` | Both of the below, in parallel |-| `pnpm dev:server` | API only on `:8790`; never rebuilds the UI |-| `pnpm dev:frontend` | Vite only on `:3000`, proxying `/api/*` to the API |-| `pnpm dev:server:ui` | Rebuilds the UI, then the API serves it too on `:8790` |+Open `http://localhost:3000`. Frontend changes update through Vite HMR; server changes automatically restart the API on `:8790`. Vite proxies `/api/*` to the API. Local server scripts resolve `@truefoundry/utils` from source (`exports.development`), so a utils `dist/` build is not required for `pnpm dev`. For drain testing without server hot reload, use `pnpm dev:no-watch` instead of `pnpm dev`.-Open `:3000` for UI work. `:8790` serves the UI only when a build exists in `packages/frontend/dist`.+The workspace utils package is ESM so the host server and source schemas share one ESM dependency graph. `NODE_OPTIONS=--conditions=development` selects `src/` at runtime, and TypeScript uses the same condition for source-based static analysis. Development, lint, typecheck, tests, OpenAPI generation, and migrations do not read or recreate `packages/harness/dist`; release builds, package checks, and Docker smoke tests create it intentionally.-Migrations run automatically on startup. To migrate without starting HTTP:+| Script | Runs |+| ------------------- | ---------------------------------------------------------------------------------- |+| `pnpm dev:infra` | Postgres + Redis in the foreground |+| `pnpm dev` | Server (`tsx watch`) + Vite |+| `pnpm dev:no-watch` | Same, but API without hot reload (`NODE_ENV=production`) so Ctrl+C exercises drain |+| `pnpm clean` | Workspace build outputs and the ESLint cache |+| `pnpm clean:all` | The same outputs plus all workspace `node_modules` directories |++Migrations run automatically on server startup. To migrate without starting HTTP:```bashpnpm --filter @truefoundry/server migrate```-## Work on the UI (local)+Workspace checks:-Vite serves the UI from source with hot reload and proxies `/api/*` to `:8790`, so UI edits need no-rebuild or server restart. `FRONTEND_PORT` moves it off `:3000`, `VITE_SERVER_URL` points it at another-API. See [`packages/frontend/README.md`](packages/frontend/README.md).+```bash+pnpm build+pnpm test+pnpm typecheck+```++Root `build` / `typecheck` (and CI) include utils, server, and frontend. `FRONTEND_PORT` moves Vite off `:3000`, `VITE_SERVER_URL` points it at another API. See [`packages/frontend/README.md`](packages/frontend/README.md).## Serving the UI from the server@@ -62,17 +71,18 @@ Deployments are one process on one origin: `/api/*` (including `/api/v1/docs` an`../frontend/dist`; the image sets an absolute path). It is not required: with no build there the serverlogs a warning and serves the API only, which is what running the server behind Vite needs.-## Docker Compose+## Docker Compose smoke test++Full stack in containers — built server image serves API + UI (no Vite HMR):```bash-docker compose up --build+pnpm smoke # build, wait for healthy services, then check /healthz and the UI app shell+pnpm smoke:down # stop the stack```-One image serves both the UI and the API. Compose starts Postgres 17 (data in `./data/postgres`) and-Redis, and the server waits for both to be healthy, runs migrations, then listens on-`http://localhost:8790`.+Open `http://localhost:8791`. Secrets and Postgres credentials come from `packages/server/.env` (`MODEL_API_KEY`, etc.). Host ports and in-network DB/Redis targets are fixed in Compose so they do not collide with development: Postgres `:5433`, Redis `:6380`, app `:8791` (vs `pnpm dev:infra` on `:5432`/`:6379` and `pnpm dev` on `:8790`/`:3000`).-The local `.env` file, `packages/server/registry/`, and `data/` are ignored by Git. Docker Compose requires `packages/server/.env` and mounts the registry read-only into the server container.+Requires `packages/server/.env` and a `packages/server/registry/` directory (mounted read-only). `.env`, `registry/`, and `data/` are gitignored. Development infra stores Postgres under `./data/dev/postgres`.## SDK generation@@ -99,4 +109,6 @@ Or namespaced:import { core, agentSession } from '@truefoundry/utils';```+Workspace-only `development` exports are removed from the published package. Its staged `dist/package.json` remains CommonJS so `require()` uses `.js`, while ESM consumers use `.mjs`. This preserves existing consumers such as `tfy-llm-gateway`; they do not need source changes. Consumer compatibility is checked against a packed artifact, including root, barrel, deep skill imports, and both CJS and ESM loading.+Server-only deps (`hono`, `@hono/node-server`, `@hono/swagger-ui`, `yaml`) live in `packages/server` and never reach library consumers.diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlnew file mode 100644index 000000000..c56c6a534--- /dev/null+++ b/docker-compose.dev.yml@@ -0,0 +1,33 @@+# Host-backed development infra. Project name keeps containers separate from+# docker-compose.yml. Host ports match packages/server/.env defaults.+name: harness-dev++services:+ postgres:+ image: postgres:17+ env_file:+ - path: packages/server/.env+ required: true+ ports:+ - '5432:5432'+ volumes:+ - ./data/dev/postgres:/var/lib/postgresql/data+ healthcheck:+ test: ['CMD-SHELL', 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"']+ interval: 5s+ timeout: 5s+ retries: 10+ restart: unless-stopped++ # Shared by all server replicas: carries executor peering (cross-replica+ # turn cancel via request-reply).+ redis:+ image: redis:7-alpine+ ports:+ - '6379:6379'+ healthcheck:+ test: ['CMD', 'redis-cli', 'ping']+ interval: 5s+ timeout: 3s+ retries: 5+ restart: unless-stoppeddiff --git a/docker-compose.yml b/docker-compose.ymlindex 55fd9c679..2c2e6b6f1 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -1,11 +1,17 @@+# Full-stack smoke test. Reads packages/server/.env for secrets (e.g.+# MODEL_API_KEY) and credentials; host ports and in-network DB/Redis targets+# are opinionated here so they do not collide with or inherit host-dev values.+name: harness+services:postgres:image: postgres:17env_file:- path: packages/server/.envrequired: true+ # Host 5433 avoids conflict with docker-compose.dev.yml on 5432.ports:- - '5432:5432'+ - '5433:5432'volumes:- ./data/postgres:/var/lib/postgresql/datahealthcheck:@@ -19,8 +25,9 @@ services:# turn cancel via request-reply).redis:image: redis:7-alpine+ # Host 6380 avoids conflict with docker-compose.dev.yml on 6379.ports:- - '${REDIS_PORT:-6379}:6379'+ - '6380:6379'healthcheck:test: ['CMD', 'redis-cli', 'ping']interval: 5s@@ -34,15 +41,19 @@ services:context: .image: truefoundry-server:latestports:- - '${PORT:-8790}:8790'+ # Host 8791 avoids conflict with host `pnpm dev` on 8790.+ - '8791:8790'environment:- # PORT the server listens on inside the container (defaults to 8790).+ # Wins over env_file / image defaults so a host .env cannot flip this.+ NODE_ENV: production+ # Inside the container; host mapping above is 8791.PORT: 8790- # Compose network hostname; credentials still come from env_file.+ # Compose network hosts — do not use packages/server/.env localhost values.POSTGRES_HOST: postgres+ POSTGRES_PORT: 5432REDIS_URL: redis://redis:6379- # Environment variables (MODEL_API_KEY, POSTGRES_*, etc.) are read from this file.- # Copy packages/server/.env.example to packages/server/.env and fill it in.+ # Secrets and Postgres credentials (MODEL_API_KEY, POSTGRES_USER, …).+ # `environment` above overrides any colliding keys from this file.env_file:- path: packages/server/.envrequired: truediff --git a/package.json b/package.jsonindex 8f8974886..d4d16e898 100644--- a/package.json+++ b/package.json@@ -4,7 +4,9 @@"packageManager": "[email protected]+sha512.b767e9a98fc87aec0f42daefcd0e84941c2cdb45d73c4e1e68860fb2bdfdbe032ab592105479e5e05c237f740c8a5ffdbbb52385797ddc2296745a1bbb883e8d","scripts": {"build": "pnpm --filter @truefoundry/utils build && pnpm --filter @truefoundry/server build && pnpm --filter frontend build",- "typecheck": "pnpm --filter @truefoundry/utils typecheck && pnpm --filter @truefoundry/utils build && pnpm --filter @truefoundry/server typecheck && pnpm --filter frontend typecheck",+ "clean": "node scripts/clean.mjs",+ "clean:all": "node scripts/clean.mjs --dependencies",+ "typecheck": "pnpm --filter @truefoundry/utils typecheck && pnpm --filter @truefoundry/server typecheck && pnpm --filter frontend typecheck","lint": "eslint . --fix --cache --cache-location .eslintcache","lint:ci": "eslint . --cache --cache-location .eslintcache","format": "prettier --write . --cache --config .prettierrc",@@ -13,9 +15,13 @@"test": "pnpm --filter @truefoundry/utils test && pnpm --filter @truefoundry/server test && pnpm --filter frontend test","test:store:local": "bash scripts/test-store-local.sh","dev": "pnpm --parallel --filter @truefoundry/server --filter frontend dev",+ "dev:no-watch": "pnpm --parallel --filter @truefoundry/server --filter frontend dev:no-watch",+ "dev:infra": "docker compose -f docker-compose.dev.yml up","dev:server": "pnpm --filter @truefoundry/server dev","dev:frontend": "pnpm --filter frontend dev","dev:server:ui": "pnpm --filter frontend build && pnpm dev:server",+ "smoke": "docker compose up --build --wait && node -e \"Promise.all([fetch('http://127.0.0.1:8791/healthz'), fetch('http://127.0.0.1:8791/')]).then(async ([health, ui]) => { if (!health.ok) throw new Error('healthz returned ' + health.status); const html = await ui.text(); if (!ui.ok || !html.includes('id=\\\"root\\\"')) throw new Error('UI did not return its app shell'); console.log('healthz and UI OK'); })\"",+ "smoke:down": "docker compose down","openapi:write": "pnpm --filter @truefoundry/server openapi:write","ui:shot": "node ui-shots/shot.mjs","ui:clean": "node ui-shots/clean.mjs",diff --git a/packages/frontend/README.md b/packages/frontend/README.mdindex 72bf1a3fb..1060d3d92 100644--- a/packages/frontend/README.md+++ b/packages/frontend/README.md@@ -15,8 +15,11 @@ No login (`auth: false`). Skills are not wired in v1.## Local development+For the full host workflow (Compose Postgres/Redis, then API + Vite), see the root+[`README.md`](../../README.md#development).+```bash-pnpm dev # API on :8790 and Vite on :3000 together+pnpm dev # API on :8790 and Vite on :3000 together (after `pnpm dev:infra`)pnpm dev:frontend # or Vite alone, against an API that is already up```@@ -46,7 +49,7 @@ The Monaco workers land outside Vite's asset pipeline and cannot be precompressethose on the fly.```bash-docker compose up --build # UI + API on http://localhost:8790+docker compose up --build # UI + API on http://localhost:8791```## Catalogs (model + MCP)diff --git a/packages/frontend/package.json b/packages/frontend/package.jsonindex 740726fc8..7b5648c2b 100644--- a/packages/frontend/package.json+++ b/packages/frontend/package.json@@ -7,7 +7,8 @@"private": true,"type": "module","scripts": {- "dev": "vite",+ "dev": "trap 'exit 0' INT TERM; vite",+ "dev:no-watch": "pnpm run dev","build": "tsc --noEmit && vite build","preview": "vite preview","typecheck": "tsc --noEmit",diff --git a/packages/harness/AGENTS.md b/packages/harness/AGENTS.mdindex 56c303fe5..ba0cd3fc0 100644--- a/packages/harness/AGENTS.md+++ b/packages/harness/AGENTS.md@@ -1,2 +1,3 @@+- Workspace source MUST remain ESM so `exports.development` can load `src/` without a build. Published `dist/package.json` MUST remain CommonJS and omit development conditions while exposing CJS `.js` and ESM `.mjs` outputs.- Top-level public package surfaces (`core`, `agent-session`, and other exported entrypoints) MAY use optional (`?`) properties for caller ergonomics.- Within this package, records, snapshots, store INPUT types, and other internal contracts MUST NOT use `?`. Absence MUST be an explicit required `| null` or `| undefined` field; prefer `null` for domain absence and `undefined` only when update/patch semantics must distinguish “not provided” from “clear.” Public surfaces adapt by supplying those explicit absences when calling inward. This forces internal object literals to be exhaustive under `tsc`, preventing forgotten fields and silent data loss.diff --git a/packages/harness/package.json b/packages/harness/package.jsonindex 7cb0c52b3..93e87488e 100644--- a/packages/harness/package.json+++ b/packages/harness/package.json@@ -5,27 +5,43 @@"author": "Truefoundry","license": "UNLICENSED","private": false,- "type": "commonjs",+ "type": "module","main": "./dist/index.js","module": "./dist/index.mjs","types": "./dist/index.d.ts","exports": {".": {+ "development": {+ "types": "./src/index.ts",+ "default": "./src/index.ts"+ },"types": "./dist/index.d.ts","require": "./dist/index.js","default": "./dist/index.mjs"},"./core": {+ "development": {+ "types": "./src/core/index.ts",+ "default": "./src/core/index.ts"+ },"types": "./dist/core/index.d.ts","require": "./dist/core/index.js","default": "./dist/core/index.mjs"},"./agent-session": {+ "development": {+ "types": "./src/agent-session/index.ts",+ "default": "./src/agent-session/index.ts"+ },"types": "./dist/agent-session/index.d.ts","require": "./dist/agent-session/index.js","default": "./dist/agent-session/index.mjs"},"./request-reply": {+ "development": {+ "types": "./src/request-reply/index.ts",+ "default": "./src/request-reply/index.ts"+ },"types": "./dist/request-reply/index.d.ts","require": "./dist/request-reply/index.js","default": "./dist/request-reply/index.mjs"@@ -39,6 +55,10 @@"default": "./dist/*.js"},"./*": {+ "development": {+ "types": "./src/*.ts",+ "default": "./src/*.ts"+ },"types": "./dist/*.d.ts","require": "./dist/*.js","default": "./dist/*.mjs"diff --git a/packages/harness/scripts/check-dist.mjs b/packages/harness/scripts/check-dist.mjsindex e3282c5ee..fc6ef3d98 100644--- a/packages/harness/scripts/check-dist.mjs+++ b/packages/harness/scripts/check-dist.mjs@@ -41,10 +41,18 @@ if (!fs.existsSync(distPkgPath)) {} else {const distPkg = JSON.parse(fs.readFileSync(distPkgPath, 'utf-8'));const staged = JSON.stringify(distPkg);+ if (distPkg.type !== 'commonjs') {+ failures += 1;+ console.error('FAIL dist/package.json type must be "commonjs"');+ }if (staged.includes('./dist/')) {failures += 1;console.error('FAIL dist/package.json still references ./dist/ paths');}+ if (staged.includes('./src/') || staged.includes('"development"')) {+ failures += 1;+ console.error('FAIL dist/package.json must not ship development → src/ export conditions');+ }}if (failures > 0) {diff --git a/packages/harness/scripts/make-dist-package-json.mjs b/packages/harness/scripts/make-dist-package-json.mjsindex 591f10abf..95da6b129 100644--- a/packages/harness/scripts/make-dist-package-json.mjs+++ b/packages/harness/scripts/make-dist-package-json.mjs@@ -18,12 +18,29 @@ function stripDistPrefix(value) {return value;}+// Workspace-only: local `tsx` uses exports.development → src/. Published+// packages must not ship those conditions (src/ is not in the tarball).+function omitDevelopmentConditions(value) {+ if (Array.isArray(value)) {+ return value.map(omitDevelopmentConditions);+ }+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value)+ .filter(([key]) => key !== 'development')+ .map(([key, entry]) => [key, omitDevelopmentConditions(entry)]),+ );+ }+ return value;+}+const distPkg = {...pkg,+ type: 'commonjs',main: stripDistPrefix(pkg.main),module: stripDistPrefix(pkg.module),types: stripDistPrefix(pkg.types),- exports: stripDistPrefix(pkg.exports),+ exports: omitDevelopmentConditions(stripDistPrefix(pkg.exports)),files: ['**/*'],};delete distPkg.scripts;diff --git a/packages/harness/src/core/mcp/LocalToolMCP.ts b/packages/harness/src/core/mcp/LocalToolMCP.tsindex cb7afe5fd..2bc216413 100644--- a/packages/harness/src/core/mcp/LocalToolMCP.ts+++ b/packages/harness/src/core/mcp/LocalToolMCP.ts@@ -1,6 +1,6 @@import type { CallToolRequest, ListToolsResult } from '@modelcontextprotocol/sdk/types.js';import { type AnyZodObject, z } from 'zod';-import zodToJsonSchema from 'zod-to-json-schema';+import { zodToJsonSchema } from 'zod-to-json-schema';import type { ApprovalDecision } from '../events/schema';import type { InternalToolCallInfo } from '../llm/LLMTypes';import type { AgentTracing } from '../tracing/AgentTracing';diff --git a/packages/harness/tsup.config.ts b/packages/harness/tsup.config.tsindex 7bae0eac5..da5c9d611 100644--- a/packages/harness/tsup.config.ts+++ b/packages/harness/tsup.config.ts@@ -10,6 +10,9 @@ export default defineConfig({// bundle mode, but with every file as an entry nothing actually inlines.bundle: true,esbuildPlugins: [esbuildPluginFilePathExtensions({ esmExtension: 'mjs', cjsExtension: 'js' })],+ outExtension({ format }) {+ return { js: format === 'cjs' ? '.js' : '.mjs' };+ },dts: false,splitting: false,// TODO(oss): revisit sourcemaps at the public release — with sourcesContentdiff --git a/packages/server/.env.example b/packages/server/.env.exampleindex e5ffafd42..650b4e5a9 100644--- a/packages/server/.env.example+++ b/packages/server/.env.example@@ -21,7 +21,8 @@ PORT=8790# Required. Redis connection URL shared by all server replicas; carries# executor peering so a cancel that lands on one replica reaches the replica-# running the turn. docker-compose provides this automatically.+# running the turn. Use localhost for host `pnpm dev`; `docker-compose.yml`+# overrides this to redis://redis:6379 for the server container.REDIS_URL=redis://localhost:6379# Required. Default API key for the OpenAI-compatible API at models.yaml's@@ -75,9 +76,9 @@ MODEL_API_KEY=<your-api-key># SANDBOX_PREVIEW_URL_EXPIRY_SECONDS=3600# ----------------------------------------------------------------------------# Postgres (required). Used by the server pool and by the Compose postgres-# service (via env_file). Compose overrides POSTGRES_HOST=postgres for the-# server container; keep localhost here for host-side tools.+# Postgres (required). Used by the server pool and by Compose postgres+# services (via env_file). Keep localhost here for host `pnpm dev`;+# `docker-compose.yml` overrides POSTGRES_HOST/PORT for the server container.# ---------------------------------------------------------------------------POSTGRES_USER=harnessPOSTGRES_PASSWORD=harnessdiff --git a/packages/server/package.json b/packages/server/package.jsonindex e7f21b320..09b66b89d 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -8,14 +8,14 @@"type": "module","scripts": {"build": "tsc --noEmit && tsup",- "dev": "tsx --env-file=.env src/main.ts",- "migrate": "tsx --env-file=.env src/db/postgres/migrate-cli.ts",- "typecheck": "tsc --noEmit",- "openapi:write": "tsx --env-file=.env.test scripts/write-openapi.ts",- "test": "tsx --env-file=.env.test --test \"src/**/*.test.ts\"",+ "dev": "NODE_OPTIONS='--conditions=development' NODE_ENV=development tsx watch --env-file=.env src/main.ts",+ "dev:no-watch": "NODE_OPTIONS='--conditions=development' NODE_ENV=production tsx --env-file=.env src/main.ts",+ "migrate": "NODE_OPTIONS='--conditions=development' tsx --env-file=.env src/db/postgres/migrate-cli.ts",+ "typecheck": "tsc --noEmit && tsc --noEmit -p tests/tsconfig.json",+ "openapi:write": "NODE_OPTIONS='--conditions=development' tsx --env-file=.env.test scripts/write-openapi.ts",+ "test": "NODE_OPTIONS='--conditions=development' tsx --env-file=.env.test --test \"src/**/*.test.ts\"","test:store:postgres": "jest --config jest.store.postgres.config.cjs",- "test:store:sqlite": "jest --config jest.store.sqlite.config.cjs",- "start": "node dist/main.js"+ "test:store:sqlite": "jest --config jest.store.sqlite.config.cjs"},"dependencies": {"@hono/node-server": "^2.0.11",diff --git a/packages/server/src/main.ts b/packages/server/src/main.tsindex 15dca0928..97d46bd12 100644--- a/packages/server/src/main.ts+++ b/packages/server/src/main.ts@@ -117,55 +117,55 @@ try {process.exit(1);});- // Graceful drain: stop accepting new connections, cancel running turns as- // abandoned, wait for them to persist terminal state, then exit. Without- // this, Node (running as PID 1 in the container) ignores SIGTERM and docker- // stop escalates to SIGKILL after its grace period.- let shuttingDown = false;- const shutdown = async (signal: NodeJS.Signals) => {- if (shuttingDown) return;- shuttingDown = true;- logger.info(`Received ${signal}, draining connections before shutdown`);+ // Graceful drain is the safe default for built and direct execution.+ // Development watch mode opts out so tsx can restart without waiting for a drain.+ if (process.env['NODE_ENV'] !== 'development') {+ let shuttingDown = false;+ const shutdown = async (signal: NodeJS.Signals) => {+ if (shuttingDown) return;+ shuttingDown = true;+ logger.info(`Received ${signal}, draining connections before shutdown`);- // Arm at the start of each shutdown; unref so this timer alone cannot keep the process alive.- setTimeout(() => {- logger.warn(`Drain timed out after ${String(configuration.GRACEFUL_TIMEOUT_SECONDS)}s, exiting`);- process.exit(1);- }, configuration.GRACEFUL_TIMEOUT_SECONDS * 1000).unref();+ // Arm at the start of each shutdown; unref so this timer alone cannot keep the process alive.+ setTimeout(() => {+ logger.warn(`Drain timed out after ${String(configuration.GRACEFUL_TIMEOUT_SECONDS)}s, exiting`);+ process.exit(1);+ }, configuration.GRACEFUL_TIMEOUT_SECONDS * 1000).unref();- const closed = new Promise<void>(resolve => {- server.close(() => {- resolve();+ const closed = new Promise<void>(resolve => {+ server.close(() => {+ resolve();+ });});- });- // Sets the registry's shutdown reason immediately so late track() (in-flight create-turn still- // inside session.createTurn) aborts as Abandoned; then drains the registry. await- // closed covers the gap where the registry is empty before that late track().- await activeTurns.shutdownAndWait(CancellationReason.Abandoned);- await closed;- // Stop serving peer requests (waits for in-flight replies), then close- // the clients this process owns: the subscriber duplicate and the primary.- await requestReplyExecutor.drain();- await requestReplySubscriber.close().catch((error: unknown) => {- logger.warn('[Redis] Error closing subscriber client during shutdown', {- error: error instanceof Error ? error.message : String(error),+ // Sets the registry's shutdown reason immediately so late track() (in-flight create-turn still+ // inside session.createTurn) aborts as Abandoned; then drains the registry. await+ // closed covers the gap where the registry is empty before that late track().+ await activeTurns.shutdownAndWait(CancellationReason.Abandoned);+ await closed;+ // Stop serving peer requests (waits for in-flight replies), then close+ // the clients this process owns: the subscriber duplicate and the primary.+ await requestReplyExecutor.drain();+ await requestReplySubscriber.close().catch((error: unknown) => {+ logger.warn('[Redis] Error closing subscriber client during shutdown', {+ error: error instanceof Error ? error.message : String(error),+ });});- });- await redis.close().catch((error: unknown) => {- logger.warn('[Redis] Error closing client during shutdown', {- error: error instanceof Error ? error.message : String(error),+ await redis.close().catch((error: unknown) => {+ logger.warn('[Redis] Error closing client during shutdown', {+ error: error instanceof Error ? error.message : String(error),+ });});+ await db.destroy();+ process.exit(0);+ };+ process.on('SIGTERM', signal => {+ void shutdown(signal);});- await db.destroy();- process.exit(0);- };- process.on('SIGTERM', signal => {- void shutdown(signal);- });- process.on('SIGINT', signal => {- void shutdown(signal);- });+ process.on('SIGINT', signal => {+ void shutdown(signal);+ });+ }} catch (error) {console.error('Failed to start server:', error instanceof Error ? error.message : error);process.exit(1);diff --git a/packages/server/tests/tsconfig.json b/packages/server/tests/tsconfig.jsonnew file mode 100644index 000000000..a32dd4f23--- /dev/null+++ b/packages/server/tests/tsconfig.json@@ -0,0 +1,4 @@+{+ "extends": "../tsconfig.json",+ "include": ["**/*"]+}diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.jsonindex e3504fd99..4d723d148 100644--- a/packages/server/tsconfig.json+++ b/packages/server/tsconfig.json@@ -3,11 +3,12 @@"compilerOptions": {"types": ["node", "jest"],"noEmit": true,+ "customConditions": ["development"],"paths": {"openai/resources/chat": ["../harness/node_modules/openai/resources/chat/index.d.ts"]}},- "include": ["src/**/*", "tests/**/*", "scripts/**/*", "tsup.config.ts"],+ "include": ["src/**/*", "scripts/**/*", "tsup.config.ts"],// node:test files under src/ stay out of the Jest-typed project."exclude": ["node_modules", "dist", "src/**/*.test.ts"]}diff --git a/scripts/clean.mjs b/scripts/clean.mjsnew file mode 100644index 000000000..68449bdda--- /dev/null+++ b/scripts/clean.mjs@@ -0,0 +1,34 @@+import { readdir, rm } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const packagesDir = path.join(rootDir, 'packages');+const removeDependencies = process.argv.slice(2).includes('--dependencies');+const unknownArguments = process.argv.slice(2).filter(argument => argument !== '--dependencies');++if (unknownArguments.length > 0) {+ throw new Error(`Unknown clean arguments: ${unknownArguments.join(', ')}`);+}++const packageDirectories = (await readdir(packagesDir, { withFileTypes: true }))+ .filter(entry => entry.isDirectory())+ .map(entry => path.join(packagesDir, entry.name));++const targets = [+ path.join(rootDir, '.eslintcache'),+ ...packageDirectories.map(directory => path.join(directory, 'dist')),+];++if (removeDependencies) {+ targets.push(path.join(rootDir, 'node_modules'));+ targets.push(...packageDirectories.map(directory => path.join(directory, 'node_modules')));+}++await Promise.all(targets.map(target => rm(target, { recursive: true, force: true })));++console.log(+ removeDependencies+ ? 'Removed build outputs, ESLint cache, and node_modules'+ : 'Removed build outputs and ESLint cache',+);