The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Initial commit: extract agent harness into pnpm workspace.
Debajyoti Chatterjeee5d7f8392627
diff --git a/.gitignore b/.gitignorenew file mode 100644index 000000000..47ee49850--- /dev/null+++ b/.gitignore@@ -0,0 +1,11 @@+node_modules/+dist/+*.tgz+.DS_Store+*.log+.env+packages/server/src/config/.env+coverage/+.turbo/+*.tsbuildinfo+.pnpm-store/diff --git a/.npmrc b/.npmrcnew file mode 100644index 000000000..c8fd4e79a--- /dev/null+++ b/.npmrc@@ -0,0 +1 @@+confirm-modules-purge=falsediff --git a/README.md b/README.mdnew file mode 100644index 000000000..1fa461935--- /dev/null+++ b/README.md@@ -0,0 +1,32 @@+# TrueFoundry harness workspace++pnpm workspace with:++| Package | Path | Role |+| --- | --- | --- |+| `@truefoundry/utils` | [`packages/harness`](packages/harness) | Published library (`core` + `agentSession`) |+| `@truefoundry/server` | [`packages/server`](packages/server) | Future CLI/HTTP server (private; depends on utils) |++## Develop++```bash+pnpm install+pnpm build+pnpm test+pnpm typecheck+```++## Library imports++```ts+import { AgentThread } from '@truefoundry/utils/core';+import { Sessions } from '@truefoundry/utils/agent-session';+```++Or namespaced:++```ts+import { core, agentSession } from '@truefoundry/utils';+```++Server-only deps (`hono`, `@hono/node-server`, `@hono/swagger-ui`, `yaml`) live in `packages/server` and never reach library consumers.diff --git a/package.json b/package.jsonnew file mode 100644index 000000000..0c2fbb6f2--- /dev/null+++ b/package.json@@ -0,0 +1,12 @@+{+ "name": "@truefoundry/harness-workspace",+ "private": true,+ "packageManager": "[email protected]+sha512.b767e9a98fc87aec0f42daefcd0e84941c2cdb45d73c4e1e68860fb2bdfdbe032ab592105479e5e05c237f740c8a5ffdbbb52385797ddc2296745a1bbb883e8d",+ "scripts": {+ "build": "pnpm --filter @truefoundry/utils build && pnpm --filter @truefoundry/server build",+ "typecheck": "pnpm --filter @truefoundry/utils typecheck && pnpm --filter @truefoundry/utils build && pnpm --filter @truefoundry/server typecheck",+ "test": "pnpm --filter @truefoundry/utils test",+ "dev:server": "pnpm --filter @truefoundry/server dev",+ "pack:dry": "pnpm --filter @truefoundry/utils pack:dry"+ }+}diff --git a/packages/harness/.npmignore b/packages/harness/.npmignorenew file mode 100644index 000000000..c939b47fc--- /dev/null+++ b/packages/harness/.npmignore@@ -0,0 +1,5 @@+# Never ship docs to the npm registry page / tarball.+README*+readme*+*.md+**/*.mddiff --git a/packages/harness/jest.config.cjs b/packages/harness/jest.config.cjsnew file mode 100644index 000000000..2a9cf8b0c--- /dev/null+++ b/packages/harness/jest.config.cjs@@ -0,0 +1,26 @@+/** @type {import('jest').Config} */+module.exports = {+ testEnvironment: 'node',+ transform: {+ '^.+\\.tsx?$': [+ '@swc/jest',+ {+ jsc: {+ parser: { syntax: 'typescript', decorators: true },+ target: 'es2022',+ },+ module: { type: 'commonjs' },+ },+ ],+ },+ moduleNameMapper: {+ '^(\\.{1,2}/.*)\\.js$': '$1',+ },+ setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],+ testTimeout: 30000,+ maxWorkers: '50%',+ roots: ['<rootDir>/tests'],+ testMatch: ['**/tests/**/*.test.ts'],+ // Compile-time suites are enforced by `tsc --noEmit`, not the Jest runner.+ testPathIgnorePatterns: ['\\.compile\\.test\\.ts$'],+};diff --git a/packages/harness/package.json b/packages/harness/package.jsonnew file mode 100644index 000000000..4717bffd7--- /dev/null+++ b/packages/harness/package.json@@ -0,0 +1,64 @@+{+ "name": "@truefoundry/utils",+ "version": "0.1.0",+ "description": "TrueFoundry agent core and session library",+ "author": "Truefoundry",+ "license": "UNLICENSED",+ "private": false,+ "type": "module",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ },+ "./core": {+ "types": "./dist/core/index.d.ts",+ "import": "./dist/core/index.js"+ },+ "./agent-session": {+ "types": "./dist/agentSession/index.d.ts",+ "import": "./dist/agentSession/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "pnpm run build:js && pnpm run build:dts && pnpm run build:scripts",+ "build:js": "tsup",+ "build:dts": "tsc -p tsconfig.build.json --emitDeclarationOnly",+ "build:scripts": "mkdir -p dist/sandbox-scripts && cp src/core/sandbox/scripts/*.py dist/sandbox-scripts/",+ "typecheck": "tsc --noEmit",+ "test": "jest --config jest.config.cjs --forceExit",+ "pack:dry": "pnpm pack --dry-run",+ "prepack": "node -e \"const fs=require('node:fs'); for (const f of fs.readdirSync('.')) { if (/^readme(\\.(md|txt|markdown))?$/i.test(f)) { console.error('Refusing to pack: remove '+f+' so the npm page has no README'); process.exit(1); } }\""+ },+ "dependencies": {+ "@daytona/sdk": "^0.190.0",+ "@hono/zod-openapi": "^0.19.10",+ "@modelcontextprotocol/sdk": "^1.29.0",+ "@nats-io/nats-core": "3.0.2",+ "@opentelemetry/api": "^1.9.0",+ "@opentelemetry/core": "^2.9.0",+ "dedent": "^1.7.2",+ "openai": "^4.104.0",+ "ulid": "^3.0.2",+ "winston": "^3.13.0",+ "ws": "^8.21.0",+ "zod": "^3.24.3",+ "zod-to-json-schema": "^3.25.1"+ },+ "devDependencies": {+ "@swc/core": "^1.11.0",+ "@swc/jest": "^0.2.37",+ "@types/jest": "^29.5.14",+ "@types/node": "^24.12.0",+ "@types/ws": "^8.5.10",+ "jest": "^29.7.0",+ "tsup": "^8.5.0",+ "typescript": "^7.0.2"+ }+}diff --git a/packages/harness/src/agentSession/ITurnResourceResolver.ts b/packages/harness/src/agentSession/ITurnResourceResolver.tsnew file mode 100644index 000000000..20b14d1ba--- /dev/null+++ b/packages/harness/src/agentSession/ITurnResourceResolver.ts@@ -0,0 +1,62 @@+import type { Logger } from 'winston';+import type { AgentCapability } from '../core/capabilities/AgentCapability';+import type { AgentDefinition } from '../core/runtime/AgentDefinition';+import type { AgentInfo } from '../core/runtime/AgentThread.types';+import type { Sandbox, SandboxInfo } from '../core/sandbox/Sandbox';+import type { AgentTracing } from '../core/tracing/AgentTracing';+import type { TurnRecord } from './models/TurnRecord';+import type { AgentSpec } from './schemas/agentSpec';++/**+ * Per-run wiring contract consumed by SessionHandle.run(). Implementations hold+ * per-request state (secrets, providers, caches) freely.+ */+export interface ITurnResourceResolver<TTurnCustom extends object = Record<string, never>> {+ /** Forwarded to AgentThread / orchestrator / RemoteMCP. */+ readonly logger: Logger;+ /** Called exactly once per run, before any other method. */+ createTracing(): AgentTracing;+ /**+ * Called exactly once per run, before any thread is built; the harness holds+ * the result and shares the same reference across all threads. Return+ * undefined when the run needs no sandbox. `existing` carries the previous+ * turn's sandbox info for cross-turn reattach.+ */+ resolveSandbox(input: {+ spec: AgentSpec;+ existing?: SandboxInfo | undefined;+ previousTurn?: TurnRecord<TTurnCustom> | undefined;+ signal: AbortSignal;+ tracing: AgentTracing;+ }): Promise<Sandbox | undefined>;+ /**+ * Called once per thread_id; calls for different ids may overlap (parallel+ * sub-agent spawns), so implementations must be concurrency-safe across ids.+ * `agent_info` is set for sub-agent threads. `previousTurn` is read-only:+ * branch on it, but never load state into capabilities — return blank+ * instances; the AgentThread constructor is the sole hydration path.+ * `extraCapabilities` are appended after the built-in capabilities.+ */+ resolveAgentDefinition(input: {+ spec: AgentSpec;+ thread_id: string;+ agent_info?: AgentInfo | undefined;+ previousTurn?: TurnRecord<TTurnCustom> | undefined;+ signal: AbortSignal;+ tracing: AgentTracing;+ }): Promise<{+ definition: AgentDefinition;+ extraCapabilities?: AgentCapability[] | undefined;+ }>;+ /**+ * Release per-run resources. Called by the harness at the end of the run:+ * by TurnHandle.stream() in its finally (AFTER the terminal state write), or by+ * SessionHandle.run() when it throws before a TurnHandle exists — so resources acquired+ * during a failed run (e.g. a sandbox VM) are still released. Best-effort:+ * the harness logs and swallows errors — close() can never flip a terminal+ * state or fail the turn. Must be idempotent. The resolver owns cleanup+ * because it owns acquisition: the run flow calls this one method without+ * knowing what was resolved.+ */+ close(): Promise<void>;+}diff --git a/packages/harness/src/agentSession/README.md b/packages/harness/src/agentSession/README.mdnew file mode 100644index 000000000..2468b7b10--- /dev/null+++ b/packages/harness/src/agentSession/README.md@@ -0,0 +1,16 @@+# agentSession++Middle library: durable sessions/turns over `ISessionStore`, wired to the public harness for execution.++**Deps:** `agentSession → harness`. Never reverse.++## Scope++- Zod product contracts (`schemas/`) — no `sequence_number`, no SSE envelopes+- `Sessions` / `SessionHandle` / `TurnHandle` — storage + `run()` / `stream()`+- `ISessionStore` + `InMemorySessionStore` (reference impl)+- `ITurnResourceResolver` / `TurnResourceResolver` — per-run secrets/providers++## Not in v1++Private gateway adoption (handlers, Redis store, ActiveTurnRegistry, SSE fan-out, `/subscribe`) is **out of scope**. §4 of the design plan is a mapping sketch only — gradual adapt later; this package does not replace private gateway code.diff --git a/packages/harness/src/agentSession/SessionHandle.ts b/packages/harness/src/agentSession/SessionHandle.tsnew file mode 100644index 000000000..dafa7b359--- /dev/null+++ b/packages/harness/src/agentSession/SessionHandle.ts@@ -0,0 +1,412 @@+/**+ * Bound session handle: starts turns via {@link SessionHandle.run}.+ */+import { ulid } from 'ulid';+import type { AgentDefinition } from '../core/runtime/AgentDefinition';+import { AgentThread } from '../core/runtime/AgentThread';+import type { AgentThreadSendBatch, AgentThreadSnapshot } from '../core/runtime/AgentThread.types';+import { AgentThreadOrchestrator } from '../core/runtime/AgentThreadOrchestrator';+import {+ isApprovalDecisionMessage,+ isClientSideToolResponseMessage,+ isInputUserMessage,+} from '../core/runtime/contextUtils';+import type { CreateDynamicSubAgentThread } from '../core/runtime/CreateDynamicSubAgentThread';+import type { Sandbox } from '../core/sandbox/Sandbox';+import type { AgentTracing } from '../core/tracing/AgentTracing';+import { builtinsFromSpec } from './builtinsFromSpec';+import type { ITurnResourceResolver } from './ITurnResourceResolver';+import type { SessionRecord } from './models/SessionRecord';+import { MAIN_THREAD_ID, TURN_SERIALIZATION_VERSION, type TurnRecord } from './models/TurnRecord';+import type { TurnCreatedEvent, TurnDoneEvent, TurnEvent } from './schemas/events';+import type { TokenPagination } from './schemas/pagination';+import type { TurnInputItem } from './schemas/turn';+import type { ISessionStore } from './store/ISessionStore';+import { TurnHandle } from './TurnHandle';++function resolvePreviousTurnId(+ requested: 'auto' | string | null | undefined,+ lastTurnId: string | undefined,+): string | undefined {+ if (requested === null) {+ return undefined;+ }+ if (requested === undefined || requested === 'auto') {+ return lastTurnId;+ }+ return requested;+}++function toSendBatch(input: TurnInputItem[] | undefined): AgentThreadSendBatch {+ if (!input || input.length === 0) {+ return [];+ }+ if (input.every(msg => isApprovalDecisionMessage(msg) || isClientSideToolResponseMessage(msg))) {+ return input;+ }+ if (input.every(isInputUserMessage)) {+ return input;+ }+ throw new Error('input must be homogeneous: all user messages, or all approval/tool-response messages');+}++function threadsRecordFromMap(threads: Map<string, AgentThread>): Record<string, AgentThreadSnapshot> {+ const out: Record<string, AgentThreadSnapshot> = {};+ for (const [id, thread] of threads) {+ out[id] = thread.toSnapshot();+ }+ return out;+}++export class SessionHandle<+ TSessionCustom extends object = Record<string, never>,+ TTurnCustom extends object = Record<string, never>,+> {+ private readonly store: ISessionStore<TSessionCustom, TTurnCustom>;+ private readonly tenantName: string;+ private session: SessionRecord<TSessionCustom>;++ constructor(options: {+ store: ISessionStore<TSessionCustom, TTurnCustom>;+ tenantName: string;+ session: SessionRecord<TSessionCustom>;+ }) {+ this.store = options.store;+ this.tenantName = options.tenantName;+ this.session = options.session;+ }++ get session_id(): string {+ return this.session.session_id;+ }++ get tenant_name(): string {+ return this.tenantName;+ }++ get agent_spec() {+ return this.session.agent_spec;+ }++ get custom(): TSessionCustom | undefined {+ return this.session.custom;+ }++ get record(): SessionRecord<TSessionCustom> {+ return this.session;+ }++ /**+ * Prepares and commits a new turn — NO execution happens here (execution =+ * TurnHandle.stream()). Builds threads from the previous turn's snapshot, then+ * sends the input through the orchestrator fully drained (validation ++ * context append; empty input still preflights threads awaiting user input),+ * then persists via one atomic store.createTurn LAST. A send/validation+ * failure therefore persists nothing. The returned turn is durable with+ * state { status: 'running' }.+ *+ * On any failure, run() closes the resolver (best-effort) before rethrowing,+ * so resources acquired here (e.g. a sandbox VM) never outlive a failed run.+ * On success, ownership of resolver.close() passes to TurnHandle.stream().+ *+ * `previous_turn_id`: omitted/`'auto'` → session tip; `null` → new root+ * (no parent, even on a non-empty session); string → fork from that turn+ * (must exist). Concurrent `'auto'` forks both succeed.+ */+ async run(input: {+ input?: TurnInputItem[] | undefined;+ /** 'auto'/omitted → session.last_turn_id; null → new root; id → fork from that turn. */+ previous_turn_id?: 'auto' | string | null | undefined;+ signal: AbortSignal;+ resolver: ITurnResourceResolver<TTurnCustom>;+ /** Value = stored as-is. Fn = merge over previous turn's custom. Omitted = undefined. */+ custom?: TTurnCustom | ((previous?: TTurnCustom) => TTurnCustom) | undefined;+ /**+ * Forwarded to store.createTurn: sets session.title in the same atomic+ * unit IF the session has none; never overwrites. The caller derives the+ * value (e.g. from the first user message) — the library does not.+ */+ update_session_title_if_not_exist?: string | undefined;+ }): Promise<TurnHandle<TTurnCustom>> {+ const previousTurnId = resolvePreviousTurnId(input.previous_turn_id, this.session.last_turn_id);+ const previous = previousTurnId+ ? await this.store.getTurn({+ tenant_name: this.tenantName,+ session_id: this.session.session_id,+ turn_id: previousTurnId,+ })+ : undefined;++ const custom = typeof input.custom === 'function' ? input.custom(previous?.custom) : input.custom;++ const spec = this.session.agent_spec;+ // Dispose-on-early-failure: any resource acquired below (sandbox handle,+ // MCP connections) is owned by run() until the TurnHandle is returned; from then+ // on TurnHandle.stream()'s finally owns resolver.close(). On any throw in this+ // acquisition phase we close the resolver (best-effort, error swallowed)+ // and rethrow — same pattern as the gateway's sessionTurnHandler, which+ // wraps getAgent/handler.init and calls gatewayStore.dispose() on failure.+ try {+ const tracing = input.resolver.createTracing();+ const sandbox = await input.resolver.resolveSandbox({+ spec,+ existing: previous?.snapshot.sandbox_info,+ previousTurn: previous,+ signal: input.signal,+ tracing,+ });++ const agentThreads = await this.buildThreads({+ previous,+ resolver: input.resolver,+ sandbox,+ tracing,+ signal: input.signal,+ });++ const createDynamicSubAgentThread = this.makeCreateDynamicSubAgentThread({+ resolver: input.resolver,+ previous,+ sandbox,+ tracing,+ });++ const orchestrator = new AgentThreadOrchestrator({+ agentThreads,+ createDynamicSubAgentThread,+ tracing,+ logger: input.resolver.logger,+ });++ // SEND BEFORE COMMIT — validate + append; throw ⇒ nothing persisted.+ const sendBatch = toSendBatch(input.input);+ for await (const _ of orchestrator.send(sendBatch)) {+ // drain only+ }++ const turnId = ulid().toLowerCase();+ const now = new Date().toISOString();+ const turnRecord: TurnRecord<TTurnCustom> = {+ serialization_version: TURN_SERIALIZATION_VERSION,+ turn_id: turnId,+ session_id: this.session.session_id,+ first_turn_id: previous?.first_turn_id ?? turnId,+ ancestor_ids: previous ? [...previous.ancestor_ids, previous.turn_id] : [],+ ...(previousTurnId !== undefined ? { previous_turn_id: previousTurnId } : {}),+ state: { status: 'running' },+ input: input.input ?? [],+ snapshot: {+ threads: threadsRecordFromMap(agentThreads),+ ...(previous?.snapshot.mcp_servers !== undefined ? { mcp_servers: previous.snapshot.mcp_servers } : {}),+ ...(previous?.snapshot.sandbox_info !== undefined ? { sandbox_info: previous.snapshot.sandbox_info } : {}),+ },+ created_at: now,+ updated_at: now,+ ...(custom !== undefined ? { custom } : {}),+ };++ await this.store.createTurn({+ tenant_name: this.tenantName,+ turn: turnRecord,+ update_session_title_if_not_exist: input.update_session_title_if_not_exist,+ });++ const refreshed = await this.store.getSession({+ tenant_name: this.tenantName,+ session_id: this.session.session_id,+ });+ if (refreshed) {+ this.session = refreshed;+ }++ return new TurnHandle({+ store: this.store,+ tenantName: this.tenantName,+ turn: turnRecord,+ orchestrator,+ resolver: input.resolver,+ signal: input.signal,+ });+ } catch (error) {+ await input.resolver.close().catch(closeError => {+ input.resolver.logger.warn('TurnResourceResolver.close() failed after run() error', {+ err: closeError,+ });+ });+ throw error;+ }+ }++ /** Returns the turn handle (store-backed; not executable), or undefined if not found. */+ async getTurn(turn_id: string): Promise<TurnHandle<TTurnCustom> | undefined> {+ const turn = await this.store.getTurn({+ tenant_name: this.tenantName,+ session_id: this.session.session_id,+ turn_id,+ });+ if (!turn) {+ return undefined;+ }+ return TurnHandle.fromRecord({+ store: this.store,+ tenantName: this.tenantName,+ turn,+ });+ }++ /** Paginated list of this session's turn records. */+ async listTurns(input: {+ limit: number;+ page_token?: string | undefined;+ }): Promise<{ data: TurnRecord<TTurnCustom>[]; pagination: TokenPagination }> {+ return this.store.listTurns({+ tenant_name: this.tenantName,+ session_id: this.session.session_id,+ limit: input.limit,+ page_token: input.page_token,+ });+ }++ /**+ * Paginated session-wide feed of persisted events across turns, including+ * turn.created / turn.done lifecycle events. Reads from the store only —+ * nothing is synthesized on read.+ */+ async listEvents(input: { limit: number; page_token?: string; last_turn_id?: string }): Promise<{+ data: Array<{ turn_id: string; event: TurnCreatedEvent | TurnDoneEvent | TurnEvent }>;+ pagination: TokenPagination;+ }> {+ return this.store.listSessionEvents({+ tenant_name: this.tenantName,+ session_id: this.session.session_id,+ limit: input.limit,+ page_token: input.page_token,+ last_turn_id: input.last_turn_id,+ });+ }++ private async buildThreads(input: {+ previous: TurnRecord<TTurnCustom> | undefined;+ resolver: ITurnResourceResolver<TTurnCustom>;+ sandbox: Sandbox | undefined;+ tracing: AgentTracing;+ signal: AbortSignal;+ }): Promise<Map<string, AgentThread>> {+ const snapshots = input.previous?.snapshot.threads;+ const threadIds = snapshots ? Object.keys(snapshots) : [MAIN_THREAD_ID];+ const map = new Map<string, AgentThread>();+ for (const threadId of threadIds) {+ const data = snapshots?.[threadId];+ map.set(+ threadId,+ await this.buildThread({+ threadId,+ data,+ resolver: input.resolver,+ previous: input.previous,+ sandbox: input.sandbox,+ tracing: input.tracing,+ signal: input.signal,+ }),+ );+ }+ return map;+ }++ private async buildThread(input: {+ threadId: string;+ data?: AgentThreadSnapshot | undefined;+ resolver: ITurnResourceResolver<TTurnCustom>;+ previous: TurnRecord<TTurnCustom> | undefined;+ sandbox: Sandbox | undefined;+ tracing: AgentTracing;+ signal: AbortSignal;+ }): Promise<AgentThread> {+ const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({+ spec: this.session.agent_spec,+ thread_id: input.threadId,+ agent_info: input.data?.agent_info,+ previousTurn: input.previous,+ signal: input.signal,+ tracing: input.tracing,+ });+ const isChild = Boolean(input.data?.parent);+ const capabilities = [+ ...builtinsFromSpec({+ spec: this.session.agent_spec,+ definition,+ isChild,+ sandboxAvailable: Boolean(input.sandbox),+ tracing: input.tracing,+ logger: input.resolver.logger,+ }),+ ...(extraCapabilities ?? []),+ ];+ return new AgentThread({+ definition,+ threadId: input.threadId,+ title: input.data?.agent_info?.name ?? (isChild ? input.threadId : 'main'),+ sandbox: input.sandbox,+ context: input.data?.context,+ currentContextUsage: input.data?.current_context_usage,+ parent: input.data?.parent,+ agentInfo: input.data?.agent_info,+ preComputedCompletion: input.data?.completion,+ capabilities,+ capabilityState: input.data?.capability_state,+ tracing: input.tracing,+ logger: input.resolver.logger,+ });+ }++ private makeCreateDynamicSubAgentThread(input: {+ resolver: ITurnResourceResolver<TTurnCustom>;+ previous: TurnRecord<TTurnCustom> | undefined;+ sandbox: Sandbox | undefined;+ tracing: AgentTracing;+ }): CreateDynamicSubAgentThread {+ return async params => {+ const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({+ spec: this.session.agent_spec,+ thread_id: params.threadId,+ agent_info: params.request,+ previousTurn: input.previous,+ signal: params.signal,+ tracing: input.tracing,+ });+ const childDefinition: AgentDefinition = {+ ...definition,+ toolSets: params.parentDefinition.toolSets ?? definition.toolSets,+ ...(params.request.model !== undefined+ ? {+ model: params.request.model,+ modelClient: definition.modelClient,+ }+ : {}),+ instruction: params.request.input,+ };+ const capabilities = [+ ...builtinsFromSpec({+ spec: this.session.agent_spec,+ definition: childDefinition,+ isChild: true,+ sandboxAvailable: Boolean(input.sandbox),+ tracing: input.tracing,+ logger: input.resolver.logger,+ }),+ ...(extraCapabilities ?? []),+ ];+ return new AgentThread({+ definition: childDefinition,+ threadId: params.threadId,+ title: params.request.name,+ sandbox: input.sandbox,+ parent: params.parent,+ agentInfo: params.request,+ capabilities,+ tracing: input.tracing,+ logger: input.resolver.logger,+ });+ };+ }+}diff --git a/packages/harness/src/agentSession/Sessions.ts b/packages/harness/src/agentSession/Sessions.tsnew file mode 100644index 000000000..1d9d94daa--- /dev/null+++ b/packages/harness/src/agentSession/Sessions.ts@@ -0,0 +1,63 @@+/**+ * Storage-only session collection: create / get. Behavior arrives per run via+ * the resolver on {@link SessionHandle.run}.+ */+import type { AgentSpec } from './schemas/agentSpec';+import { SessionHandle } from './SessionHandle';+import type { ISessionStore } from './store/ISessionStore';++export class Sessions<+ TSessionCustom extends object = Record<string, never>,+ TTurnCustom extends object = Record<string, never>,+> {+ private readonly store: ISessionStore<TSessionCustom, TTurnCustom>;++ constructor(deps: { sessionStore: ISessionStore<TSessionCustom, TTurnCustom> }) {+ this.store = deps.sessionStore;+ }++ /**+ * Creates and persists a new session. `agent_spec` is the fully hydrated+ * spec; the store may internally persist a blob and/or a uri/id.+ */+ async create(input: {+ tenant_name: string;+ session_id: string;+ agent_spec: AgentSpec;+ custom?: TSessionCustom | undefined;+ }): Promise<SessionHandle<TSessionCustom, TTurnCustom>> {+ await this.store.createSession(input);+ const record = await this.store.getSession({+ tenant_name: input.tenant_name,+ session_id: input.session_id,+ });+ if (!record) {+ throw new Error(`Session create succeeded but getSession returned undefined: ${input.session_id}`);+ }+ return new SessionHandle({+ store: this.store,+ tenantName: input.tenant_name,+ session: record,+ });+ }++ /**+ * Returns the session with `agent_spec` hydrated (even if the store persists+ * only a uri/id), or undefined if not found. Read-only: does not bump+ * last_activity_timestamp_ms.+ */+ async get(input: {+ tenant_name: string;+ session_id: string;+ }): Promise<SessionHandle<TSessionCustom, TTurnCustom> | undefined> {+ const record = await this.store.getSession(input);+ if (!record) {+ return undefined;+ }+ return new SessionHandle({+ store: this.store,+ tenantName: input.tenant_name,+ session: record,+ });+ }+}diff --git a/packages/harness/src/agentSession/TurnHandle.ts b/packages/harness/src/agentSession/TurnHandle.tsnew file mode 100644index 000000000..a39f69b29--- /dev/null+++ b/packages/harness/src/agentSession/TurnHandle.ts@@ -0,0 +1,457 @@+/**+ * Durable turn handle. {@link TurnHandle.stream} is execute-once (persist-before-yield).+ */+import type { MCPAuthRequiredEvent, ModelMessageDeltaEvent, ThreadDoneEvent } from '../core/events/eventSchemas';+import { EventType as HarnessEventType, newEventId } from '../core/events/eventSchemas';+import type { RegisteredPassthroughEvent } from '../core/events/PassthroughEvents';+import { getEmptyUsage } from '../core/llm/LLMTypes';+import { getEmptyMetric } from '../core/llm/metrics';+import {+ InternalEventType,+ type AgentThreadExecutionEvent,+ type AgentThreadExecutionResult,+ type InternalMCPAuthRequiredEvent,+ type InternalThreadDoneEvent,+} from '../core/runtime/AgentThread.types';+import type { AgentThreadOrchestrator } from '../core/runtime/AgentThreadOrchestrator';+import type { ITurnResourceResolver } from './ITurnResourceResolver';+import type { TurnRecord } from './models/TurnRecord';+import { EventType, type TurnCreatedEvent, type TurnDoneEvent, type TurnEvent } from './schemas/events';+import type { TokenPagination } from './schemas/pagination';+import { CancellationReason, type TerminalTurnState, type TurnInputItem, type TurnState } from './schemas/turn';+import type { ISessionStore } from './store/ISessionStore';++/** Streaming yield union — deltas pass through; never persisted. No sequence_number. */+export type TurnStreamingEvent =+ | TurnCreatedEvent+ | TurnDoneEvent+ | TurnEvent+ | ModelMessageDeltaEvent+ | RegisteredPassthroughEvent;++function cancellationReasonFromAbortReason(abortReason: unknown): CancellationReason {+ if (abortReason === CancellationReason.ServerExecutionTimeout) {+ return CancellationReason.ServerExecutionTimeout;+ }+ if (abortReason === CancellationReason.CancelledForNextTurn) {+ return CancellationReason.CancelledForNextTurn;+ }+ return CancellationReason.ClientCancelled;+}++function toThreadDoneEvent(event: InternalThreadDoneEvent): ThreadDoneEvent {+ const state =+ event.status === 'error'+ ? { status: 'error' as const, error: event.error, ...(event.output && { output: event.output }) }+ : { status: 'done' as const, output: event.output };+ return {+ type: HarnessEventType.THREAD_DONE,+ id: newEventId(),+ created_at: new Date().toISOString(),+ parent: event.parent,+ thread_id: event.thread_id,+ title: event.title,+ state,+ };+}++function toMCPAuthRequiredEvent(event: InternalMCPAuthRequiredEvent): MCPAuthRequiredEvent {+ return {+ type: HarnessEventType.MCP_AUTH_REQUIRED,+ id: event.id,+ created_at: event.created_at,+ thread_id: event.thread_id,+ mcp_servers: event.mcp_servers.map(({ thread_ids: _threadIds, ...server }) => server),+ };+}++export class TurnHandle<TTurnCustom extends object = Record<string, never>> {+ private readonly store: ISessionStore<object, TTurnCustom>;+ private readonly tenantName: string;+ private turn: TurnRecord<TTurnCustom>;+ private readonly orchestrator: AgentThreadOrchestrator | undefined;+ private readonly resolver: ITurnResourceResolver<TTurnCustom> | undefined;+ private readonly signal: AbortSignal | undefined;+ private streamStarted = false;++ constructor(options: {+ store: ISessionStore<object, TTurnCustom>;+ tenantName: string;+ turn: TurnRecord<TTurnCustom>;+ orchestrator?: AgentThreadOrchestrator | undefined;+ resolver?: ITurnResourceResolver<TTurnCustom> | undefined;+ signal?: AbortSignal | undefined;+ }) {+ this.store = options.store;+ this.tenantName = options.tenantName;+ this.turn = options.turn;+ this.orchestrator = options.orchestrator;+ this.resolver = options.resolver;+ this.signal = options.signal;+ }++ /** Store-only handle (e.g. from {@link SessionHandle.getTurn}) — stream() is not available. */+ static fromRecord<TCustom extends object = Record<string, never>>(options: {+ store: ISessionStore<object, TCustom>;+ tenantName: string;+ turn: TurnRecord<TCustom>;+ }): TurnHandle<TCustom> {+ return new TurnHandle(options);+ }++ get id(): string {+ return this.turn.turn_id;+ }++ get session_id(): string {+ return this.turn.session_id;+ }++ get previous_turn_id(): string | undefined {+ return this.turn.previous_turn_id;+ }++ get input(): TurnInputItem[] {+ return this.turn.input;+ }++ get state(): TurnState {+ return this.turn.state;+ }++ get created_at(): string {+ return this.turn.created_at;+ }++ get custom(): TTurnCustom | undefined {+ return this.turn.custom;+ }++ get record(): TurnRecord<TTurnCustom> {+ return this.turn;+ }++ /**+ * Executes the turn. Single consumer, callable ONCE — a second call throws:+ * this generator IS the execution (persist-before-yield). Execute-only: the+ * input was already sent and validated in run(); nothing is sent here.+ * Sole terminal writer — done/cancelled/error is written to the store from+ * inside this generator; honors the AbortSignal passed to run(). On every+ * exit path the resolver is closed best-effort in a finally, after the+ * terminal write.+ *+ * Two consumption patterns (both caller-side; this method is identical for both):+ *+ * // STREAMING — pipe events out as they happen (e.g. SSE):+ * for await (const e of turn.stream()) yield sse(e);+ *+ * // NON-STREAMING — drain in background, respond immediately with the+ * // running turn. The caller owns the active-turn registry, the .catch+ * // (store-write failures reject the drain; agent errors do NOT — they+ * // become terminal 'error' events inside), and graceful shutdown.+ * const drain = (async () => { for await (const _ of turn.stream()); })()+ * .catch(err => logger.error('turn drain failed', err));+ * activeTurns.set(turn.id, { controller, drain });+ * drain.finally(() => activeTurns.delete(turn.id));+ * return turnCreatedResponse(turn);+ *+ * Yields the delta-inclusive streaming union: deltas pass through to the+ * consumer but are NEVER persisted. Events carry no sequence_number; yield+ * order ≡ persist order (single sequential generator), so callers that need+ * numbering (e.g. SSE resume) stamp it at their own transport boundary.+ */+ async *stream(): AsyncGenerator<TurnStreamingEvent> {+ if (this.streamStarted) {+ throw new Error('TurnHandle.stream() is single-use and was already called');+ }+ this.streamStarted = true;++ const orchestrator = this.orchestrator;+ const resolver = this.resolver;+ const signal = this.signal;+ if (!orchestrator || !resolver || !signal) {+ throw new Error('TurnHandle.stream() is only available on turns returned from SessionHandle.run()');+ }++ let caughtError: Error | undefined;+ let executeResult: AgentThreadExecutionResult | undefined;+ let generator: AsyncGenerator<AgentThreadExecutionEvent, AgentThreadExecutionResult, unknown> | undefined;++ try {+ const turnCreated: TurnCreatedEvent = {+ type: EventType.TURN_CREATED,+ id: newEventId(),+ turn_id: this.turn.turn_id,+ previous_turn_id: this.turn.previous_turn_id ?? null,+ ...(this.turn.input.length > 0 ? { input: this.turn.input } : {}),+ state: { status: 'running' },+ created_at: this.turn.created_at,+ thread_id: null,+ };+ await this.store.appendToEvents({+ tenant_name: this.tenantName,+ session_id: this.turn.session_id,+ turn_id: this.turn.turn_id,+ events: [turnCreated],+ });+ yield turnCreated;++ generator = orchestrator.execute({ signal });+ let iterResult = await generator.next();+ while (!iterResult.done) {+ const event = iterResult.value;+ const yielded = await this.persistExecutionEvent(event);+ if (yielded) {+ yield yielded;+ }+ iterResult = await generator.next();+ }+ executeResult = iterResult.value;+ } catch (error) {+ caughtError = error instanceof Error ? error : new Error(String(error));+ } finally {+ if (generator) {+ const emptyResult: AgentThreadExecutionResult = {+ output: null,+ required_actions: [],+ metrics: { total: getEmptyMetric() },+ };+ await generator.return(emptyResult);+ }++ const createdAt = new Date().toISOString();+ let terminalState: TerminalTurnState;+ if (signal.aborted) {+ terminalState = {+ status: 'cancelled',+ reason: cancellationReasonFromAbortReason(signal.reason),+ completed_at: createdAt,+ };+ } else if (caughtError) {+ terminalState = {+ status: 'error',+ message: caughtError.message,+ completed_at: createdAt,+ };+ } else if (executeResult?.root_agent_error) {+ terminalState = {+ status: 'error',+ message: executeResult.root_agent_error.error,+ completed_at: createdAt,+ };+ } else if (executeResult === undefined) {+ // Consumer abandoned the generator (break/return) without aborting —+ // no executeResult, no error, signal not aborted.+ terminalState = {+ status: 'cancelled',+ reason: CancellationReason.ClientCancelled,+ completed_at: createdAt,+ };+ } else {+ terminalState = {+ status: 'done',+ output: executeResult.output,+ required_actions: executeResult.required_actions,+ completed_at: createdAt,+ };+ }++ const turnDone: TurnDoneEvent = {+ type: EventType.TURN_DONE,+ id: newEventId(),+ created_at: createdAt,+ state: terminalState,+ thread_id: null,+ };++ try {+ await this.store.updateTurnState({+ tenant_name: this.tenantName,+ session_id: this.turn.session_id,+ turn_id: this.turn.turn_id,+ state: terminalState,+ });+ await this.store.appendToEvents({+ tenant_name: this.tenantName,+ session_id: this.turn.session_id,+ turn_id: this.turn.turn_id,+ events: [turnDone],+ });+ this.turn = { ...this.turn, state: terminalState, updated_at: createdAt };+ } catch (persistError) {+ // Store-write failures reject the stream (caller drain .catch).+ await resolver.close().catch(() => {});+ // eslint-disable-next-line no-unsafe-finally -- deliberate: the terminal-state write runs in finally and its failure must reject the stream+ throw persistError;+ }++ await resolver.close().catch(err => {+ resolver.logger.warn('TurnResourceResolver.close() failed', { err });+ });++ yield turnDone;+ }+ }++ /** Paginated read of this turn's persisted events. */+ async listEvents(input: { limit: number; page_token?: string; order?: 'asc' | 'desc' }): Promise<{+ data: Array<TurnEvent | TurnCreatedEvent | TurnDoneEvent | RegisteredPassthroughEvent>;+ pagination: TokenPagination;+ }> {+ return this.store.listTurnEvents({+ tenant_name: this.tenantName,+ session_id: this.turn.session_id,+ turn_id: this.turn.turn_id,+ limit: input.limit,+ page_token: input.page_token,+ order: input.order,+ });+ }++ /**+ * Persist side effects for one execution event; return a streaming yield when+ * the event should be emitted to the consumer (null = side-effect only / skip).+ */+ private async persistExecutionEvent(event: AgentThreadExecutionEvent): Promise<TurnStreamingEvent | null> {+ const scope = {+ tenant_name: this.tenantName,+ session_id: this.turn.session_id,+ turn_id: this.turn.turn_id,+ };++ switch (event.type) {+ case HarnessEventType.MODEL_MESSAGE:+ case HarnessEventType.MODEL_MESSAGE_DELTA:+ case HarnessEventType.TOOL_RESPONSE:+ // Stream only — durable model/tool content lands via AGENT_CONTEXT_APPEND.output.+ return event;++ case InternalEventType.AGENT_CREATE_SUBAGENT:+ return null;++ case InternalEventType.CAPABILITY_STATE: {+ await this.store.patchThreadCapabilityState({+ ...scope,+ thread_id: event.thread_id,+ key: event.key,+ state: event.state,+ });+ return null;+ }++ case HarnessEventType.AGENT_CONTEXT_OVERWRITE: {+ await this.store.overwriteThreadContext({ ...scope, event });+ return null;+ }++ case InternalEventType.AGENT_CONTEXT_APPEND: {+ await this.store.appendToThreadContext({+ ...scope,+ thread_id: event.thread_id,+ context: event.context,+ current_context_usage: event.current_context_usage,+ completion: event.completion,+ });+ if (event.output.length > 0) {+ await this.store.appendToEvents({+ ...scope,+ events: event.output,+ });+ }+ return null;+ }++ case InternalEventType.AGENT_DONE: {+ if (!event.parent) {+ return null;+ }+ const threadDone = toThreadDoneEvent(event);+ await this.store.removeThreads({+ ...scope,+ thread_ids: [event.thread_id],+ });+ await this.store.appendToEvents({+ ...scope,+ events: [threadDone],+ });+ return threadDone;+ }++ case HarnessEventType.THREAD_CREATED: {+ await this.store.addThreads({+ ...scope,+ threads: [+ {+ thread_id: event.thread_id,+ parent: event.parent,+ agent_info: event.agent_info,+ context: [],+ current_context_usage: getEmptyUsage(),+ },+ ],+ });+ await this.store.appendToEvents({+ ...scope,+ events: [event],+ });+ return event;+ }++ case InternalEventType.MCP_AUTH_REQUIRED: {+ const authEvent = toMCPAuthRequiredEvent(event);+ await this.store.appendToEvents({+ ...scope,+ events: [authEvent],+ });+ return authEvent;+ }++ case HarnessEventType.MCP_INITIALIZE: {+ await this.store.patchMCPServers({+ ...scope,+ mcp_servers: event.mcp_servers.map(initInfo => ({+ id: initInfo.id,+ name: initInfo.name,+ session_id: initInfo.session_id,+ transport_type: initInfo.transport_type,+ })),+ });+ await this.store.appendToEvents({+ ...scope,+ events: [event],+ });+ return event;+ }++ case HarnessEventType.SANDBOX_CREATED: {+ await this.store.patchSandboxInfo({+ ...scope,+ sandbox_info: { sandbox_id: event.sandbox_id },+ });+ await this.store.appendToEvents({+ ...scope,+ events: [event],+ });+ return event;+ }++ case HarnessEventType.TOOL_APPROVAL_REQUIRED:+ case HarnessEventType.TOOL_RESPONSE_REQUIRED: {+ await this.store.appendToEvents({+ ...scope,+ events: [event],+ });+ return event;+ }++ default: {+ // Registered passthrough (orchestrator unwraps PASSTHROUGH before yield).+ await this.store.appendToEvents({+ ...scope,+ events: [event],+ });+ return event;+ }+ }+ }+}diff --git a/packages/harness/src/agentSession/TurnResourceResolver.ts b/packages/harness/src/agentSession/TurnResourceResolver.tsnew file mode 100644index 000000000..6b04d481f--- /dev/null+++ b/packages/harness/src/agentSession/TurnResourceResolver.ts@@ -0,0 +1,205 @@+import type { Logger } from 'winston';+import type { AgentCapability } from '../core/capabilities/AgentCapability';+import type { ILLM } from '../core/llm/ILLM';+import type { ToolSource } from '../core/mcp/IMCPServer';+import { RemoteMCP, type RemoteMcpHeaders } from '../core/mcp/RemoteMCP';+import type { ToolSelectorConfig } from '../core/mcp/ToolSelectorPolicy';+import { ToolSet } from '../core/mcp/ToolSet';+import type { AgentDefinition } from '../core/runtime/AgentDefinition';+import type { AgentInfo } from '../core/runtime/AgentThread.types';+import type { Sandbox, SandboxInfo } from '../core/sandbox/Sandbox';+import type { AgentTracing } from '../core/tracing/AgentTracing';+import { NOOP_AGENT_TRACING } from '../core/tracing/NoopAgentTracing';+import type { ITurnResourceResolver } from './ITurnResourceResolver';+import type { TurnRecord } from './models/TurnRecord';+import type { AgentSpec } from './schemas/agentSpec';++/**+ * Factory that creates a Sandbox handle for a run (reattach via+ * existingSandboxId). `spec` carries the sandbox-relevant agent settings+ * (e.g. config.sandbox.file_downloads) so implementations can shape the+ * Sandbox per run without the factory type growing a field per option.+ */+export type TurnSandboxFactory = (input: {+ spec: AgentSpec;+ existingSandboxId?: string | undefined;+ signal: AbortSignal;+ tracing: AgentTracing;+}) => Promise<Sandbox>;++function specWantsSandbox(spec: AgentSpec): boolean {+ return spec.config?.sandbox?.enabled === true;+}++function toSelectors(entry: {+ enable_tools: string[];+ disable_tools: string[];+ preload_tools: string[];+ require_approval_for_tools: string[];+}): ToolSelectorConfig {+ return {+ enableTools: entry.enable_tools,+ disableTools: entry.disable_tools,+ preloadTools: entry.preload_tools,+ requireApprovalForTools: entry.require_approval_for_tools,+ };+}++/**+ * Batteries-included base implementation. Construct-and-go for the default+ * behavior; subclass and override to customize (tool sources, sandbox,+ * tracing).+ */+export class TurnResourceResolver<+ TTurnCustom extends object = Record<string, never>,+> implements ITurnResourceResolver<TTurnCustom> {+ readonly #sources = new Map<string, Promise<ToolSource>>();+ #sandbox?: Sandbox | undefined;++ constructor(+ protected readonly deps: {+ /** Model name → client. Called once per resolved definition. */+ llm: (model: string) => ILLM;+ /**+ * MCP server name → connection details. Required to use spec.mcp_servers:+ * the AgentSpec carries names only (no url/headers on the wire) — the+ * runtime supplies the catalog. Called once per distinct server name per+ * turn. Throw for unknown names. `headers` supports the async resolver form.+ */+ mcp: (name: string) => Promise<{ url: string; headers?: RemoteMcpHeaders }>;+ /** One sandbox type per runtime. Omit = no sandbox support. */+ sandboxProvider?: TurnSandboxFactory | undefined;+ /** Forwarded to RemoteMCP / AgentThread (required by their constructors). */+ logger: Logger;+ },+ ) {}++ get logger(): Logger {+ return this.deps.logger;+ }++ /** Default: no-op tracing. Override to plug in a real tracer. */+ createTracing(): AgentTracing {+ return NOOP_AGENT_TRACING;+ }++ /**+ * Default: creates a sandbox iff a provider is configured AND the spec wants+ * one; reattaches to the previous turn's VM via `existing.sandbox_id` when+ * present. Overrides that resolve their own sandbox must assign it so+ * close() can release it (or override close() too).+ */+ async resolveSandbox(input: {+ spec: AgentSpec;+ existing?: SandboxInfo | undefined;+ previousTurn?: TurnRecord<TTurnCustom> | undefined;+ signal: AbortSignal;+ tracing: AgentTracing;+ }): Promise<Sandbox | undefined> {+ if (!this.deps.sandboxProvider || !specWantsSandbox(input.spec)) return undefined;+ this.#sandbox = await this.deps.sandboxProvider({+ spec: input.spec,+ existingSandboxId: input.existing?.sandbox_id,+ signal: input.signal,+ tracing: input.tracing,+ });+ return this.#sandbox;+ }++ /**+ * Closes the sandbox HANDLE if one was resolved. This releases only this+ * process's connection (local bridge); the sandbox VM keeps running and the+ * next turn reattaches via `existing.sandbox_id`.+ *+ * Tool sources (MCP connections) are intentionally NOT closed: the run's+ * AbortSignal already aborts their in-flight calls, and connections are+ * per-run objects that are simply dropped. If deterministic MCP socket+ * release is ever needed, add it here — no contract change required.+ *+ * Subclasses that acquire additional resources MUST override, release+ * their own resources best-effort, and call `await super.close()`.+ * Idempotent; never throws.+ */+ async close(): Promise<void> {+ const sandbox = this.#sandbox;+ this.#sandbox = undefined;+ await sandbox?.close().catch(() => {});+ }++ /**+ * Default: maps the spec directly to a definition — spec.mcp_servers carry+ * names only; deps.mcp resolves each name to url/headers, and the result+ * becomes a RemoteMCP source (deduped per turn via getOrCreateToolSource)+ * wrapped in a per-agent ToolSet view. Passes the previous turn's persisted+ * MCP session_id into RemoteMCP for cross-turn stateful resume.+ */+ async resolveAgentDefinition(input: {+ spec: AgentSpec;+ thread_id: string;+ agent_info?: AgentInfo | undefined;+ previousTurn?: TurnRecord<TTurnCustom> | undefined;+ signal: AbortSignal;+ tracing: AgentTracing;+ }): Promise<{+ definition: AgentDefinition;+ extraCapabilities?: AgentCapability[] | undefined;+ }> {+ const { spec, agent_info: agentInfo, previousTurn, signal, tracing } = input;+ const toolSets = await Promise.all(+ (spec.mcp_servers ?? []).map(async entry => {+ const source = await this.getOrCreateToolSource({+ id: entry.name,+ create: async () => {+ const { url, headers } = await this.deps.mcp(entry.name);+ return new RemoteMCP({+ id: entry.name,+ name: entry.name,+ url,+ headers: headers ?? {},+ sessionId: previousTurn?.snapshot.mcp_servers?.[entry.name]?.session_id,+ logger: this.deps.logger,+ tracing,+ signal,+ });+ },+ });+ return new ToolSet({+ source,+ selectors: toSelectors(entry),+ preload: entry.preload,+ });+ }),+ );+ return {+ definition: {+ model: spec.model.name,+ modelClient: this.deps.llm(spec.model.name),+ instruction: agentInfo ? agentInfo.input : spec.instructions,+ messages: spec.messages?.map(m => ({+ role: 'user' as const,+ content: m.content,+ })),+ modelParams: spec.model.params,+ responseFormat: spec.response_format,+ iterationLimit: spec.config?.iteration_limit,+ toolSets,+ },+ };+ }++ /**+ * Returns the tool source for `id`, creating it on first call — use from+ * resolveAgentDefinition overrides so agents sharing a server share one+ * connection. Single-flight by id: the promise is stored synchronously (no+ * await between get and set), so overlapping resolveAgentDefinition calls+ * can never double-create. Rejections stay cached: one attempt per turn.+ * Do not override.+ */+ protected getOrCreateToolSource(input: { id: string; create: () => Promise<ToolSource> }): Promise<ToolSource> {+ const cached = this.#sources.get(input.id);+ if (cached) return cached;+ const made = input.create();+ this.#sources.set(input.id, made);+ return made;+ }+}diff --git a/packages/harness/src/agentSession/builtinsFromSpec.ts b/packages/harness/src/agentSession/builtinsFromSpec.tsnew file mode 100644index 000000000..55449daa2--- /dev/null+++ b/packages/harness/src/agentSession/builtinsFromSpec.ts@@ -0,0 +1,70 @@+/**+ * Maps AgentSpec runtime config flags to public harness builtin capabilities.+ * Plan / ask-user-secret stay gateway-side (extraCapabilities on the resolver).+ */+import type { Logger } from 'winston';+import type { AgentCapability } from '../core/capabilities/AgentCapability';+import { askUserQuestion } from '../core/capabilities/builtins/AskUserQuestion';+import { contextCompaction } from '../core/capabilities/builtins/ContextCompaction';+import { currentDateTime } from '../core/capabilities/builtins/CurrentDateTime';+import { dynamicSubAgents } from '../core/capabilities/builtins/DynamicSubAgents';+import { largeToolResponse } from '../core/capabilities/builtins/LargeToolResponse';+import { openUI } from '../core/capabilities/builtins/OpenUI';+import type { AgentDefinition } from '../core/runtime/AgentDefinition';+import type { AgentTracing } from '../core/tracing/AgentTracing';+import type { AgentSpec } from './schemas/agentSpec';++export function builtinsFromSpec(input: {+ spec: AgentSpec;+ definition: AgentDefinition;+ /** Root thread only — child threads omit interactive builtins. */+ isChild: boolean;+ sandboxAvailable: boolean;+ tracing: AgentTracing;+ logger: Logger;+}): AgentCapability[] {+ const { spec, definition, isChild, sandboxAvailable, tracing, logger } = input;+ const config = spec.config;+ const capabilities: AgentCapability[] = [currentDateTime({ tracing })];++ const compaction = config?.context_management?.compaction;+ if (!compaction || compaction.enabled !== false) {+ capabilities.push(+ contextCompaction({+ definition,+ compactionThresholdTokens: compaction?.compaction_threshold_tokens,+ }),+ );+ }++ if (!isChild && (config?.ask_user_questions === undefined || config.ask_user_questions.enabled)) {+ capabilities.push(askUserQuestion());+ }++ const dynamicSubAgentsEnabled =+ config?.dynamic_sub_agents === undefined || config.dynamic_sub_agents.enabled !== false;+ if (!isChild && dynamicSubAgentsEnabled) {+ capabilities.push(+ dynamicSubAgents({+ sandboxAvailable,+ tracing,+ }),+ );+ }++ const large = config?.context_management?.large_tool_response;+ if (!large || large.enabled !== false) {+ capabilities.push(+ largeToolResponse({+ dynamicSubAgentsPresent: !isChild && dynamicSubAgentsEnabled,+ logger,+ }),+ );+ }++ if (!isChild && config?.generative_ui?.enabled) {+ capabilities.push(openUI());+ }++ return capabilities;+}diff --git a/packages/harness/src/agentSession/index.ts b/packages/harness/src/agentSession/index.tsnew file mode 100644index 000000000..7607c5c10--- /dev/null+++ b/packages/harness/src/agentSession/index.ts@@ -0,0 +1,54 @@+/**+ * Public agent session middle library.+ * Zod product contracts and session/turn runtime.+ */++export { AgentSpecSchema, DEFAULT_AGENT_CONFIG_ITERATION_LIMIT, RuntimeConfigSchema } from './schemas/agentSpec';+export type { AgentSpec } from './schemas/agentSpec';++export {+ CancellationReason,+ CreateTurnRequestSchema,+ PreviousTurnIdInputSchema,+ TurnInputItemSchema,+ TurnSchema,+ TurnStateCancelledReasonSchema,+ TurnStateCancelledSchema,+ TurnStateDoneSchema,+ TurnStateErrorSchema,+ TurnStateRunningSchema,+ TurnStateSchema,+} from './schemas/turn';+export type { TerminalTurnState, Turn, TurnInputItem, TurnState } from './schemas/turn';++export { CreateSessionRequestSchema, SessionSchema, UpdateSessionRequestSchema } from './schemas/session';+export type { Session } from './schemas/session';++export {+ EventType,+ SessionEventItemSchema,+ TurnCreatedEventSchema,+ TurnDoneEventSchema,+ TurnEventSchema,+} from './schemas/events';+export type { SessionEventItem, TurnCreatedEvent, TurnDoneEvent, TurnEvent } from './schemas/events';++export { TokenPaginationSchema } from './schemas/pagination';+export type { TokenPagination } from './schemas/pagination';++export type { SessionRecord } from './models/SessionRecord';+export { MAIN_THREAD_ID, TURN_SERIALIZATION_VERSION } from './models/TurnRecord';+export type { TurnRecord, TurnSnapshot } from './models/TurnRecord';++export { InMemorySessionStore } from './store/InMemorySessionStore';+export type { ISessionStore } from './store/ISessionStore';+export { SessionStoreConflictError, SessionStoreNotFoundError } from './store/SessionStoreErrors';++export type { ITurnResourceResolver } from './ITurnResourceResolver';+export { TurnResourceResolver } from './TurnResourceResolver';+export type { TurnSandboxFactory } from './TurnResourceResolver';++export { SessionHandle } from './SessionHandle';+export { Sessions } from './Sessions';+export { TurnHandle } from './TurnHandle';+export type { TurnStreamingEvent } from './TurnHandle';diff --git a/packages/harness/src/agentSession/models/SessionRecord.ts b/packages/harness/src/agentSession/models/SessionRecord.tsnew file mode 100644index 000000000..7d3cd0475--- /dev/null+++ b/packages/harness/src/agentSession/models/SessionRecord.ts@@ -0,0 +1,32 @@+import type { AgentSpec } from '../schemas/agentSpec';++/**+ * Every Session / SessionRecord exposes a hydrated `agent_spec`. Persistence+ * may store the full blob or only a uri/id — an ISessionStore impl detail.+ * `getSession` MUST hydrate so callers (and Session.run) never see a bare+ * pointer; agent resolution stays inside the store. Callers rewrite the+ * binding via the updateSession patch.+ */+export interface SessionRecord<TCustom extends object = Record<string, never>> {+ session_id: string;+ /** Always hydrated on read. Source of `spec` in SessionHandle.run(). */+ agent_spec: AgentSpec;+ /**+ * Wire SessionSchema.title (nullable). Written via updateSession patch or+ * createTurn's update_session_title_if_not_exist (first write wins; caller derives).+ */+ title?: string | null | undefined;+ /**+ * Session tip — used for `previous_turn_id: 'auto'` resolution and turn+ * listing anchors. Advanced only by `createTurn` (atomic link).+ */+ last_turn_id?: string | undefined;+ created_at: string;+ updated_at: string;+ /**+ * Liveness clock (ms since epoch). The store bumps it on createSession,+ * updateSession, and createTurn — never on reads.+ */+ last_activity_timestamp_ms: number;+ custom?: TCustom | undefined;+}diff --git a/packages/harness/src/agentSession/models/TurnRecord.ts b/packages/harness/src/agentSession/models/TurnRecord.tsnew file mode 100644index 000000000..237f8c797--- /dev/null+++ b/packages/harness/src/agentSession/models/TurnRecord.ts@@ -0,0 +1,36 @@+import type { MCPServerInitInfo } from '../../core/events/eventSchemas';+import type { AgentThreadSnapshot } from '../../core/runtime/AgentThread.types';+import type { SandboxInfo } from '../../core/sandbox/Sandbox';+import type { TurnInputItem, TurnState } from '../schemas/turn';++/** Root thread id for every session. */+export const MAIN_THREAD_ID = 'main';++/**+ * Public wire / store shape — JSON-friendly `Record`, not `Map`, so every+ * backend can persist it directly. In-process runtime may still use Map;+ * adapt at the store/Session boundary.+ */+export interface TurnSnapshot {+ threads: Record<string, AgentThreadSnapshot>;+ mcp_servers?: Record<string, MCPServerInitInfo> | undefined;+ sandbox_info?: SandboxInfo | undefined;+}++export interface TurnRecord<TCustom extends object = Record<string, never>> {+ serialization_version: number;+ turn_id: string;+ session_id: string;+ first_turn_id: string;+ ancestor_ids: string[];+ previous_turn_id?: string | undefined;+ state: TurnState;+ input: TurnInputItem[];+ snapshot: TurnSnapshot;+ created_at: string;+ updated_at: string;+ custom?: TCustom | undefined;+}++/** Current serialization version for TurnRecord. */+export const TURN_SERIALIZATION_VERSION = 1;diff --git a/packages/harness/src/agentSession/schemas/agentSpec.ts b/packages/harness/src/agentSession/schemas/agentSpec.tsnew file mode 100644index 000000000..a3b9eb20a--- /dev/null+++ b/packages/harness/src/agentSession/schemas/agentSpec.ts@@ -0,0 +1,238 @@+/** AgentSpec wire schema — the inline agent definition a session is created with. */+import { z } from '@hono/zod-openapi';+import { DEFAULT_CONTEXT_COMPACTION_THRESHOLD_TOKENS } from '../../core/capabilities/builtins/ContextCompaction';+import {+ DEFAULT_INDIVIDUAL_TOOL_TOKEN_THRESHOLD,+ DEFAULT_PREVIEW_NUMBER_OF_CHARACTERS,+ DEFAULT_TOTAL_TOOL_TOKEN_THRESHOLD,+} from '../../core/capabilities/builtins/LargeToolResponse';+import {+ DEFAULT_DISABLE_TOOLS,+ DEFAULT_ENABLE_TOOLS,+ DEFAULT_PRELOAD_TOOLS,+ DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS,+ REQUIRE_APPROVAL_TOOLS_SELECTOR_TAGS,+ TOOLS_SELECTOR_TAGS,+} from '../../core/mcp/toolSelectors';+import { ResponseFormatSchema } from '../../core/llm/responseFormat';++export const DEFAULT_AGENT_CONFIG_ITERATION_LIMIT = 100;++// --- Model ---++const ModelParamsSchema = z+ .object({+ max_tokens: z.number().optional(),+ temperature: z.number().optional(),+ top_p: z.number().optional(),+ top_k: z.number().optional(),+ parallel_tool_calls: z.boolean().optional(),+ reasoning_effort: z.string().optional(),+ })+ .passthrough() // this ensures extra model params are allowed+ .openapi('ModelParams');++const ModelSpecSchema = z+ .object({+ name: z.string().min(1, 'model.name must not be empty'),+ params: ModelParamsSchema.optional(),+ })+ .openapi('Model');++// --- MCP servers ---++// Literal tool name (not a tag).+const LiteralToolSelectorSchema = z+ .string()+ .min(1)+ .refine(s => !s.startsWith('@'), { message: 'Invalid tool selector tag' });++// enable_tools / disable_tools / preload_tools: @all, @read-only, or a literal name.+const EnableToolSelectorSchema = z.union([z.enum(TOOLS_SELECTOR_TAGS), LiteralToolSelectorSchema]);++// require_approval_for_tools: @all, @write, @destructive, or a literal name.+const RequireApprovalToolSelectorSchema = z.union([+ z.enum(REQUIRE_APPROVAL_TOOLS_SELECTOR_TAGS),+ LiteralToolSelectorSchema,+]);++// `preload` defaults to false; use `preload_tools` to eagerly load specific tools when not fully preloading.+// Auth headers are not part of the spec — they come from the MCP_HEADERS /+// MCP_{NAME}_HEADERS env vars.+const MCPServerRequestSchema = z+ .object({+ name: z.string().min(1, 'mcp_servers[].name must not be empty'),+ // Which tools to enable. Default: all tools.+ enable_tools: z.array(EnableToolSelectorSchema).default(DEFAULT_ENABLE_TOOLS),+ // Which tools to disable (subtracted from enable_tools). Default: none.+ disable_tools: z.array(EnableToolSelectorSchema).default(DEFAULT_DISABLE_TOOLS),+ // When the server is not fully preloaded (`preload: false`), which tools to+ // still preload into context. A non-empty list implies `preload: false`.+ preload_tools: z.array(EnableToolSelectorSchema).default(DEFAULT_PRELOAD_TOOLS),+ // Tools that require human approval before execution. Default: @write + @destructive.+ require_approval_for_tools: z.array(RequireApprovalToolSelectorSchema).default(DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS),+ // Whether this server's tools are preloaded into context. Default: false.+ // When false, tools are discovered lazily and only `preload_tools` stay eager.+ preload: z.boolean().optional().default(false),+ })+ .openapi('MCPServer');++// --- Runtime config ---++const CompactionSettingsSchema = z.object({+ enabled: z.boolean().default(true),+ compaction_threshold_tokens: z+ .number()+ .int()+ .positive()+ .optional()+ .default(DEFAULT_CONTEXT_COMPACTION_THRESHOLD_TOKENS),+});++const LargeToolResponseSettingsSchema = z.object({+ enabled: z.boolean().default(true),+ individual_tool_response_token_threshold: z+ .number()+ .int()+ .positive()+ .optional()+ .default(DEFAULT_INDIVIDUAL_TOOL_TOKEN_THRESHOLD),+ total_tool_response_token_threshold: z+ .number()+ .int()+ .positive()+ .optional()+ .default(DEFAULT_TOTAL_TOOL_TOKEN_THRESHOLD),+ preview_number_of_characters: z.number().int().positive().optional().default(DEFAULT_PREVIEW_NUMBER_OF_CHARACTERS),+});++const BASIC_AUTH_USERNAME_PATTERN = /^\S+$/;++/** True when any hostname segment contains `*` (e.g. `*.github.com`). */+function hostContainsWildcard(host: string): boolean {+ return host.split('.').some(segment => segment.includes('*'));+}++const SandboxAuthInjectMatchSchema = z.object({+ hosts: z+ .array(+ z+ .string()+ .min(1)+ .refine(host => !hostContainsWildcard(host), {+ message: 'Hosts must be exact hostnames without wildcards',+ }),+ )+ .min(1),+});++const SandboxBasicAuthDataSchema = z.object({+ type: z.literal('basic'),+ username: z.string().regex(BASIC_AUTH_USERNAME_PATTERN, 'Username must be non-empty and contain no whitespace'),+ password: z.string().min(1),+});++const SandboxGitAuthInjectSchema = z.object({+ type: z.literal('git'),+ match: SandboxAuthInjectMatchSchema,+ auth_data: SandboxBasicAuthDataSchema,+});++const SandboxNetworkPolicySchema = z+ .object({+ auth_inject: z+ .array(SandboxGitAuthInjectSchema)+ .max(1, 'At most one auth inject rule is supported (type: git)')+ .optional(),+ })+ .openapi('SandboxNetworkPolicy');++const SandboxConfigSchema = z+ .object({+ enabled: z.boolean(),+ file_downloads: z.boolean().default(true),+ network_policy: SandboxNetworkPolicySchema.optional(),+ })+ .openapi('SandboxConfig');++const DynamicSubAgentsConfigSchema = z+ .object({+ enabled: z.boolean().default(true),+ })+ .openapi('DynamicSubAgentsConfig');++const LargeToolResponseConfigSchema = LargeToolResponseSettingsSchema.pick({+ enabled: true,+}).openapi('LargeToolResponseConfig');++const ContextManagementConfigSchema = z+ .object({+ compaction: CompactionSettingsSchema.default({ enabled: true }),+ large_tool_response: LargeToolResponseConfigSchema.default({ enabled: true }),+ })+ .openapi('ContextManagementConfig');++const GenerativeUIConfigSchema = z+ .object({+ enabled: z.boolean().default(true),+ })+ .openapi('GenerativeUIConfig');++const AskUserQuestionsConfigSchema = z+ .object({+ enabled: z.boolean().default(true),+ })+ .openapi('AskUserQuestionsConfig');++export const RuntimeConfigSchema = z+ .object({+ iteration_limit: z.number().int().positive().max(1024).default(DEFAULT_AGENT_CONFIG_ITERATION_LIMIT),+ sandbox: SandboxConfigSchema.optional(),+ dynamic_sub_agents: DynamicSubAgentsConfigSchema.optional(),+ context_management: ContextManagementConfigSchema.optional().default({+ compaction: { enabled: true },+ large_tool_response: { enabled: true },+ }),+ generative_ui: GenerativeUIConfigSchema.optional(),+ ask_user_questions: AskUserQuestionsConfigSchema.optional(),+ })+ .openapi('RuntimeConfig');++// --- Skills ---++const SkillMountSchema = z+ .object({+ name: z.string().trim().min(1).describe('Name of a skill declared in skills.yaml.'),+ preload: z.boolean().default(false).describe('If true, the SKILL.md content is injected into the agent context.'),+ })+ .openapi('SkillMount');++// --- Response format / messages ---++const AgentSpecUserMessageSchema = z+ .object({+ type: z.literal('user.message'),+ content: z+ .string()+ .min(1, 'User message content must not be empty')+ .refine(content => content.trim().length > 0, 'User message content must not be empty'),+ })+ .openapi('AgentSpecUserMessage');++// --- Agent spec ---++export const AgentSpecSchema = z+ .object({+ model: ModelSpecSchema,+ instructions: z.string().optional(),+ messages: z.array(AgentSpecUserMessageSchema).optional(),+ mcp_servers: z.array(MCPServerRequestSchema).optional(),+ response_format: ResponseFormatSchema.optional(),+ skills: z.array(SkillMountSchema).optional(),+ config: RuntimeConfigSchema.optional(),+ variables: z.record(z.string(), z.string()).optional(),+ })+ .describe('Agent Definition')+ .openapi('AgentSpec');++export type AgentSpec = z.infer<typeof AgentSpecSchema>;diff --git a/packages/harness/src/agentSession/schemas/events.ts b/packages/harness/src/agentSession/schemas/events.tsnew file mode 100644index 000000000..ce446e1eb--- /dev/null+++ b/packages/harness/src/agentSession/schemas/events.ts@@ -0,0 +1,89 @@+/**+ * Turn/session event product schemas. Event payloads come from the harness; this+ * module owns turn lifecycle events (turn.created / turn.done) and the persisted+ * event unions the store writes. SSE streaming envelopes stay in server/schemas.+ */+import { z } from '@hono/zod-openapi';+import {+ EventIdSchema,+ EventType as HarnessEventType,+ MCPAuthRequiredEventSchema,+ MCPInitializeEventSchema,+ ModelMessageEventSchema,+ SandboxCreatedEventSchema,+ ThreadCreatedEventSchema,+ ThreadDoneEventSchema,+ ToolApprovalRequiredEventSchema,+ ToolResponseEventSchema,+ ToolResponseRequiredEventSchema,+} from '../../core/events/eventSchemas';+import {+ TurnInputItemSchema,+ TurnStateCancelledSchema,+ TurnStateDoneSchema,+ TurnStateErrorSchema,+ TurnStateRunningSchema,+} from './turn';++/** Harness event types plus the turn lifecycle types owned by agentSession. */+export const EventType = {+ ...HarnessEventType,+ TURN_CREATED: 'turn.created',+ TURN_DONE: 'turn.done',+} as const;++export const TurnCreatedEventSchema = z+ .object({+ type: z.literal(EventType.TURN_CREATED),+ id: EventIdSchema,+ turn_id: z.string(),+ previous_turn_id: z.string().nullable(),+ input: z.array(TurnInputItemSchema).optional(),+ state: TurnStateRunningSchema,+ created_at: z.string(),+ thread_id: z.string().nullable(),+ })+ .openapi('TurnCreatedEvent');++export const TurnDoneEventSchema = z+ .object({+ type: z.literal(EventType.TURN_DONE),+ id: EventIdSchema,+ state: z.discriminatedUnion('status', [TurnStateDoneSchema, TurnStateCancelledSchema, TurnStateErrorSchema]),+ created_at: z.string(),+ thread_id: z.string().nullable(),+ })+ .openapi('TurnDoneEvent');++/** Persisted turn content events — no deltas, no lifecycle. */+export const TurnEventSchema = z+ .discriminatedUnion('type', [+ ModelMessageEventSchema,+ ToolResponseEventSchema,+ ThreadCreatedEventSchema,+ ThreadDoneEventSchema,+ MCPAuthRequiredEventSchema,+ MCPInitializeEventSchema,+ SandboxCreatedEventSchema,+ ToolApprovalRequiredEventSchema,+ ToolResponseRequiredEventSchema,+ ])+ .openapi('TurnEvent');++/** turn.created, turn.done, or a persisted turn event — no deltas. */+const SessionEventSchema = z+ .discriminatedUnion('type', [TurnCreatedEventSchema, TurnDoneEventSchema, ...TurnEventSchema.options])+ .openapi('SessionEvent');++/** One row on the session timeline: which turn emitted the event plus the event payload. */+export const SessionEventItemSchema = z+ .object({+ turn_id: z.string(),+ event: SessionEventSchema,+ })+ .openapi('SessionEventItem');++export type TurnCreatedEvent = z.infer<typeof TurnCreatedEventSchema>;+export type TurnDoneEvent = z.infer<typeof TurnDoneEventSchema>;+export type TurnEvent = z.infer<typeof TurnEventSchema>;+export type SessionEventItem = z.infer<typeof SessionEventItemSchema>;diff --git a/packages/harness/src/agentSession/schemas/pagination.ts b/packages/harness/src/agentSession/schemas/pagination.tsnew file mode 100644index 000000000..6b1bba6d3--- /dev/null+++ b/packages/harness/src/agentSession/schemas/pagination.ts@@ -0,0 +1,12 @@+/** Token pagination wire schema. */+import { z } from '@hono/zod-openapi';++export const TokenPaginationSchema = z+ .object({+ next_page_token: z.string().optional(),+ previous_page_token: z.string().optional(),+ limit: z.number().int().positive(),+ })+ .openapi('TokenPagination');++export type TokenPagination = z.infer<typeof TokenPaginationSchema>;diff --git a/packages/harness/src/agentSession/schemas/session.ts b/packages/harness/src/agentSession/schemas/session.tsnew file mode 100644index 000000000..c9989c0a4--- /dev/null+++ b/packages/harness/src/agentSession/schemas/session.ts@@ -0,0 +1,27 @@+/** Session product schemas. A session owns an inline AgentSpec. */+import { z } from '@hono/zod-openapi';+import { AgentSpecSchema } from './agentSpec';++export const SessionSchema = z+ .object({+ id: z.string(),+ agent_spec: AgentSpecSchema,+ title: z.string().nullable(),+ created_at: z.string(),+ updated_at: z.string(),+ })+ .openapi('Session');++export const CreateSessionRequestSchema = z+ .object({+ agent_spec: AgentSpecSchema,+ })+ .openapi('CreateSessionRequest');++export const UpdateSessionRequestSchema = z+ .object({+ agent_spec: AgentSpecSchema.optional(),+ })+ .openapi('UpdateSessionRequest');++export type Session = z.infer<typeof SessionSchema>;diff --git a/packages/harness/src/agentSession/schemas/turn.ts b/packages/harness/src/agentSession/schemas/turn.tsnew file mode 100644index 000000000..ab7869d90--- /dev/null+++ b/packages/harness/src/agentSession/schemas/turn.ts@@ -0,0 +1,114 @@+/** Turn product schemas: turn state, input items, and create-turn request. */+import { z } from '@hono/zod-openapi';+import {+ ActionRequiredEventSchema,+ AgentInputUserMessageSchema,+ ModelMessageEventSchema,+ UserToolApprovalMessageSchema,+ UserToolResponseMessageSchema,+} from '../../core/events/eventSchemas';++export enum CancellationReason {+ // AbortController.abort() reason for the max-execution timer.+ ServerExecutionTimeout = 'server-execution-timeout',+ // Emitted when the client cancels the run.+ ClientCancelled = 'client-cancelled',+ // Prior turn aborted because the client started a new turn.+ CancelledForNextTurn = 'cancelled-for-next-turn',+}++export const TurnStateRunningSchema = z+ .object({+ status: z.literal('running'),+ })+ .openapi('TurnStateRunning');++export const TurnStateCancelledReasonSchema = z+ .nativeEnum(CancellationReason)+ .describe('Reason for the cancellation.')+ .openapi('TurnStateCancelledReason');++export const TurnStateCancelledSchema = z+ .object({+ status: z.literal('cancelled'),+ reason: TurnStateCancelledReasonSchema,+ completed_at: z.string(),+ })+ .openapi('TurnStateCancelled');++export const TurnStateErrorSchema = z+ .object({+ status: z.literal('error'),+ message: z.string(),+ completed_at: z.string(),+ })+ .openapi('TurnStateError');++export const TurnStateDoneSchema = z+ .object({+ status: z.literal('done'),+ output: ModelMessageEventSchema.nullable(),+ required_actions: z.array(ActionRequiredEventSchema),+ completed_at: z.string(),+ })+ .openapi('TurnStateDone');++export const TurnStateSchema = z+ .discriminatedUnion('status', [+ TurnStateRunningSchema,+ TurnStateDoneSchema,+ TurnStateCancelledSchema,+ TurnStateErrorSchema,+ ])+ .openapi('TurnState');++export const TurnInputItemSchema = z+ .discriminatedUnion('type', [+ AgentInputUserMessageSchema,+ UserToolApprovalMessageSchema,+ UserToolResponseMessageSchema,+ ])+ .openapi('TurnInputItem');++export const TurnSchema = z+ .object({+ id: z.string(),+ session_id: z.string(),+ previous_turn_id: z.string().nullable(),+ input: z.array(TurnInputItemSchema).optional(),+ state: TurnStateSchema,+ created_at: z.string(),+ })+ .openapi('Turn');++export const PreviousTurnIdInputSchema = z+ .union([z.literal('auto'), z.string().min(1)])+ .nullable()+ .openapi('PreviousTurnIdInput');++export const CreateTurnRequestSchema = z+ .object({+ input: z.array(TurnInputItemSchema).optional(),+ previous_turn_id: PreviousTurnIdInputSchema.optional()+ .default('auto')+ .describe(`Defaults to 'auto' (chain to session last turn). Use 'null' for the session's first turn.`),+ })+ .superRefine((data, ctx) => {+ if (!data.input) return;+ const hasUser = data.input.some(msg => 'type' in msg && msg.type === 'user.message');+ const hasApprovalOrToolResponse = data.input.some(+ msg => 'type' in msg && (msg.type === 'user.tool_approval' || msg.type === 'user.tool_response'),+ );+ if (hasUser && hasApprovalOrToolResponse) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'input must not mix user messages with approval decisions or client-side tool responses',+ });+ }+ })+ .openapi('CreateTurnRequest');++export type Turn = z.infer<typeof TurnSchema>;+export type TurnInputItem = z.infer<typeof TurnInputItemSchema>;+export type TurnState = z.infer<typeof TurnStateSchema>;+export type TerminalTurnState = Exclude<TurnState, { status: 'running' }>;diff --git a/packages/harness/src/agentSession/store/ISessionStore.ts b/packages/harness/src/agentSession/store/ISessionStore.tsnew file mode 100644index 000000000..d0b046c7e--- /dev/null+++ b/packages/harness/src/agentSession/store/ISessionStore.ts@@ -0,0 +1,246 @@+import type { MCPServerInitInfo, ThreadOverwriteContextEvent } from '../../core/events/eventSchemas';+import type { RegisteredPassthroughEvent } from '../../core/events/PassthroughEvents';+import type { CompletionUsage } from '../../core/llm/LLMTypes';+import type {+ AgentThreadSnapshot,+ ContextMessage,+ SubAgentCompletionMarker,+} from '../../core/runtime/AgentThread.types';+import type { SandboxInfo } from '../../core/sandbox/Sandbox';+import type { SessionRecord } from '../models/SessionRecord';+import type { TurnRecord } from '../models/TurnRecord';+import type { AgentSpec } from '../schemas/agentSpec';+import type { TurnCreatedEvent, TurnDoneEvent, TurnEvent } from '../schemas/events';+import type { TokenPagination } from '../schemas/pagination';+import type { TerminalTurnState } from '../schemas/turn';++/**+ * Session/turn persistence contract. Pure durability: no streaming, SSE, or+ * subscription members. Turn-scoped ops take session_id (membership check).+ * Capability durability goes through patchThreadCapabilityState only. Agent+ * binding is session-scoped: reads always return a hydrated agent_spec even+ * if the backend persists a uri/id.+ */+export interface ISessionStore<+ TSessionCustom extends object = Record<string, never>,+ TTurnCustom extends object = Record<string, never>,+> {+ /**+ * Accepts a hydrated AgentSpec. Impl may persist the blob and/or a uri/id derived+ * from it — callers do not pass a bare pointer through this API.+ * Sets `last_activity_timestamp_ms` (= now) on create.+ */+ createSession(input: {+ tenant_name: string;+ session_id: string;+ agent_spec: AgentSpec;+ custom?: TSessionCustom | undefined;+ }): Promise<void>;++ /**+ * MUST return SessionRecord with `agent_spec` fully hydrated, even if the backend+ * only stores a uri/id (or named-agent ref). Hydration is the store's job — harness+ * and SessionHandle.run never resolve agents themselves.+ * Does **not** bump `last_activity_timestamp_ms` (read path).+ */+ getSession(input: { tenant_name: string; session_id: string }): Promise<SessionRecord<TSessionCustom> | undefined>;++ /**+ * PATCH semantics — update only the provided fields:+ * - agent_spec: rewrite binding (full spec and/or backing uri/id). Next getSession hydrates.+ * - title: set/replace the session title.+ * Bumps `last_activity_timestamp_ms` (= now). Same liveness rule applies to any+ * future session-update fields: update session ⇒ touch activity.+ */+ updateSession(input: {+ tenant_name: string;+ session_id: string;+ agent_spec?: AgentSpec | undefined;+ title?: string | undefined;+ }): Promise<void>;++ /**+ * Paginated list of the tenant's sessions ordered by `created_at`+ * (`order` defaults to `desc`). `start_timestamp` / `end_timestamp` are+ * inclusive ISO-8601 bounds on `created_at`.+ * Does **not** bump `last_activity_timestamp_ms` (read path).+ */+ listSessions(input: {+ tenant_name: string;+ limit: number;+ page_token?: string | undefined;+ order?: 'asc' | 'desc' | undefined;+ start_timestamp?: string | undefined;+ end_timestamp?: string | undefined;+ }): Promise<{ data: SessionRecord<TSessionCustom>[]; pagination: TokenPagination }>;++ /**+ * Creates the turn AND advances `session.last_turn_id`.+ *+ * Atomicity (store contract): insert turn + set `last_turn_id` (+ session+ * turn-list append if the backend has one) MUST be one atomic unit per+ * session. Concurrent createTurn on the same session must not drop a turn+ * row or leave `last_turn_id` pointing at a turn that was never created.+ * The implementation supplies the mechanism (session lock, row lock/tx, …).+ *+ * Also bumps `session.last_activity_timestamp_ms` in that same atomic unit.+ *+ * Fork semantics for `turn.previous_turn_id`:+ * - `undefined` — new root turn (no parent); always allowed.+ * - string — must reference an **existing** turn in this session (fork/chain+ * from that turn). Tip-equality is NOT required; concurrent forks from the+ * same tip both succeed. Unknown id → not-found.+ * `last_turn_id` always advances to the new turn in the same atomic unit.+ *+ * `update_session_title_if_not_exist`: when set AND `session.title` is+ * unset/null, set it in the same atomic unit; an existing title is NEVER+ * overwritten (first write wins). The caller derives the value; the store+ * only conditionally sets it.+ */+ createTurn(input: {+ tenant_name: string;+ turn: TurnRecord<TTurnCustom>;+ update_session_title_if_not_exist?: string | undefined;+ }): Promise<void>;++ /** Returns the turn record, or undefined if not found in this session. */+ getTurn(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ }): Promise<TurnRecord<TTurnCustom> | undefined>;++ /** Paginated list of the session's turn records, stable ordering. */+ listTurns(input: {+ tenant_name: string;+ session_id: string;+ limit: number;+ page_token?: string | undefined;+ }): Promise<{ data: TurnRecord<TTurnCustom>[]; pagination: TokenPagination }>;++ /**+ * Writes the terminal state. Store contract — **first terminal write wins**:+ * - Allowed: `running` → `done` | `cancelled` | `error`.+ * - Rejected with **409** (or equivalent conflict): any write when status is already+ * terminal — including done→cancelled, cancelled→done, error→*, terminal→running.+ * - Missing turn → 404 / not-found.+ *+ * Check under the same concurrency control as other turn mutations (lock/CAS) —+ * not a racy read-then-write outside the critical section.+ */+ updateTurnState(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ state: TerminalTurnState;+ }): Promise<void>;++ /**+ * Durable event log for the turn. MUST include lifecycle rows: a+ * `TurnCreatedEvent` at the start of the stream and a terminal `TurnDoneEvent`+ * (or its cancelled/error shape) at the end. Every turn written through this+ * API persists lifecycle in the stream — implementations never synthesize+ * missing created/done rows on read.+ */+ appendToEvents(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ events: Array<TurnEvent | TurnCreatedEvent | TurnDoneEvent | RegisteredPassthroughEvent>;+ }): Promise<void>;++ /** Adds thread snapshots to the turn (sub-agent spawns). */+ addThreads(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ threads: AgentThreadSnapshot[];+ }): Promise<void>;++ /** Removes threads from the turn by id. */+ removeThreads(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ thread_ids: string[];+ }): Promise<void>;++ /** Appends messages to a thread's context; optionally updates usage / completion marker. */+ appendToThreadContext(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ thread_id: string;+ context: ContextMessage[];+ current_context_usage?: CompletionUsage | undefined;+ completion?: SubAgentCompletionMarker | undefined;+ }): Promise<void>;++ /** Replaces a thread's context wholesale (context-overwrite event). */+ overwriteThreadContext(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ event: ThreadOverwriteContextEvent;+ }): Promise<void>;++ /** Patches the turn snapshot's MCP server init info (by source id). */+ patchMCPServers(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ mcp_servers: MCPServerInitInfo[];+ }): Promise<void>;++ /** Patches the turn snapshot's sandbox info (id for cross-turn reattach). */+ patchSandboxInfo(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ sandbox_info: SandboxInfo;+ }): Promise<void>;++ /** Generic capability KV — store has zero Plan/feature knowledge. */+ patchThreadCapabilityState(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ thread_id: string;+ key: string;+ state: unknown;+ }): Promise<void>;++ /** Paginated read of one turn's persisted events, insertion order (asc default). */+ listTurnEvents(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ limit: number;+ page_token?: string | undefined;+ order?: 'asc' | 'desc' | undefined;+ }): Promise<{+ data: Array<TurnEvent | TurnCreatedEvent | TurnDoneEvent | RegisteredPassthroughEvent>;+ pagination: TokenPagination;+ }>;++ /**+ * Paginated session-wide feed of persisted events across turns, including+ * turn.created / turn.done lifecycle rows. Reads only — never synthesizes.+ *+ * Includes events from **running** turns (the HTTP layer may 409 separately;+ * that is not store semantics). Ordering: newest-first across the flattened+ * feed. `last_turn_id` anchors the window to that turn plus its ancestors+ * (the `ancestor_ids` chain, oldest first) — sibling branches from forks are+ * excluded; omit to use the full session turn list.+ */+ listSessionEvents(input: {+ tenant_name: string;+ session_id: string;+ limit: number;+ page_token?: string | undefined;+ last_turn_id?: string | undefined;+ }): Promise<{+ data: Array<{ turn_id: string; event: TurnCreatedEvent | TurnDoneEvent | TurnEvent }>;+ pagination: TokenPagination;+ }>;+}diff --git a/packages/harness/src/agentSession/store/InMemorySessionStore.ts b/packages/harness/src/agentSession/store/InMemorySessionStore.tsnew file mode 100644index 000000000..2c9da40c7--- /dev/null+++ b/packages/harness/src/agentSession/store/InMemorySessionStore.ts@@ -0,0 +1,459 @@+import type { MCPServerInitInfo, ThreadOverwriteContextEvent } from '../../core/events/eventSchemas';+import type { RegisteredPassthroughEvent } from '../../core/events/PassthroughEvents';+import type { CompletionUsage } from '../../core/llm/LLMTypes';+import type {+ AgentThreadSnapshot,+ ContextMessage,+ SubAgentCompletionMarker,+} from '../../core/runtime/AgentThread.types';+import type { SandboxInfo } from '../../core/sandbox/Sandbox';+import type { SessionRecord } from '../models/SessionRecord';+import type { TurnRecord } from '../models/TurnRecord';+import type { AgentSpec } from '../schemas/agentSpec';+import type { TurnCreatedEvent, TurnDoneEvent, TurnEvent } from '../schemas/events';+import type { TokenPagination } from '../schemas/pagination';+import type { TerminalTurnState } from '../schemas/turn';+import type { ISessionStore } from './ISessionStore';+import { SessionStoreConflictError, SessionStoreNotFoundError } from './SessionStoreErrors';++type StoredEvent = TurnEvent | TurnCreatedEvent | TurnDoneEvent | RegisteredPassthroughEvent;++interface StoredSession<TSessionCustom extends object> {+ record: SessionRecord<TSessionCustom>;+ turnIds: string[];+}++function deepCopy<T>(value: T): T {+ return structuredClone(value);+}++function sessionKey(tenant: string, sessionId: string): string {+ return `${tenant}:${sessionId}`;+}++function turnKey(tenant: string, sessionId: string, turnId: string): string {+ return `${tenant}:${sessionId}:${turnId}`;+}++function encodeOffset(offset: number): string {+ return String(offset);+}++function decodeOffset(token: string | undefined): number {+ if (token === undefined || token === '') return 0;+ const n = Number(token);+ if (!Number.isInteger(n) || n < 0) {+ throw new SessionStoreConflictError(`Invalid page_token: ${token}`);+ }+ return n;+}++function paginate<T>(items: T[], limit: number, pageToken?: string): { data: T[]; pagination: TokenPagination } {+ const offset = decodeOffset(pageToken);+ const slice = items.slice(offset, offset + limit);+ return {+ data: slice,+ pagination: {+ limit,+ ...(offset + limit < items.length ? { next_page_token: encodeOffset(offset + limit) } : {}),+ ...(offset > 0 ? { previous_page_token: encodeOffset(Math.max(0, offset - limit)) } : {}),+ },+ };+}++/**+ * Reference ISessionStore implementation. Proves the contract without SSE/subscription+ * hooks. Deep-copies on read/write boundaries so callers cannot mutate stored state.+ */+export class InMemorySessionStore<+ TSessionCustom extends object = Record<string, never>,+ TTurnCustom extends object = Record<string, never>,+> implements ISessionStore<TSessionCustom, TTurnCustom> {+ private readonly sessions = new Map<string, StoredSession<TSessionCustom>>();+ private readonly turns = new Map<string, TurnRecord<TTurnCustom>>();+ private readonly events = new Map<string, StoredEvent[]>();+ /** Per-session promise chain for atomic createTurn / updateTurnState. */+ private readonly locks = new Map<string, Promise<void>>();++ private async withLock<T>(key: string, fn: () => T | Promise<T>): Promise<T> {+ const prev = this.locks.get(key) ?? Promise.resolve();+ let release!: () => void;+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ this.locks.set(+ key,+ prev.then(() => gate),+ );+ await prev;+ try {+ return await fn();+ } finally {+ release();+ }+ }++ async createSession(input: {+ tenant_name: string;+ session_id: string;+ agent_spec: AgentSpec;+ custom?: TSessionCustom | undefined;+ }): Promise<void> {+ const key = sessionKey(input.tenant_name, input.session_id);+ if (this.sessions.has(key)) {+ throw new SessionStoreConflictError(`Session already exists: ${input.session_id}`);+ }+ const now = new Date().toISOString();+ const record: SessionRecord<TSessionCustom> = {+ session_id: input.session_id,+ agent_spec: deepCopy(input.agent_spec),+ title: null,+ created_at: now,+ updated_at: now,+ last_activity_timestamp_ms: Date.now(),+ ...(input.custom !== undefined ? { custom: deepCopy(input.custom) } : {}),+ };+ this.sessions.set(key, { record, turnIds: [] });+ }++ async getSession(input: {+ tenant_name: string;+ session_id: string;+ }): Promise<SessionRecord<TSessionCustom> | undefined> {+ const stored = this.sessions.get(sessionKey(input.tenant_name, input.session_id));+ return stored ? deepCopy(stored.record) : undefined;+ }++ async updateSession(input: {+ tenant_name: string;+ session_id: string;+ agent_spec?: AgentSpec | undefined;+ title?: string | undefined;+ }): Promise<void> {+ const key = sessionKey(input.tenant_name, input.session_id);+ const stored = this.sessions.get(key);+ if (!stored) {+ throw new SessionStoreNotFoundError(`Session not found: ${input.session_id}`);+ }+ if (input.agent_spec !== undefined) {+ stored.record.agent_spec = deepCopy(input.agent_spec);+ }+ if (input.title !== undefined) {+ stored.record.title = input.title;+ }+ stored.record.updated_at = new Date().toISOString();+ stored.record.last_activity_timestamp_ms = Date.now();+ }++ async listSessions(input: {+ tenant_name: string;+ limit: number;+ page_token?: string | undefined;+ order?: 'asc' | 'desc' | undefined;+ start_timestamp?: string | undefined;+ end_timestamp?: string | undefined;+ }): Promise<{ data: SessionRecord<TSessionCustom>[]; pagination: TokenPagination }> {+ const prefix = `${input.tenant_name}:`;+ const records: SessionRecord<TSessionCustom>[] = [];+ for (const [key, stored] of this.sessions) {+ if (!key.startsWith(prefix)) continue;+ const createdAt = stored.record.created_at;+ if (input.start_timestamp !== undefined && createdAt < input.start_timestamp) continue;+ if (input.end_timestamp !== undefined && createdAt > input.end_timestamp) continue;+ records.push(stored.record);+ }+ records.sort((a, b) =>+ input.order === 'asc' ? a.created_at.localeCompare(b.created_at) : b.created_at.localeCompare(a.created_at),+ );+ const page = paginate(records, input.limit, input.page_token);+ return { data: deepCopy(page.data), pagination: page.pagination };+ }++ async createTurn(input: {+ tenant_name: string;+ turn: TurnRecord<TTurnCustom>;+ update_session_title_if_not_exist?: string | undefined;+ }): Promise<void> {+ const sKey = sessionKey(input.tenant_name, input.turn.session_id);+ return this.withLock(sKey, () => {+ const stored = this.sessions.get(sKey);+ if (!stored) {+ throw new SessionStoreNotFoundError(`Session not found: ${input.turn.session_id}`);+ }+ const previousTurnId = input.turn.previous_turn_id;+ if (previousTurnId !== undefined) {+ const prevKey = turnKey(input.tenant_name, input.turn.session_id, previousTurnId);+ if (!this.turns.has(prevKey)) {+ throw new SessionStoreNotFoundError(`previous_turn_id not found in session: ${previousTurnId}`);+ }+ }+ const tKey = turnKey(input.tenant_name, input.turn.session_id, input.turn.turn_id);+ if (this.turns.has(tKey)) {+ throw new SessionStoreConflictError(`Turn already exists: ${input.turn.turn_id}`);+ }+ this.turns.set(tKey, deepCopy(input.turn));+ this.events.set(tKey, []);+ stored.turnIds.push(input.turn.turn_id);+ stored.record.last_turn_id = input.turn.turn_id;+ stored.record.last_activity_timestamp_ms = Date.now();+ stored.record.updated_at = new Date().toISOString();+ if (+ input.update_session_title_if_not_exist !== undefined &&+ (stored.record.title === undefined || stored.record.title === null)+ ) {+ stored.record.title = input.update_session_title_if_not_exist;+ }+ });+ }++ async getTurn(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ }): Promise<TurnRecord<TTurnCustom> | undefined> {+ const turn = this.turns.get(turnKey(input.tenant_name, input.session_id, input.turn_id));+ return turn ? deepCopy(turn) : undefined;+ }++ async listTurns(input: {+ tenant_name: string;+ session_id: string;+ limit: number;+ page_token?: string | undefined;+ }): Promise<{ data: TurnRecord<TTurnCustom>[]; pagination: TokenPagination }> {+ const stored = this.sessions.get(sessionKey(input.tenant_name, input.session_id));+ if (!stored) {+ throw new SessionStoreNotFoundError(`Session not found: ${input.session_id}`);+ }+ const records = stored.turnIds.map(id => {+ const turn = this.turns.get(turnKey(input.tenant_name, input.session_id, id));+ if (!turn) {+ throw new SessionStoreNotFoundError(`Turn not found: ${id}`);+ }+ return deepCopy(turn);+ });+ return paginate(records, input.limit, input.page_token);+ }++ async updateTurnState(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ state: TerminalTurnState;+ }): Promise<void> {+ const sKey = sessionKey(input.tenant_name, input.session_id);+ const tKey = turnKey(input.tenant_name, input.session_id, input.turn_id);+ return this.withLock(sKey, () => {+ const turn = this.turns.get(tKey);+ if (!turn) {+ throw new SessionStoreNotFoundError(`Turn not found: ${input.turn_id}`);+ }+ if (turn.state.status !== 'running') {+ throw new SessionStoreConflictError(+ `Turn ${input.turn_id} is already terminal (${turn.state.status}); first terminal write wins`,+ );+ }+ turn.state = deepCopy(input.state);+ turn.updated_at = new Date().toISOString();+ });+ }++ async appendToEvents(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ events: Array<TurnEvent | TurnCreatedEvent | TurnDoneEvent | RegisteredPassthroughEvent>;+ }): Promise<void> {+ const tKey = turnKey(input.tenant_name, input.session_id, input.turn_id);+ const list = this.events.get(tKey);+ if (!list) {+ throw new SessionStoreNotFoundError(`Turn not found: ${input.turn_id}`);+ }+ list.push(...deepCopy(input.events));+ }++ private requireTurn(tenant: string, sessionId: string, turnId: string): TurnRecord<TTurnCustom> {+ const turn = this.turns.get(turnKey(tenant, sessionId, turnId));+ if (!turn) {+ throw new SessionStoreNotFoundError(`Turn not found: ${turnId}`);+ }+ return turn;+ }++ async addThreads(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ threads: AgentThreadSnapshot[];+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ for (const thread of input.threads) {+ turn.snapshot.threads[thread.thread_id] = deepCopy(thread);+ }+ turn.updated_at = new Date().toISOString();+ }++ async removeThreads(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ thread_ids: string[];+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ for (const id of input.thread_ids) {+ delete turn.snapshot.threads[id];+ }+ turn.updated_at = new Date().toISOString();+ }++ async appendToThreadContext(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ thread_id: string;+ context: ContextMessage[];+ current_context_usage?: CompletionUsage | undefined;+ completion?: SubAgentCompletionMarker | undefined;+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ const thread = turn.snapshot.threads[input.thread_id];+ if (!thread) {+ throw new SessionStoreNotFoundError(`Thread not found: ${input.thread_id}`);+ }+ thread.context.push(...deepCopy(input.context));+ if (input.current_context_usage !== undefined) {+ thread.current_context_usage = deepCopy(input.current_context_usage);+ }+ if (input.completion !== undefined) {+ thread.completion = deepCopy(input.completion);+ }+ turn.updated_at = new Date().toISOString();+ }++ async overwriteThreadContext(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ event: ThreadOverwriteContextEvent;+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ const threadId = input.event.thread_id;+ const thread = turn.snapshot.threads[threadId];+ if (!thread) {+ throw new SessionStoreNotFoundError(`Thread not found: ${threadId}`);+ }+ thread.context = deepCopy(input.event.context);+ if (input.event.current_context_usage !== undefined) {+ thread.current_context_usage = deepCopy(input.event.current_context_usage);+ }+ turn.updated_at = new Date().toISOString();+ }++ async patchMCPServers(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ mcp_servers: MCPServerInitInfo[];+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ if (!turn.snapshot.mcp_servers) {+ turn.snapshot.mcp_servers = {};+ }+ for (const server of input.mcp_servers) {+ turn.snapshot.mcp_servers[server.id] = deepCopy(server);+ }+ turn.updated_at = new Date().toISOString();+ }++ async patchSandboxInfo(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ sandbox_info: SandboxInfo;+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ turn.snapshot.sandbox_info = deepCopy(input.sandbox_info);+ turn.updated_at = new Date().toISOString();+ }++ async patchThreadCapabilityState(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ thread_id: string;+ key: string;+ state: unknown;+ }): Promise<void> {+ const turn = this.requireTurn(input.tenant_name, input.session_id, input.turn_id);+ const thread = turn.snapshot.threads[input.thread_id];+ if (!thread) {+ throw new SessionStoreNotFoundError(`Thread not found: ${input.thread_id}`);+ }+ if (!thread.capability_state) {+ thread.capability_state = {};+ }+ thread.capability_state[input.key] = deepCopy(input.state);+ turn.updated_at = new Date().toISOString();+ }++ async listTurnEvents(input: {+ tenant_name: string;+ session_id: string;+ turn_id: string;+ limit: number;+ page_token?: string | undefined;+ order?: 'asc' | 'desc' | undefined;+ }): Promise<{+ data: Array<TurnEvent | TurnCreatedEvent | TurnDoneEvent | RegisteredPassthroughEvent>;+ pagination: TokenPagination;+ }> {+ const list = this.events.get(turnKey(input.tenant_name, input.session_id, input.turn_id));+ if (!list) {+ throw new SessionStoreNotFoundError(`Turn not found: ${input.turn_id}`);+ }+ const ordered = input.order === 'desc' ? [...list].reverse() : list;+ const page = paginate(ordered, input.limit, input.page_token);+ return { data: deepCopy(page.data), pagination: page.pagination };+ }++ async listSessionEvents(input: {+ tenant_name: string;+ session_id: string;+ limit: number;+ page_token?: string | undefined;+ last_turn_id?: string | undefined;+ }): Promise<{+ data: Array<{ turn_id: string; event: TurnCreatedEvent | TurnDoneEvent | TurnEvent }>;+ pagination: TokenPagination;+ }> {+ const stored = this.sessions.get(sessionKey(input.tenant_name, input.session_id));+ if (!stored) {+ throw new SessionStoreNotFoundError(`Session not found: ${input.session_id}`);+ }+ let turnIds = stored.turnIds;+ if (input.last_turn_id) {+ const anchor = this.turns.get(turnKey(input.tenant_name, input.session_id, input.last_turn_id));+ if (!anchor) {+ throw new SessionStoreNotFoundError(`Turn not found: ${input.last_turn_id}`);+ }+ turnIds = [...anchor.ancestor_ids, anchor.turn_id];+ }+ const flattened: Array<{ turn_id: string; event: TurnCreatedEvent | TurnDoneEvent | TurnEvent }> = [];+ for (const turnId of turnIds) {+ const evts = this.events.get(turnKey(input.tenant_name, input.session_id, turnId)) ?? [];+ for (const event of evts) {+ if (isSessionFeedEvent(event)) {+ flattened.push({ turn_id: turnId, event });+ }+ }+ }+ // Newest first for session feed.+ flattened.reverse();+ const page = paginate(flattened, input.limit, input.page_token);+ return { data: deepCopy(page.data), pagination: page.pagination };+ }+}++function isSessionFeedEvent(event: StoredEvent): event is TurnCreatedEvent | TurnDoneEvent | TurnEvent {+ return event.type === 'turn.created' || event.type === 'turn.done' || !('event' in event);+}diff --git a/packages/harness/src/agentSession/store/SessionStoreErrors.ts b/packages/harness/src/agentSession/store/SessionStoreErrors.tsnew file mode 100644index 000000000..b22bc0b45--- /dev/null+++ b/packages/harness/src/agentSession/store/SessionStoreErrors.ts@@ -0,0 +1,15 @@+/** Store conflict (e.g. first-terminal-wins violation, concurrent createTurn). */+export class SessionStoreConflictError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'SessionStoreConflictError';+ }+}++/** Store not-found (session or turn missing). */+export class SessionStoreNotFoundError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'SessionStoreNotFoundError';+ }+}diff --git a/packages/harness/src/core/InstructionBuilder.ts b/packages/harness/src/core/InstructionBuilder.tsnew file mode 100644index 000000000..897bad39d--- /dev/null+++ b/packages/harness/src/core/InstructionBuilder.ts@@ -0,0 +1,119 @@+/**+ * Builds a structured XML system prompt as a tree of named sections.+ *+ * Each node is an XML section (e.g. `<sandbox>`) that can contain+ * plain text and/or nested sections. Children are always rendered+ * in insertion order.+ *+ * @example+ * // Creating nested and sibling sections:+ *+ * const root = InstructionBuilder.createSystemPrompt(ROOT_AGENT_IDENTITY);+ *+ * // Add a leaf section (tag + text, no further nesting)+ * root.addSection('rules', 'Follow these rules...');+ *+ * // Add raw text without a wrapping tag+ * root.addContent('Some standalone text');+ *+ * // Begin a section you want to nest into — returns the child builder+ * const capabilities = root.beginSection('capabilities');+ * capabilities.addSection('tool-a', 'Tool A instructions');+ * capabilities.addSection('tool-b', 'Tool B instructions');+ *+ * // Nest deeper — beginSection on a child+ * const sandbox = capabilities.beginSection('sandbox');+ * sandbox.addContent('Sandbox overview');+ * sandbox.addSection('skill', 'Skill details');+ *+ * // Back to root level — just use the root reference again+ * root.addSection('user-instructions', userInput, true); // escapeContent = true+ *+ * console.log(root.build());+ *+ * // Output:+ * // <system-prompt>+ * // <agent-identity>...</agent-identity>+ * // <rules>Follow these rules...</rules>+ * // Some standalone text+ * // <capabilities>+ * // <tool-a>Tool A instructions</tool-a>+ * // <tool-b>Tool B instructions</tool-b>+ * // <sandbox>+ * // Sandbox overview+ * // <skill>Skill details</skill>+ * // </sandbox>+ * // </capabilities>+ * // <user-instructions><![CDATA[...]]></user-instructions>+ * // </system-prompt>+ */++export const ROOT_AGENT_IDENTITY =+ 'You are the Agent, an AI assistant that helps users accomplish tasks by leveraging available tools and capabilities.';++export class InstructionBuilder {+ /** The XML tag name for this section node. */+ private currentTag: string;+ private escapeContent: boolean;+ private children: (string | InstructionBuilder)[] = [];++ constructor(currentTag: string, escapeContent = false) {+ this.currentTag = currentTag;+ this.escapeContent = escapeContent;+ }++ /** Creates the root `<system-prompt>` node with the given identity in `<agent-identity>`. */+ static createSystemPrompt(identity: string): InstructionBuilder {+ const builder = new InstructionBuilder('system-prompt');+ builder.addSection('agent-identity', identity);+ return builder;+ }++ /** Adds raw text (no wrapping tag) to this section. Empty strings are ignored. */+ addContent(content: string): this {+ const trimmed = content.trim();+ if (trimmed) this.children.push(trimmed);+ return this;+ }++ /**+ * Adds a leaf section: `<tag>content</tag>`. Empty content is ignored.+ * Set escapeContent = true to wrap content in CDATA (for arbitrary/untrusted text).+ */+ addSection(tag: string, content: string, escapeContent = false): this {+ const trimmed = content.trim();+ if (!trimmed) return this;+ const child = new InstructionBuilder(tag, escapeContent);+ child.children.push(trimmed);+ this.children.push(child);+ return this;+ }++ /** Creates a nested section and returns it so you can add children to it. */+ beginSection(tag: string): InstructionBuilder {+ const child = new InstructionBuilder(tag);+ this.children.push(child);+ return child;+ }++ /** Recursively renders the tree into an XML string. Empty sections are skipped. */+ build(): string {+ const inner: string[] = [];+ for (const child of this.children) {+ if (typeof child === 'string') {+ inner.push(child);+ } else {+ const output = child.build();+ if (output) inner.push(output);+ }+ }++ if (inner.length === 0) return '';++ const body = inner.join('\n\n');+ if (this.escapeContent) {+ return `<${this.currentTag}><![CDATA[\n${body}\n]]></${this.currentTag}>`;+ }+ return `<${this.currentTag}>\n${body}\n</${this.currentTag}>`;+ }+}diff --git a/packages/harness/src/core/capabilities/AgentCapability.ts b/packages/harness/src/core/capabilities/AgentCapability.tsnew file mode 100644index 000000000..8cfbe0065--- /dev/null+++ b/packages/harness/src/core/capabilities/AgentCapability.ts@@ -0,0 +1,25 @@+import type { InstructionBuilder } from '../InstructionBuilder';+import type { IToolSet } from '../mcp/IMCPServer';+import type {+ PostToolCallAgentContextProcessor,+ PreLLMAgentContextProcessor,+ PreLLMEphemeralAgentContextProcessor,+ PreSendContextProcessor,+} from './AgentContextProcessor';+import type { ToolResponseProcessor } from './ToolResponseProcessor';++export interface AgentCapability {+ readonly systemToolSets?: readonly IToolSet[] | undefined;+ readonly preSendProcessors?: readonly PreSendContextProcessor[] | undefined;+ readonly preLLMProcessors?: readonly PreLLMAgentContextProcessor[] | undefined;+ readonly preLLMEphemeralProcessors?: readonly PreLLMEphemeralAgentContextProcessor[] | undefined;+ readonly postToolCallProcessors?: readonly PostToolCallAgentContextProcessor[] | undefined;+ readonly toolResponseProcessors?: readonly ToolResponseProcessor[] | undefined;+ readonly instructionBuilders?: readonly ((builder: InstructionBuilder) => void)[] | undefined;+ /**+ * Cross-turn durable state. `key` must be unique across capabilities on a+ * thread (`tfy.` reserved for builtins). `load` hydrates from the previous+ * turn's capability_state; writes go through CAPABILITY_STATE events.+ */+ readonly state?: { key: string; load(state: unknown): void };+}diff --git a/packages/harness/src/core/capabilities/AgentContextProcessor.ts b/packages/harness/src/core/capabilities/AgentContextProcessor.tsnew file mode 100644index 000000000..de56d3163--- /dev/null+++ b/packages/harness/src/core/capabilities/AgentContextProcessor.ts@@ -0,0 +1,49 @@+import type { ChatCompletionMessageParam } from 'openai/resources/chat';+import type { ThreadOverwriteContextEvent } from '../events/eventSchemas';+import type { CompletionUsage } from '../llm/LLMTypes';+import type {+ AgentThreadAppendContext,+ ContextMessage,+ InternalCapabilityStateEvent,+ InternalPassthroughEvent,+} from '../runtime/AgentThread.types';+import type { Sandbox } from '../sandbox/Sandbox';++/** Ambient thread snapshot passed Readonly to every capability processor hook. */+export interface AgentThreadExecutionContext {+ threadId: string;+ sandbox?: Sandbox | undefined;+ currentContextUsage: CompletionUsage;+ context: ContextMessage[];+}++export type AgentContextProcessorOverwriteContext = Omit<ThreadOverwriteContextEvent, 'thread_id'>;++export type AgentContextProcessorAppendContext = Omit<AgentThreadAppendContext, 'thread_id'>;++/** Processors omit thread_id — AgentThread stamps it (same as append/overwrite). */+export type AgentContextProcessorCapabilityState = Omit<InternalCapabilityStateEvent, 'thread_id'>;++export type AgentContextProcessorOutput =+ | AgentContextProcessorOverwriteContext+ | AgentContextProcessorAppendContext+ | InternalPassthroughEvent+ | AgentContextProcessorCapabilityState;++export interface PreSendContextProcessor {+ processPreSend(execution: Readonly<AgentThreadExecutionContext>): AsyncIterable<AgentContextProcessorAppendContext>;+}++// NOTE: Saved in Redis, Saved in AgentThread in memory. Persisted accross Agent Loop.+export interface PreLLMAgentContextProcessor {+ processPreLLM(execution: Readonly<AgentThreadExecutionContext>): AsyncIterable<AgentContextProcessorOutput>;+}++export interface PostToolCallAgentContextProcessor {+ processPostToolCall(execution: Readonly<AgentThreadExecutionContext>): AsyncIterable<AgentContextProcessorOutput>;+}++// NOTE: Not saved in Redis, Not saved in AgentThread in memory. Not persisted accross Agent Loop.+export interface PreLLMEphemeralAgentContextProcessor {+ processPreLLMEphemeral(input: ChatCompletionMessageParam[]): ChatCompletionMessageParam[] | undefined;+}diff --git a/packages/harness/src/core/capabilities/ToolResponseProcessor.ts b/packages/harness/src/core/capabilities/ToolResponseProcessor.tsnew file mode 100644index 000000000..71d78e552--- /dev/null+++ b/packages/harness/src/core/capabilities/ToolResponseProcessor.ts@@ -0,0 +1,16 @@+import type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';+import type { ToolCallResult } from '../mcp/executeToolCalls';+import type { SandboxInfo } from '../sandbox/Sandbox';+import type { AgentThreadExecutionContext } from './AgentContextProcessor';++export interface ToolResponseProcessorResult {+ sandboxCreated?: SandboxInfo | undefined;+ events?: readonly RegisteredPassthroughEvent[] | undefined;+}++export interface ToolResponseProcessor {+ process(+ result: ToolCallResult[],+ execution: Readonly<AgentThreadExecutionContext>,+ ): Promise<ToolResponseProcessorResult>;+}diff --git a/packages/harness/src/core/capabilities/builtins/AskUserQuestion.ts b/packages/harness/src/core/capabilities/builtins/AskUserQuestion.tsnew file mode 100644index 000000000..3b5fa134c--- /dev/null+++ b/packages/harness/src/core/capabilities/builtins/AskUserQuestion.ts@@ -0,0 +1,72 @@+import { z } from 'zod';+import { ClientSideTool } from '../../mcp/ClientSideTool';+import { toolResultResponse } from '../../mcp/IMCPServer';+import { defineTool, type ToolDefinition } from '../../mcp/LocalToolMCP';+import type { AgentCapability } from '../AgentCapability';+import { OPENUI_SECTION_TAG } from './OpenUI';++const ASK_USER_QUESTION_SERVER_ID = 'ask-user-question';+const ASK_USER_QUESTION_TOOL_NAME = 'ask_user_question';++const askUserQuestionInputSchema = z.object({+ question: z.string().describe('The question to ask the user.'),+ options: z+ .array(z.string())+ .min(0)+ .max(5)+ .describe(+ '0-5 mutually exclusive choices, each mapping to a distinct outcome. A free-text input is always rendered alongside.',+ ),+});++export class AskUserQuestion extends ClientSideTool {+ readonly name = ASK_USER_QUESTION_SERVER_ID;+ readonly displayName = 'AskUserQuestion';+ override readonly tracingEnabled = false;++ constructor() {+ super();+ }++ protected getTools(): ToolDefinition[] {+ return [+ defineTool({+ name: ASK_USER_QUESTION_TOOL_NAME,+ description: [+ 'Ask the user a question when clarification or a decision is needed before proceeding. Only ask when the answer meaningfully changes what you do next.',+ '',+ 'Rules:',+ '- Provide as many options as the question needs (0-5). When you include options, each must be a genuinely distinct, mutually exclusive outcome that meaningfully changes what you do next.',+ `- MUST NOT use <${OPENUI_SECTION_TAG}> for asking the user a question.`,+ '- The user picks exactly one option — multi-select is not available.',+ '- Options must be mutually exclusive. If a valid choice is a combination of other options, include it as a separate option with the combined data.',+ '- Every option must commit the user to a specific outcome. Do not add an option whose purpose is to let the user describe, specify, or type their own answer. Do not add an option like "Other" or "Something else".',+ '',+ 'Example (distinct options):',+ 'question: "<your question>"',+ 'options: ["<Option A>", "<Option B>", "<Option C>"]',+ '',+ 'Example (combined options):',+ 'question: "<your question>"',+ 'options: ["<Option A>", "<Option B>", "<Option A and B — combined details>"]',+ '',+ 'Avoid:',+ 'options: ["<Option A>", "<Option B>", "Other"]',+ ].join('\n'),+ schema: askUserQuestionInputSchema,+ handler: async () => {+ return toolResultResponse({+ text: 'This tool requires client-side execution and cannot be run server-side.',+ isError: true,+ });+ },+ }),+ ];+ }+}++export function askUserQuestion(): AgentCapability {+ return {+ systemToolSets: [new AskUserQuestion()],+ };+}diff --git a/packages/harness/src/core/capabilities/builtins/ContextCompaction.ts b/packages/harness/src/core/capabilities/builtins/ContextCompaction.tsnew file mode 100644index 000000000..a5a3dead2--- /dev/null+++ b/packages/harness/src/core/capabilities/builtins/ContextCompaction.ts@@ -0,0 +1,232 @@+import type { ChatCompletionCreateParams } from 'openai/resources/chat';+import { EventType, newEventId } from '../../events/eventSchemas';+import type { ILLM } from '../../llm/ILLM';+import type { AgentDefinition } from '../../runtime/AgentDefinition';+import type { ContextMessage } from '../../runtime/AgentThread.types';+import { internalSystemMessage, isInternalSystemMessage, isLLMContextMessage } from '../../runtime/contextUtils';+import type { AgentCapability } from '../AgentCapability';+import type {+ AgentContextProcessorOutput,+ AgentThreadExecutionContext,+ PreLLMAgentContextProcessor,+} from '../AgentContextProcessor';++export const DEFAULT_CONTEXT_COMPACTION_THRESHOLD_TOKENS = 50 * 1000;++// https://platform.openai.com/tokenizer+const PROMPT_TOKENS = 931;+const PROMPT = `+Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.+This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.++Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:++1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:+ - The user's explicit requests and intents+ - Your approach to addressing the user's requests+ - Key decisions, technical concepts and code patterns+ - Specific details like:+ - file names+ - full code snippets+ - function signatures+ - file edits+ - Errors that you ran into and how you fixed them+ - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.+2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.++Your summary should include the following sections:++1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail+2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.+3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.+4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.+5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.+6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.+6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.+7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.+8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.+ If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.++Here's an example of how your output should be structured:++<example>+<analysis>+[Your thought process, ensuring all points are covered thoroughly and accurately]+</analysis>++<summary>+1. Primary Request and Intent:+ [Detailed description]++2. Key Technical Concepts:+ - [Concept 1]+ - [Concept 2]+ - [...]+++3. Errors and fixes:+ - [Detailed description of error 1]:+ - [How you fixed the error]+ - [User feedback on the error if any]+ - [...]++4. Problem Solving:+ [Description of solved problems and ongoing troubleshooting]++5. All user messages:+ - [Detailed non tool use user message]+ - [...]++6. Pending Tasks:+ - [Task 1]+ - [Task 2]+ - [...]++7. Current Work:+ [Precise description of current work]++8. Optional Next Step:+ [Optional Next step to take]++</summary>+</example>++Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.++There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:+<example>+## Compact Instructions+When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.+</example>++<example>+# Summary instructions+When you are using compact - please focus on test output and code changes. Include file reads verbatim.+</example>+`;++const CONTINUATION_MESSAGE = internalSystemMessage(+ 'The above is the summarised context of the work so far. The Agent must not repeat or re-run any work that was already completed. If results were already obtained, the Agent should present them directly.',+);+Object.freeze(CONTINUATION_MESSAGE);+// https://platform.openai.com/tokenizer+const CONTINUATION_MESSAGE_TOKENS = 42;++function createSummarizationCandidate(context: ContextMessage[]) {+ let candidate = '';+ let index = -1;+ for (const m of context) {+ index += 1;+ if (isInternalSystemMessage(m)) {+ continue;+ }+ if (!isLLMContextMessage(m)) {+ continue;+ }+ switch (m.role) {+ case 'user':+ if (typeof m.content === 'string') {+ candidate += `<${index}><user>:` + m.content;+ } else {+ const parts: string[] = [];+ for (const p of m.content) {+ if (p.type === 'text') {+ parts.push(p.text);+ } else {+ parts.push(`[user attached a ${p.type} here, no longer available after summarization]`);+ }+ }+ candidate += `<${index}><user>:` + parts.join('\n');+ }+ break;+ case 'tool':+ candidate += `<${index}><tool-response id=${m.tool_call_id}>:` + m.content;+ break;+ case 'assistant':+ for (const block of m.thinking_blocks ?? []) {+ if (block.type === 'thinking') {+ candidate += `<${index}><assistant-thinking>:` + block.thinking;+ }+ }+ candidate += `<${index}><assistant>:` + m.content;+ for (const t of m.tool_calls ?? []) {+ candidate += `<tool-call id=${t.id} name=${t.function.name}>:` + t.function.arguments;+ }+ }+ }+ return candidate;+}++export class ContextCompaction implements PreLLMAgentContextProcessor {+ private model: string;+ private modelClient: ILLM;+ private compactionThresholdTokens: number;++ constructor(input: { model: string; modelClient: ILLM; compactionThresholdTokens: number }) {+ this.model = input.model;+ this.modelClient = input.modelClient;+ this.compactionThresholdTokens = input.compactionThresholdTokens;+ }++ async *processPreLLM(+ execution: Readonly<AgentThreadExecutionContext>,+ ): AsyncGenerator<AgentContextProcessorOutput, void, unknown> {+ if (execution.currentContextUsage.total_tokens + PROMPT_TOKENS < this.compactionThresholdTokens) {+ return;+ }++ const body: ChatCompletionCreateParams = {+ model: this.model,+ messages: [+ { role: 'user', content: createSummarizationCandidate(execution.context) },+ { role: 'user', content: PROMPT },+ ],+ stream: false,+ };++ const response = await this.modelClient.createNonStream(body);+ const context: ContextMessage[] = [{ role: 'assistant', content: response.output.content }, CONTINUATION_MESSAGE];++ yield {+ type: EventType.AGENT_CONTEXT_OVERWRITE,+ id: newEventId(),+ created_at: new Date().toISOString(),+ reason: 'compaction',+ context: context,+ current_context_usage: {+ total_tokens: response.usage.total_tokens + CONTINUATION_MESSAGE_TOKENS,+ // NOTE(agent): This is not really correct.+ // This is not taking into account that the original request had+ // tool definition in them.+ // This will get refreshed in the next LLM call.+ prompt_tokens: response.usage.prompt_tokens + CONTINUATION_MESSAGE_TOKENS,+ completion_tokens: 0,+ },+ compaction_llm_usage: response.usage,+ };+ }+}++export interface ContextCompactionSettings {+ compactionThresholdTokens?: number | undefined;+}++export function contextCompaction(options: {+ definition: AgentDefinition;+ settings?: ContextCompactionSettings | undefined;+ compactionThresholdTokens?: number | undefined;+}): AgentCapability {+ const threshold =+ options.compactionThresholdTokens ??+ options.settings?.compactionThresholdTokens ??+ DEFAULT_CONTEXT_COMPACTION_THRESHOLD_TOKENS;+ return {+ preLLMProcessors: [+ new ContextCompaction({+ model: options.definition.model,+ modelClient: options.definition.modelClient,+ compactionThresholdTokens: threshold,+ }),+ ],+ };+}diff --git a/packages/harness/src/core/capabilities/builtins/CurrentDateTime.ts b/packages/harness/src/core/capabilities/builtins/CurrentDateTime.tsnew file mode 100644index 000000000..249806e4e--- /dev/null+++ b/packages/harness/src/core/capabilities/builtins/CurrentDateTime.ts@@ -0,0 +1,49 @@+import { z } from 'zod';+import { type CallToolResponse, toolResultResponse } from '../../mcp/IMCPServer';+import { defineTool, LocalToolMCP, type ToolDefinition } from '../../mcp/LocalToolMCP';+import type { AgentTracing } from '../../tracing/AgentTracing';+import type { AgentCapability } from '../AgentCapability';++export const CURRENT_DATETIME_SERVER_ID = 'current-datetime';+export const GET_CURRENT_DATETIME_TOOL_NAME = 'get_current_datetime';++const inputSchema = z.object({}).strict();++export class CurrentDateTime extends LocalToolMCP {+ readonly name = CURRENT_DATETIME_SERVER_ID;+ readonly displayName = 'CurrentDateTime';++ constructor(tracing: AgentTracing) {+ super({ tracing });+ }++ private tools: ToolDefinition[] = [+ defineTool({+ name: GET_CURRENT_DATETIME_TOOL_NAME,+ description: 'Returns the current datetime in ISO-8601 (UTC) and unix epoch MS format.',+ schema: inputSchema,+ handler: async () => this.getCurrentDateTime(),+ }),+ ];++ protected getTools(): ToolDefinition[] {+ return this.tools;+ }++ // Date.prototype.toISOString() is spec-guaranteed to return UTC (suffix 'Z').+ // Date.prototype.getTime() returns UTC epoch ms regardless of process timezone.+ private getCurrentDateTime(): CallToolResponse {+ const now = new Date();+ const payload = {+ unixEpochMS: now.getTime(),+ iso: now.toISOString(),+ };+ return toolResultResponse({ text: JSON.stringify(payload) });+ }+}++export function currentDateTime(options: { tracing: AgentTracing }): AgentCapability {+ return {+ systemToolSets: [new CurrentDateTime(options.tracing)],+ };+}diff --git a/packages/harness/src/core/capabilities/builtins/DynamicSubAgents.ts b/packages/harness/src/core/capabilities/builtins/DynamicSubAgents.tsnew file mode 100644index 000000000..e06c845b8--- /dev/null+++ b/packages/harness/src/core/capabilities/builtins/DynamicSubAgents.ts@@ -0,0 +1,159 @@+import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import dedent from 'dedent';+import { z } from 'zod';+import { InstructionBuilder } from '../../InstructionBuilder';+import type { InternalToolCallInfo } from '../../llm/LLMTypes';+import { defineTool, LocalToolMCP, type ToolDefinition } from '../../mcp/LocalToolMCP';+import type { AgentTracing } from '../../tracing/AgentTracing';+import type { AgentCapability } from '../AgentCapability';++export const SUB_AGENT_TOOL_NAME = 'create_sub_agent';+export const SUB_AGENTS_SERVER_ID = 'sub_agents';+export const SUB_AGENTS_REMINDER_TAG = 'sub-agents';++export const SUB_AGENT_IDENTITY =+ 'You are the Agent operating as a sub-agent that has been delegated a specific task. The Agent has access to the same tools as the parent agent. The Agent must focus on completing the delegated task and return a concise result. The Agent cannot ask questions to the user.';++export interface ModelSetEntry {+ description: string;+ model_params?: Record<string, unknown> | undefined;+}++export type ModelSetConfig = Record<string, ModelSetEntry>;++export function createDynamicSubAgentLargeToolResponseGuidance(): string {+ return dedent`+ For large unstructured output like web search, documentation lookup, or broad search results,+ the Agent should prefer delegating to a sub-agent and ask it to return only the relevant summary, with citations+ when they improve verification.`;+}++export function buildDynamicSubAgentsInstruction(+ builder: InstructionBuilder,+ params: { sandboxAvailable: boolean },+): void {+ const sandboxGuidance = params.sandboxAvailable+ ? dedent`+ When both sub-agents and sandbox are available, the Agent should always use sandbox code for mechanical data processing.+ The Agent should use sub-agents for tasks that return large unstructured text (e.g. web search, documentation lookup) or+ where multi-step reasoning is needed to process and summarize the results.`+ : '';++ const paragraphs = [+ dedent`The Agent can create sub-agents using the ${SUB_AGENT_TOOL_NAME} tool. Sub-agents are best for tasks that involve one or more tool calls that would fill up the context window or are blocked due to "Large Tool Response",+ or tasks requiring exploration and reasoning that can be clearly delegated.`,+ createDynamicSubAgentLargeToolResponseGuidance(),+ ...(sandboxGuidance ? [sandboxGuidance] : []),+ dedent`The Agent should ask the sub-agent to include references or citations when they would improve reliability or make+ verification easier.`,+ ];++ builder.addSection(SUB_AGENTS_REMINDER_TAG, paragraphs.join('\n\n').trim());+}++export class DynamicSubAgents extends LocalToolMCP {+ readonly name = SUB_AGENTS_SERVER_ID;+ readonly displayName = 'DynamicSubAgents';+ override readonly tracingEnabled = false;+ private tools: ToolDefinition[];++ private getCreateSubAgentDescription(modelSetConfig?: ModelSetConfig): string {+ let modelSetGuidance = '';+ const modelSetModels = modelSetConfig ? Object.keys(modelSetConfig) : [];+ if (modelSetConfig && modelSetModels.length > 0) {+ const modelList = Object.entries(modelSetConfig)+ .map(([key, entry]) => `- [${key}]: ${entry.description}`)+ .join('\n');+ modelSetGuidance = dedent`+ Pick a suitable model for the task being delegated from the following list of models and their descriptions:+ ${modelList}+ `;+ }++ const paragraphs = [+ `Delegate a well-defined task to a sub-agent. The Agent must not delegate the whole work to the sub-agent.`,+ `The sub-agent has access to the same tools and the same sandbox environment as the parent Agent. Files created or modified by either agent are shared and remain available to both.`,+ ...(modelSetGuidance ? [modelSetGuidance] : []),+ `The sub-agent has NO access to the prior conversation or the user's original message. The Agent must provide a clear, self-contained instruction that includes all necessary context, the exact task to perform, any constraints, what outputs are expected, and what work has already been completed so effort is not duplicated.`,+ ];++ return paragraphs.join('\n\n').trim();+ }++ private getCreateSubAgentTool(modelSetConfig?: ModelSetConfig): ToolDefinition {+ const modelKeys = Object.keys(modelSetConfig ?? {});+ if (modelKeys.length > 0) {+ return defineTool({+ name: SUB_AGENT_TOOL_NAME,+ description: this.getCreateSubAgentDescription(modelSetConfig),+ schema: z.object({+ name: z.string().min(1),+ input: z.string().min(1),+ model: z.enum(modelKeys as [string, ...string[]]),+ }),+ handler: async input => ({+ createSubAgent: {+ type: 'dynamic',+ name: input.name,+ input: input.input,+ model: input.model,+ },+ }),+ });+ }+ return defineTool({+ name: SUB_AGENT_TOOL_NAME,+ description: this.getCreateSubAgentDescription(modelSetConfig),+ schema: z.object({+ name: z.string().min(1),+ input: z.string().min(1),+ }),+ handler: async input => ({+ createSubAgent: {+ type: 'dynamic',+ name: input.name,+ input: input.input,+ },+ }),+ });+ }++ constructor({ modelSetConfig, tracing }: { modelSetConfig?: ModelSetConfig; tracing: AgentTracing }) {+ super({ tracing });+ this.tools = [this.getCreateSubAgentTool(modelSetConfig)];+ }++ protected getTools(): ToolDefinition[] {+ return this.tools;+ }++ override async toolCallInfo(+ params: CallToolRequest['params'],+ _resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ return {+ type: 'truefoundry-system',+ mcp_server_id: this.mcpServerId,+ mcp_server_name: this.name,+ original_tool_name: params.name,+ is_approval_required: false,+ is_thread_creation: true,+ };+ }+}++export function dynamicSubAgents(options: {+ modelSetConfig?: ModelSetConfig | undefined;+ sandboxAvailable: boolean;+ tracing: AgentTracing;+}): AgentCapability {+ const toolSet = new DynamicSubAgents({ ...(options.modelSetConfig !== undefined ? { modelSetConfig: options.modelSetConfig } : {}), tracing: options.tracing });+ return {+ systemToolSets: [toolSet],+ instructionBuilders: [+ builder => {+ buildDynamicSubAgentsInstruction(builder, { sandboxAvailable: options.sandboxAvailable });+ },+ ],+ };+}diff --git a/packages/harness/src/core/capabilities/builtins/LargeToolResponse.ts b/packages/harness/src/core/capabilities/builtins/LargeToolResponse.tsnew file mode 100644index 000000000..28fa5f0c4--- /dev/null+++ b/packages/harness/src/core/capabilities/builtins/LargeToolResponse.ts@@ -0,0 +1,234 @@+import dedent from 'dedent';+import type { Logger } from 'winston';+import { estimateTokensForString } from '../../llm/usage';+import type { ToolCallResult } from '../../mcp/executeToolCalls';+import type { Sandbox, SandboxInfo } from '../../sandbox/Sandbox';+import { createSandboxLargeToolResponseGuidance, SANDBOX_SCHEMA_INFER_TAG } from '../../sandbox/Sandbox';+import { extractErrorLogFields } from '../../util/errorLogFields';+import type { AgentCapability } from '../AgentCapability';+import type { AgentThreadExecutionContext } from '../AgentContextProcessor';+import type { ToolResponseProcessor, ToolResponseProcessorResult } from '../ToolResponseProcessor';+import { createDynamicSubAgentLargeToolResponseGuidance } from './DynamicSubAgents';++export const DEFAULT_INDIVIDUAL_TOOL_TOKEN_THRESHOLD = 6000;+export const DEFAULT_TOTAL_TOOL_TOKEN_THRESHOLD = 10000;+export const DEFAULT_PREVIEW_NUMBER_OF_CHARACTERS = 100;+const FAILURE_MESSAGE_TRUNCATION_LENGTH = 500;++type ResultCategory = 'failure' | 'sandbox' | 'mcp';++interface ToolResultWithInfo {+ toolCallResult: ToolCallResult;+ originalContent: string;+ originalTokens: number;+ category: ResultCategory;+}++function categorize(result: ToolCallResult, sandbox: Sandbox | undefined): ResultCategory {+ if (result.failure) return 'failure';+ if (!result.info) {+ throw new Error(`Unreachable`);+ }+ if (sandbox && result.info.toolSet === sandbox) return 'sandbox';+ return 'mcp';+}++function createContentPreview(content: string, previewChars: number): string {+ if (content.length <= previewChars * 2) {+ return content;+ }+ return `${content.slice(0, previewChars)}\n...\n${content.slice(-previewChars)}`;+}++export class LargeToolResponseProcessor implements ToolResponseProcessor {+ private dynamicSubAgentsPresent: boolean;+ private individualTokenThreshold: number;+ private totalTokenThreshold: number;+ private previewNumberOfCharacters: number;+ private readonly logger: Logger;++ constructor(param: {+ dynamicSubAgentsPresent: boolean;+ individualTokenThreshold: number;+ totalTokenThreshold: number;+ previewNumberOfCharacters: number;+ logger: Logger;+ }) {+ if (param.individualTokenThreshold > param.totalTokenThreshold) {+ throw new Error(+ `individualTokenThreshold (${param.individualTokenThreshold}) must be <= totalTokenThreshold (${param.totalTokenThreshold})`,+ );+ }+ this.dynamicSubAgentsPresent = param.dynamicSubAgentsPresent;+ this.individualTokenThreshold = param.individualTokenThreshold;+ this.totalTokenThreshold = param.totalTokenThreshold;+ this.previewNumberOfCharacters = param.previewNumberOfCharacters ?? DEFAULT_PREVIEW_NUMBER_OF_CHARACTERS;+ this.logger = param.logger.child({ module: 'LargeToolResponse' });+ }++ private createLargeToolResponseGuidance(sandbox: Sandbox | undefined): string {+ const steps = ['Check if some parameter can be passed in order to reduce the output size.'];++ if (sandbox) {+ steps.push(createSandboxLargeToolResponseGuidance());+ }++ if (this.dynamicSubAgentsPresent) {+ steps.push(createDynamicSubAgentLargeToolResponseGuidance());+ }++ return `Content too big. To handle a large tool call the Agent can do the following:\n${steps+ .map((step, index) => `${index + 1}. ${step}`)+ .join('\n')}`;+ }++ private createFileDumpMessage(params: { filePath: string; preview: string }): string {+ const { filePath, preview } = params;+ const steps: string[] = [+ dedent`Use sandbox to read parts of the file or extract data.+ Use ${SANDBOX_SCHEMA_INFER_TAG} to undertand the schema.`,+ ];++ if (this.dynamicSubAgentsPresent) {+ steps.push(+ `${createDynamicSubAgentLargeToolResponseGuidance()} The Agent must pass file path to sub-agent also.`,+ );+ }++ const guidance = `The Agent can do the following to handle it:\n${steps+ .map((step, index) => `${index + 1}. ${step}`)+ .join('\n')}`;++ return `Content too large. Result saved to: ${filePath}.\n\n${guidance}\n\nPreview (first and last ${this.previewNumberOfCharacters} chars):\n${preview}`;+ }++ private buildResultsWithInfo(results: ToolCallResult[], sandbox: Sandbox | undefined): ToolResultWithInfo[] {+ return results.map(toolCallResult => ({+ toolCallResult,+ originalContent: toolCallResult.message.content,+ originalTokens: estimateTokensForString(toolCallResult.message.content),+ category: categorize(toolCallResult, sandbox),+ }));+ }++ private blockResult(+ entry: ToolResultWithInfo,+ pendingSandboxDumps: ToolResultWithInfo[],+ sandbox: Sandbox | undefined,+ ): number {+ const preview = createContentPreview(entry.originalContent, this.previewNumberOfCharacters);++ let newContent: string;+ switch (entry.category) {+ case 'failure':+ newContent = entry.originalContent.slice(0, FAILURE_MESSAGE_TRUNCATION_LENGTH);+ break;+ case 'sandbox':+ newContent = `Content too big. The Agent should write to a file if required and use grep and sed.\n\nPreview:\n${preview}`;+ break;+ case 'mcp':+ newContent = `${this.createLargeToolResponseGuidance(sandbox)}\n\nPreview (first and last ${this.previewNumberOfCharacters} chars):\n${preview}`;+ if (sandbox) {+ pendingSandboxDumps.push(entry);+ }+ break;+ }++ entry.toolCallResult.message.content = newContent;+ entry.toolCallResult.isStructuredContent = false;+ return Math.max(0, entry.originalTokens - estimateTokensForString(newContent));+ }++ private async uploadToSandboxAndPrependFilePath(+ entry: ToolResultWithInfo,+ index: number,+ sandbox: Sandbox,+ ): Promise<SandboxInfo | undefined> {+ if (!entry.toolCallResult.info) {+ throw new Error(`Unreachable`);+ }+ const sanitizedName = entry.toolCallResult.info.originalToolName.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 40);+ const epoch = Date.now();+ const fileName = `${sanitizedName}_${index}_${epoch}.txt`;+ try {+ const stored = await sandbox.writeArtifact({+ fileName,+ content: Buffer.from(entry.originalContent),+ sourceTool: entry.toolCallResult.info,+ });+ const preview = createContentPreview(entry.originalContent, this.previewNumberOfCharacters);+ entry.toolCallResult.message.content = this.createFileDumpMessage({ filePath: stored.filePath, preview });+ entry.toolCallResult.isStructuredContent = false;+ return stored.sandboxCreated;+ } catch (error) {+ this.logger.error('Failed to upload to sandbox', extractErrorLogFields(error));+ return undefined;+ }+ }++ private async executeSandboxDumps(entries: ToolResultWithInfo[], sandbox: Sandbox): Promise<SandboxInfo | undefined> {+ const results = await Promise.all(+ entries.map((entry, index) => this.uploadToSandboxAndPrependFilePath(entry, index, sandbox)),+ );+ return results.find(r => r !== undefined);+ }++ async process(+ results: ToolCallResult[],+ execution: Readonly<AgentThreadExecutionContext>,+ ): Promise<ToolResponseProcessorResult> {+ const sandbox = execution.sandbox;+ const resultsWithInfo = this.buildResultsWithInfo(results, sandbox);+ let runningTotal = resultsWithInfo.reduce((sum, e) => sum + e.originalTokens, 0);++ if (runningTotal < this.individualTokenThreshold) {+ return {};+ }++ const pendingSandboxDumps: ToolResultWithInfo[] = [];++ const unblocked: ToolResultWithInfo[] = [];+ for (const entry of resultsWithInfo) {+ if (entry.originalTokens >= this.individualTokenThreshold) {+ runningTotal -= this.blockResult(entry, pendingSandboxDumps, sandbox);+ } else {+ unblocked.push(entry);+ }+ }++ const sortedUnblocked = [...unblocked].sort((a, b) => b.originalTokens - a.originalTokens);+ for (const entry of sortedUnblocked) {+ if (runningTotal < this.totalTokenThreshold) {+ break;+ }+ runningTotal -= this.blockResult(entry, pendingSandboxDumps, sandbox);+ }++ const sandboxCreated = sandbox ? await this.executeSandboxDumps(pendingSandboxDumps, sandbox) : undefined;+ return sandboxCreated !== undefined ? { sandboxCreated } : {};+ }+}++export interface LargeToolResponseSettings {+ individualTokenThreshold?: number | undefined;+ totalTokenThreshold?: number | undefined;+ previewNumberOfCharacters?: number | undefined;+}++export function largeToolResponse(options: {+ dynamicSubAgentsPresent: boolean;+ settings?: LargeToolResponseSettings | undefined;+ logger: Logger;+}): AgentCapability {+ return {+ toolResponseProcessors: [+ new LargeToolResponseProcessor({+ dynamicSubAgentsPresent: options.dynamicSubAgentsPresent,+ individualTokenThreshold: options.settings?.individualTokenThreshold ?? DEFAULT_INDIVIDUAL_TOOL_TOKEN_THRESHOLD,+ totalTokenThreshold: options.settings?.totalTokenThreshold ?? DEFAULT_TOTAL_TOOL_TOKEN_THRESHOLD,+ previewNumberOfCharacters: options.settings?.previewNumberOfCharacters ?? DEFAULT_PREVIEW_NUMBER_OF_CHARACTERS,+ logger: options.logger,+ }),+ ],+ };+}diff --git a/packages/harness/src/core/capabilities/builtins/OpenUI.ts b/packages/harness/src/core/capabilities/builtins/OpenUI.tsnew file mode 100644index 000000000..92df79603--- /dev/null+++ b/packages/harness/src/core/capabilities/builtins/OpenUI.ts@@ -0,0 +1,258 @@+import dedent from 'dedent';+import { InstructionBuilder } from '../../InstructionBuilder';+import type { AgentCapability } from '../AgentCapability';++export const OPENUI_SECTION_TAG = 'openui';+export const OPENUI_MARKDOWN_FENCING_TAG = 'openui-markdown-fencing';+export const OPENUI_SYNTAX_RULES_TAG = 'openui-syntax-rules';+export const OPENUI_COMPONENT_SIGNATURES_TAG = 'openui-component-signatures';+export const OPENUI_BUILTIN_FUNCTIONS_TAG = 'openui-builtin-functions';+export const OPENUI_HOISTING_AND_STREAMING_TAG = 'openui-hoisting-and-streaming';+export const OPENUI_EXAMPLES_TAG = 'openui-examples';+export const OPENUI_IMPORTANT_RULES_TAG = 'openui-important-rules';+export const OPENUI_FINAL_VERIFICATION_TAG = 'openui-final-verification';+export const OPENUI_USER_INTERACTION_CHECKLIST_TAG = 'openui-user-interaction-checklist';++export function buildOpenUIInstruction(builder: InstructionBuilder): void {+ const openui = builder.beginSection(OPENUI_SECTION_TAG);++ openui.addSection(+ OPENUI_MARKDOWN_FENCING_TAG,+ dedent`+ All openui, code must be fenced within openui block.+ \`\`\`openui+ code+ \`\`\``,+ );++ openui.addSection(+ OPENUI_SYNTAX_RULES_TAG,+ dedent`+ 1. Each statement is on its own line: \`identifier = Expression\`+ 2. \`root\` is the entry point — every program must define \`root = Stack(...)\`+ 3. Expressions are: strings ("..."), numbers, booleans (true/false), null, arrays ([...]), objects ({...}), or component calls TypeName(arg1, arg2, ...)+ 4. Use references for readability: define \`name = ...\` on one line, then use \`name\` later+ 5. EVERY variable (except root) MUST be referenced by at least one other variable. Unreferenced variables are silently dropped and will NOT render. Always include defined variables in their parent's children/items array.+ 6. Arguments are POSITIONAL (order matters, not names). Write \`Stack([children], "row", "l")\` NOT \`Stack([children], direction: "row", gap: "l")\` — colon syntax is NOT supported and silently breaks+ 7. Optional arguments can be omitted from the end+ - Strings use double quotes with backslash escaping`,+ );++ openui.addSection(+ OPENUI_COMPONENT_SIGNATURES_TAG,+ dedent`+ Arguments marked with ? are optional. Sub-components can be inline or referenced; prefer references for better streaming.+ Props typed \`ActionExpression\` accept an Action([@steps...]) expression. See the Action section for available steps (@ToAssistant, @OpenUrl).+ Props marked \`$binding<type>\` accept a \`$variable\` reference for two-way binding.++ Layout:+ Stack([children], direction?: "row" | "column", gap?: "none" | "xs" | "s" | "m" | "l" | "xl" | "2xl", align?: "start" | "center" | "end" | "stretch" | "baseline", justify?: "start" | "center" | "end" | "between" | "around" | "evenly", wrap?: boolean) — Flex container. direction: "row"|"column" (default "column"). gap: "none"|"xs"|"s"|"m"|"l"|"xl"|"2xl" (default "m"). align: "start"|"center"|"end"|"stretch"|"baseline". justify: "start"|"center"|"end"|"between"|"around"|"evenly".+ Tabs(items: TabItem[]) — Tabbed container+ TabItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is tab label, content is array of components+ Accordion(items: AccordionItem[]) — Collapsible sections+ AccordionItem(value: string, trigger: string, content: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[]) — value is unique id, trigger is section title+ Steps(items: StepsItem[]) — Step-by-step guide+ StepsItem(title: string, details: string) — title and details text for one step+ Carousel(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[][], variant?: "card" | "sunk") — Horizontal scrollable carousel+ Separator(orientation?: "horizontal" | "vertical", decorative?: boolean) — Visual divider between content sections+ Modal(title: string, open?: $binding<boolean>, children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps)[], size?: "sm" | "md" | "lg") — Modal dialog. open is a reactive $boolean binding — set to true to open, X/Escape/backdrop auto-closes. Put Form with buttons inside children.+ - For grid-like layouts, use Stack with direction "row" and wrap set to true.+ - Prefer justify "start" (or omit justify) with wrap=true for stable columns instead of uneven gutters.+ - Use nested Stacks when you need explicit rows/sections.+ - Show/hide sections: $editId != "" ? Card([editForm]) : null+ - Modal: Modal("Title", $showModal, [content]) — $showModal is boolean, X/Escape auto-closes. Put Form with its own buttons inside children.+ - Use Tabs for alternative views (chart types, data sections) — no $variable needed+ - Shared filter across Tabs: same $days binding in Query args works across all TabItems++ Content:+ Card(children: (TextContent | MarkDownRenderer | CardHeader | Callout | TextCallout | CodeBlock | Image | ImageBlock | ImageGallery | Separator | HorizontalBarChart | RadarChart | PieChart | RadialChart | SingleStackedBarChart | ScatterChart | AreaChart | BarChart | LineChart | Table | TagBlock | Form | Buttons | Steps | Tabs | Carousel | Stack)[], variant?: "card" | "sunk" | "clear", direction?: "row" | "column", gap?: "none" | "xs" | "s" | "m" | "l" | "xl" | "2xl", align?: "start" | "center" | "end" | "stretch" | "baseline", justify?: "start" | "center" | "end" | "between" | "around" | "evenly", wrap?: boolean) — Styled container. variant: "card" (default, elevated) | "sunk" (recessed) | "clear" (transparent). Always full width. Accepts all Stack flex params (default: direction "column"). Cards flex to share space in row/wrap layouts.+ CardHeader(title?: string, subtitle?: string) — Header with optional title and subtitle+ TextContent(text: string, size?: "small" | "default" | "large" | "small-heavy" | "large-heavy") — Text block. Supports markdown. Optional size: "small" | "default" | "large" | "small-heavy" | "large-heavy".+ MarkDownRenderer(textMarkdown: string, variant?: "clear" | "card" | "sunk") — Renders markdown text with optional container variant+ Callout(variant: "info" | "warning" | "error" | "success" | "neutral", title: string, description: string, visible?: $binding<boolean>) — Callout banner. Optional visible is a reactive $boolean — auto-dismisses after 3s by setting $visible to false.+ TextCallout(variant?: "neutral" | "info" | "warning" | "success" | "danger", title?: string, description?: string) — Text callout with variant, title, and description+ Image(alt: string, src?: string) — Image with alt text and optional URL+ ImageBlock(src: string, alt?: string) — Image block with loading state+ ImageGallery(images: {src: string, alt?: string, details?: string}[]) — Gallery grid of images with modal preview+ CodeBlock(language: string, codeString: string) — Syntax-highlighted code block+ - Use Cards to group related KPIs or sections. Stack with direction "row" for side-by-side layouts.+ - Success toast: Callout("success", "Saved", "Done.", $showSuccess) — use @Set($showSuccess, true) in save action, auto-dismisses after 3s. For errors: result.status == "error" ? Callout("error", "Failed", result.error) : null+ - KPI card: Card([TextContent("Label", "small"), TextContent("" + @Count(@Filter(data.rows, "field", "==", "value")), "large-heavy")])++ Tables:+ Table(columns: Col[]) — Data table — column-oriented. Each Col holds its own data array.+ Col(label: string, data, type?: "string" | "number" | "action") — Column definition — holds label + data array+ - Table is COLUMN-oriented: Table([Col("Label", dataArray), Col("Count", countArray, "number")]). Use array pluck for data: data.rows.fieldName+ - Col data can be component arrays for styled cells: Col("Status", @Each(data.rows, "item", Tag(item.status, null, "sm", item.status == "open" ? "success" : "danger")))+ - Row actions: Col("Actions", @Each(data.rows, "t", Button("Edit", Action([@Set($showEdit, true), @Set($editId, t.id)]))))+ - Sortable: sorted = @Sort(data.rows, $sortField, "desc"). Bind $sortField to Select. Use sorted.fieldName for Col data+ - Searchable: filtered = @Filter(data.rows, "title", "contains", $search). Bind $search to Input+ - Chain sort + filter: filtered = @Filter(...) then sorted = @Sort(filtered, ...) — use sorted for both Table and Charts+ - Empty state: @Count(data.rows) > 0 ? Table([...]) : TextContent("No data yet")++ Charts (2D):+ BarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Vertical bars; use for comparing values across categories with one or more series+ LineChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Lines over categories; use for trends and continuous data over time+ AreaChart(labels: string[], series: Series[], variant?: "linear" | "natural" | "step", xLabel?: string, yLabel?: string) — Filled area under lines; use for cumulative totals or volume trends over time+ RadarChart(labels: string[], series: Series[]) — Spider/web chart; use for comparing multiple variables across one or more entities+ HorizontalBarChart(labels: string[], series: Series[], variant?: "grouped" | "stacked", xLabel?: string, yLabel?: string) — Horizontal bars; prefer when category labels are long or for ranked lists+ Series(category: string, values: number[]) — One data series+ - Charts accept column arrays: LineChart(labels, [Series("Name", values)]). Use array pluck: LineChart(data.rows.day, [Series("Views", data.rows.views)])+ - Use Cards to wrap charts with CardHeader for titled sections+ - Chart + Table from same source: use @Sort or @Filter result for both LineChart and Table Col data+ - Multiple chart views: use Tabs — Tabs([TabItem("line", "Line", [LineChart(...)]), TabItem("bar", "Bar", [BarChart(...)])])++ Charts (1D):+ PieChart(labels: string[], values: number[], variant?: "pie" | "donut") — Circular slices; use plucked arrays: PieChart(data.categories, data.values)+ RadialChart(labels: string[], values: number[]) — Radial bars; use plucked arrays: RadialChart(data.categories, data.values)+ SingleStackedBarChart(labels: string[], values: number[]) — Single horizontal stacked bar; use plucked arrays: SingleStackedBarChart(data.categories, data.values)+ Slice(category: string, value: number) — One slice with label and numeric value+ - PieChart and BarChart need NUMBERS, not objects. For list data, use @Count(@Filter(...)) to aggregate:+ - PieChart from list: \`PieChart(["Low", "Med", "High"], [@Count(@Filter(data.rows, "priority", "==", "low")), @Count(@Filter(data.rows, "priority", "==", "medium")), @Count(@Filter(data.rows, "priority", "==", "high"))], "donut")\`+ - KPI from count: \`TextContent("" + @Count(@Filter(data.rows, "status", "==", "open")), "large-heavy")\`++ Charts (Scatter):+ ScatterChart(datasets: ScatterSeries[], xLabel?: string, yLabel?: string) — X/Y scatter plot; use for correlations, distributions, and clustering+ ScatterSeries(name: string, points: Point[]) — Named dataset+ Point(x: number, y: number, z?: number) — Data point with numeric coordinates++ Data Display:+ TagBlock(tags: string[]) — tags is an array of strings+ Tag(text: string, icon?: string, size?: "sm" | "md" | "lg", variant?: "neutral" | "info" | "success" | "warning" | "danger") — Styled tag/badge with optional icon and variant+ - Color-mapped Tag: Tag(value, null, "sm", value == "high" ? "danger" : value == "medium" ? "warning" : "neutral")`,+ );++ openui.addSection(+ OPENUI_BUILTIN_FUNCTIONS_TAG,+ dedent`+ Data functions prefixed with \`@\` to distinguish from components. These are the ONLY functions available — do NOT invent new ones.+ Use @-prefixed built-in functions (@Count, @Sum, @Avg, @Min, @Max, @Round) on Query results — do NOT hardcode computed values.++ @Count(array) → number — Returns array length+ @First(array) → element — Returns first element of array+ @Last(array) → element — Returns last element of array+ @Sum(numbers[]) → number — Sum of numeric array+ @Avg(numbers[]) → number — Average of numeric array+ @Min(numbers[]) → number — Minimum value in array+ @Max(numbers[]) → number — Maximum value in array+ @Sort(array, field, direction?) → sorted array — Sort array by field. Direction: "asc" (default) or "desc"+ @Filter(array, field, operator: "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains", value) → filtered array — Filter array by field value+ @Round(number, decimals?) → number — Round to N decimal places (default 0)+ @Abs(number) → number — Absolute value+ @Floor(number) → number — Round down to nearest integer+ @Ceil(number) → number — Round up to nearest integer+ @Each(array, varName, template) — Evaluate template for each element. varName is the loop variable — use it ONLY inside the template expression (inline). Do NOT create a separate statement for the template.++ Builtins compose — output of one is input to the next:+ \`@Count(@Filter(data.rows, "field", "==", "val"))\` for KPIs/chart values, \`@Round(@Avg(data.rows.score), 1)\`, \`@Each(data.rows, "item", Comp(item.field))\` for per-item rendering.+ Array pluck: \`data.rows.field\` extracts a field from every row → use with @Sum, @Avg, charts, tables.++ IMPORTANT @Each rule: The loop variable (e.g. "item") is ONLY available inside the @Each template expression. Always inline the template — do NOT extract it to a separate statement.+ CORRECT: \`Col("Actions", @Each(rows, "t", Button("Edit", Action([@Set($id, t.id)]))))\`+ WRONG: \`myBtn = Button("Edit", Action([@Set($id, t.id)]))\` then \`Col("Actions", @Each(rows, "t", myBtn))\` — t is undefined in myBtn.`,+ );++ openui.addSection(+ OPENUI_HOISTING_AND_STREAMING_TAG,+ dedent`+ openui-lang supports hoisting: a reference can be used BEFORE it is defined. The parser resolves all references after the full input is parsed.++ During streaming, the output is re-parsed on every chunk. Undefined references are temporarily unresolved and appear once their definitions stream in. This creates a progressive top-down reveal — structure first, then data fills in.++ Recommended statement order for optimal streaming:+ 1. \`root = Stack(...)\` — UI shell appears immediately+ 2. $variable declarations — state ready for bindings+ 3. Query statements — defaults resolve immediately so components render with data+ 4. Component definitions — fill in with data already available+ 5. Data values — leaf content last++ Always write the root = Stack(...) statement first so the UI shell appears immediately, even before child data has streamed in.`,+ );++ openui.addSection(+ OPENUI_EXAMPLES_TAG,+ dedent`+ Example 1 — Table (column-oriented):++ root = Stack([title, tbl])+ title = TextContent("Top Languages", "large-heavy")+ tbl = Table([Col("Language", langs), Col("Users (M)", users), Col("Year", years)])+ langs = ["Python", "JavaScript", "Java", "TypeScript", "Go"]+ users = [15.7, 14.2, 12.1, 8.5, 5.2]+ years = [1991, 1995, 1995, 2012, 2009]++ Example 2 — Bar chart:++ root = Stack([title, chart])+ title = TextContent("Q4 Revenue", "large-heavy")+ chart = BarChart(labels, [s1, s2], "grouped")+ labels = ["Oct", "Nov", "Dec"]+ s1 = Series("Product A", [120, 150, 180])+ s2 = Series("Product B", [90, 110, 140])++ Example 3 — Form with validation:++ root = Stack([title, form])+ title = TextContent("Contact Us", "large-heavy")+ form = Form("contact", btns, [nameField, emailField, countryField, msgField])+ nameField = FormControl("Name", Input("name", "Your name", "text", { required: true, minLength: 2 }))+ emailField = FormControl("Email", Input("email", "[email protected]", "email", { required: true, email: true }))+ countryField = FormControl("Country", Select("country", countryOpts, "Select...", { required: true }))+ msgField = FormControl("Message", TextArea("message", "Tell us more...", 4, { required: true, minLength: 10 }))+ countryOpts = [SelectItem("us", "United States"), SelectItem("uk", "United Kingdom"), SelectItem("de", "Germany")]+ btns = Buttons([Button("Submit", Action([@ToAssistant("Submit")]), "primary"), Button("Cancel", Action([@ToAssistant("Cancel")]), "secondary")])++ Example 4 — Tabs with mixed content:++ root = Stack([title, tabs])+ title = TextContent("React vs Vue", "large-heavy")+ tabs = Tabs([tabReact, tabVue])+ tabReact = TabItem("react", "React", reactContent)+ tabVue = TabItem("vue", "Vue", vueContent)+ reactContent = [TextContent("React is a library by Meta for building UIs."), Callout("info", "Note", "React uses JSX syntax.")]+ vueContent = [TextContent("Vue is a progressive framework by Evan You."), Callout("success", "Tip", "Vue has a gentle learning curve.")]`,+ );++ openui.addSection(+ OPENUI_IMPORTANT_RULES_TAG,+ dedent`+ - When asked about data, generate realistic/plausible data+ - Choose components that best represent the content (tables for comparisons, charts for trends, forms for input, etc.)+ - When you render data in an openui block (tables, charts, KPI cards), do NOT repeat the same numbers/facts in the markdown text outside the block.+ - Text outside the openui block can optionally include:+ 1. **Qualitative insights** — patterns, anomalies, or recommendations that aren't obvious from the visual (e.g. "the high input-to-output ratio suggests document processing")+ 2. **Actionable next steps** — what the user can do next+ 3. **Caveats/context** — things the data doesn't show+ - If all the information is already visible in the openui components, a brief one-line summary is sufficient — do not enumerate the same values again.`,+ );++ openui.addSection(+ OPENUI_FINAL_VERIFICATION_TAG,+ dedent`+ Before finishing, walk your output and verify:+ 1. root = Stack(...) is the FIRST line (for optimal streaming).+ 2. Every referenced name is defined. Every defined name (other than root) is reachable from root.++ - For grid-like layouts, use Stack with direction "row" and wrap=true. Avoid justify="between" unless you specifically want large gutters.+ - For forms, define one FormControl reference per field so controls can stream progressively.+ - For forms, always provide the second Form argument with Buttons(...) actions: Form(name, buttons, fields).+ - Never nest Form inside Form.+ - Use @Reset($var1, $var2) after form submit to restore defaults — not @Set($var, "")+ - Multi-query refresh: Action([@Run(mutation), @Run(query1), @Run(query2), @Reset(...)])+ - $variables are reactive: changing via Select or @Set re-evaluates all Queries and expressions referencing them+ - Use existing components (Tabs, Accordion, Modal) before inventing ternary show/hide patterns`,+ );++ openui.addSection(+ OPENUI_USER_INTERACTION_CHECKLIST_TAG,+ dedent`+ 1. Will the response be UI heavy and will contain components which are not supported by markdown? Use openui if the answer is yes.+ 2. \`\`\`openui\`\`\` fencing must be closed.`,+ );+}++export function openUI(): AgentCapability {+ return {+ instructionBuilders: [buildOpenUIInstruction],+ };+}diff --git a/packages/harness/src/core/errors.ts b/packages/harness/src/core/errors.tsnew file mode 100644index 000000000..4689a5dae--- /dev/null+++ b/packages/harness/src/core/errors.ts@@ -0,0 +1,62 @@+export type AgentHarnessErrorCode =+ | 'invalid_agent_input'+ | 'invalid_send_input'+ | 'agent_sandbox_required'+ | 'tool_name_collision'+ | 'mcp_connection_failed'+ | 'capability_state_error';++export class AgentHarnessError extends Error {+ constructor(+ readonly code: AgentHarnessErrorCode,+ message: string,+ options?: ErrorOptions,+ ) {+ super(message, options);+ this.name = 'AgentHarnessError';+ }+}++export class InvalidAgentInputError extends AgentHarnessError {+ constructor(message: string, options?: ErrorOptions) {+ super('invalid_agent_input', message, options);+ this.name = 'InvalidAgentInputError';+ }+}++export class InvalidAgentSendInputError extends AgentHarnessError {+ constructor(message: string, options?: ErrorOptions) {+ super('invalid_send_input', message, options);+ this.name = 'InvalidAgentSendInputError';+ }+}++export class AgentSandboxRequiredError extends AgentHarnessError {+ constructor(message: string, options?: ErrorOptions) {+ super('agent_sandbox_required', message, options);+ this.name = 'AgentSandboxRequiredError';+ }+}++export class ToolNameCollisionError extends AgentHarnessError {+ constructor(message: string, options?: ErrorOptions) {+ super('tool_name_collision', message, options);+ this.name = 'ToolNameCollisionError';+ }+}++/**+ * A remote MCP connection or tool call failed. Harness code can't throw the gateway's HTTPException,+ * so it throws this instead and carries `statusCode` (401 auth, 403 tool, 400 selector, 502 transport)+ * that the gateway boundary turns back into the right HTTP status.+ */+export class McpConnectionError extends AgentHarnessError {+ constructor(+ message: string,+ readonly statusCode: number,+ options?: ErrorOptions,+ ) {+ super('mcp_connection_failed', message, options);+ this.name = 'McpConnectionError';+ }+}diff --git a/packages/harness/src/core/events/PassthroughEvents.ts b/packages/harness/src/core/events/PassthroughEvents.tsnew file mode 100644index 000000000..c3909776d--- /dev/null+++ b/packages/harness/src/core/events/PassthroughEvents.ts@@ -0,0 +1,22 @@+import type { z } from 'zod';++/**+ * Global declaration-merging registry for private/feature passthrough events.+ *+ * Tradeoffs:+ * - Merging is ambient: there is no runtime registration table.+ * - Every TypeScript program that typechecks harness consumers must include the+ * augmentation file(s) (see `src/agent/agentPassthroughEvents.d.ts`, and+ * `tsconfig.json` / `tsconfig.test.json` includes). Without augmentation,+ * `RegisteredPassthroughEvent` collapses to `never`.+ * - Compile fixtures: `tests/unit-tests/agent/harness/passthroughRegistration.compile.test.ts`.+ * - A future typed registry or `AgentThread<TPassthroughEvent>` generic is deferred.+ */+// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- declaration merging registry+export interface AgentPassthroughEventSchemaMap {}++export type RegisteredPassthroughEvent = {+ [K in keyof AgentPassthroughEventSchemaMap]: AgentPassthroughEventSchemaMap[K] extends z.ZodType<infer Event>+ ? Event & { type: K }+ : never;+}[keyof AgentPassthroughEventSchemaMap];diff --git a/packages/harness/src/core/events/eventSchemas.ts b/packages/harness/src/core/events/eventSchemas.tsnew file mode 100644index 000000000..35ab7ad99--- /dev/null+++ b/packages/harness/src/core/events/eventSchemas.ts@@ -0,0 +1,371 @@+// Harness wire-format event schemas (OpenAPI-decorated Zod).+import { z } from '@hono/zod-openapi';+import { ulid } from 'ulid';+import {+ CompletionUsageSchema,+ EnrichedAssistantMessageSchema,+ ExtendedChunkDeltaSchema,+ FinishReasonSchema,+ InternalEnrichedAssistantMessageSchema,+ LLMToolMessageSchema,+ LLMUserMessageSchema,+} from '../llm/LLMTypes';++export function newEventId(): string {+ return ulid().toLowerCase();+}++/** Canonical string constants for harness wire-level and user-input event `type` fields. */+export const EventType = {+ AGENT_CONTEXT_OVERWRITE: 'agent.context.overwrite',+ MCP_AUTH_REQUIRED: 'mcp.auth_required',+ MCP_INITIALIZE: 'mcp.initialize',+ MODEL_MESSAGE: 'model.message',+ MODEL_MESSAGE_DELTA: 'model.message.delta',+ SANDBOX_CREATED: 'sandbox.created',+ THREAD_CREATED: 'thread.created',+ THREAD_DONE: 'thread.done',+ TOOL_RESPONSE: 'tool.response',+ TOOL_APPROVAL_REQUIRED: 'tool.approval_required',+ TOOL_RESPONSE_REQUIRED: 'tool.response_required',+ USER_TOOL_APPROVAL: 'user.tool_approval',+ USER_TOOL_RESPONSE: 'user.tool_response',+ USER_MESSAGE: 'user.message',+} as const;++export const EventIdSchema = z.string().openapi({+ description: 'Unique identifier for the event',+});++export const AgentParentSchema = z+ .object({+ thread_id: z.string(),+ tool_call_id: z.string(),+ })+ .openapi('AgentParent');++export const AgentInfoSchema = z+ .object({+ type: z.literal('dynamic'),+ name: z.string(),+ input: z.string(),+ model: z.string().min(1).optional(),+ })+ .openapi('AgentInfo');++export const AgentApprovalDecisionAllowSchema = z.object({ status: z.literal('allow') }).openapi('ApprovalAllow');++export const AgentApprovalDecisionDenySchema = z+ .object({ status: z.literal('deny'), reason: z.string().optional() })+ .openapi('ApprovalDeny');++export const ApprovalDecisionSchema = z+ .discriminatedUnion('status', [AgentApprovalDecisionAllowSchema, AgentApprovalDecisionDenySchema])+ .openapi('ApprovalDecision');++export const UserToolApprovalMessageSchema = z+ .object({+ type: z.literal(EventType.USER_TOOL_APPROVAL),+ thread_id: z.string().min(1, 'thread_id is required'),+ tool_call_id: z.string().min(1, 'tool_call_id is required'),+ approval: ApprovalDecisionSchema,+ })+ .openapi('UserToolApprovalEvent');++export const UserToolResponseMessageSchema = z+ .object({+ type: z.literal(EventType.USER_TOOL_RESPONSE),+ thread_id: z.string().min(1, 'thread_id is required'),+ tool_call_id: z.string().min(1, 'tool_call_id is required'),+ content: z.string().min(1, 'content cannot be empty'),+ })+ .openapi('UserToolResponseEvent');++export const TextContentPartSchema = z+ .object({+ type: z.literal('text'),+ text: z.string(),+ })+ .openapi('TextContent');+export type TextContentPart = z.infer<typeof TextContentPartSchema>;++export const FileContentPartSchema = z+ .object({+ type: z.literal('file'),+ name: z.string(),+ data: z.string().describe('Data URI: `data:<mime>;base64,<payload>`. MIME type is parsed from the URI.'),+ })+ .openapi('FileContent');+export type FileContentPart = z.infer<typeof FileContentPartSchema>;++export const UserContentPartSchema = z+ .discriminatedUnion('type', [TextContentPartSchema, FileContentPartSchema])+ .openapi('UserMessageContentItem');+export type UserContentPart = z.infer<typeof UserContentPartSchema>;++export const AgentInputUserMessageSchema = z+ .object({+ type: z.literal(EventType.USER_MESSAGE),+ content: z.union([z.string(), z.array(UserContentPartSchema)]),+ })+ .openapi('UserMessage');+export type AgentInputUserMessage = z.infer<typeof AgentInputUserMessageSchema>;++// persisted to redis - thread_id is stripped+export const AgentApprovalDecisionMessageSchema = UserToolApprovalMessageSchema.omit({+ thread_id: true,+});++export const InputTokensBreakdownSchema = z.object({+ harness: z.number().int().nonnegative(),+ skills: z.number().int().nonnegative(),+ instructions: z.number().int().nonnegative(),+ tool_definitions: z.number().int().nonnegative(),+ messages: z.number().int().nonnegative(),+});++export const ModelMessageUsageSchema = z+ .object({+ input_tokens: z.number().int().nonnegative(),+ output_tokens: z.number().int().nonnegative(),+ cache_read_tokens: z.number().int().nonnegative().optional(),+ cache_write_tokens: z.number().int().nonnegative().optional(),+ input_tokens_breakdown: InputTokensBreakdownSchema,+ })+ .openapi('ModelMessageUsage');++export const ModelMessageEventSchema = EnrichedAssistantMessageSchema.omit({ role: true })+ .extend({+ type: z.literal(EventType.MODEL_MESSAGE),+ id: EventIdSchema,+ thread_id: z.string(),+ finish_reason: FinishReasonSchema.optional(),+ created_at: z.string(),+ usage: ModelMessageUsageSchema.optional(),+ })+ .openapi('ModelMessageEvent');++export const ModelMessageDeltaEventSchema = ExtendedChunkDeltaSchema.omit({+ role: true,+ function_call: true,+ thinking_blocks: true,+})+ .extend({+ type: z.literal(EventType.MODEL_MESSAGE_DELTA),+ id: EventIdSchema,+ thread_id: z.string(),+ created_at: z.string().optional(),+ finish_reason: FinishReasonSchema.optional(),+ usage: ModelMessageUsageSchema.optional(),+ })+ .openapi('ModelMessageDeltaEvent');++export const ToolResponseEventSchema = LLMToolMessageSchema.omit({ role: true })+ .extend({+ type: z.literal(EventType.TOOL_RESPONSE),+ id: EventIdSchema,+ thread_id: z.string(),+ created_at: z.string(),+ })+ .openapi('ToolResponseEvent');++export const ThreadCreatedEventSchema = z+ .object({+ type: z.literal(EventType.THREAD_CREATED),+ id: EventIdSchema,+ agent_info: AgentInfoSchema,+ created_at: z.string(),+ parent: AgentParentSchema,+ thread_id: z.string(),+ title: z.string(),+ })+ .openapi('ThreadCreatedEvent');++export const ThreadStateDoneSchema = z+ .object({+ status: z.literal('done'),+ output: ModelMessageEventSchema,+ })+ .openapi('ThreadStateDone');++export const ThreadStateErrorSchema = z+ .object({+ status: z.literal('error'),+ error: z.string(),+ output: ModelMessageEventSchema.optional(),+ })+ .openapi('ThreadStateError');++export const ThreadStateSchema = z+ .discriminatedUnion('status', [ThreadStateDoneSchema, ThreadStateErrorSchema])+ .openapi('ThreadState');++export const BaseThreadDoneEventSchema = z+ .object({+ parent: AgentParentSchema.optional(),+ thread_id: z.string(),+ title: z.string(),+ })+ .openapi('BaseThreadDoneEvent');++export const ThreadDoneEventSchema = BaseThreadDoneEventSchema.extend({+ type: z.literal(EventType.THREAD_DONE),+ id: EventIdSchema,+ created_at: z.string(),+ state: ThreadStateSchema,+}).openapi('ThreadDoneEvent');++const ContextMessageSchema = z.union([+ LLMUserMessageSchema,+ InternalEnrichedAssistantMessageSchema,+ LLMToolMessageSchema,+ AgentApprovalDecisionMessageSchema,+]);++export const ThreadOverwriteContextEventSchema = z.object({+ // TODO(agent): This will be used by summarization.++ // TODO(agent): For summarization, we will add a AgentExecutionContextSummarizationStart and AgentExecutionContextSummarizationEnd+ // event. Summarization can take some time, this will ensure that the customer is aware of what is happening.+ type: z.literal(EventType.AGENT_CONTEXT_OVERWRITE),+ id: EventIdSchema,+ created_at: z.string(),+ thread_id: z.string(),++ // NOTE: add other reasons here.+ reason: z.literal('compaction'),+ context: z.array(ContextMessageSchema),+ // Estimated token usage of the new (compacted) context for the next LLM call's budget+ current_context_usage: CompletionUsageSchema,+ // Actual token usage consumed by the compaction LLM call itself+ compaction_llm_usage: CompletionUsageSchema,+});++export const MCPServerAuthInfoSchema = z+ .object({+ id: z.string(),+ name: z.string(),+ auth_url: z.string(),+ })+ .openapi('MCPServerAuthInfo');++export const BaseMCPAuthRequiredEventSchema = z+ .object({+ id: EventIdSchema,+ created_at: z.string(),+ // This is a run-level event, not tied to a single thread.+ thread_id: z.string().nullable(),+ })+ .openapi('BaseMCPAuthRequiredEvent');++export const MCPAuthRequiredEventSchema = BaseMCPAuthRequiredEventSchema.extend({+ type: z.literal(EventType.MCP_AUTH_REQUIRED),+ mcp_servers: z.array(MCPServerAuthInfoSchema),+}).openapi('MCPAuthRequiredEvent');++export const MCPServerInitInfoSchema = z+ .object({+ id: z.string(),+ name: z.string(),+ session_id: z.string().optional(),+ transport_type: z.enum(['streamable-http', 'sse']).optional(),+ })+ .openapi('MCPServerInitInfo');++export const MCPInitializeEventSchema = z+ .object({+ type: z.literal(EventType.MCP_INITIALIZE),+ id: EventIdSchema,+ created_at: z.string(),+ thread_id: z.string(),+ mcp_servers: z.array(MCPServerInitInfoSchema),+ })+ .openapi('MCPInitializeEvent');++export const SandboxCreatedEventSchema = z+ .object({+ type: z.literal(EventType.SANDBOX_CREATED),+ id: EventIdSchema,+ created_at: z.string(),+ sandbox_id: z.string(),+ // This is a run-level event, sandbox once created is reused by all threads,+ // and future turns as well.+ thread_id: z.string().nullable(),+ })+ .openapi('SandboxCreatedEvent');++export const ToolCallRefSchema = z+ .object({+ id: z.string(),+ source_event_id: z.string(),+ })+ .openapi('ToolCallRef');++export const ToolApprovalRequiredEventSchema = z+ .object({+ type: z.literal(EventType.TOOL_APPROVAL_REQUIRED),+ id: EventIdSchema,+ created_at: z.string(),+ thread_id: z.string(),+ tool_calls: z.array(ToolCallRefSchema),+ })+ .openapi('ToolApprovalRequiredEvent');++export const ToolResponseRequiredEventSchema = z+ .object({+ type: z.literal(EventType.TOOL_RESPONSE_REQUIRED),+ id: EventIdSchema,+ created_at: z.string(),+ thread_id: z.string(),+ tool_calls: z.array(ToolCallRefSchema),+ })+ .openapi('ToolResponseRequiredEvent');++export const ActionRequiredEventSchema = z+ .discriminatedUnion('type', [+ ToolApprovalRequiredEventSchema,+ ToolResponseRequiredEventSchema,+ MCPAuthRequiredEventSchema,+ ])+ .openapi('ActionRequiredEvent');++/** Neutral harness output-event membership (not an HTTP/OpenAPI AgentResponse aggregate). */+export const AgentOutputEventSchema = z.union([+ ModelMessageEventSchema,+ ToolResponseEventSchema,+ ThreadCreatedEventSchema,+ ThreadDoneEventSchema,+ MCPAuthRequiredEventSchema,+ MCPInitializeEventSchema,+ SandboxCreatedEventSchema,+ ToolApprovalRequiredEventSchema,+ ToolResponseRequiredEventSchema,+]);++export type AgentParent = z.infer<typeof AgentParentSchema>;+export type AgentInfo = z.infer<typeof AgentInfoSchema>;+export type ApprovalDecision = z.infer<typeof ApprovalDecisionSchema>;+export type UserToolApprovalMessage = z.infer<typeof UserToolApprovalMessageSchema>;+export type UserToolResponseMessage = z.infer<typeof UserToolResponseMessageSchema>;+export type AgentApprovalDecisionMessage = z.infer<typeof AgentApprovalDecisionMessageSchema>;+export type InputTokensBreakdown = z.infer<typeof InputTokensBreakdownSchema>;+export type ModelMessageUsage = z.infer<typeof ModelMessageUsageSchema>;+export type ModelMessageEvent = z.infer<typeof ModelMessageEventSchema>;+export type ModelMessageDeltaEvent = z.infer<typeof ModelMessageDeltaEventSchema>;+export type ToolResponseEvent = z.infer<typeof ToolResponseEventSchema>;+export type ThreadCreatedEvent = z.infer<typeof ThreadCreatedEventSchema>;+export type ThreadStateError = z.infer<typeof ThreadStateErrorSchema>;+export type ThreadState = z.infer<typeof ThreadStateSchema>;+export type BaseThreadDoneEvent = z.infer<typeof BaseThreadDoneEventSchema>;+export type ThreadDoneEvent = z.infer<typeof ThreadDoneEventSchema>;+export type ThreadOverwriteContextEvent = z.infer<typeof ThreadOverwriteContextEventSchema>;+export type BaseMCPAuthRequiredEvent = z.infer<typeof BaseMCPAuthRequiredEventSchema>;+export type MCPServerAuthInfo = z.infer<typeof MCPServerAuthInfoSchema>;+export type MCPAuthRequiredEvent = z.infer<typeof MCPAuthRequiredEventSchema>;+export type MCPServerInitInfo = z.infer<typeof MCPServerInitInfoSchema>;+export type MCPInitializeEvent = z.infer<typeof MCPInitializeEventSchema>;+export type SandboxCreatedEvent = z.infer<typeof SandboxCreatedEventSchema>;+export type ToolApprovalRequiredEvent = z.infer<typeof ToolApprovalRequiredEventSchema>;+export type ToolResponseRequiredEvent = z.infer<typeof ToolResponseRequiredEventSchema>;+export type ActionRequiredEvent = z.infer<typeof ActionRequiredEventSchema>;+export type AgentOutputEvent = z.infer<typeof AgentOutputEventSchema>;diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsnew file mode 100644index 000000000..d17c3042d--- /dev/null+++ b/packages/harness/src/core/index.ts@@ -0,0 +1,106 @@+/**+ * Public agent execution harness.+ * Intentional consumer-facing exports only (production API).+ */++// Runtime+export type { AgentDefinition } from './runtime/AgentDefinition';+export { AgentThread } from './runtime/AgentThread';+export type { AgentInfo, AgentParent } from './runtime/AgentThread.types';+export { AgentThreadOrchestrator } from './runtime/AgentThreadOrchestrator';+export type { CreateDynamicSubAgentThread } from './runtime/CreateDynamicSubAgentThread';+export { isAgentInputUserMessage, isEmptyMessageContent, isFileContentPart } from './runtime/UserInputMessage';+export type { AgentInputUserMessage } from './runtime/UserInputMessage';++// Capability contracts+export type { AgentCapability } from './capabilities/AgentCapability';+export type {+ AgentContextProcessorOutput,+ AgentThreadExecutionContext,+ PostToolCallAgentContextProcessor,+ PreLLMEphemeralAgentContextProcessor,+} from './capabilities/AgentContextProcessor';++// Built-in factories+export { askUserQuestion } from './capabilities/builtins/AskUserQuestion';+export { contextCompaction } from './capabilities/builtins/ContextCompaction';+export { currentDateTime } from './capabilities/builtins/CurrentDateTime';+export { SUB_AGENT_IDENTITY, dynamicSubAgents } from './capabilities/builtins/DynamicSubAgents';+export { largeToolResponse } from './capabilities/builtins/LargeToolResponse';+export { openUI } from './capabilities/builtins/OpenUI';++// MCP contracts+export type { ApprovalDecision } from './events/eventSchemas';+export { ClientSideTool } from './mcp/ClientSideTool';+export { isAuthRequired, toolResultResponse } from './mcp/IMCPServer';+export type {+ AgentToolSchema,+ AuthRequiredResponse,+ CallToolResponse,+ IToolSet,+ ListToolsResponse,+ MCPAuthRequired,+ ToolSource,+} from './mcp/IMCPServer';+export { LocalToolMCP, defineTool } from './mcp/LocalToolMCP';+export type { ToolDefinition } from './mcp/LocalToolMCP';++// Remote MCP server, split into a shared, policy-free connection (`RemoteMCP`) and a per-agent policy+// wrapper (`ToolSet`). `RemoteMCP` connects itself from a `url` + `headers`; the networking helpers+// live in the harness-internal `remoteMcpClient` module.+export { RemoteMCP } from './mcp/RemoteMCP';+export type { RemoteMcpHeaders, ResolveHeadersResult } from './mcp/RemoteMCP';+export type { RemoteMcpConnection, RemoteMcpTransportType } from './mcp/remoteMcpClient';+export type { ToolSelectorConfig } from './mcp/ToolSelectorPolicy';+export { ToolSet } from './mcp/ToolSet';++// LLM contracts+export type { ILLM } from './llm/ILLM';+export type { CompletionUsage, LLMUserMessage } from './llm/LLMTypes';+export { OpenAILLM } from './llm/OpenAILLM';+export { ResponseFormatSchema, toOpenAIResponseFormat } from './llm/responseFormat';+export type { ResponseFormat } from './llm/responseFormat';++// Event contracts+export {+ EventType,+ MCPAuthRequiredEventSchema,+ MCPInitializeEventSchema,+ ModelMessageDeltaEventSchema,+ ModelMessageEventSchema,+ SandboxCreatedEventSchema,+ ThreadCreatedEventSchema,+ ThreadDoneEventSchema,+ ToolApprovalRequiredEventSchema,+ ToolResponseEventSchema,+ ToolResponseRequiredEventSchema,+ newEventId,+} from './events/eventSchemas';+export type { AgentThreadMetric } from './llm/metrics';+export { InternalEventType } from './runtime/AgentThread.types';+export type { AgentThreadSendBatch, ContextMessage } from './runtime/AgentThread.types';+export type { SandboxInfo } from './sandbox/Sandbox';++// Tracing+export type {+ AgentExecutionTrace,+ AgentLocalToolTrace,+ AgentRemoteMcpToolTrace,+ AgentTracing,+} from './tracing/AgentTracing';++// Errors / utils+export { AgentHarnessError, McpConnectionError } from './errors';+export { extractErrorLogFields } from './util/errorLogFields';++// Sandbox (concrete implementation; provider details exported for composition)+export {+ DaytonaSandboxProviderSettingsSchema,+ SandboxProviderSettingsSchema,+ createSandboxProvider,+} from './sandbox/provider/createSandboxProvider';+export type { CreateSandboxProviderInput, SandboxProviderSettings } from './sandbox/provider/createSandboxProvider';+export { DaytonaSandboxProvider } from './sandbox/provider/DaytonaProvider';+export type { SandboxProvider } from './sandbox/provider/Provider';+export { TFYSandboxProvider } from './sandbox/provider/TFYSandboxProvider';+export { Sandbox } from './sandbox/Sandbox';diff --git a/packages/harness/src/core/llm/ILLM.ts b/packages/harness/src/core/llm/ILLM.tsnew file mode 100644index 000000000..e7af95f9a--- /dev/null+++ b/packages/harness/src/core/llm/ILLM.ts@@ -0,0 +1,11 @@+import type { ChatCompletionCreateParams, ChatCompletionCreateParamsStreaming } from 'openai/resources/chat';+import type { ExtendedChatCompletionChunk, RawAssistantMessageWithUsage } from './LLMTypes';++export type AgentMetadata = Record<string, string>;++export interface ILLM {+ create(+ body: ChatCompletionCreateParamsStreaming,+ ): AsyncGenerator<ExtendedChatCompletionChunk, RawAssistantMessageWithUsage, unknown>;+ createNonStream(body: ChatCompletionCreateParams): Promise<RawAssistantMessageWithUsage>;+}diff --git a/packages/harness/src/core/llm/LLMTypes.ts b/packages/harness/src/core/llm/LLMTypes.tsnew file mode 100644index 000000000..d02234dc6--- /dev/null+++ b/packages/harness/src/core/llm/LLMTypes.ts@@ -0,0 +1,207 @@+// TODO(agent): We should not maintain choices anymore.+// https://platform.claude.com/docs/en/api/messages/create+// https://platform.openai.com/docs/api-reference/responses/object#responses-object-output+// Check the above page and check code to and come up with a streaming structure that does not expose+// choices to upstream.++// TODO(agent): At this point, we can write the types from scratch. No point in keeping the old OpenAI baggage.+import { z } from '@hono/zod-openapi';+import type { ChatCompletionChunk } from 'openai/resources/chat';+import {+ ChatCompletionAssistantMessageParamSchema,+ ChatCompletionChunkDeltaSchema,+ ChatCompletionChunkDeltaToolCallSchema,+ ChatCompletionChunkFinishReasonSchema,+ ChatCompletionMessageToolCallSchema,+ ChatCompletionToolMessageParamSchema,+ ChatCompletionUserMessageParamSchema,+} from './openaiSchemas';++export const ThinkingBlockSchema = z+ .object({+ type: z.literal('thinking'),+ thinking: z.string(),+ signature: z.string().optional(),+ })+ .openapi('ThinkingBlock');++export const RedactedThinkingBlockSchema = z+ .object({+ type: z.literal('redacted_thinking'),+ data: z.string(),+ })+ .openapi('RedactedThinkingBlock');++export const ThinkingBlockUnionSchema = z.union([ThinkingBlockSchema, RedactedThinkingBlockSchema]);++export const InternalToolCallInfoSchema = z.object({+ type: z.enum(['truefoundry-system', 'mcp']),+ mcp_server_id: z.string(),+ mcp_server_name: z.string(),+ original_tool_name: z.string(),+ is_approval_required: z.boolean().optional(),+ is_deferred: z.boolean().optional(),+ is_client_side: z.boolean().optional(),+ // Runtime + wire: deviation from origin/main OpenAPI (which omitted this field) is accepted.+ is_thread_creation: z.boolean().optional(),+});++export const TrueFoundrySystemToolInfoSchema = z+ .object({+ type: z.literal('truefoundry-system'),+ name: z.string(),+ })+ .openapi('TrueFoundrySystemToolInfo');++export const MCPToolInfoSchema = z+ .object({+ type: z.literal('mcp'),+ server_id: z.string(),+ server_name: z.string(),+ name: z.string(),+ })+ .openapi('MCPToolInfo');++export const RawToolCallSchema = ChatCompletionMessageToolCallSchema.extend({+ provider_specific_fields: z.record(z.string(), z.unknown()).optional(),+}).openapi('RawToolCall');++export const InternalEnrichedToolCallSchema = RawToolCallSchema.extend({+ tool_info: InternalToolCallInfoSchema,+});++export const ToolInfoSchema = z+ .discriminatedUnion('type', [TrueFoundrySystemToolInfoSchema, MCPToolInfoSchema])+ .openapi('ToolInfo');++export const EnrichedToolCallSchema = RawToolCallSchema.extend({+ tool_info: ToolInfoSchema,+}).openapi('ToolCall');++export const RawAssistantMessageSchema = ChatCompletionAssistantMessageParamSchema.omit({+ tool_calls: true,+ audio: true,+ function_call: true,+})+ .extend({+ tool_calls: z.array(RawToolCallSchema).optional(),+ thinking_blocks: z.array(ThinkingBlockUnionSchema).optional(),+ /** Plain-text thinking content streamed incrementally for frontend display; redundant with thinking_blocks[].thinking. */+ reasoning_content: z.string().optional(),+ })+ .openapi('RawAssistantMessage');++export const InternalEnrichedAssistantMessageSchema = RawAssistantMessageSchema.omit({+ tool_calls: true,+}).extend({+ tool_calls: z.array(InternalEnrichedToolCallSchema).optional(),+});++// `thinking_blocks` omitted: kept on the internal message for Redis replay, hidden from the client event.+export const EnrichedAssistantMessageSchema = RawAssistantMessageSchema.omit({+ tool_calls: true,+ thinking_blocks: true,+})+ .extend({+ tool_calls: z.array(EnrichedToolCallSchema).optional(),+ })+ .openapi('EnrichedAssistantMessage');++export const ExtendedChunkDeltaToolCallSchema = ChatCompletionChunkDeltaToolCallSchema.extend({+ tool_info: ToolInfoSchema.optional(),+ provider_specific_fields: z.record(z.string(), z.unknown()).optional(),+}).openapi('ExtendedChunkDeltaToolCall');++export const ExtendedChunkDeltaSchema = ChatCompletionChunkDeltaSchema.omit({ tool_calls: true })+ .extend({+ tool_calls: z.array(ExtendedChunkDeltaToolCallSchema).optional(),+ /** Structured thinking blocks from the gateway; accumulated into complete blocks (with signatures) for multi-turn replay. */+ thinking_blocks: z.array(ThinkingBlockUnionSchema).optional(),+ /** Plain-text thinking content streamed incrementally for frontend display; not stored — redundant with thinking_blocks[].thinking. */+ reasoning_content: z.string().optional(),+ })+ .openapi('ExtendedChunkDelta');++export const LLMUserMessageSchema = ChatCompletionUserMessageParamSchema.pick({+ role: true,+ content: true,+}).openapi('LLMUserMessage');++export const LLMToolMessageSchema = ChatCompletionToolMessageParamSchema.omit({ content: true })+ .extend({+ // TODO(agent): Where do I update the Zod code for this change?+ content: z.string(),+ })+ .openapi('LLMToolMessage');++export const CompletionUsageSchema = z+ .object({+ completion_tokens: z.number().int().nonnegative(),+ prompt_tokens: z.number().int().nonnegative(),+ total_tokens: z.number().int().nonnegative(),+ completion_tokens_details: z+ .object({+ reasoning_tokens: z.number().int().nonnegative().optional(),+ })+ .optional(),+ prompt_tokens_details: z+ .object({+ cached_tokens: z.number().int().nonnegative().optional(),+ })+ .optional(),+ cache_read_input_tokens: z.number().int().nonnegative().optional(),+ cache_creation_input_tokens: z.number().int().nonnegative().optional(),+ })+ .openapi('CompletionUsage');++export const FinishReasonSchema = ChatCompletionChunkFinishReasonSchema.openapi('FinishReason');++export type ThinkingBlock = z.infer<typeof ThinkingBlockSchema>;+export type RedactedThinkingBlock = z.infer<typeof RedactedThinkingBlockSchema>;+export type InternalToolCallInfo = z.infer<typeof InternalToolCallInfoSchema>;+export type TrueFoundrySystemToolInfo = z.infer<typeof TrueFoundrySystemToolInfoSchema>;+export type MCPToolInfo = z.infer<typeof MCPToolInfoSchema>;+export type ToolInfo = z.infer<typeof ToolInfoSchema>;+export type InternalEnrichedToolCall = z.infer<typeof InternalEnrichedToolCallSchema>;+export type EnrichedToolCall = z.infer<typeof EnrichedToolCallSchema>;+export type RawAssistantMessage = z.infer<typeof RawAssistantMessageSchema>;+export type InternalEnrichedAssistantMessage = z.infer<typeof InternalEnrichedAssistantMessageSchema>;+export type EnrichedAssistantMessage = z.infer<typeof EnrichedAssistantMessageSchema>;+export type ExtendedDeltaToolCall = z.infer<typeof ExtendedChunkDeltaToolCallSchema>;+export type ExtendedDelta = z.infer<typeof ExtendedChunkDeltaSchema>;+export type LLMUserMessage = z.infer<typeof LLMUserMessageSchema>;+export type LLMToolMessage = z.infer<typeof LLMToolMessageSchema>;+export type CompletionUsage = z.infer<typeof CompletionUsageSchema>;+export type FinishReason = z.infer<typeof FinishReasonSchema>;++export function getEmptyUsage(): CompletionUsage {+ return { prompt_tokens: 0, total_tokens: 0, completion_tokens: 0 };+}++/**+ * Extended choice type that includes thought_signature in the delta.+ */+interface ExtendedChoice extends Omit<ChatCompletionChunk.Choice, 'delta'> {+ /**+ * A chat completion delta generated by streamed model responses, with thought_signature support.+ */+ delta: ExtendedDelta;+}++/**+ * Extended chat completion chunk that includes thought_signature in tool calls.+ */+export interface ExtendedChatCompletionChunk extends Omit<ChatCompletionChunk, 'choices'> {+ /**+ * A list of chat completion choices, with thought_signature support in deltas.+ */+ choices: Array<ExtendedChoice>;+}++export interface RawAssistantMessageWithUsage {+ output: RawAssistantMessage;+ usage: CompletionUsage;+ finish_reason: FinishReason;+}++export const UNKNOWN_TOOL_NAME = 'unknown';diff --git a/packages/harness/src/core/llm/OpenAILLM.ts b/packages/harness/src/core/llm/OpenAILLM.tsnew file mode 100644index 000000000..1690bfcc2--- /dev/null+++ b/packages/harness/src/core/llm/OpenAILLM.ts@@ -0,0 +1,235 @@+import OpenAI from 'openai';+import type { RequestOptions } from 'openai/core';+import type { ChatCompletionCreateParams, ChatCompletionCreateParamsStreaming } from 'openai/resources/chat';+import type { Logger } from 'winston';+import { extractErrorLogFields } from '../util/errorLogFields';+import type { ILLM } from './ILLM';+import {+ getEmptyUsage,+ type CompletionUsage,+ type ExtendedChatCompletionChunk,+ type RawAssistantMessage,+ type RawAssistantMessageWithUsage,+} from './LLMTypes';++/** Static headers, or a resolver invoked on every request. */+export type LLMHeaders = Record<string, string> | (() => Record<string, string>);++export interface OpenAILLMConfig {+ /** Base URL of an OpenAI-compatible chat completions API. */+ baseURL: string;+ /** API key, sent as `Authorization: Bearer <key>`. */+ apiKey: string;+ /** Extra per-request headers (take precedence over client defaults). */+ headers?: LLMHeaders | undefined;+ logger: Logger;+ signal?: AbortSignal | undefined;+ /** Response header carrying the served model's context length, if the API exposes one. */+ servedContextLengthHeader?: string | undefined;+ onServedModelContextLength?: (contextLength: number) => void | undefined;+}++/** ILLM implementation for any OpenAI-compatible chat completions API. */+export class OpenAILLM implements ILLM {+ private readonly client: OpenAI;+ private readonly headers?: LLMHeaders | undefined;+ private readonly logger: Logger;+ private readonly signal?: AbortSignal | undefined;+ private readonly servedContextLengthHeader?: string | undefined;+ private readonly onServedModelContextLength?: ((contextLength: number) => void) | undefined;++ constructor(config: OpenAILLMConfig) {+ this.client = new OpenAI({+ baseURL: config.baseURL,+ apiKey: config.apiKey,+ });+ this.headers = config.headers;+ this.logger = config.logger;+ this.signal = config.signal;+ this.servedContextLengthHeader = config.servedContextLengthHeader;+ this.onServedModelContextLength = config.onServedModelContextLength;+ }++ private buildRequestOptions(): RequestOptions {+ return {+ headers: typeof this.headers === 'function' ? this.headers() : this.headers,+ signal: this.signal,+ };+ }++ async *create(+ body: ChatCompletionCreateParamsStreaming,+ ): AsyncGenerator<ExtendedChatCompletionChunk, RawAssistantMessageWithUsage, unknown> {+ const newMessage: Partial<RawAssistantMessageWithUsage> & Pick<RawAssistantMessageWithUsage, 'output'> = {+ output: {+ role: 'assistant',+ content: '',+ },+ };+ let response;+ let servedModelContextLengthHeader: string | null = null;++ try {+ const { data, response: httpResponse } = await this.client.chat.completions+ .create(body, this.buildRequestOptions())+ .withResponse();+ response = data;+ if (this.servedContextLengthHeader) {+ servedModelContextLengthHeader = httpResponse.headers.get(this.servedContextLengthHeader);+ }+ } catch (error) {+ if (this.signal?.aborted) {+ this.logger.debug(`LLM call aborted`, extractErrorLogFields(error));+ } else {+ this.logger.error(`Error creating chat completion`, extractErrorLogFields(error));+ }+ throw error;+ }++ for await (const event of response) {+ yield event;+ accumulateTokensFromChunk(event, newMessage, this.logger);+ }+ // Record after the stream drains so the last completed LLM call wins.+ const servedModelContextLength = Number(servedModelContextLengthHeader);+ if (servedModelContextLength > 0) {+ this.onServedModelContextLength?.(servedModelContextLength);+ }++ return {+ usage: newMessage.usage+ ? newMessage.usage+ : estimateTokensForAssistantMessage(body, newMessage.output, this.logger),+ output: newMessage.output,+ finish_reason: newMessage.finish_reason ?? null,+ };+ }++ async createNonStream(body: ChatCompletionCreateParams): Promise<RawAssistantMessageWithUsage> {+ // TODO(agent): this is not really efficient. Rewrite this.+ const llmStream = this.create({ ...body, stream: true });+ let result = await llmStream.next();+ while (!result.done) {+ result = await llmStream.next();+ }++ if (result.value) {+ return result.value;+ } else {+ throw Error('unreachable');+ }+ }+}++function estimateTokensForAssistantMessage(+ _request: ChatCompletionCreateParamsStreaming,+ _response: RawAssistantMessage,+ logger: Logger,+): CompletionUsage {+ // TODO(usage): fill this.+ logger.error(`Did not recieve usage from LLM, estimation is not implemented.`);+ return getEmptyUsage();+}++/**+ * Accumulates tokens from a streaming chunk into the messages buffer.+ * Handles content and tool calls accumulation for each choice in the chunk.+ * Supports thought_signature for models like gemini-3-pro-preview.+ */+function accumulateTokensFromChunk(+ chunk: ExtendedChatCompletionChunk,+ message: Partial<RawAssistantMessageWithUsage> & Pick<RawAssistantMessageWithUsage, 'output'>,+ logger: Logger,+): void {+ for (const choice of chunk.choices) {+ // Initialize message if it doesn't exist and get reference+ // Validate role only if it's explicitly present (typically only in first chunk)+ // Most chunks won't have role in delta, which is normal+ if (choice.delta?.role !== undefined && choice.delta?.role !== 'assistant') {+ logger.warn(`Unexpected role: ${choice.delta?.role}`);+ throw Error(`Unexpected role: ${choice.delta?.role}`);+ }++ if (choice.delta?.content) {+ message.output.content = message.output.content + choice.delta.content;+ }+ // ToDo (handle refusal in the message, currently not handled)++ if (choice.delta?.thinking_blocks) {+ if (!message.output.thinking_blocks) {+ message.output.thinking_blocks = [];+ }+ for (const tb of choice.delta.thinking_blocks) {+ if (tb.type === 'thinking') {+ const blocks = message.output.thinking_blocks;+ const last = blocks[blocks.length - 1];+ // Last thinking block without signature is still in-progress — append to it.+ // Otherwise start a new block.+ let current;+ if (last?.type === 'thinking' && !last.signature) {+ current = last;+ } else {+ current = { type: 'thinking' as const, thinking: '' };+ blocks.push(current);+ }+ if (tb.thinking) {+ current.thinking += tb.thinking;+ }+ if (tb.signature) {+ current.signature = tb.signature;+ }+ } else if (tb.type === 'redacted_thinking') {+ message.output.thinking_blocks.push(tb);+ }+ }+ }++ if (choice.delta?.tool_calls) {+ if (!message.output.tool_calls) {+ message.output.tool_calls = [];+ }++ for (const toolCallDelta of choice.delta.tool_calls) {+ const toolCallIndex = toolCallDelta.index;+ const functionDelta = toolCallDelta.function;++ // Initialize tool call if it doesn't exist+ if (!message.output.tool_calls[toolCallIndex]) {+ message.output.tool_calls[toolCallIndex] = {+ id: toolCallDelta.id || '',+ type: 'function',+ function: {+ name: functionDelta?.name || '',+ arguments: functionDelta?.arguments || '',+ },+ ...(toolCallDelta.provider_specific_fields && {+ provider_specific_fields: toolCallDelta.provider_specific_fields,+ }),+ };+ } else {+ const existingToolCall = message.output.tool_calls[toolCallIndex];+ if (functionDelta?.name) {+ existingToolCall.function.name = functionDelta.name;+ }+ if (functionDelta?.arguments) {+ existingToolCall.function.arguments += functionDelta.arguments;+ }+ if (toolCallDelta.id) {+ existingToolCall.id = toolCallDelta.id;+ }+ if (toolCallDelta.provider_specific_fields) {+ existingToolCall.provider_specific_fields =+ existingToolCall.provider_specific_fields ?? toolCallDelta.provider_specific_fields;+ }+ }+ }+ }+ }+ if (chunk.usage) {+ message.usage = chunk.usage;+ }+ const finishReason = chunk.choices[0]?.finish_reason;+ if (finishReason) {+ message.finish_reason = finishReason;+ }+}diff --git a/packages/harness/src/core/llm/metrics.ts b/packages/harness/src/core/llm/metrics.tsnew file mode 100644index 000000000..397830f48--- /dev/null+++ b/packages/harness/src/core/llm/metrics.ts@@ -0,0 +1,33 @@+import type { CompletionUsage } from './LLMTypes';+import { getEmptyUsage } from './LLMTypes';+import { mergeUsage } from './usage';++export interface AgentThreadMetric {+ iterations: number;+ total_tool_calls: number;+ total_summarizations: number;+ usage: CompletionUsage;+ total_sub_agents: number;+}++export interface AgentThreadMetrics {+ total: AgentThreadMetric;+}++export function getEmptyMetric(): AgentThreadMetric {+ return {+ iterations: 0,+ total_tool_calls: 0,+ total_summarizations: 0,+ usage: getEmptyUsage(),+ total_sub_agents: 0,+ };+}++export function addMetrics(target: AgentThreadMetric, source: AgentThreadMetric): void {+ target.iterations += source.iterations;+ target.total_tool_calls += source.total_tool_calls;+ target.total_summarizations += source.total_summarizations;+ target.total_sub_agents += source.total_sub_agents;+ target.usage = mergeUsage(target.usage, source.usage);+}diff --git a/packages/harness/src/core/llm/openaiSchemas.ts b/packages/harness/src/core/llm/openaiSchemas.tsnew file mode 100644index 000000000..5698b6564--- /dev/null+++ b/packages/harness/src/core/llm/openaiSchemas.ts@@ -0,0 +1,144 @@+/**+ * Canonical OpenAI wire schemas with OpenAPI component names.+ * Nested composites are rebuilt from decorated leaves so `$ref`s are preserved.+ */+import { z } from '@hono/zod-openapi';++export const ChatCompletionContentPartTextSchema = z+ .object({+ type: z.literal('text'),+ text: z.string(),+ })+ .openapi('ChatCompletionContentPartText');++export const ChatCompletionContentPartRefusalSchema = z+ .object({+ type: z.literal('refusal'),+ refusal: z.string(),+ })+ .openapi('ChatCompletionContentPartRefusal');++export const ChatCompletionContentPartImageSchema = z+ .object({+ type: z.literal('image_url'),+ image_url: z.object({+ url: z.string(),+ detail: z.enum(['auto', 'low', 'high']).optional(),+ }),+ })+ .openapi('ChatCompletionContentPartImage');++export const ChatCompletionContentPartInputAudioSchema = z+ .object({+ type: z.literal('input_audio'),+ input_audio: z.object({+ data: z.string(),+ format: z.enum(['wav', 'mp3']),+ }),+ })+ .openapi('ChatCompletionContentPartInputAudio');++export const ChatCompletionContentPartFileSchema = z+ .object({+ type: z.literal('file'),+ file: z.object({+ file_data: z.string().optional(),+ file_id: z.string().optional(),+ filename: z.string().optional(),+ }),+ })+ .openapi('ChatCompletionContentPartFile');++// User-message content parts (matches OpenAI's `ChatCompletionContentPart`).+export const ChatCompletionContentPartSchema = z.union([+ ChatCompletionContentPartTextSchema,+ ChatCompletionContentPartImageSchema,+ ChatCompletionContentPartInputAudioSchema,+ ChatCompletionContentPartFileSchema,+]);++export const ChatCompletionMessageToolCallSchema = z+ .object({+ id: z.string(),+ type: z.literal('function'),+ function: z.object({+ name: z.string(),+ arguments: z.string(),+ }),+ })+ .openapi('ChatCompletionMessageToolCall');++export const ChatCompletionChunkDeltaToolCallSchema = z+ .object({+ index: z.number().int().nonnegative(),+ id: z.string().optional(),+ type: z.literal('function').optional(),+ function: z+ .object({+ name: z.string().optional(),+ arguments: z.string().optional(),+ })+ .optional(),+ })+ .openapi('ChatCompletionChunkDeltaToolCall');++export const ChatCompletionChunkDeltaSchema = z+ .object({+ content: z.string().nullable().optional(),+ refusal: z.string().nullable().optional(),+ role: z.enum(['developer', 'system', 'user', 'assistant', 'tool']).optional(),+ function_call: z+ .object({+ name: z.string().optional(),+ arguments: z.string().optional(),+ })+ .optional(),+ tool_calls: z.array(ChatCompletionChunkDeltaToolCallSchema).optional(),+ })+ .openapi('ChatCompletionChunkDelta');++export const ChatCompletionAssistantMessageParamSchema = z+ .object({+ role: z.literal('assistant'),+ audio: z.object({ id: z.string() }).nullable().optional(),+ content: z+ .union([+ z.string(),+ z.array(z.union([ChatCompletionContentPartTextSchema, ChatCompletionContentPartRefusalSchema])),+ ])+ .nullable()+ .optional(),+ function_call: z+ .object({+ name: z.string(),+ arguments: z.string(),+ })+ .nullable()+ .optional(),+ name: z.string().optional(),+ refusal: z.string().nullable().optional(),+ tool_calls: z.array(ChatCompletionMessageToolCallSchema).optional(),+ })+ .openapi('ChatCompletionAssistantMessageParam');++// `content` is wider here than in our pipeline; `LLMToolMessageSchema` narrows it to string.+export const ChatCompletionToolMessageParamSchema = z+ .object({+ role: z.literal('tool'),+ tool_call_id: z.string(),+ content: z.union([z.string(), z.array(ChatCompletionContentPartTextSchema)]),+ })+ .openapi('ChatCompletionToolMessageParam');++export const ChatCompletionUserMessageParamSchema = z+ .object({+ role: z.literal('user'),+ content: z.union([z.string(), z.array(ChatCompletionContentPartSchema)]),+ name: z.string().optional(),+ })+ .openapi('ChatCompletionUserMessageParam');++export const ChatCompletionChunkFinishReasonSchema = z+ .enum(['stop', 'length', 'tool_calls', 'content_filter', 'function_call'])+ .nullable()+ .openapi('ChatCompletionChunkFinishReason');diff --git a/packages/harness/src/core/llm/responseFormat.ts b/packages/harness/src/core/llm/responseFormat.tsnew file mode 100644index 000000000..a454937cf--- /dev/null+++ b/packages/harness/src/core/llm/responseFormat.ts@@ -0,0 +1,54 @@+import { z } from '@hono/zod-openapi';+import type { ChatCompletionCreateParamsStreaming } from 'openai/resources/chat';++/**+ * Wire/runtime response format (Zod). Kept in core so AgentDefinition and AgentSpec+ * share one type without agentSession → core inversion.+ * `passthrough()` lets unknown fields within a known `type` flow through to the LLM.+ */+export const ResponseFormatSchema = z+ .discriminatedUnion('type', [+ z.object({ type: z.literal('text') }).passthrough(),+ z.object({ type: z.literal('json_object') }).passthrough(),+ z+ .object({+ type: z.literal('json_schema'),+ json_schema: z+ .object({+ name: z.string(),+ description: z.string().optional(),+ schema: z.record(z.string(), z.unknown()).optional(),+ strict: z.boolean().nullable().optional(),+ })+ .passthrough(),+ })+ .passthrough(),+ ])+ .openapi('ResponseFormat');++export type ResponseFormat = z.infer<typeof ResponseFormatSchema>;++type OpenAIResponseFormat = NonNullable<ChatCompletionCreateParamsStreaming['response_format']>;++/**+ * Maps our wire ResponseFormat into the OpenAI SDK shape for the chat.completions body.+ * Field-by-field so exactOptionalPropertyTypes stays happy without assertions.+ */+export function toOpenAIResponseFormat(format: ResponseFormat): OpenAIResponseFormat {+ if (format.type === 'text') {+ return { type: 'text' };+ }+ if (format.type === 'json_object') {+ return { type: 'json_object' };+ }+ const { name, description, schema, strict } = format.json_schema;+ return {+ type: 'json_schema',+ json_schema: {+ name,+ ...(description !== undefined ? { description } : {}),+ ...(schema !== undefined ? { schema } : {}),+ ...(strict !== undefined ? { strict } : {}),+ },+ };+}diff --git a/packages/harness/src/core/llm/toOpenAIChatMessage.ts b/packages/harness/src/core/llm/toOpenAIChatMessage.tsnew file mode 100644index 000000000..39abf945d--- /dev/null+++ b/packages/harness/src/core/llm/toOpenAIChatMessage.ts@@ -0,0 +1,102 @@+import type {+ ChatCompletionContentPart,+ ChatCompletionMessageParam,+ ChatCompletionMessageToolCall,+} from 'openai/resources/chat';+import type { LLMContextMessage } from '../runtime/AgentThread.types';+import type { LLMUserMessage } from './LLMTypes';++/**+ * Maps harness context messages to the OpenAI chat message param shape.+ * Strips `tool_info` from assistant tool_calls; omits empty `tool_calls`.+ * Built field-by-field for exactOptionalPropertyTypes (no assertions).+ */+export function toOpenAIChatMessage(msg: LLMContextMessage): ChatCompletionMessageParam {+ if (msg.role === 'user') {+ return { role: 'user', content: toOpenAIUserContent(msg.content) };+ }++ if (msg.role === 'tool') {+ return {+ role: 'tool',+ tool_call_id: msg.tool_call_id,+ content: msg.content,+ };+ }++ // assistant+ const content =+ msg.content !== undefined && msg.content !== null ? { content: msg.content } : {};+ const refusal =+ msg.refusal !== undefined && msg.refusal !== null ? { refusal: msg.refusal } : {};+ const name = msg.name !== undefined ? { name: msg.name } : {};++ if (!msg.tool_calls?.length) {+ return { role: 'assistant', ...content, ...refusal, ...name };+ }++ return {+ role: 'assistant',+ ...content,+ ...refusal,+ ...name,+ tool_calls: msg.tool_calls.map(toOpenAIToolCall),+ };+}++function toOpenAIToolCall(tc: {+ id: string;+ function: { name: string; arguments: string };+}): ChatCompletionMessageToolCall {+ return {+ id: tc.id,+ type: 'function',+ function: {+ name: tc.function.name,+ arguments: tc.function.arguments,+ },+ };+}++function toOpenAIUserContent(content: LLMUserMessage['content']): string | ChatCompletionContentPart[] {+ if (typeof content === 'string') {+ return content;+ }++ const parts: ChatCompletionContentPart[] = [];+ for (const part of content) {+ if (part.type === 'text') {+ parts.push({ type: 'text', text: part.text });+ continue;+ }+ if (part.type === 'image_url') {+ parts.push({+ type: 'image_url',+ image_url: {+ url: part.image_url.url,+ ...(part.image_url.detail !== undefined ? { detail: part.image_url.detail } : {}),+ },+ });+ continue;+ }+ if (part.type === 'input_audio') {+ parts.push({+ type: 'input_audio',+ input_audio: {+ data: part.input_audio.data,+ format: part.input_audio.format,+ },+ });+ continue;+ }+ parts.push({+ type: 'file',+ file: {+ ...(part.file.file_data !== undefined ? { file_data: part.file.file_data } : {}),+ ...(part.file.file_id !== undefined ? { file_id: part.file.file_id } : {}),+ ...(part.file.filename !== undefined ? { filename: part.file.filename } : {}),+ },+ });+ }+ return parts;+}diff --git a/packages/harness/src/core/llm/usage.ts b/packages/harness/src/core/llm/usage.tsnew file mode 100644index 000000000..4258a5739--- /dev/null+++ b/packages/harness/src/core/llm/usage.ts@@ -0,0 +1,22 @@+import type { CompletionUsage } from './LLMTypes';++export function estimateTokensForString(s: string): number {+ return s.length / 4;+}++export function mergeUsage(a: CompletionUsage, b: CompletionUsage): CompletionUsage {+ return {+ prompt_tokens: a.prompt_tokens + b.prompt_tokens,+ completion_tokens: a.completion_tokens + b.completion_tokens,+ total_tokens: a.total_tokens + b.total_tokens,+ cache_read_input_tokens: (a.cache_read_input_tokens ?? 0) + (b.cache_read_input_tokens ?? 0),+ cache_creation_input_tokens: (a.cache_creation_input_tokens ?? 0) + (b.cache_creation_input_tokens ?? 0),+ prompt_tokens_details: {+ cached_tokens: (a.prompt_tokens_details?.cached_tokens ?? 0) + (b.prompt_tokens_details?.cached_tokens ?? 0),+ },+ completion_tokens_details: {+ reasoning_tokens:+ (a.completion_tokens_details?.reasoning_tokens ?? 0) + (b.completion_tokens_details?.reasoning_tokens ?? 0),+ },+ };+}diff --git a/packages/harness/src/core/mcp/ClientSideTool.ts b/packages/harness/src/core/mcp/ClientSideTool.tsnew file mode 100644index 000000000..09ac6711d--- /dev/null+++ b/packages/harness/src/core/mcp/ClientSideTool.ts@@ -0,0 +1,36 @@+import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import type { InternalToolCallInfo } from '../llm/LLMTypes';+import { NOOP_AGENT_TRACING } from '../tracing/NoopAgentTracing';+import type { CallToolResponse } from './IMCPServer';+import { LocalToolMCP } from './LocalToolMCP';++// NOTE(agent): ClientSideTool is never executed server-side. When the LLM calls a client-side+// tool, deriveAgentExecutionState() detects `is_client_side: true` on the tool_info and+// transitions to `user-input-required` before callTool() is ever reached.+// The callTool() override exists only as a safety net for impossible states.+export abstract class ClientSideTool extends LocalToolMCP {+ protected constructor() {+ super({ tracing: NOOP_AGENT_TRACING });+ }++ override async callTool(params: CallToolRequest['params']): Promise<CallToolResponse> {+ return {+ clientSideToolRequired: {+ tool_info: await this.toolCallInfo(params),+ },+ };+ }++ override async toolCallInfo(+ params: CallToolRequest['params'],+ _resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ return {+ type: 'truefoundry-system',+ original_tool_name: params.name,+ mcp_server_id: this.mcpServerId,+ mcp_server_name: this.name,+ is_client_side: true,+ };+ }+}diff --git a/packages/harness/src/core/mcp/IMCPServer.ts b/packages/harness/src/core/mcp/IMCPServer.tsnew file mode 100644index 000000000..650b8a1e7--- /dev/null+++ b/packages/harness/src/core/mcp/IMCPServer.ts@@ -0,0 +1,133 @@+import type { CallToolRequest, CallToolResult, ListToolsResult } from '@modelcontextprotocol/sdk/types.js';+import type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';+import type { AgentInfo, ApprovalDecision, MCPServerAuthInfo, MCPServerInitInfo } from '../events/eventSchemas';+import type { InternalToolCallInfo } from '../llm/LLMTypes';+import type { SandboxInfo } from '../sandbox/Sandbox';++export interface MCPAuthRequired {+ servers: MCPServerAuthInfo[];+}++export type ToolSchema = ListToolsResult['tools'][number];++export interface AgentToolSchema extends ToolSchema {+ preload: boolean;+}++export interface AuthRequiredResponse {+ authRequired: MCPAuthRequired;+}++export function isAuthRequired(response: ListToolsResponse | CallToolResponse): response is AuthRequiredResponse {+ return 'authRequired' in response;+}++export interface ListToolsResolvedResponse {+ result: { tools: AgentToolSchema[] };+ wasInitialized: MCPServerInitInfo | undefined;+}++export type ListToolsResponse = ListToolsResolvedResponse | AuthRequiredResponse;++export interface CallToolResolvedResponse {+ result: CallToolResult;+ wasInitialized: MCPServerInitInfo | undefined;+ // Set to true on the call that created the sandbox; emits `sandbox.created` upstream.+ sandboxCreated?: boolean | undefined;+ // Set on every sandbox-backed call; used for tracing.+ sandboxInfo?: SandboxInfo | undefined;+ events?: readonly RegisteredPassthroughEvent[] | undefined;+}++export type CallToolResultResponse = CallToolResolvedResponse | AuthRequiredResponse;++export interface CallToolCreateSubAgentResponse {+ createSubAgent: AgentInfo;+}++export interface ApprovalRequiredResponse {+ approvalRequired: { tool_info: InternalToolCallInfo };+}++export function isApprovalRequiredResponse(response: CallToolResponse): response is ApprovalRequiredResponse {+ return 'approvalRequired' in response;+}++export interface ClientSideToolRequiredResponse {+ clientSideToolRequired: { tool_info: InternalToolCallInfo };+}++export function isClientSideToolRequiredResponse(+ response: CallToolResponse,+): response is ClientSideToolRequiredResponse {+ return 'clientSideToolRequired' in response;+}++export type CallToolResponse =+ | CallToolResultResponse+ | CallToolCreateSubAgentResponse+ | ApprovalRequiredResponse+ | ClientSideToolRequiredResponse;++export function isCallToolResponseCreateSubAgent(+ response: CallToolResponse,+): response is CallToolCreateSubAgentResponse {+ return 'createSubAgent' in response;+}++export function isCallToolResponseResult(response: CallToolResponse): response is CallToolResolvedResponse {+ return 'result' in response;+}++type CallToolResultMetadata = Omit<CallToolResolvedResponse, 'result'>;++const EMPTY_METADATA: CallToolResultMetadata = { wasInitialized: undefined };++export function toolResultResponse(params: {+ text: string;+ overrides?: Partial<CallToolResultMetadata> | undefined;+ isError?: boolean | undefined;+}): CallToolResolvedResponse {+ return {+ result: { content: [{ type: 'text', text: params.text }], ...(params.isError && { isError: true }) },+ ...EMPTY_METADATA,+ ...params.overrides,+ };+}++/** Narrow public MCP server contract. Private implementations may expose additional members. */+export interface IToolSet {+ readonly name: string;+ readonly id: string;+ readonly description?: string | undefined;++ // True when every exposed tool is eager. DeferredTool uses the inverse.+ readonly preload: boolean;++ // Outcome-oriented preflight flag: Tool.ts calls listTools() initially when+ // this is true. It does not expose enable/disable/preload selector policy.+ readonly hasPreloadedTools: boolean;++ listTools(): Promise<ListToolsResponse>;++ callTool(params: CallToolRequest['params'], approvalDecision?: ApprovalDecision): Promise<CallToolResponse>;++ toolCallInfo(params: CallToolRequest['params'], resolveUnderlyingTool?: boolean): Promise<InternalToolCallInfo>;++ // Existing synchronous Code Mode allow-list. Optional implementations fall+ // back to the current unrestricted envelope; callTool still enforces policy.+ getAllowedToolNamesForSandbox?(): string[] | undefined;+}++/** Policy-free tool provider; a {@link ToolSet} wraps it to layer per-agent selector policy on top. */+export interface ToolSource {+ readonly name: string;+ readonly id: string;+ readonly description?: string | undefined;++ listTools(): Promise<ListToolsResolvedResponse | AuthRequiredResponse>;++ callTool(params: CallToolRequest['params'], approvalDecision?: ApprovalDecision): Promise<CallToolResponse>;++ toolCallInfo(params: CallToolRequest['params'], resolveUnderlyingTool?: boolean): Promise<InternalToolCallInfo>;+}diff --git a/packages/harness/src/core/mcp/LocalToolMCP.ts b/packages/harness/src/core/mcp/LocalToolMCP.tsnew file mode 100644index 000000000..c488139c0--- /dev/null+++ b/packages/harness/src/core/mcp/LocalToolMCP.ts@@ -0,0 +1,146 @@+import type { CallToolRequest, ListToolsResult } from '@modelcontextprotocol/sdk/types.js';+import { type AnyZodObject, z } from 'zod';+import zodToJsonSchema from 'zod-to-json-schema';+import type { ApprovalDecision } from '../events/eventSchemas';+import type { InternalToolCallInfo } from '../llm/LLMTypes';+import type { AgentTracing } from '../tracing/AgentTracing';+import {+ type CallToolResponse,+ isCallToolResponseResult,+ type IToolSet,+ type ListToolsResolvedResponse,+ toolResultResponse,+} from './IMCPServer';++function withValidatedInput<T extends z.ZodTypeAny>(+ schema: T,+ fn: (input: z.infer<T>, approvalDecision?: ApprovalDecision) => Promise<CallToolResponse>,+) {+ return async (raw: unknown, approvalDecision?: ApprovalDecision): Promise<CallToolResponse> => {+ const parsed = schema.safeParse(raw);+ if (!parsed.success) {+ return toolResultResponse({+ text: JSON.stringify({ error: 'Validation failed', details: parsed.error.flatten() }),+ isError: true,+ });+ }+ return fn(parsed.data, approvalDecision);+ };+}++export type ToolDefinition = ListToolsResult['tools'][number] & {+ execute: (raw: unknown, approvalDecision?: ApprovalDecision) => Promise<CallToolResponse>;+};++type ToolInputSchema = ListToolsResult['tools'][number]['inputSchema'];++function toJsonSchema(schema: AnyZodObject): ToolInputSchema {+ // Once we update zod see if we can remove `schema as any`+ // https://github.com/colinhacks/zod/issues/577+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- zod-to-json-schema typing lag+ return zodToJsonSchema(schema as any, { strictUnions: true }) as ToolInputSchema;+}++export function defineTool<T extends AnyZodObject>(config: {+ name: string;+ description: string;+ schema: T;+ // Handlers may opt into the approvalDecision (forwarded by the agent loop after the+ // user approves an approval-gated tool). Handlers that don't declare it ignore it.+ handler: (input: z.infer<T>, approvalDecision?: ApprovalDecision) => Promise<CallToolResponse>;+}): ToolDefinition {+ const jsonSchema = toJsonSchema(config.schema);+ return {+ name: config.name,+ description: config.description,+ inputSchema: jsonSchema,+ execute: withValidatedInput(config.schema, config.handler),+ };+}++/**+ * In-process {@link IToolSet} base for local tools: static tool list, allow-all (never filtered or+ * approval-gated), executed in-process within a local trace span. Base for all local/client-side tools.+ */+export abstract class LocalToolMCP implements IToolSet {+ abstract readonly name: string;+ abstract readonly displayName: string;+ readonly description: string = '';+ readonly preload: boolean = true;+ readonly hasPreloadedTools: boolean = true;+ readonly tracingEnabled: boolean = true;++ private readonly tracing: AgentTracing;++ protected constructor(options: { tracing: AgentTracing }) {+ this.tracing = options.tracing;+ }++ get id(): string {+ return this.mcpServerId;+ }++ protected get mcpServerId(): string {+ return this.name;+ }++ protected abstract getTools(): ToolDefinition[];++ async listTools(): Promise<ListToolsResolvedResponse> {+ return {+ result: {+ tools: this.getTools().map(t => ({+ name: t.name,+ description: t.description,+ inputSchema: t.inputSchema,+ preload: true,+ })),+ },+ wasInitialized: undefined,+ };+ }++ async callTool(params: CallToolRequest['params'], approvalDecision?: ApprovalDecision): Promise<CallToolResponse> {+ return this.tracing.withLocalToolSpan(+ {+ displayName: this.displayName,+ toolName: params.name,+ input: JSON.stringify(params.arguments),+ enabled: this.tracingEnabled,+ },+ async span => {+ const response = await this.executeTool(params, approvalDecision);+ span.setOutput(JSON.stringify(response));+ if (isCallToolResponseResult(response) && response.sandboxInfo) {+ span.setSandboxId(response.sandboxInfo.sandbox_id);+ }+ return response;+ },+ );+ }++ // Local tools are not approval gated by default+ async toolCallInfo(+ params: CallToolRequest['params'],+ _resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ return {+ type: 'truefoundry-system',+ mcp_server_id: this.mcpServerId,+ mcp_server_name: this.name,+ original_tool_name: params.name,+ is_approval_required: false,+ };+ }++ private async executeTool(+ params: CallToolRequest['params'],+ approvalDecision?: ApprovalDecision,+ ): Promise<CallToolResponse> {+ const tool = this.getTools().find(t => t.name === params.name);+ if (!tool) {+ return toolResultResponse({ text: JSON.stringify({ error: `Unknown tool: ${params.name}` }), isError: true });+ }+ return tool.execute(params.arguments, approvalDecision);+ }+}diff --git a/packages/harness/src/core/mcp/RemoteMCP.ts b/packages/harness/src/core/mcp/RemoteMCP.tsnew file mode 100644index 000000000..fc22bb7e3--- /dev/null+++ b/packages/harness/src/core/mcp/RemoteMCP.ts@@ -0,0 +1,283 @@+import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import type { Logger } from 'winston';+import { McpConnectionError } from '../errors';+import type { MCPServerInitInfo } from '../events/eventSchemas';+import type { InternalToolCallInfo } from '../llm/LLMTypes';+import type { AgentTracing } from '../tracing/AgentTracing';+import { NOOP_AGENT_TRACING } from '../tracing/NoopAgentTracing';+import {+ type AgentToolSchema,+ type AuthRequiredResponse,+ type CallToolResolvedResponse,+ type ListToolsResolvedResponse,+ type MCPAuthRequired,+ type ToolSource,+} from './IMCPServer';+import { paginateWithCursorGuard } from './pagination';+import {+ connectRemoteMcp,+ isSessionExpiredError,+ type RemoteMcpConnection,+ type RemoteMcpTransportType,+} from './remoteMcpClient';++/** Redacted url for trace spans: scheme + host + path only, so userinfo/query secrets never leak. */+function redactUrlForTrace(url: string): string {+ try {+ const u = new URL(url);+ return `${u.protocol}//${u.host}${u.pathname}`;+ } catch {+ return '';+ }+}++/** What a headers resolver returns: the headers to send, or a signal that auth is required. */+export type ResolveHeadersResult = { headers: Record<string, string> } | { authRequired: MCPAuthRequired };++/** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */+export type RemoteMcpHeaders = Record<string, string> | (() => Promise<ResolveHeadersResult>);++type ExecuteResult<T> = { result: T; wasInitialized: MCPServerInitInfo | undefined } | AuthRequiredResponse;++/**+ * Connection/session half of a remote MCP server: owns the transport (connects itself from `url` ++ * `headers`), session id, raw tool cache, connect single-flight and session-expiry retry. Policy-free+ * — a per-agent {@link ToolSet} layers policy.+ */+export class RemoteMCP implements ToolSource {+ readonly name: string;+ readonly id: string;+ readonly description?: string | undefined;++ private readonly url: string;+ private readonly headers: RemoteMcpHeaders;+ private readonly signal: AbortSignal;+ private readonly logger: Logger;+ private readonly tracing: AgentTracing;+ private readonly connectTimeoutMs?: number | undefined;+ // Redacted display url for trace spans (derived from url; unused when tracing is a no-op).+ private readonly traceUrl: string;++ private _connection?: RemoteMcpConnection | undefined;+ private isConnected = false;+ private connectPromise: Promise<MCPServerInitInfo | undefined> | undefined;+ // undefined = never connected, string = stateful session id, null = stateless/SSE.+ private sessionId: string | null | undefined;+ private resolvedTransportType?: RemoteMcpTransportType | undefined;+ private cachedTools?: AgentToolSchema[] | undefined;++ constructor(params: {+ name: string;+ id: string;+ description?: string | undefined;+ url: string;+ headers: RemoteMcpHeaders;+ logger: Logger;+ tracing?: AgentTracing | undefined;+ sessionId?: string | undefined;+ transportType?: RemoteMcpTransportType | undefined;+ connectTimeoutMs?: number | undefined;+ signal: AbortSignal;+ }) {+ this.name = params.name;+ this.id = params.id;+ this.description = params.description;+ this.url = params.url;+ this.headers = params.headers;+ this.signal = params.signal;+ this.sessionId = params.sessionId;+ this.resolvedTransportType = params.transportType;+ this.connectTimeoutMs = params.connectTimeoutMs;+ this.logger = params.logger;+ this.tracing = params.tracing ?? NOOP_AGENT_TRACING;+ this.traceUrl = redactUrlForTrace(params.url);+ }++ getSessionId(): string | undefined {+ return this.sessionId ?? undefined;+ }++ private get connection(): RemoteMcpConnection {+ if (!this._connection) {+ throw new Error(`Remote MCP '${this.name}' not connected - connectIfNeeded() must run first`);+ }+ return this._connection;+ }++ private async resetConnection(): Promise<void> {+ this.isConnected = false;+ this.sessionId = undefined;+ this.cachedTools = undefined;+ this.connectPromise = undefined;+ await this.closeAndClearConnection();+ }++ private async closeAndClearConnection(): Promise<void> {+ await this._connection?.close().catch(() => {});+ this._connection = undefined;+ }++ private async resolveHeaders(): Promise<ResolveHeadersResult> {+ if (typeof this.headers !== 'function') return { headers: this.headers };+ return await this.headers();+ }++ private async executeWithSessionRetry<T>(operation: () => Promise<T>): Promise<ExecuteResult<T>> {+ // Auth is re-checked on every operation, not only on the first connect: a registered server's OAuth+ // can be revoked or expire mid-request, and callers must get authRequired rather than a generic+ // upstream failure. When already connected the resolved headers are unused (connect is skipped).+ const headersResult = await this.resolveHeaders();+ if ('authRequired' in headersResult) return { authRequired: headersResult.authRequired };+ return this.connectAndRun(headersResult.headers, operation, true);+ }++ private async connectAndRun<T>(+ headers: Record<string, string>,+ operation: () => Promise<T>,+ canRetry: boolean,+ ): Promise<ExecuteResult<T>> {+ try {+ const initInfo = await this.connectIfNeeded(headers);+ return { result: await operation(), wasInitialized: initInfo };+ } catch (error) {+ if (canRetry && isSessionExpiredError(error)) {+ this.logger.info(`Session expired for remote MCP ${this.name}, reinitializing...`);+ await this.resetConnection();+ return this.connectAndRun(headers, operation, false);+ }+ throw error;+ }+ }++ private async loadTools(): Promise<{ tools: AgentToolSchema[] }> {+ return this.tracing.withRemoteMcpToolSpan(+ { method: 'tools/list', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },+ async span => {+ const tools = await paginateWithCursorGuard(+ async cursor => {+ const page = await this.connection.listTools(cursor);+ return { items: page.tools, ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}) };+ },+ this.name,+ this.logger,+ );+ this.cachedTools = tools.map(t => ({ ...t, preload: true }));+ span.setNumberOfTools(this.cachedTools.length);+ return { tools: this.cachedTools };+ },+ );+ }++ /** Unfiltered tool list (no policy). The per-agent wrapper applies selectors on top. */+ async listTools(): Promise<ListToolsResolvedResponse | AuthRequiredResponse> {+ if (this.cachedTools) {+ return { result: { tools: this.cachedTools }, wasInitialized: undefined };+ }+ const response = await this.executeWithSessionRetry(() => this.loadTools());+ if ('authRequired' in response) return response;+ return { result: { tools: response.result.tools }, wasInitialized: response.wasInitialized };+ }++ async callTool(params: CallToolRequest['params']): Promise<CallToolResolvedResponse | AuthRequiredResponse> {+ const response = await this.executeWithSessionRetry(() =>+ this.tracing.withRemoteMcpToolSpan(+ {+ method: 'tools/call',+ serverName: this.name,+ serverId: this.id,+ serverUrl: this.traceUrl,+ toolName: params.name,+ input: JSON.stringify(params.arguments),+ enabled: true,+ },+ async span => {+ const result = await this.connection.callTool(params);+ span.setOutput(JSON.stringify(result));+ return result;+ },+ ),+ );+ if ('authRequired' in response) return response;+ return { result: response.result, wasInitialized: response.wasInitialized };+ }++ async toolCallInfo(+ params: CallToolRequest['params'],+ _resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ return {+ type: 'mcp',+ original_tool_name: params.name,+ mcp_server_id: this.id,+ mcp_server_name: this.name,+ is_approval_required: false,+ };+ }++ private async connectIfNeeded(headers: Record<string, string>): Promise<MCPServerInitInfo | undefined> {+ if (this.isConnected) return undefined;+ if (this.connectPromise) {+ // Wait for the in-flight connect, but only its originator emits the init metadata.+ await this.connectPromise;+ return undefined;+ }++ const existingSessionId = this.sessionId;+ this.connectPromise = (async (): Promise<MCPServerInitInfo | undefined> => {+ let connection: RemoteMcpConnection;+ try {+ await this.closeAndClearConnection();+ connection = await this.tracing.withRemoteMcpToolSpan(+ { method: 'initialize', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },+ async span => {+ const sessionIdValue = this.sessionId ?? undefined;+ const conn = await connectRemoteMcp({+ url: this.url,+ headers,+ ...(sessionIdValue !== undefined ? { sessionId: sessionIdValue } : {}),+ // Hint from a prior connect+ ...(this.resolvedTransportType !== undefined ? { knownTransportType: this.resolvedTransportType } : {}),+ ...(this.connectTimeoutMs !== undefined ? { connectTimeoutMs: this.connectTimeoutMs } : {}),+ signal: this.signal,+ onClose: () => {+ this.isConnected = false;+ },+ onError: error => {+ this.logger.error(`Error on remote MCP transport ${this.name}`, { error });+ },+ });+ span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));+ return conn;+ },+ );+ } catch (error) {+ await this.closeAndClearConnection();+ throw this.toConnectError(error);+ }+ this._connection = connection;+ this.resolvedTransportType = connection.transportType;+ this.isConnected = true;+ this.sessionId = connection.sessionId;+ if (existingSessionId === this.sessionId) {+ return undefined;+ }+ return {+ name: this.name,+ id: this.id,+ session_id: this.sessionId ?? undefined,+ transport_type: this.resolvedTransportType,+ };+ })().finally(() => {+ this.connectPromise = undefined;+ });+ return this.connectPromise;+ }++ private toConnectError(error: unknown): McpConnectionError {+ const statusCode = error instanceof McpConnectionError ? error.statusCode : 502;+ const message = error instanceof Error ? error.message : String(error);+ return new McpConnectionError(`Failed to connect to remote MCP server '${this.name}': ${message}`, statusCode, {+ cause: error,+ });+ }+}diff --git a/packages/harness/src/core/mcp/ToolSelectorPolicy.ts b/packages/harness/src/core/mcp/ToolSelectorPolicy.tsnew file mode 100644index 000000000..b72d15592--- /dev/null+++ b/packages/harness/src/core/mcp/ToolSelectorPolicy.ts@@ -0,0 +1,117 @@+import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';+import type { AgentToolSchema } from './IMCPServer';+import {+ DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS,+ isToolAllowed,+ literalToolNames,+ selectorsIncludeAll,+ toolMatchesAnySelector,+ toolRequiresApproval,+} from './toolSelectors';++/**+ * Per-server tool selectors. Enable/disable/preload tags: `@all`, `@read-only`.+ * Approval tags: `@all`, `@write`, `@destructive`.+ */+export interface ToolSelectorConfig {+ enableTools: string[];+ disableTools: string[];+ preloadTools: string[];+ requireApprovalForTools?: string[] | undefined;+}++/**+ * Encapsulates enable/disable/preload/approval selector policy for a single MCP server. Pure: it+ * never throws or does IO — callers decide how to surface a disallowed/missing tool so each can+ * raise its own error type.+ */+export class ToolSelectorPolicy {+ readonly preload: boolean;+ readonly hasPreloadedTools: boolean;++ private readonly enableTools: string[];+ private readonly disableTools: string[];+ private readonly preloadTools: string[];+ private readonly requireApprovalForTools: string[];+ // Tool names that survived enable/disable filtering on the most recent filterAndAnnotate() call.+ // Used by the sandbox allow-list and as the fast path for callTool gating.+ private resolvedAllowedToolNames: string[] | undefined;++ constructor(params: { selectors: ToolSelectorConfig; preload: boolean }) {+ this.enableTools = params.selectors.enableTools;+ this.disableTools = params.selectors.disableTools;+ this.preloadTools = params.selectors.preloadTools;+ this.requireApprovalForTools = params.selectors.requireApprovalForTools ?? DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS;+ this.preload = params.preload;+ this.hasPreloadedTools = params.preload || this.preloadTools.length > 0;+ }++ /** Literal enable_tools names that are not present on the server (caller throws if non-empty). */+ missingEnableLiterals(tools: AgentToolSchema[]): string[] {+ const availableNames = new Set(tools.map(t => t.name));+ return literalToolNames(this.enableTools).filter(name => !availableNames.has(name));+ }++ /** Filter by enable/disable, record the resolved allow-list, and annotate per-tool preload. */+ filterAndAnnotate(tools: AgentToolSchema[]): AgentToolSchema[] {+ const filtered = tools.filter(tool =>+ isToolAllowed({+ toolName: tool.name,+ annotations: tool.annotations,+ enableSelectors: this.enableTools,+ disableSelectors: this.disableTools,+ }),+ );+ this.resolvedAllowedToolNames = filtered.map(t => t.name);+ return filtered.map(tool => ({ ...tool, preload: this.isToolPreloaded(tool.name, tool.annotations) }));+ }++ private isToolPreloaded(toolName: string, annotations: ToolAnnotations | undefined): boolean {+ // Fully-preloaded server: every allowed tool is loaded into context.+ if (this.preload) return true;+ // Otherwise only the tools matching `preload_tools` stay eager.+ return toolMatchesAnySelector(toolName, annotations, this.preloadTools);+ }++ /**+ * Whether a tool may be called. Uses the resolved allow-list once listTools() has run; before that+ * falls back to matching against the raw selectors, resolving annotations lazily only when needed.+ */+ async isAllowed(toolName: string, resolveAnnotations: () => Promise<ToolAnnotations | undefined>): Promise<boolean> {+ if (this.resolvedAllowedToolNames) {+ return this.resolvedAllowedToolNames.includes(toolName);+ }+ return isToolAllowed({+ toolName,+ annotations: await resolveAnnotations(),+ enableSelectors: this.enableTools,+ disableSelectors: this.disableTools,+ });+ }++ /**+ * Best-effort allow-list for the sandbox. After a listTools() call returns the concrete names;+ * before that, `@all` with no disables means "unrestricted" (undefined), else the literal names.+ */+ allowedNamesForSandbox(): string[] | undefined {+ if (this.resolvedAllowedToolNames) {+ return this.resolvedAllowedToolNames;+ }+ if (selectorsIncludeAll(this.enableTools) && this.disableTools.length === 0) {+ return undefined;+ }+ return literalToolNames(this.enableTools);+ }++ /**+ * Approvals are always enabled. Required if the agent's own selectors match OR the tool is+ * write/destructive — the default set is a floor the per-agent selectors can widen but never+ * drop below.+ */+ requiresApproval(toolName: string, annotations: ToolAnnotations | undefined): boolean {+ return (+ toolRequiresApproval(toolName, annotations, this.requireApprovalForTools) ||+ toolRequiresApproval(toolName, annotations, DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS)+ );+ }+}diff --git a/packages/harness/src/core/mcp/ToolSet.ts b/packages/harness/src/core/mcp/ToolSet.tsnew file mode 100644index 000000000..49e6a03ff--- /dev/null+++ b/packages/harness/src/core/mcp/ToolSet.ts@@ -0,0 +1,133 @@+import type { CallToolRequest, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';+import { McpConnectionError } from '../errors';+import type { ApprovalDecision } from '../events/eventSchemas';+import type { InternalToolCallInfo } from '../llm/LLMTypes';+import {+ isAuthRequired,+ isCallToolResponseResult,+ toolResultResponse,+ type AgentToolSchema,+ type CallToolResponse,+ type IToolSet,+ type ListToolsResponse,+ type ToolSource,+} from './IMCPServer';+import { ToolSelectorPolicy, type ToolSelectorConfig } from './ToolSelectorPolicy';++/**+ * Per-agent {@link IToolSet} view over a shared, policy-free {@link ToolSource}, applying the+ * enable/disable/preload/approval selectors. Many can wrap one source without policy bleed.+ */+export class ToolSet implements IToolSet {+ readonly name: string;+ readonly id: string;+ readonly description?: string | undefined;+ readonly preload: boolean;+ readonly hasPreloadedTools: boolean;++ private readonly source: ToolSource;+ private readonly policy: ToolSelectorPolicy;++ constructor(params: { source: ToolSource; selectors: ToolSelectorConfig; preload: boolean }) {+ this.source = params.source;+ this.name = params.source.name;+ this.id = params.source.id;+ this.description = params.source.description;+ this.policy = new ToolSelectorPolicy({+ selectors: params.selectors,+ preload: params.preload,+ });+ this.preload = this.policy.preload;+ this.hasPreloadedTools = this.policy.hasPreloadedTools;+ }++ getAllowedToolNamesForSandbox(): string[] | undefined {+ return this.policy.allowedNamesForSandbox();+ }++ async listTools(): Promise<ListToolsResponse> {+ const response = await this.source.listTools();+ if (isAuthRequired(response)) return response;++ const tools = response.result.tools;+ const missingTools = this.policy.missingEnableLiterals(tools);+ if (missingTools.length > 0) {+ throw new McpConnectionError(+ `Requested tools not found in MCP server ${this.name}: ${missingTools.join(', ')}`,+ 400,+ );+ }++ return {+ result: { tools: this.policy.filterAndAnnotate(tools) },+ wasInitialized: response.wasInitialized,+ };+ }++ async callTool(params: CallToolRequest['params'], decision?: ApprovalDecision): Promise<CallToolResponse> {+ // Prime the source and surface auth-required before the annotation-based allow/approval checks+ // (which would otherwise see missing annotations and wrongly 403).+ const listed = await this.source.listTools();+ if (isAuthRequired(listed)) return listed;+ const annotations = findAnnotations(listed.result.tools, params.name);++ await this.assertToolAllowed(params.name, annotations);++ const tool_info = await this.buildToolCallInfo(params, annotations);+ if (!decision && tool_info.is_approval_required) {+ return { approvalRequired: { tool_info } };+ }++ if (decision?.status === 'deny') {+ const reason = decision.reason ?? 'no reason provided';+ return toolResultResponse({+ text: JSON.stringify({ error: `User denied tool call: ${reason}` }),+ isError: true,+ });+ }++ const response = await this.source.callTool(params, decision);+ // The priming listTools() may have captured the first-connect init; carry it forward since the+ // subsequent callTool sees an already-open connection and reports none.+ if (listed.wasInitialized && isCallToolResponseResult(response) && !response.wasInitialized) {+ return { ...response, wasInitialized: listed.wasInitialized };+ }+ return response;+ }++ async toolCallInfo(+ params: CallToolRequest['params'],+ resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ const annotations = await this.resolveAnnotations(params.name);+ return this.buildToolCallInfo(params, annotations, resolveUnderlyingTool);+ }++ private async assertToolAllowed(toolName: string, annotations: ToolAnnotations | undefined): Promise<void> {+ const allowed = await this.policy.isAllowed(toolName, async () => annotations);+ if (!allowed) {+ throw new McpConnectionError(`Tool '${toolName}' is not allowed on MCP server ${this.name}`, 403);+ }+ }++ private async buildToolCallInfo(+ params: CallToolRequest['params'],+ annotations: ToolAnnotations | undefined,+ resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ return {+ ...(await this.source.toolCallInfo(params, resolveUnderlyingTool)),+ is_approval_required: this.policy.requiresApproval(params.name, annotations),+ };+ }++ private async resolveAnnotations(toolName: string): Promise<ToolAnnotations | undefined> {+ const listed = await this.source.listTools();+ if (isAuthRequired(listed)) return undefined;+ return findAnnotations(listed.result.tools, toolName);+ }+}++function findAnnotations(tools: AgentToolSchema[], toolName: string): ToolAnnotations | undefined {+ return tools.find(t => t.name === toolName)?.annotations;+}diff --git a/packages/harness/src/core/mcp/convertMCPServers.ts b/packages/harness/src/core/mcp/convertMCPServers.tsnew file mode 100644index 000000000..4bdc828fe--- /dev/null+++ b/packages/harness/src/core/mcp/convertMCPServers.ts@@ -0,0 +1,88 @@+import type { ChatCompletionTool } from 'openai/resources/chat';+import type { MCPServerInitInfo } from '../events/eventSchemas';+import type { MCPAuthRequired } from '../mcp/IMCPServer';+import { type IToolSet, isAuthRequired } from './IMCPServer';+import { getUniqueSanitizedToolName } from './toolNames';++export interface MappedMCPTool {+ toolSet: IToolSet;+ originalToolName: string;+}++export interface ConvertToolsResult {+ tools: ChatCompletionTool[];+ toolMapping: Map<string, MappedMCPTool>;+}++export interface ConvertMCPServersToToolsResult {+ convertedTools: ConvertToolsResult;+ initializationInfo: MCPServerInitInfo[];+ authRequirementInfo: MCPAuthRequired[];+}++export async function convertMCPServersToTools(params: {+ tfyManagedServers: IToolSet[];+ userServers: IToolSet[];+}): Promise<ConvertMCPServersToToolsResult> {+ const { tfyManagedServers, userServers } = params;+ const tools: ChatCompletionTool[] = [];+ const toolMapping = new Map<string, MappedMCPTool>();+ const initializationInfo: MCPServerInitInfo[] = [];+ const authRequirementInfo: MCPAuthRequired[] = [];+ const registeredNames = new Set<string>();++ // Skip non-preloaded servers that have no preloaded tools, to avoid unnecessary listTools() calls and OAuth triggers.+ // Non-preloaded servers with some preloaded tools are kept so those tools can be registered.+ const filteredUserServers = userServers.filter(s => s.preload || s.hasPreloadedTools);++ // TFY-managed servers first so they claim their original tool names before user servers.+ const sortedTfyServers = [...tfyManagedServers].sort((a, b) => (a.name > b.name ? 1 : -1));+ const sortedUserServers = [...filteredUserServers].sort((a, b) => (a.name > b.name ? 1 : -1));+ const allServers = [...sortedTfyServers, ...sortedUserServers];++ const listResults = await Promise.all(+ allServers.map(async server => ({ serverName: server.name, response: await server.listTools() })),+ );++ for (let i = 0; i < allServers.length; i++) {+ const listResult = listResults[i];+ if (!listResult) continue;+ const { serverName, response: listResponse } = listResult;+ if (isAuthRequired(listResponse)) {+ authRequirementInfo.push(listResponse.authRequired);+ continue;+ }+ const { result: mcpTools, wasInitialized } = listResponse;+ if (wasInitialized) {+ initializationInfo.push(wasInitialized);+ }++ const toolSet = allServers[i]!;+ const sortedTools = [...mcpTools.tools].sort((a, b) => (a.name > b.name ? 1 : -1));+ for (const mcpTool of sortedTools) {+ if (!mcpTool.preload) continue;+ const { name: toolName } = getUniqueSanitizedToolName(mcpTool.name, registeredNames);+ registeredNames.add(toolName);+ const description = `mcp server: ${serverName}\n${mcpTool.description || ''}`;+ tools.push({+ type: 'function',+ function: {+ name: toolName,+ description: description,+ parameters: {+ type: 'object',+ properties: mcpTool.inputSchema?.properties ?? {},+ required: (mcpTool.inputSchema?.required as string[]) ?? [],+ },+ },+ });++ toolMapping.set(toolName, {+ toolSet,+ originalToolName: mcpTool.name,+ });+ }+ }++ return { convertedTools: { tools, toolMapping }, initializationInfo, authRequirementInfo };+}diff --git a/packages/harness/src/core/mcp/executeToolCalls.ts b/packages/harness/src/core/mcp/executeToolCalls.tsnew file mode 100644index 000000000..a5f58905f--- /dev/null+++ b/packages/harness/src/core/mcp/executeToolCalls.ts@@ -0,0 +1,196 @@+import type { ApprovalDecision, MCPServerInitInfo } from '../events/eventSchemas';+import type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';+import type { InternalEnrichedAssistantMessage, InternalEnrichedToolCall, LLMToolMessage } from '../llm/LLMTypes';+import type { MCPAuthRequired } from '../mcp/IMCPServer';+import type { AgentThreadCreateSubAgent } from '../runtime/AgentThread.types';+import { InternalEventType } from '../runtime/AgentThread.types';+import type { SandboxInfo } from '../sandbox/Sandbox';+import type { MappedMCPTool } from './convertMCPServers';+import {+ isApprovalRequiredResponse,+ isAuthRequired,+ isCallToolResponseCreateSubAgent,+ isClientSideToolRequiredResponse,+ toolResultResponse,+} from './IMCPServer';++export interface ToolCallResult {+ message: LLMToolMessage;+ // Absent only for unknown-tool calls (LLM hallucinated a name not in toolMapping):+ // there is no backing MCP server. Downstream consumers (e.g. LargeToolResponse)+ // gate on `failure: false` before reading `info`, so the absence is naturally+ // short-circuited on the success path.+ info?: MappedMCPTool | undefined;+ failure: boolean;+ isStructuredContent: boolean;+ completedAt: string;+}++export interface ExecuteToolCallsResult {+ toolCallResults: ToolCallResult[];+ initializationInfo: MCPServerInitInfo[];+ createThreadEvents: AgentThreadCreateSubAgent[];+ sandboxCreated: SandboxInfo | undefined;+ authRequirementInfo: MCPAuthRequired[];+ approvalRequiredToolCalls: InternalEnrichedToolCall[];+ clientSideToolCalls: InternalEnrichedToolCall[];+ events: RegisteredPassthroughEvent[];+}++export async function executeToolCalls({+ assistantMessage,+ toolMapping,+ threadId,+ approvalDecisions,+}: {+ assistantMessage: InternalEnrichedAssistantMessage;+ toolMapping: Map<string, MappedMCPTool>;+ threadId: string;+ approvalDecisions: Map<string, ApprovalDecision>;+}): Promise<ExecuteToolCallsResult> {+ const toolMessages: ToolCallResult[] = [];+ const initializationInfo: MCPServerInitInfo[] = [];+ const createThreadEvents: AgentThreadCreateSubAgent[] = [];+ const authRequirementInfo: MCPAuthRequired[] = [];+ const approvalRequiredToolCalls: InternalEnrichedToolCall[] = [];+ const clientSideToolCalls: InternalEnrichedToolCall[] = [];+ const passthroughEvents: RegisteredPassthroughEvent[] = [];+ let sandboxCreated: SandboxInfo | undefined;++ if (!assistantMessage.tool_calls) {+ return {+ toolCallResults: toolMessages,+ initializationInfo,+ createThreadEvents,+ sandboxCreated,+ authRequirementInfo,+ approvalRequiredToolCalls,+ clientSideToolCalls,+ events: passthroughEvents,+ };+ }++ const toolCallPromises = assistantMessage.tool_calls.map(async toolCall => {+ const toolInfo = toolMapping.get(toolCall.function.name);+ if (!toolInfo) {+ return {+ toolCall,+ toolInfo,+ response: toolResultResponse({ text: `Tool ${toolCall.function.name} not found in tool mapping` }),+ failure: true,+ completedAt: new Date().toISOString(),+ };+ }++ try {+ const args = JSON.parse(toolCall.function.arguments || '{}');+ const response = await toolInfo.toolSet.callTool(+ {+ name: toolInfo.originalToolName,+ arguments: args,+ },+ approvalDecisions.get(toolCall.id),+ );+ return { toolCall, toolInfo, response, failure: false, completedAt: new Date().toISOString() };+ } catch (error) {+ return {+ toolCall,+ toolInfo,+ response: toolResultResponse({+ text: JSON.stringify({ error: error instanceof Error ? error.message : 'Tool execution failed' }),+ isError: true,+ }),+ failure: true,+ completedAt: new Date().toISOString(),+ };+ }+ });++ const results = await Promise.all(toolCallPromises);+ for (const { toolCall, toolInfo, response, failure, completedAt } of results) {+ if (isCallToolResponseCreateSubAgent(response)) {+ createThreadEvents.push({+ type: InternalEventType.AGENT_CREATE_SUBAGENT,+ thread_id: threadId,+ tool_call_id: toolCall.id,+ agent_info: response.createSubAgent,+ });+ continue;+ }++ if (isAuthRequired(response)) {+ authRequirementInfo.push(response.authRequired);+ // Must still emit a tool result so every tool_call in the assistant message has a+ // matching tool_result in context; otherwise the LLM API rejects the conversation.+ toolMessages.push({+ message: {+ role: 'tool',+ tool_call_id: toolCall.id,+ content: 'Waiting for user to authenticate. Please try again 1 time.',+ },+ failure: true,+ info: toolInfo,+ isStructuredContent: false,+ completedAt,+ });+ continue;+ }++ if (isApprovalRequiredResponse(response)) {+ approvalRequiredToolCalls.push(toolCall);+ continue;+ }++ if (isClientSideToolRequiredResponse(response)) {+ clientSideToolCalls.push(toolCall);+ continue;+ }++ const { result, wasInitialized } = response;++ let content: string;+ let isStructuredContent = false;+ if (result.isError) {+ content = JSON.stringify({ error: result.content });+ } else if (result.structuredContent) {+ isStructuredContent = true;+ content = JSON.stringify(result.structuredContent);+ } else if (Array.isArray(result.content)) {+ const textContent = result.content+ .filter((c): c is { type: 'text'; text: string } => c.type === 'text')+ .map(c => c.text)+ .join('\n');+ content = textContent || JSON.stringify(result.content);+ } else {+ content = JSON.stringify(result.content);+ }++ toolMessages.push({+ message: { role: 'tool' as const, tool_call_id: toolCall.id, content },+ failure,+ info: toolInfo,+ isStructuredContent,+ completedAt,+ });+ if (wasInitialized) {+ initializationInfo.push(wasInitialized);+ }+ if (response.sandboxCreated && response.sandboxInfo) {+ sandboxCreated = response.sandboxInfo;+ }+ if (response.events?.length) {+ passthroughEvents.push(...response.events);+ }+ }++ return {+ toolCallResults: toolMessages,+ initializationInfo,+ createThreadEvents,+ sandboxCreated,+ authRequirementInfo,+ approvalRequiredToolCalls,+ clientSideToolCalls,+ events: passthroughEvents,+ };+}diff --git a/packages/harness/src/core/mcp/pagination.ts b/packages/harness/src/core/mcp/pagination.tsnew file mode 100644index 000000000..314c7ff81--- /dev/null+++ b/packages/harness/src/core/mcp/pagination.ts@@ -0,0 +1,34 @@+import type { Logger } from 'winston';++/**+ * Walk an MCP cursor-paginated list to completion, guarding against servers that return a+ * previously seen cursor (which would otherwise loop forever). If a repeated cursor is seen the+ * loop stops and (when a logger is supplied) a warning is emitted naming the server.+ */+export async function paginateWithCursorGuard<T>(+ fetchNext: (cursor: string | undefined) => Promise<{ items: T[]; nextCursor?: string }>,+ serverIdentifier: string | undefined,+ logger?: Logger,+): Promise<T[]> {+ const allItems: T[] = [];+ const seenCursors = new Set<string>();+ const serverName = serverIdentifier || 'unknown';++ const firstResult = await fetchNext(undefined);+ allItems.push(...firstResult.items);+ let cursor = firstResult.nextCursor;++ while (cursor) {+ if (seenCursors.has(cursor)) {+ logger?.warn(`Detected repeated cursor "${cursor}" from server ${serverName}. Breaking pagination loop.`);+ break;+ }+ seenCursors.add(cursor);++ const result = await fetchNext(cursor);+ allItems.push(...result.items);+ cursor = result.nextCursor;+ }++ return allItems;+}diff --git a/packages/harness/src/core/mcp/remoteMcpClient.ts b/packages/harness/src/core/mcp/remoteMcpClient.tsnew file mode 100644index 000000000..29b5623d2--- /dev/null+++ b/packages/harness/src/core/mcp/remoteMcpClient.ts@@ -0,0 +1,166 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types.js';+import { context, propagation } from '@opentelemetry/api';+import { McpConnectionError } from '../errors';+import { withTimeout } from '../util/promiseUtils';+import type { ToolSchema } from './IMCPServer';++/** Networking for remote (url-based) MCP servers, kept separate so it can be mocked in tests. */++export type RemoteMcpTransportType = 'streamable-http' | 'sse';++export interface RemoteMcpConnection {+ readonly transportType: RemoteMcpTransportType;+ /** Session id for a stateful server, or null for a stateless one. */+ readonly sessionId: string | null;+ listTools(cursor?: string): Promise<{ tools: ToolSchema[]; nextCursor?: string }>;+ callTool(params: CallToolRequest['params']): Promise<CallToolResult>;+ close(): Promise<void>;+}++type McpTransport = StreamableHTTPClientTransport | SSEClientTransport;++const CLIENT_INFO = { name: 'tfy-agent-mcp-client', version: '1.0.0' } as const;+const TRANSPORT_PROBE_ORDER: RemoteMcpTransportType[] = ['streamable-http', 'sse'];++export const REQUEST_TIMEOUT_MS = 1_800_000;+export const CONNECT_TIMEOUT_MS = 30_000;++class McpClientWithTimeout extends Client {+ constructor() {+ super(CLIENT_INFO, { capabilities: {} });+ }++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ override request(req: any, schema: any, options?: any): Promise<any> {+ return super.request(req, schema, { ...options, timeout: REQUEST_TIMEOUT_MS });+ }+}++function createTransport(+ type: RemoteMcpTransportType,+ url: URL,+ headers: Record<string, string>,+ sessionId?: string,+): McpTransport {+ const requestInit = { headers };+ if (type === 'streamable-http') {+ return new StreamableHTTPClientTransport(url, { requestInit, ...(sessionId !== undefined ? { sessionId } : {}) });+ }+ return new SSEClientTransport(url, { requestInit });+}++export function isSessionExpiredError(error: unknown): boolean {+ if (!(error instanceof Error)) return false;+ if ('code' in error && error.code === 404) return true;+ return error.message.includes('HTTP 404') || error.message.toLowerCase().includes('session');+}++function isAuthError(error: unknown): boolean {+ if (!(error instanceof Error)) return false;+ if ('code' in error && error.code === 401) return true;+ return error.message.includes('HTTP 401');+}++/** Inject the active otel trace context so each request propagates its span. */+function stampTraceHeaders(headers: Record<string, string>): void {+ propagation.inject(context.active(), headers);+}++function getTransportSessionId(transport: McpTransport): string | null {+ return transport instanceof StreamableHTTPClientTransport ? (transport.sessionId ?? null) : null;+}++function toConnectError(error: unknown): McpConnectionError {+ if (error instanceof McpConnectionError) return error;+ if (isAuthError(error)) {+ return new McpConnectionError('upstream returned 401 Unauthorized (check x-tfy-mcp-headers credentials)', 401, {+ cause: error,+ });+ }+ const message = error instanceof Error ? error.message : String(error);+ return new McpConnectionError(message, 502, { cause: error });+}++function buildConnection(+ client: McpClientWithTimeout,+ transport: McpTransport,+ transportType: RemoteMcpTransportType,+ headers: Record<string, string>,+ requestOptions: { signal: AbortSignal },+): RemoteMcpConnection {+ return {+ transportType,+ sessionId: getTransportSessionId(transport),+ listTools: async (cursor?: string) => {+ stampTraceHeaders(headers);+ const response = await client.listTools(cursor ? { cursor } : undefined, requestOptions);+ return { tools: response.tools, ...(response.nextCursor !== undefined ? { nextCursor: response.nextCursor } : {}) };+ },+ callTool: async (callParams: CallToolRequest['params']): Promise<CallToolResult> => {+ stampTraceHeaders(headers);+ return (await client.callTool(callParams, undefined, requestOptions)) as CallToolResult;+ },+ close: async (): Promise<void> => {+ await client.close().catch(() => {});+ },+ };+}++/**+ * Connect to a remote MCP server, keeping the first transport that connects. `sessionId` is passed to+ * every attempt so a stateful session resumes in place instead of opening a throwaway one.+ *+ * `knownTransportType` is a hint (from a prior connect / persisted state): it's tried first for a fast+ * path, but on failure we still fall back to probing the remaining transports, so a stale or wrong+ * hint (server switched transports, bad resume data) self-heals instead of failing every turn.+ */+export async function connectRemoteMcp(params: {+ url: string;+ headers: Record<string, string>;+ sessionId?: string | undefined;+ knownTransportType?: RemoteMcpTransportType | undefined;+ connectTimeoutMs?: number | undefined;+ signal: AbortSignal;+ onClose?: () => void | undefined;+ onError?: (error: Error) => void | undefined;+}): Promise<RemoteMcpConnection> {+ const url = new URL(params.url);+ const requestOptions = { signal: params.signal };+ const candidates = params.knownTransportType+ ? [params.knownTransportType, ...TRANSPORT_PROBE_ORDER.filter(t => t !== params.knownTransportType)]+ : TRANSPORT_PROBE_ORDER;+ const failures: { transport: RemoteMcpTransportType; error: string }[] = [];++ for (const transportType of candidates) {+ const transport = createTransport(transportType, url, params.headers, params.sessionId);+ const client = new McpClientWithTimeout();+ try {+ stampTraceHeaders(params.headers);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- exactOptionalPropertyTypes mismatch between SDK Transport interface and StreamableHTTPClientTransport.sessionId+ await withTimeout(+ client.connect(transport as any, requestOptions),+ params.connectTimeoutMs ?? CONNECT_TIMEOUT_MS,+ transportType,+ );+ } catch (error) {+ await client.close().catch(() => {});+ if (isAuthError(error)) throw toConnectError(error);+ // A session-expired error means the transport is right but the session is stale: surface it so+ // the caller reconnects fresh instead of falling through to a different transport.+ if (params.sessionId && isSessionExpiredError(error)) throw toConnectError(error);+ failures.push({ transport: transportType, error: error instanceof Error ? error.message.trim() : String(error) });+ continue;+ }++ // Set on the client (not the transport) so the SDK's own onclose/onerror cleanup still runs; the+ // SDK invokes these from inside it. Only wired on the kept connection, so failed attempts stay quiet.+ client.onclose = () => params.onClose?.();+ client.onerror = error => params.onError?.(error);+ return buildConnection(client, transport, transportType, params.headers, requestOptions);+ }++ throw new McpConnectionError(`failed to connect (tried ${candidates.join(', ')}): ${JSON.stringify(failures)}`, 502);+}diff --git a/packages/harness/src/core/mcp/toolNames.ts b/packages/harness/src/core/mcp/toolNames.tsnew file mode 100644index 000000000..d83f2cec4--- /dev/null+++ b/packages/harness/src/core/mcp/toolNames.ts@@ -0,0 +1,36 @@+import { ToolNameCollisionError } from '../errors';++const VALID_TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;+const MAX_TOOL_NAME_LENGTH = 64;+export const MAX_DUP_SUFFIX = 50;++function sanitizeToolName(toolName: string): string {+ if (VALID_TOOL_NAME_PATTERN.test(toolName)) {+ return toolName;+ }+ return toolName.replace(/[^a-zA-Z0-9_-]/g, '_');+}++export function getUniqueSanitizedToolName(+ toolName: string,+ existingNames: Set<string>,+): { name: string; hadCollision: boolean } {+ const sanitized = sanitizeToolName(toolName);+ const truncated = sanitized.substring(0, MAX_TOOL_NAME_LENGTH);++ if (!existingNames.has(truncated)) {+ return { name: truncated, hadCollision: false };+ }++ const nameBase = sanitized.substring(0, MAX_TOOL_NAME_LENGTH - 2);+ for (let suffix = 1; suffix <= MAX_DUP_SUFFIX; suffix++) {+ const candidate = `${nameBase}${suffix}`;+ if (!existingNames.has(candidate)) {+ return { name: candidate, hadCollision: true };+ }+ }++ throw new ToolNameCollisionError(+ `Tool name collision limit exceeded for "${toolName}": more than ${MAX_DUP_SUFFIX} duplicates across MCP servers`,+ );+}diff --git a/packages/harness/src/core/mcp/toolSelectors.ts b/packages/harness/src/core/mcp/toolSelectors.tsnew file mode 100644index 000000000..29f718b4b--- /dev/null+++ b/packages/harness/src/core/mcp/toolSelectors.ts@@ -0,0 +1,112 @@+import type { ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';++/**+ * MCP server tool selectors are either a special tag or a literal tool name.+ *+ * @all — every tool on the server+ * @read-only — readOnlyHint === true+ * @write — readOnlyHint === false and not destructive+ * @destructive — destructiveHint === true+ */+const TOOL_TAG_ALL = '@all';+const TOOL_TAG_READ_ONLY = '@read-only';+const TOOL_TAG_WRITE = '@write';+const TOOL_TAG_DESTRUCTIVE = '@destructive';++const TOOL_TAGS = [TOOL_TAG_ALL, TOOL_TAG_READ_ONLY, TOOL_TAG_WRITE, TOOL_TAG_DESTRUCTIVE] as const;+type ToolTag = (typeof TOOL_TAGS)[number];++/** Tags allowed on `enable_tools`, `disable_tools`, and `preload_tools`. */+export const TOOLS_SELECTOR_TAGS = [TOOL_TAG_ALL, TOOL_TAG_READ_ONLY] as const;++/** Tags allowed on `require_approval_for_tools`. */+export const REQUIRE_APPROVAL_TOOLS_SELECTOR_TAGS = [TOOL_TAG_ALL, TOOL_TAG_WRITE, TOOL_TAG_DESTRUCTIVE] as const;++export const DEFAULT_ENABLE_TOOLS: string[] = [TOOL_TAG_ALL];+export const DEFAULT_DISABLE_TOOLS: string[] = [];+export const DEFAULT_PRELOAD_TOOLS: string[] = [];+export const DEFAULT_REQUIRE_APPROVAL_FOR_TOOLS: string[] = [TOOL_TAG_WRITE, TOOL_TAG_DESTRUCTIVE];++function isToolTag(selector: string): selector is ToolTag {+ return TOOL_TAGS.includes(selector as ToolTag);+}++function isReadOnly(annotations?: ToolAnnotations): boolean {+ return annotations?.readOnlyHint === true;+}++function isWrite(annotations?: ToolAnnotations): boolean {+ return annotations?.readOnlyHint === false && annotations?.destructiveHint !== true;+}++function isDestructive(annotations?: ToolAnnotations): boolean {+ return annotations?.destructiveHint === true;+}++function toolMatchesTag(tag: ToolTag, annotations: ToolAnnotations | undefined): boolean {+ switch (tag) {+ case TOOL_TAG_ALL:+ return true;+ case TOOL_TAG_READ_ONLY:+ return isReadOnly(annotations);+ case TOOL_TAG_WRITE:+ return isWrite(annotations);+ case TOOL_TAG_DESTRUCTIVE:+ return isDestructive(annotations);+ }+}++/** True if the tool matches any selector (tag or literal name). */+export function toolMatchesAnySelector(+ toolName: string,+ annotations: ToolAnnotations | undefined,+ selectors: readonly string[] | undefined,+): boolean {+ if (!selectors?.length) return false;++ for (const selector of selectors) {+ if (isToolTag(selector)) {+ if (toolMatchesTag(selector, annotations)) return true;+ } else if (selector === toolName) {+ return true;+ }+ }+ return false;+}++/**+ * Whether the tool requires human approval before execution.+ * Matches `@write`, `@destructive`, `@all`, or explicit tool names against annotations.+ * Unannotated tools are exempt unless named in `require_approval_for_tools` or covered by `@all`.+ */+export function toolRequiresApproval(+ toolName: string,+ annotations: ToolAnnotations | undefined,+ selectors: readonly string[] | undefined,+): boolean {+ if (!selectors?.length) return false;+ return toolMatchesAnySelector(toolName, annotations, selectors);+}++/** True if the tool is enabled and not disabled. */+export function isToolAllowed(params: {+ toolName: string;+ annotations: ToolAnnotations | undefined;+ enableSelectors: readonly string[];+ disableSelectors: readonly string[];+}): boolean {+ const { toolName, annotations, enableSelectors, disableSelectors } = params;+ if (!toolMatchesAnySelector(toolName, annotations, enableSelectors)) return false;+ if (toolMatchesAnySelector(toolName, annotations, disableSelectors)) return false;+ return true;+}++/** Non-tag names from a selector list (for upfront validation / sandbox allow-lists). */+export function literalToolNames(selectors: readonly string[] | undefined): string[] {+ if (!selectors) return [];+ return selectors.filter(s => !isToolTag(s));+}++export function selectorsIncludeAll(selectors: readonly string[] | undefined): boolean {+ return !!selectors?.includes(TOOL_TAG_ALL);+}diff --git a/packages/harness/src/core/runtime/AgentDefinition.ts b/packages/harness/src/core/runtime/AgentDefinition.tsnew file mode 100644index 000000000..c83e215f6--- /dev/null+++ b/packages/harness/src/core/runtime/AgentDefinition.ts@@ -0,0 +1,25 @@+import type { ILLM } from '../llm/ILLM';+import type { LLMUserMessage } from '../llm/LLMTypes';+import type { ResponseFormat } from '../llm/responseFormat';+import type { IToolSet } from '../mcp/IMCPServer';++export interface ModelParams {+ [key: string]: unknown;+}++/**+ * Static definition of an agent. Represents the authored configuration,+ * not the execution state. Inherited by sub-agent definitions.+ */+export interface AgentDefinition {+ model: string;+ modelClient: ILLM;+ instruction?: string | undefined;+ messages?: readonly LLMUserMessage[] | undefined;+ modelParams?: ModelParams | undefined;+ /** Same wire shape as AgentSpec.response_format (Zod ResponseFormat). */+ responseFormat?: ResponseFormat | undefined;+ iterationLimit?: number | undefined;++ toolSets?: readonly IToolSet[] | undefined;+}diff --git a/packages/harness/src/core/runtime/AgentThread.ts b/packages/harness/src/core/runtime/AgentThread.tsnew file mode 100644index 000000000..acef50f06--- /dev/null+++ b/packages/harness/src/core/runtime/AgentThread.ts@@ -0,0 +1,1386 @@+import type {+ ChatCompletionCreateParamsStreaming,+ ChatCompletionMessageParam,+ ChatCompletionTool,+} from 'openai/resources/chat';+import type { Logger } from 'winston';+import type { AgentCapability } from '../capabilities/AgentCapability';+import type {+ AgentContextProcessorOutput,+ AgentContextProcessorOverwriteContext,+ AgentThreadExecutionContext,+ PostToolCallAgentContextProcessor,+ PreLLMAgentContextProcessor,+ PreLLMEphemeralAgentContextProcessor,+ PreSendContextProcessor,+} from '../capabilities/AgentContextProcessor';+import { SUB_AGENT_IDENTITY } from '../capabilities/builtins/DynamicSubAgents';+import type { ToolResponseProcessor } from '../capabilities/ToolResponseProcessor';+import { AgentHarnessError, InvalidAgentSendInputError } from '../errors';+import { toOpenAIResponseFormat } from '../llm/responseFormat';+import { toOpenAIChatMessage } from '../llm/toOpenAIChatMessage';+import {+ EventType,+ newEventId,+ type AgentApprovalDecisionMessage,+ type AgentInfo,+ type AgentOutputEvent,+ type AgentParent,+ type MCPInitializeEvent,+ type MCPServerInitInfo,+ type ModelMessageDeltaEvent,+ type ModelMessageEvent,+ type ModelMessageUsage,+ type SandboxCreatedEvent,+ type ThreadOverwriteContextEvent,+ type ToolApprovalRequiredEvent,+ type ToolResponseEvent,+ type ToolResponseRequiredEvent,+ type UserToolApprovalMessage,+ type UserToolResponseMessage,+} from '../events/eventSchemas';+import type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';+import { InstructionBuilder, ROOT_AGENT_IDENTITY } from '../InstructionBuilder';+import {+ getEmptyUsage,+ type CompletionUsage,+ type ExtendedChatCompletionChunk,+ type FinishReason,+ type InternalEnrichedAssistantMessage,+ type InternalEnrichedToolCall,+ type LLMToolMessage,+ type LLMUserMessage,+ type RawAssistantMessage,+} from '../llm/LLMTypes';+import type { AgentThreadMetric } from '../llm/metrics';+import { estimateTokensForString, mergeUsage } from '../llm/usage';+import { convertMCPServersToTools, type ConvertToolsResult, type MappedMCPTool } from '../mcp/convertMCPServers';+import { executeToolCalls } from '../mcp/executeToolCalls';+import type { IToolSet, MCPAuthRequired } from '../mcp/IMCPServer';+import type { Sandbox, SandboxInfo } from '../sandbox/Sandbox';+import type { AgentTracing } from '../tracing/AgentTracing';+import type { AgentDefinition } from './AgentDefinition';+import type {+ AgentThreadConstructorInput,+ AgentThreadRuntimeSendBatch,+ AgentThreadRuntimeSendInput,+ AgentThreadSnapshot,+} from './AgentThread.types';+import {+ InternalEventType,+ type AgentThreadAppendContext,+ type AgentThreadEvent,+ type ContextMessage,+ type InternalCapabilityStateEvent,+ type InternalMCPAuthRequiredEvent,+ type InternalThreadDoneEvent,+ type SubAgentCompletionMarker,+} from './AgentThread.types';+import {+ assistantMessageContentToStringForSubAgent,+ estimateTokensForContextMessages,+ INTERNAL_SYSTEM_PROMPT,+ isApprovalDecisionMessage,+ isClientSideToolResponseMessage,+ isInputUserMessage,+ isLLMContextMessage,+ isLLMToolMessage,+ makeUnknownToolInfo,+ scanApprovalDecisions,+ toEnrichedToolCall,+ toToolCallInfo,+} from './contextUtils';+import { DeferredTool } from './DeferredTool';+import { getClosableOpenToolCallIds, OpenToolCallCloser } from './OpenToolCallCloser';+import { isEmptyMessageContent, processAgentUserInput, type AgentInputUserMessage } from './UserInputMessage';++const DEFAULT_ITERATION_LIMIT = 25;++type AgentThreadState = 'llm-call-required' | 'tool-response-required' | 'user-input-required';++type StepOutcome = 'exit' | 'continue';++const VALID_TRANSITIONS: Record<AgentThreadState, AgentThreadState[]> = {+ 'llm-call-required': ['tool-response-required', 'user-input-required'],+ 'tool-response-required': ['llm-call-required'],+ // user-input-required transitions to:+ // tool-response-required — after approval decisions are appended (approval flow)+ // llm-call-required — after client-side tool responses resolve tool calls directly+ 'user-input-required': ['tool-response-required', 'llm-call-required'],+};++function assertValidTransition(from: AgentThreadState, to: AgentThreadState): void {+ if (!VALID_TRANSITIONS[from].includes(to)) {+ throw new Error(`Invalid state transition: ${from} → ${to}`);+ }+}++function deriveAgentThreadState(context: ContextMessage[]): AgentThreadState {+ const openToolCallIds = getOpenToolCallIds(context);+ if (openToolCallIds.size === 0) return 'llm-call-required';++ const assistant = lastAssistantInContext(context);+ const decisions = scanApprovalDecisions(context);+ const hasPendingApproval = assistant?.tool_calls?.some(+ tc => openToolCallIds.has(tc.id) && tc.tool_info?.is_approval_required === true && !decisions.has(tc.id),+ );+ const hasPendingClientSideTool = assistant?.tool_calls?.some(+ tc => openToolCallIds.has(tc.id) && tc.tool_info?.is_client_side === true,+ );+ return hasPendingApproval || hasPendingClientSideTool ? 'user-input-required' : 'tool-response-required';+}++function hasToolCalls(message: InternalEnrichedAssistantMessage): boolean {+ return Boolean(message.tool_calls && message.tool_calls.length > 0);+}++// Tool call ids issued by the last assistant message that have no matching+// tool response after it. Walks the context tail-first and stops at the last+// assistant message — under the invariant that older assistant tool_calls are+// already resolved, only the last assistant message can have open ids.+function getOpenToolCallIds(context: ContextMessage[]): Set<string> {+ const resolvedToolCallIds = new Set<string>();+ const openToolCallIds = new Set<string>();+ for (let i = context.length - 1; i >= 0; i--) {+ const msg = context[i]!;+ if (!isLLMContextMessage(msg)) continue;+ if (msg.role === 'tool') {+ resolvedToolCallIds.add(msg.tool_call_id);+ continue;+ }+ if (msg.role === 'assistant') {+ for (const tc of msg.tool_calls ?? []) openToolCallIds.add(tc.id);+ for (const id of resolvedToolCallIds) openToolCallIds.delete(id);+ break;+ }+ }+ return openToolCallIds;+}++function lastAssistantInContext(context: ContextMessage[]): InternalEnrichedAssistantMessage | undefined {+ return context.findLast(+ (msg): msg is InternalEnrichedAssistantMessage => isLLMContextMessage(msg) && msg.role === 'assistant',+ );+}++// Open tool calls that block a new user message: the open set minus those OpenToolCallCloser will+// auto-close during preSend. Lets a user message resume a thread whose only open calls are dangling+// regular tool calls (which the closer repairs), while still blocking on approval/client-side/+// sub-agent calls that genuinely need resolution. Takes the already-computed open set; copies it+// since it mutates (deletes) the closable ids.+function getUnclosableOpenToolCallIds(context: ContextMessage[], openToolCallIds: Set<string>): Set<string> {+ const blockingOpenToolCallIds = new Set(openToolCallIds);+ for (const id of getClosableOpenToolCallIds(context)) {+ blockingOpenToolCallIds.delete(id);+ }+ return blockingOpenToolCallIds;+}++function buildMCPInitializeEvent(initInfo: MCPServerInitInfo[], threadId: string): MCPInitializeEvent {+ return {+ type: EventType.MCP_INITIALIZE,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: threadId,+ mcp_servers: initInfo,+ };+}++function buildMCPAuthRequiredEvent(+ authRequirementInfo: MCPAuthRequired[],+ threadId: string,+): InternalMCPAuthRequiredEvent {+ return {+ type: InternalEventType.MCP_AUTH_REQUIRED,+ id: newEventId(),+ created_at: new Date().toISOString(),+ mcp_servers: authRequirementInfo.flatMap(or => or.servers.map(s => ({ ...s, thread_ids: [threadId] }))),+ // threadId identifies which thread triggered auth for each server so AgentThreadOrchestrator can merge+ // auth events across parallel sub-agents by server.+ thread_id: null,+ };+}++function buildSandboxCreatedEvent(info: SandboxInfo): SandboxCreatedEvent {+ return {+ type: EventType.SANDBOX_CREATED,+ id: newEventId(),+ created_at: new Date().toISOString(),+ ...info,+ thread_id: null,+ };+}++function buildModelMessageEvent({+ assistantMessage,+ threadId,+ finishReason,+ usage,+ id,+}: {+ assistantMessage: InternalEnrichedAssistantMessage;+ threadId: string;+ finishReason: FinishReason;+ usage: ModelMessageUsage | undefined;+ id: string;+}): ModelMessageEvent {+ // `thinking_blocks` is persisted to the Redis context for replay; strip it from the client event.+ const { role: _, tool_calls, thinking_blocks: _thinkingBlocks, ...rest } = assistantMessage;+ const event: ModelMessageEvent = {+ ...rest,+ ...(tool_calls !== undefined ? { tool_calls: tool_calls.map(toEnrichedToolCall) } : {}),+ type: EventType.MODEL_MESSAGE,+ id,+ created_at: new Date().toISOString(),+ thread_id: threadId,+ finish_reason: finishReason,+ ...(usage && { usage }),+ };+ return event;+}++function validateUserMessage(+ message: { content: AgentInputUserMessage['content'] },+ blockingOpenToolCallIds: Set<string>,+ index: number,+): void {+ if (isEmptyMessageContent(message.content)) {+ throw new InvalidAgentSendInputError(`messages[${index}] user message has empty content`);+ }+ if (blockingOpenToolCallIds.size > 0) {+ throw new InvalidAgentSendInputError('user message cannot be sent while approvals or questions are pending');+ }+}++function validateToolMessage(+ message: LLMToolMessage | UserToolResponseMessage,+ openToolCallIds: Set<string>,+ index: number,+): void {+ if (!openToolCallIds.has(message.tool_call_id)) {+ throw new InvalidAgentSendInputError(+ `messages[${index}] no open tool call for tool_call_id '${message.tool_call_id}'`,+ );+ }+}++function validateApprovalMessage(+ message: UserToolApprovalMessage,+ pendingApprovalIds: Set<string>,+ index: number,+): void {+ if (!pendingApprovalIds.has(message.tool_call_id)) {+ throw new InvalidAgentSendInputError(+ `messages[${index}] no pending approval for tool_call_id '${message.tool_call_id}'`,+ );+ }+}++function getPendingApprovalToolCalls(context: ContextMessage[]): InternalEnrichedToolCall[] {+ const openToolCallIds = getOpenToolCallIds(context);+ const decisions = scanApprovalDecisions(context);+ const assistant = lastAssistantInContext(context);+ return (assistant?.tool_calls ?? []).filter(+ tc => openToolCallIds.has(tc.id) && tc.tool_info?.is_approval_required === true && !decisions.has(tc.id),+ );+}++function getPendingClientSideToolCalls(context: ContextMessage[]): InternalEnrichedToolCall[] {+ const openToolCallIds = getOpenToolCallIds(context);+ const assistant = lastAssistantInContext(context);+ return (assistant?.tool_calls ?? []).filter(+ tc => openToolCallIds.has(tc.id) && tc.tool_info?.is_client_side === true,+ );+}++function validateInputMessageTypesGivenContext(+ context: ContextMessage[],+ messages: AgentThreadRuntimeSendInput[],+): void {+ // Full open set: validates incoming tool responses and dedupes within the batch.+ const openToolCallIds = getOpenToolCallIds(context);+ // Subset that blocks a fresh user message: excludes calls OpenToolCallCloser will auto-close+ // during preSend, so a dangling regular tool call doesn't reject a user message it will repair.+ const blockingOpenToolCallIds = getUnclosableOpenToolCallIds(context, openToolCallIds);+ const pendingApprovalIds = new Set(getPendingApprovalToolCalls(context).map(tc => tc.id));+ const pendingClientSideIds = new Set(getPendingClientSideToolCalls(context).map(tc => tc.id));++ for (let i = 0; i < messages.length; i++) {+ const m = messages[i]!;+ if (isApprovalDecisionMessage(m)) {+ validateApprovalMessage(m, pendingApprovalIds, i);+ pendingApprovalIds.delete(m.tool_call_id);+ } else if (isInputUserMessage(m)) {+ validateUserMessage(m, blockingOpenToolCallIds, i);+ } else if (isClientSideToolResponseMessage(m) || isLLMToolMessage(m)) {+ validateToolMessage(m, openToolCallIds, i);+ openToolCallIds.delete(m.tool_call_id);+ blockingOpenToolCallIds.delete(m.tool_call_id);+ pendingClientSideIds.delete(m.tool_call_id);+ } else {+ const _exhaustive: never = m;+ throw new InvalidAgentSendInputError(`messages[${i}] has unsupported type: ${JSON.stringify(_exhaustive)}`);+ }+ }++ // A send for a thread awaiting user input must resolve every pending approval and client-side+ // tool call in the same batch; any left unresolved (including an empty batch) is a blocker.+ if (pendingApprovalIds.size > 0 || pendingClientSideIds.size > 0) {+ const missing = [...pendingApprovalIds, ...pendingClientSideIds];+ throw new InvalidAgentSendInputError(+ `Send batch must resolve all pending tool calls awaiting user input. Missing: ${missing.join(', ')}`,+ );+ }+}++async function buildModelMessageDeltaEvent({+ chunk,+ threadId,+ toolMapping,+ usage,+ id,+ logger,+}: {+ chunk: ExtendedChatCompletionChunk;+ threadId: string;+ toolMapping: Map<string, MappedMCPTool>;+ usage: ModelMessageUsage | undefined;+ id: string;+ logger: Logger;+}): Promise<ModelMessageDeltaEvent | undefined> {+ const choice = chunk.choices[0];+ const delta = choice?.delta;+ const finishReason = choice?.finish_reason;++ if (!delta || (Object.keys(delta).length === 0 && !finishReason && !usage)) {+ return;+ }++ // Drop empty deltas that carry no displayable or actionable data+ if (!delta.tool_calls?.length && !delta.content && !delta.reasoning_content && !finishReason && !usage) {+ return;+ }++ const toolCalls = delta.tool_calls || [];+ for (const toolCall of toolCalls) {+ if (toolCall.function?.name) {+ const toolInfo = toolMapping.get(toolCall.function.name);+ if (!toolInfo) {+ logger.warn(`LLM called unknown tool: Tool ${toolCall.function.name} not found in tool mapping.`);+ toolCall.tool_info = toToolCallInfo(makeUnknownToolInfo(toolCall.function.name));+ continue;+ }+ toolCall.tool_info = toToolCallInfo(+ await toolInfo.toolSet.toolCallInfo({ name: toolInfo.originalToolName }, false /* resolveUnderlyingTool */),+ );+ }+ }++ // Strip legacy `function_call` and replay-only `thinking_blocks` so neither reaches the client or delta stream.+ const { role: _, function_call: _functionCall, thinking_blocks: _thinkingBlocks, ...deltaWithoutRole } = delta;+ return {+ ...deltaWithoutRole,+ type: EventType.MODEL_MESSAGE_DELTA,+ id,+ thread_id: threadId,+ ...(finishReason && { finish_reason: finishReason }),+ ...(usage && { usage }),+ };+}++async function buildContextAssistantMessage(+ assistantMessage: RawAssistantMessage,+ toolMapping: Map<string, MappedMCPTool>,+): Promise<InternalEnrichedAssistantMessage> {+ // Omit tool_calls when empty; OpenAI rejects `tool_calls: []` on replay.+ if (!assistantMessage.tool_calls?.length) {+ const { tool_calls: _drop, ...rest } = assistantMessage;+ return rest;+ }++ // Sequential loop instead of Promise.all: the first call populates the MCP server's tool cache+ // (via listTools), making subsequent calls instant cache hits.+ // No race conditions either way but parallelism buys nothing here.+ const enrichedToolCalls = [];+ for (const toolCall of assistantMessage.tool_calls) {+ const toolInfo = toolMapping.get(toolCall.function.name);+ if (!toolInfo) {+ enrichedToolCalls.push({ ...toolCall, tool_info: makeUnknownToolInfo(toolCall.function.name) });+ continue;+ }+ const tool_info = await toolInfo.toolSet.toolCallInfo(+ {+ name: toolInfo.originalToolName,+ arguments: tryParseToolArgs(toolCall.function.arguments),+ },+ // During context persistence, we have the complete message and hence the tool arguments are available.+ // Hence, we resolve the underlying tool to get the tool information.+ true /* resolveUnderlyingTool */,+ );+ enrichedToolCalls.push({ ...toolCall, tool_info });+ }+ return { ...assistantMessage, tool_calls: enrichedToolCalls };+}++function isJsonObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++// Args are only used by DeferredTool to delegate to the underlying server.+// Defensive parse — hallucinated JSON shouldn't crash assistant-message construction.+function tryParseToolArgs(args: string | undefined): Record<string, unknown> {+ if (!args) return {};+ try {+ const parsed: unknown = JSON.parse(args);+ return isJsonObject(parsed) ? parsed : {};+ } catch {+ return {};+ }+}++// State-sync contract: in-memory state must stay consistent with what the consumer+// def foo():+// for x in range(1, 10):+// yield x+// # This cannot raise exception+// # This does not execute if update_redis fails.+// update_local_context(x)+// for x in foo():+// # This can raise exception.+// update_redis(x)++export class AgentThread {+ readonly threadId: string;+ readonly parent?: AgentParent | undefined;+ readonly definition: AgentDefinition;+ readonly title: string;+ readonly agentInfo?: AgentInfo | undefined;++ private context: ContextMessage[];+ private currentContextUsage: CompletionUsage;+ private preSendContextProcessors: PreSendContextProcessor[];+ private preLLMContextProcessors: PreLLMAgentContextProcessor[];+ private preEphemeralLLMContextProcessors: PreLLMEphemeralAgentContextProcessor[];+ private postToolCallContextProcessor: PostToolCallAgentContextProcessor[];++ private instruction: string | undefined;+ private toolResponseProcessors: ToolResponseProcessor[];+ private instructionBuilders: readonly ((builder: InstructionBuilder) => void)[];+ private systemToolSets: readonly IToolSet[];+ private deferredTool?: DeferredTool | undefined;+ private convertedTools: ConvertToolsResult | undefined;+ private pendingSandboxCreatedEvents: SandboxCreatedEvent[] = [];+ private sandbox?: Sandbox | undefined;+ private readonly tracing: AgentTracing;+ private readonly logger: Logger;++ private _iterations = 0;+ private _totalToolCalls = 0;+ private _totalSummarizations = 0;+ private _totalSubAgents = 0;+ private _cumulativeUsage: CompletionUsage = getEmptyUsage();+ private tfyManagedServerNames = new Set<string>();++ private contextBusy = false;+ private preSendRanThisTurn = false;+ private currentState: AgentThreadState | null = null;+ private readonly preComputedCompletion?: SubAgentCompletionMarker | undefined;+ /** Mirrored capability KV — source for toSnapshot().capability_state. */+ private capabilityState: Record<string, unknown> = {};+ private readonly capabilityStateKeys: ReadonlySet<string>;++ constructor(input: AgentThreadConstructorInput) {+ this.tracing = input.tracing;+ this.logger = input.logger.child({ module: 'AgentThread' });+ this.threadId = input.threadId;+ this.definition = input.definition;+ this.context = input.context ? [...input.context] : [];+ this.title = input.title;+ this.parent = input.parent;+ this.currentContextUsage = input.currentContextUsage ?? getEmptyUsage();+ this.agentInfo = input.agentInfo;+ this.preComputedCompletion = input.preComputedCompletion;+ this.sandbox = input.sandbox;++ const capabilities = input.capabilities ?? [];+ this.systemToolSets = capabilities.flatMap(c => c.systemToolSets ?? []);+ this.preLLMContextProcessors = capabilities.flatMap(c => c.preLLMProcessors ?? []);+ this.preEphemeralLLMContextProcessors = capabilities.flatMap(c => c.preLLMEphemeralProcessors ?? []);+ this.postToolCallContextProcessor = capabilities.flatMap(c => c.postToolCallProcessors ?? []);+ this.toolResponseProcessors = capabilities.flatMap(c => c.toolResponseProcessors ?? []);+ this.instructionBuilders = capabilities.flatMap(c => c.instructionBuilders ?? []);+ const capabilityPreSend = capabilities.flatMap(c => c.preSendProcessors ?? []);+ // OpenToolCallCloser is fixed core before contributed preSend processors.+ this.preSendContextProcessors = [new OpenToolCallCloser(), ...capabilityPreSend];++ assertUniqueStateKeys(capabilities);+ const claimed = claimCapabilityState(capabilities, input.capabilityState, this.logger);+ this.capabilityState = claimed;+ this.capabilityStateKeys = new Set(+ capabilities.map(c => c.state?.key).filter((k): k is string => typeof k === 'string'),+ );+ for (const capability of capabilities) {+ if (!capability.state) continue;+ const value = claimed[capability.state.key];+ if (value !== undefined) {+ capability.state.load(value);+ }+ }++ if (this.definition.toolSets?.length) {+ this.deferredTool = new DeferredTool(this.definition.toolSets, {+ tracing: this.tracing,+ logger: input.logger,+ });+ }++ if (this.sandbox) {+ this.sandbox.configureCodeMode(this.definition.toolSets ?? []);+ }++ this.instruction = this.buildInstruction(this.definition.instruction);+ }++ private buildInstruction(userInstruction?: string): string {+ const identity = this.parent ? SUB_AGENT_IDENTITY : ROOT_AGENT_IDENTITY;+ const builder = InstructionBuilder.createSystemPrompt(identity);+ const capabilities = builder.beginSection('agent-capabilities');+ capabilities.addSection('internal-messages', INTERNAL_SYSTEM_PROMPT);++ if (this.sandbox) {+ this.sandbox.buildInstruction(capabilities);+ }+ if (this.deferredTool) {+ this.deferredTool.buildInstruction(capabilities);+ }+ for (const build of this.instructionBuilders) {+ build(capabilities);+ }+ if (!this.parent && userInstruction?.trim()) {+ builder.addSection('user-instructions', userInstruction.trim(), true);+ }+ return builder.build();+ }++ public async *send(messages: AgentThreadRuntimeSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {+ // An empty batch is a no-op only when the thread is not awaiting user input.+ // While awaiting input, fall through so the validator rejects the empty/incomplete batch.+ if (messages.length === 0 && !this.isAwaitingUserInput()) {+ return;+ }+ this.throwIfContextBusy();++ this.contextBusy = true;+ try {+ for await (const event of this.executeContextProcessors('preSend')) {+ yield event;+ }+ this.preSendRanThisTurn = true;++ validateInputMessageTypesGivenContext(this.context, messages);++ const approvals: UserToolApprovalMessage[] = [];+ const clientSideToolResponses: UserToolResponseMessage[] = [];+ const contextMessages: (LLMUserMessage | LLMToolMessage)[] = [];++ for (const m of messages) {+ if (isApprovalDecisionMessage(m)) {+ approvals.push(m);+ } else if (isClientSideToolResponseMessage(m)) {+ clientSideToolResponses.push(m);+ } else if (isInputUserMessage(m)) {+ const result = await processAgentUserInput(m, this.sandbox);+ contextMessages.push(result.message);+ if (result.sandboxCreated) {+ this.pendingSandboxCreatedEvents.push(buildSandboxCreatedEvent(result.sandboxCreated));+ }+ } else if (isLLMToolMessage(m)) {+ contextMessages.push(m);+ } else {+ const _exhaustive: never = m;+ throw new InvalidAgentSendInputError(`Unsupported send input: ${JSON.stringify(_exhaustive)}`);+ }+ }++ if (approvals.length > 0 || clientSideToolResponses.length > 0) {+ const approvalContext: AgentApprovalDecisionMessage[] = approvals.map(a => ({+ type: EventType.USER_TOOL_APPROVAL,+ tool_call_id: a.tool_call_id,+ approval: a.approval,+ }));+ const toolResponseContext: LLMToolMessage[] = clientSideToolResponses.map(m => ({+ role: 'tool',+ tool_call_id: m.tool_call_id,+ content: m.content,+ }));+ yield* this.appendToContext({+ context: [...approvalContext, ...toolResponseContext],+ output: [],+ });+ }+ if (contextMessages.length > 0) {+ yield* this.appendToContext({ context: contextMessages, output: [] });+ }+ } finally {+ this.contextBusy = false;+ }+ }++ private throwIfContextBusy(): void {+ if (this.contextBusy) {+ throw new Error(`context is busy for thread ${this.threadId}`);+ }+ }++ private deriveState(): AgentThreadState {+ const next = deriveAgentThreadState(this.context);+ if (this.currentState) {+ assertValidTransition(this.currentState, next);+ }+ this.currentState = next;+ return next;+ }++ private *appendToContext(opts: {+ context: ContextMessage[];+ output: AgentOutputEvent[];+ overwriteUsage?: CompletionUsage | undefined;+ updateCumulativeUsage?: boolean | undefined;+ completion?: SubAgentCompletionMarker | undefined;+ }): Generator<AgentThreadAppendContext, void, unknown> {+ const { context, output, overwriteUsage, updateCumulativeUsage, completion } = opts;++ const newCurrentContextUsage =+ overwriteUsage ?? mergeUsage(this.currentContextUsage, estimateTokensForContextMessages(context));++ const event: AgentThreadAppendContext = {+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ thread_id: this.threadId,+ context,+ output,+ current_context_usage: newCurrentContextUsage,+ ...(completion && { completion }),+ };++ yield event;++ this.context = this.context.concat(context);+ this.currentContextUsage = newCurrentContextUsage;+ if (updateCumulativeUsage && overwriteUsage) {+ this._cumulativeUsage = mergeUsage(this._cumulativeUsage, overwriteUsage);+ }+ }++ private *overwriteContext(+ payload: AgentContextProcessorOverwriteContext,+ ): Generator<ThreadOverwriteContextEvent, void, unknown> {+ const event: ThreadOverwriteContextEvent = {+ thread_id: this.threadId,+ ...payload,+ };+ yield event;+ this.context = payload.context;+ this._cumulativeUsage = mergeUsage(this._cumulativeUsage, payload.compaction_llm_usage);+ this.currentContextUsage = payload.current_context_usage;+ this._totalSummarizations++;+ }++ private generateErrorEvent(message: string, output?: ModelMessageEvent): InternalThreadDoneEvent {+ return {+ type: InternalEventType.AGENT_DONE,+ status: 'error',+ thread_id: this.threadId,+ title: this.title,+ error: message,+ parent: this.parent,+ send_to_parent: this.parent+ ? {+ role: 'tool',+ content: message,+ tool_call_id: this.parent.tool_call_id,+ }+ : undefined,+ ...(output && { output }),+ };+ }++ public hasOpenToolCallId(toolCallId: string): boolean {+ return getOpenToolCallIds(this.context).has(toolCallId);+ }++ // True when this thread is paused waiting on the user to resolve a pending tool+ // approval or a client-side tool response.+ public isAwaitingUserInput(): boolean {+ return (+ getPendingApprovalToolCalls(this.context).length > 0 || getPendingClientSideToolCalls(this.context).length > 0+ );+ }++ // Pure validation of an input batch against this thread's current context; throws+ // on an invalid/incomplete batch without mutating the context.+ public validateSendInput(messages: AgentThreadRuntimeSendBatch): void {+ validateInputMessageTypesGivenContext(this.context, messages);+ }++ public toSnapshot(): AgentThreadSnapshot {+ const capability_state = Object.keys(this.capabilityState).length > 0 ? { ...this.capabilityState } : undefined;+ const base: AgentThreadSnapshot = {+ thread_id: this.threadId,+ context: this.context,+ current_context_usage: this.currentContextUsage,+ ...(capability_state && { capability_state }),+ };++ if (this.parent && this.agentInfo) {+ return {+ ...base,+ parent: this.parent,+ agent_info: this.agentInfo,+ ...(this.preComputedCompletion && { completion: this.preComputedCompletion }),+ };+ }++ return base;+ }++ public getAgentThreadMetrics(): AgentThreadMetric {+ return {+ iterations: this._iterations,+ total_tool_calls: this._totalToolCalls,+ total_summarizations: this._totalSummarizations,+ usage: { ...this._cumulativeUsage },+ total_sub_agents: this._totalSubAgents,+ };+ }++ private transformToLLMRequest(tools: ChatCompletionTool[]): ChatCompletionCreateParamsStreaming {+ let messages: ChatCompletionMessageParam[] = [];++ if (this.instruction) {+ messages.push({+ role: 'system',+ content: this.instruction,+ });+ }++ if (this.definition.messages) {+ for (const msg of this.definition.messages) {+ if (isLLMContextMessage(msg)) {+ messages.push(toOpenAIChatMessage(msg));+ }+ }+ }++ // NOTE: all this code-golf is to remove `tool_info` before sending the message to Gateway+ // ApprovalDecisionMessage rows are persisted in context but must not be sent to the LLM.+ const contextMessages = this.context.filter(isLLMContextMessage).map(msg => toOpenAIChatMessage(msg));++ messages.push(...contextMessages);++ for (const processor of this.preEphemeralLLMContextProcessors) {+ messages = processor.processPreLLMEphemeral(messages) ?? messages;+ }++ // modelParams may include provider extensions (e.g. reasoning_effort) beyond the SDK's+ // ChatCompletionCreateParamsStreaming field set; assign after constructing the typed body.+ const requestBody: ChatCompletionCreateParamsStreaming = {+ model: this.definition.model,+ messages,+ stream: true,+ ...(this.definition.responseFormat !== undefined+ ? { response_format: toOpenAIResponseFormat(this.definition.responseFormat) }+ : {}),+ };+ if (this.definition.modelParams) {+ Object.assign(requestBody, this.definition.modelParams);+ }++ if (tools.length > 0) {+ requestBody.tools = tools;+ }++ return requestBody;+ }++ private computeAssistantMessageUsage(params: {+ requestBody: ChatCompletionCreateParamsStreaming;+ usage: CompletionUsage;+ toolMapping: Map<string, MappedMCPTool>;+ }): ModelMessageUsage {+ const { requestBody, usage, toolMapping } = params;+ // Sub-agents have no <user-instructions> section — their agent.instruction is+ // SUB_AGENT_IDENTITY which is harness content, not user-defined instructions.+ const trimmedInstruction = this.definition.instruction?.trim() ?? '';+ const instructionsEstimate = this.parent ? 0 : Math.round(estimateTokensForString(trimmedInstruction));++ const skillsEstimate = this.sandbox?.estimateSkillsTokens() ?? 0;++ let tfyManagedToolTokens = 0;+ let userToolTokens = 0;+ if (requestBody.tools) {+ for (const tool of requestBody.tools) {+ const toolTokens = Math.round(estimateTokensForString(JSON.stringify(tool)));+ const info = toolMapping.get(tool.function.name);+ if (info && this.tfyManagedServerNames.has(info.toolSet.name)) {+ tfyManagedToolTokens += toolTokens;+ } else {+ userToolTokens += toolTokens;+ }+ }+ }++ const totalInstructionTokens = Math.round(estimateTokensForString(this.instruction ?? ''));+ const harnessInstructionTokens = Math.max(0, totalInstructionTokens - instructionsEstimate - skillsEstimate);+ const harnessEstimate = harnessInstructionTokens + tfyManagedToolTokens;++ const estimatedComponentsTotal = harnessEstimate + skillsEstimate + instructionsEstimate + userToolTokens;+ const messagesEstimate = Math.max(0, usage.prompt_tokens - estimatedComponentsTotal);++ return {+ input_tokens: usage.prompt_tokens,+ output_tokens: usage.completion_tokens,+ cache_read_tokens: usage.cache_read_input_tokens ?? usage.prompt_tokens_details?.cached_tokens,+ cache_write_tokens: usage.cache_creation_input_tokens,+ input_tokens_breakdown: {+ harness: harnessEstimate,+ skills: skillsEstimate,+ instructions: instructionsEstimate,+ tool_definitions: userToolTokens,+ messages: messagesEstimate,+ },+ };+ }++ private executeContextProcessors(hook: 'preSend'): AsyncGenerator<AgentThreadAppendContext, void, unknown>;+ private executeContextProcessors(+ hook: 'preLLM' | 'postToolCall',+ ): AsyncGenerator<+ | ThreadOverwriteContextEvent+ | AgentThreadAppendContext+ | { type: typeof InternalEventType.PASSTHROUGH; event: RegisteredPassthroughEvent }+ | InternalCapabilityStateEvent,+ void,+ unknown+ >;+ private async *executeContextProcessors(+ hook: 'preSend' | 'preLLM' | 'postToolCall',+ ): AsyncGenerator<+ | ThreadOverwriteContextEvent+ | AgentThreadAppendContext+ | { type: typeof InternalEventType.PASSTHROUGH; event: RegisteredPassthroughEvent }+ | InternalCapabilityStateEvent,+ void,+ unknown+ > {+ let processors: ((+ execution: Readonly<AgentThreadExecutionContext>,+ ) => AsyncIterable<AgentContextProcessorOutput>)[];+ switch (hook) {+ case 'preSend':+ processors = this.preSendContextProcessors.map(p => p.processPreSend.bind(p));+ break;+ case 'preLLM':+ processors = this.preLLMContextProcessors.map(p => p.processPreLLM.bind(p));+ break;+ case 'postToolCall':+ processors = this.postToolCallContextProcessor.map(p => p.processPostToolCall.bind(p));+ break;+ default:+ throw new Error(`Unknown hook: ${hook}`);+ }++ const execution: Readonly<AgentThreadExecutionContext> = {+ threadId: this.threadId,+ sandbox: this.sandbox,+ currentContextUsage: this.currentContextUsage,+ context: this.context,+ };++ for (const processor of processors) {+ for await (const response of processor(execution)) {+ switch (response.type) {+ case InternalEventType.AGENT_CONTEXT_APPEND:+ yield* this.appendToContext({+ context: response.context,+ output: response.output,+ overwriteUsage: response.current_context_usage ?? this.currentContextUsage,+ });+ break;+ case EventType.AGENT_CONTEXT_OVERWRITE:+ yield* this.overwriteContext(response);+ break;+ case InternalEventType.PASSTHROUGH:+ yield response;+ break;+ case InternalEventType.CAPABILITY_STATE:+ if (!this.capabilityStateKeys.has(response.key)) {+ throw new AgentHarnessError(+ 'capability_state_error',+ `CAPABILITY_STATE key '${response.key}' is not declared by any capability on thread '${this.threadId}'`,+ );+ }+ this.capabilityState[response.key] = response.state;+ yield {+ type: InternalEventType.CAPABILITY_STATE,+ thread_id: this.threadId,+ key: response.key,+ state: response.state,+ };+ break;+ default: {+ const _exhaustive: never = response;+ return _exhaustive;+ }+ }+ }+ }+ }++ private async init(): Promise<{+ initializationInfo: MCPServerInitInfo[];+ authRequirementInfo: MCPAuthRequired[];+ }> {+ if (this.convertedTools) {+ return { initializationInfo: [], authRequirementInfo: [] };+ }+ return this.initTools();+ }++ private async initTools(): Promise<{+ initializationInfo: MCPServerInitInfo[];+ authRequirementInfo: MCPAuthRequired[];+ }> {+ const tfyManagedServers: IToolSet[] = [...this.systemToolSets];+ if (this.sandbox) {+ tfyManagedServers.push(this.sandbox);+ }+ if (this.deferredTool) {+ tfyManagedServers.push(this.deferredTool);+ }+ const userServers = [...(this.definition.toolSets ?? [])];++ const { convertedTools, initializationInfo, authRequirementInfo } = await convertMCPServersToTools({+ tfyManagedServers,+ userServers,+ });+ this.convertedTools = convertedTools;+ this.tfyManagedServerNames = new Set(tfyManagedServers.map(s => s.name));+ return { initializationInfo, authRequirementInfo };+ }++ private getConvertedTools(): ConvertToolsResult {+ if (!this.convertedTools) {+ throw new Error('unreachable');+ }+ return this.convertedTools;+ }++ private async *stepLLMCall(+ tools: ChatCompletionTool[],+ toolMapping: Map<string, MappedMCPTool>,+ signal?: AbortSignal,+ ): AsyncGenerator<AgentThreadEvent, { outcome: StepOutcome; modelMessageEventId: string }, unknown> {+ const modelMessageEventId = newEventId();+ if (signal?.aborted) {+ return { outcome: 'exit', modelMessageEventId };+ }++ for await (const event of this.executeContextProcessors('preLLM')) {+ yield event;+ }++ const requestBody = this.transformToLLMRequest(tools);+ const llmStream = this.definition.modelClient.create(requestBody);++ // We start the delta stream with a model message event.+ yield {+ type: EventType.MODEL_MESSAGE,+ thread_id: this.threadId,+ created_at: new Date().toISOString(),+ id: modelMessageEventId,+ } satisfies ModelMessageEvent;++ let firstDeltaTimestamped = false;+ let result = await llmStream.next();+ let usage: ModelMessageUsage | undefined = undefined;+ while (!result.done) {+ const chunk = result.value;+ if (chunk.usage) {+ usage = this.computeAssistantMessageUsage({ requestBody, usage: chunk.usage, toolMapping });+ }+ const event = await buildModelMessageDeltaEvent({+ chunk,+ threadId: this.threadId,+ toolMapping,+ usage,+ id: modelMessageEventId,+ logger: this.logger,+ });+ if (event) {+ if (!firstDeltaTimestamped) {+ firstDeltaTimestamped = true;+ yield { ...event, created_at: new Date().toISOString() };+ } else {+ yield event;+ }+ }+ result = await llmStream.next();+ }++ if (!result.value) {+ throw Error('unreachable');+ }++ // If the stream was aborted mid-way, result.value.output is only a partial+ // accumulation of the deltas — not the true complete response. Skip the+ // final model.message event to avoid emitting an inconsistent assembled message.+ if (signal?.aborted) {+ return { outcome: 'exit', modelMessageEventId };+ }++ // should be computed by this point but in case provider never gives out any delta with usage key, compute it now.+ if (!usage) {+ usage = this.computeAssistantMessageUsage({ requestBody, usage: result.value.usage, toolMapping });+ }+ const assistantMessage: InternalEnrichedAssistantMessage = await buildContextAssistantMessage(+ result.value.output,+ toolMapping,+ );+ const finishReason = result.value.finish_reason;+ const agentAssistantMessage = buildModelMessageEvent({+ assistantMessage,+ threadId: this.threadId,+ finishReason,+ usage,+ id: modelMessageEventId,+ });++ let completion: SubAgentCompletionMarker | undefined;+ if (this.parent) {+ if (finishReason === 'length') {+ const errorMessage = assistantMessageContentToStringForSubAgent(+ assistantMessage.content,+ 'max_tokens breached',+ );+ completion = {+ type: 'error',+ output: agentAssistantMessage,+ error_message: errorMessage,+ send_to_parent: { role: 'tool', tool_call_id: this.parent.tool_call_id, content: errorMessage },+ };+ } else if (!hasToolCalls(assistantMessage)) {+ const content = assistantMessageContentToStringForSubAgent(assistantMessage.content);+ completion = {+ type: 'done',+ output: agentAssistantMessage,+ send_to_parent: { role: 'tool', tool_call_id: this.parent.tool_call_id, content },+ };+ }+ }++ yield* this.appendToContext({+ context: [assistantMessage],+ output: [agentAssistantMessage],+ overwriteUsage: result.value.usage,+ updateCumulativeUsage: true,+ completion,+ });++ if (finishReason === 'length') {+ const errorContent = completion?.error_message ?? 'max_tokens breached';+ yield this.generateErrorEvent(errorContent, agentAssistantMessage);+ return { outcome: 'exit', modelMessageEventId };+ }++ if (!hasToolCalls(assistantMessage)) {+ yield {+ type: InternalEventType.AGENT_DONE,+ status: 'done',+ thread_id: this.threadId,+ title: this.title,+ output: agentAssistantMessage,+ parent: this.parent,+ send_to_parent: completion?.send_to_parent,+ };+ return { outcome: 'exit', modelMessageEventId };+ }++ return { outcome: 'continue', modelMessageEventId };+ }++ private async *stepToolResponse(+ toolMapping: Map<string, MappedMCPTool>,+ ): AsyncGenerator<AgentThreadEvent, StepOutcome, unknown> {+ const assistantMessage = lastAssistantInContext(this.context);+ if (!assistantMessage) {+ throw new Error('unreachable');+ }++ const openIds = getOpenToolCallIds(this.context);+ const openCalls = assistantMessage.tool_calls?.filter(tc => openIds.has(tc.id)) ?? [];+ const decisions = scanApprovalDecisions(this.context);++ const assistantForExecution: InternalEnrichedAssistantMessage = {+ ...assistantMessage,+ tool_calls: openCalls,+ };+ const {+ toolCallResults,+ initializationInfo,+ createThreadEvents,+ sandboxCreated,+ authRequirementInfo,+ approvalRequiredToolCalls,+ clientSideToolCalls: _clientSideToolCalls,+ events: passthroughEvents,+ } = await executeToolCalls({+ assistantMessage: assistantForExecution,+ toolMapping,+ threadId: this.threadId,+ approvalDecisions: decisions,+ });+ if (approvalRequiredToolCalls.length > 0) {+ throw new Error('Unreachable');+ }+ this._totalToolCalls += toolCallResults.length;+ this._totalSubAgents += createThreadEvents.length;++ if (initializationInfo.length > 0) {+ yield buildMCPInitializeEvent(initializationInfo, this.threadId);+ }++ if (sandboxCreated) {+ yield buildSandboxCreatedEvent(sandboxCreated);+ }++ for (const event of passthroughEvents) {+ yield { type: InternalEventType.PASSTHROUGH, event };+ }++ const toolIdsBeforeProcessing = toolCallResults.map(t => t.message.tool_call_id);+ const toolResponseExecution: Readonly<AgentThreadExecutionContext> = {+ threadId: this.threadId,+ sandbox: this.sandbox,+ currentContextUsage: this.currentContextUsage,+ context: this.context,+ };+ for (const processor of this.toolResponseProcessors) {+ const processorResult = await processor.process(toolCallResults, toolResponseExecution);+ if (processorResult.sandboxCreated) {+ yield buildSandboxCreatedEvent(processorResult.sandboxCreated);+ }+ for (const event of processorResult.events ?? []) {+ yield { type: InternalEventType.PASSTHROUGH, event };+ }+ }+ if (toolIdsBeforeProcessing.length !== toolCallResults.length) {+ throw Error('Some tool call processor has removed tool call.');+ }+ const toolIdsAfterProcessing = new Set(toolCallResults.map(t => t.message.tool_call_id));++ if (!toolIdsBeforeProcessing.every(id => toolIdsAfterProcessing.has(id))) {+ throw Error('Tool call IDs do not match after processing.');+ }++ const agentToolMessages: ToolResponseEvent[] = toolCallResults.map(t => {+ const { role: _, ...toolMessage } = t.message;+ return {+ ...toolMessage,+ type: EventType.TOOL_RESPONSE,+ id: newEventId(),+ created_at: t.completedAt,+ thread_id: this.threadId,+ };+ });+ for (const msg of agentToolMessages) {+ yield msg;+ }+ yield* this.appendToContext({+ context: toolCallResults.map(t => t.message),+ output: agentToolMessages,+ });++ if (authRequirementInfo.length > 0) {+ yield buildMCPAuthRequiredEvent(authRequirementInfo, this.threadId);+ return 'exit';+ }++ for await (const event of this.executeContextProcessors('postToolCall')) {+ yield event;+ }+ for (const event of createThreadEvents) {+ yield event;+ }+ if (createThreadEvents.length > 0) {+ return 'exit';+ }++ return 'continue';+ }++ private *stepUserInputRequired(modelMessageEventId: string): Generator<AgentThreadEvent, StepOutcome, unknown> {+ const pendingClientSideToolCalls = getPendingClientSideToolCalls(this.context);+ if (pendingClientSideToolCalls.length > 0) {+ const responseRequiredEvent: ToolResponseRequiredEvent = {+ type: EventType.TOOL_RESPONSE_REQUIRED,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: this.threadId,+ tool_calls: pendingClientSideToolCalls.map(tc => ({ id: tc.id, source_event_id: modelMessageEventId })),+ };+ yield responseRequiredEvent;+ }++ const pendingApprovalToolCalls = getPendingApprovalToolCalls(this.context);+ if (pendingApprovalToolCalls.length > 0) {+ const event: ToolApprovalRequiredEvent = {+ type: EventType.TOOL_APPROVAL_REQUIRED,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: this.threadId,+ tool_calls: pendingApprovalToolCalls.map(({ id }) => ({ id, source_event_id: modelMessageEventId })),+ };+ yield event;+ }+ return 'exit';+ }++ private buildReplayEvent(c: SubAgentCompletionMarker): InternalThreadDoneEvent {+ const base = {+ type: InternalEventType.AGENT_DONE,+ thread_id: this.threadId,+ title: this.title,+ parent: this.parent,+ send_to_parent: c.send_to_parent,+ };+ return c.type === 'done'+ ? { ...base, status: 'done', output: c.output }+ : { ...base, status: 'error', error: c.error_message ?? 'Sub-agent errored', output: c.output };+ }++ public async *execute(options?: {+ signal?: AbortSignal | undefined;+ }): AsyncGenerator<AgentThreadEvent, void, unknown> {+ const signal = options?.signal;++ this.throwIfContextBusy();+ this.contextBusy = true;+ this.currentState = null;++ // there should always be this top level try-catch block because agent execution cant raise an error. it should yield an error event.+ try {+ if (this.preComputedCompletion) {+ yield this.buildReplayEvent(this.preComputedCompletion);+ return;+ }++ if (!this.preSendRanThisTurn) {+ for await (const event of this.executeContextProcessors('preSend')) {+ yield event;+ }+ }+ this.preSendRanThisTurn = false;+ const { initializationInfo, authRequirementInfo } = await this.tracing.withInitSpan(() => this.init());++ if (initializationInfo.length > 0) {+ yield buildMCPInitializeEvent(initializationInfo, this.threadId);+ }++ if (authRequirementInfo.length > 0) {+ yield buildMCPAuthRequiredEvent(authRequirementInfo, this.threadId);+ return;+ }++ const { tools, toolMapping } = this.getConvertedTools();++ const iterationLimit = this.definition.iterationLimit ?? DEFAULT_ITERATION_LIMIT;+ // Starts empty; set only after stepLLMCall in this execute(). That is intentional:+ // user-input-required is only reachable here right after an LLM step that produced+ // pending approval/client-side tools (which sets currentModelMessageEventId first).+ // A resumed turn that is still awaiting user input never reaches this loop — orchestrator+ // send() / validateSendInput rejects empty or incomplete batches before execute runs.+ let currentModelMessageEventId = '';++ while (true) {+ while (true) {+ const sandboxCreatedEvent = this.pendingSandboxCreatedEvents.shift();+ if (sandboxCreatedEvent === undefined) break;+ yield sandboxCreatedEvent;+ }++ const state = this.deriveState();+ let outcome: StepOutcome;+ switch (state) {+ case 'llm-call-required': {+ // Cancel only before network/side-effecting steps (LLM call, tool execution), never before 'user-input-required', so the required event is always emitted once the assistant message is committed.+ if (signal?.aborted) return;+ if (this._iterations >= iterationLimit) {+ yield this.generateErrorEvent(+ `You have reached iteration limit of ${iterationLimit}, please request again`,+ );+ return;+ }+ this._iterations++;++ const llmResult = yield* this.stepLLMCall(tools, toolMapping, signal);+ outcome = llmResult.outcome;+ currentModelMessageEventId = llmResult.modelMessageEventId;+ break;+ }+ case 'tool-response-required': {+ if (signal?.aborted) return;+ outcome = yield* this.stepToolResponse(toolMapping);+ break;+ }+ case 'user-input-required': {+ // Intentionally no cancellation check here — see comment in 'llm-call-required'.+ // source_event_id comes from currentModelMessageEventId; see comment where it is declared.+ outcome = yield* this.stepUserInputRequired(currentModelMessageEventId);+ break;+ }+ default: {+ throw new Error('unreachable');+ }+ }+ if (outcome === 'exit') return;+ }+ } catch (error) {+ yield this.generateErrorEvent(error instanceof Error ? error.message : 'Unknown error occurred');+ } finally {+ this.contextBusy = false;+ }+ }+}++function assertUniqueStateKeys(capabilities: readonly AgentCapability[]): void {+ const seen = new Set<string>();+ for (const capability of capabilities) {+ const key = capability.state?.key;+ if (!key) continue;+ if (seen.has(key)) {+ throw new AgentHarnessError(+ 'capability_state_error',+ `Duplicate capability state key '${key}' — each key may be claimed by at most one capability`,+ );+ }+ seen.add(key);+ }+}++function claimCapabilityState(+ capabilities: readonly AgentCapability[],+ input: Record<string, unknown> | undefined,+ logger: Logger,+): Record<string, unknown> {+ if (!input) return {};+ const claimedKeys = new Set(capabilities.map(c => c.state?.key).filter((k): k is string => typeof k === 'string'));+ const claimed: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(input)) {+ if (!claimedKeys.has(key)) {+ logger.warn(`Dropping unclaimed capability_state key '${key}' — no capability declares it`);+ continue;+ }+ claimed[key] = value;+ }+ return claimed;+}diff --git a/packages/harness/src/core/runtime/AgentThread.types.ts b/packages/harness/src/core/runtime/AgentThread.types.tsnew file mode 100644index 000000000..017964eee--- /dev/null+++ b/packages/harness/src/core/runtime/AgentThread.types.ts@@ -0,0 +1,183 @@+import type { Logger } from 'winston';+import { z } from 'zod';+import type { AgentCapability } from '../capabilities/AgentCapability';+import type { RegisteredPassthroughEvent } from '../events/PassthroughEvents';+import type {+ ActionRequiredEvent,+ AgentApprovalDecisionMessage,+ AgentInfo,+ AgentInputUserMessage,+ AgentOutputEvent,+ AgentParent,+ BaseMCPAuthRequiredEvent,+ BaseThreadDoneEvent,+ MCPInitializeEvent,+ MCPServerAuthInfo,+ ModelMessageDeltaEvent,+ ModelMessageEvent,+ SandboxCreatedEvent,+ ThreadCreatedEvent,+ ThreadOverwriteContextEvent,+ ThreadStateError,+ ToolApprovalRequiredEvent,+ ToolResponseEvent,+ ToolResponseRequiredEvent,+ UserToolApprovalMessage,+ UserToolResponseMessage,+} from '../events/eventSchemas';+import type {+ CompletionUsage,+ InternalEnrichedAssistantMessage,+ LLMToolMessage,+ LLMUserMessage,+} from '../llm/LLMTypes';+import type { AgentThreadMetrics } from '../llm/metrics';+import type { Sandbox } from '../sandbox/Sandbox';+import type { AgentTracing } from '../tracing/AgentTracing';+import type { AgentDefinition } from './AgentDefinition';++export type { AgentInfo, AgentParent };++/** Canonical string constants for internal (non-wire) orchestration event `type` fields. */+export const InternalEventType = {+ AGENT_CREATE_SUBAGENT: 'internal.agent.create_subagent',+ AGENT_CONTEXT_APPEND: 'internal.agent.context.append',+ AGENT_DONE: 'internal.agent.done',+ // TODO(agent): revisit broader internal.* naming scheme for harness-only event types.+ PASSTHROUGH: 'agent.passthrough',+ MCP_AUTH_REQUIRED: 'internal.mcp.auth_required',+ CAPABILITY_STATE: 'internal.capability.state',+} as const;++/**+ * Cross-turn capability KV write. Processors emit without `thread_id`+ * ({@link AgentContextProcessorOutput}); AgentThread stamps `thread_id` when yielding.+ */+export interface InternalCapabilityStateEvent {+ type: typeof InternalEventType.CAPABILITY_STATE;+ thread_id: string;+ key: string;+ state: unknown;+}++export const InternalPassthroughEventSchema = z.object({+ type: z.literal(InternalEventType.PASSTHROUGH),+ event: z.custom<RegisteredPassthroughEvent>(),+});++export type InternalPassthroughEvent = z.infer<typeof InternalPassthroughEventSchema>;++export type InternalMCPServerAuthInfo = MCPServerAuthInfo & {+ thread_ids: string[];+};++export type InternalMCPAuthRequiredEvent = BaseMCPAuthRequiredEvent & {+ type: typeof InternalEventType.MCP_AUTH_REQUIRED;+ mcp_servers: InternalMCPServerAuthInfo[];+};++export type InternalThreadDoneEvent = BaseThreadDoneEvent & {+ type: typeof InternalEventType.AGENT_DONE;+ send_to_parent: LLMToolMessage | undefined;+} & ({ status: 'done'; output: ModelMessageEvent } | { status: 'error'; error: string; output?: ModelMessageEvent });++export type LLMContextMessage = LLMUserMessage | InternalEnrichedAssistantMessage | LLMToolMessage;++export type ContextMessage = LLMContextMessage | AgentApprovalDecisionMessage;++export interface AgentThreadCreateSubAgent {+ type: typeof InternalEventType.AGENT_CREATE_SUBAGENT;+ thread_id: string;+ tool_call_id: string;+ agent_info: AgentInfo;+}++export interface SubAgentCompletionMarker {+ type: 'done' | 'error';+ output: ModelMessageEvent;+ error_message?: string | undefined;+ send_to_parent: LLMToolMessage;+}++export interface AgentThreadAppendContext {+ type: typeof InternalEventType.AGENT_CONTEXT_APPEND;+ thread_id: string;+ context: ContextMessage[];+ output: AgentOutputEvent[];+ current_context_usage?: CompletionUsage | undefined;+ completion?: SubAgentCompletionMarker | undefined;+}++/** Single public send item (no internal LLM tool messages). */+export type AgentSendInput = UserToolApprovalMessage | UserToolResponseMessage | AgentInputUserMessage;++/**+ * Homogeneous public send batch: all user messages, or all approval/tool-response+ * messages. Mixed batches are rejected at the HTTP/orchestrator boundary.+ */+export type AgentThreadSendBatch = AgentInputUserMessage[] | Array<UserToolApprovalMessage | UserToolResponseMessage>;++export type AgentThreadEvent =+ | ModelMessageEvent+ | ModelMessageDeltaEvent+ | ToolResponseEvent+ | AgentThreadCreateSubAgent+ | AgentThreadAppendContext+ | ThreadOverwriteContextEvent+ | InternalThreadDoneEvent+ | InternalMCPAuthRequiredEvent+ | InternalCapabilityStateEvent+ | MCPInitializeEvent+ | SandboxCreatedEvent+ | ToolApprovalRequiredEvent+ | ToolResponseRequiredEvent+ | InternalPassthroughEvent;++export type AgentThreadExecutionEvent =+ | ThreadCreatedEvent+ | Exclude<AgentThreadEvent, InternalPassthroughEvent>+ | RegisteredPassthroughEvent;++export interface AgentThreadExecutionResult {+ output: ModelMessageEvent | null;+ required_actions: ActionRequiredEvent[];+ root_agent_error?: Pick<ThreadStateError, 'error' | 'output'> | undefined;+ metrics: AgentThreadMetrics;+}++/** Public send items plus internal LLM tool messages (child→parent delivery). */+export type AgentThreadRuntimeSendInput = AgentSendInput | LLMToolMessage;++/** Public homogeneous batches or an internal LLM tool-message batch. Not barrel-exported. */+export type AgentThreadRuntimeSendBatch = AgentThreadSendBatch | LLMToolMessage[];++export interface AgentThreadSnapshot {+ thread_id: string;+ context: ContextMessage[];+ current_context_usage: CompletionUsage;+ parent?: AgentParent | undefined;+ agent_info?: AgentInfo | undefined;+ completion?: SubAgentCompletionMarker | undefined;+ /** Cross-turn capability KV. Keys: capability.state.key; `tfy.` reserved for builtins. */+ capability_state?: Record<string, unknown> | undefined;+}++export interface AgentThreadConstructorInput {+ definition: AgentDefinition;+ threadId: string;+ title: string;+ parent?: AgentParent | undefined;+ agentInfo?: AgentInfo | undefined;+ context?: ContextMessage[] | undefined;+ currentContextUsage?: CompletionUsage | undefined;+ preComputedCompletion?: SubAgentCompletionMarker | undefined;+ sandbox?: Sandbox | undefined;+ capabilities?: readonly AgentCapability[] | undefined;+ /**+ * Previous turn's capability_state for hydration. Optional — omit on first+ * turn / fresh sub-agent. The constructor is the sole hydration site.+ */+ capabilityState?: Record<string, unknown> | undefined;+ tracing: AgentTracing;+ logger: Logger;+}diff --git a/packages/harness/src/core/runtime/AgentThreadOrchestrator.ts b/packages/harness/src/core/runtime/AgentThreadOrchestrator.tsnew file mode 100644index 000000000..4647d6105--- /dev/null+++ b/packages/harness/src/core/runtime/AgentThreadOrchestrator.ts@@ -0,0 +1,497 @@+import type { Logger } from 'winston';+import { AgentHarnessError, InvalidAgentSendInputError } from '../errors';+import {+ EventType,+ newEventId,+ type ActionRequiredEvent,+ type ModelMessageEvent,+ type ToolResponseEvent,+ type UserToolApprovalMessage,+ type UserToolResponseMessage,+} from '../events/eventSchemas';+import { addMetrics, getEmptyMetric } from '../llm/metrics';+import type { AgentExecutionTrace, AgentTracing } from '../tracing/AgentTracing';+import { onSignalAbort } from '../util/abort';+import { mergeAsyncGenerators } from '../util/promiseUtils';+import { AgentThread } from './AgentThread';+import type { AgentThreadRuntimeSendBatch } from './AgentThread.types';+import {+ InternalEventType,+ type AgentThreadAppendContext,+ type AgentThreadEvent,+ type AgentThreadExecutionEvent,+ type AgentThreadExecutionResult,+ type AgentThreadSendBatch,+ type InternalMCPAuthRequiredEvent,+ type InternalMCPServerAuthInfo,+} from './AgentThread.types';+import {+ assistantMessageContentToStringForSubAgent,+ getThreadId,+ isApprovalDecisionMessage,+ isClientSideToolResponseMessage,+ isInternalThreadDoneError,+} from './contextUtils';+import type { CreateDynamicSubAgentThread } from './CreateDynamicSubAgentThread';++const MAX_PARALLEL_SUB_AGENTS = 5;++function agentThreadEventToTerminalFields(event: AgentThreadExecutionEvent): {+ output?: ModelMessageEvent | undefined;+ requiredAction?: ActionRequiredEvent | undefined;+} {+ switch (event.type) {+ case InternalEventType.AGENT_DONE: {+ if ('parent' in event && event.parent) return {};+ if (event.status === 'error') return {};+ return { output: event.output };+ }+ case EventType.TOOL_APPROVAL_REQUIRED:+ case EventType.TOOL_RESPONSE_REQUIRED:+ return { requiredAction: event };+ default:+ return {};+ }+}++type UserToolApprovalOrResponseBatch = Array<UserToolApprovalMessage | UserToolResponseMessage>;++function isUserToolApprovalOrResponseBatch(+ messages: AgentThreadSendBatch,+): messages is UserToolApprovalOrResponseBatch {+ const first = messages[0];+ return first !== undefined && (isApprovalDecisionMessage(first) || isClientSideToolResponseMessage(first));+}++function getMainThreadId(agentThreads: Map<string, AgentThread>): string {+ for (const thread of agentThreads.values()) {+ if (!thread.parent) return thread.threadId;+ }+ throw new Error('Unreachable: no root thread found');+}++function getActiveAgentThreads(agentThreads: Map<string, AgentThread>): AgentThread[] {+ const nodes = new Set(agentThreads.keys());+ const parentNodes = new Set(+ [...agentThreads.values()].map(a => a.parent?.thread_id).filter((a): a is string => Boolean(a)),+ );+ const leaves = [...nodes].filter(id => !parentNodes.has(id));+ if (leaves.length === 0) {+ throw new Error('We cannot have zero leave agents');+ }+ return leaves.map(id => {+ const agentThread = agentThreads.get(id);+ if (!agentThread) throw new Error('unreachable');+ return agentThread;+ });+}++function mergeAuthEvents(events: InternalMCPAuthRequiredEvent[]): InternalMCPAuthRequiredEvent {+ const serverMap = new Map<string, InternalMCPServerAuthInfo>();+ for (const event of events) {+ for (const entry of event.mcp_servers) {+ const existing = serverMap.get(entry.id);+ if (existing) {+ existing.thread_ids.push(...entry.thread_ids);+ } else {+ serverMap.set(entry.id, { ...entry, thread_ids: [...entry.thread_ids] });+ }+ }+ }+ return {+ type: InternalEventType.MCP_AUTH_REQUIRED,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: null,+ mcp_servers: [...serverMap.values()],+ };+}++function wrapGeneratorWithTrace<T, TReturn = void, TNext = unknown>(+ trace: AgentExecutionTrace,+ generator: AsyncGenerator<T, TReturn, TNext>,+): AsyncGenerator<T, TReturn, TNext> {+ const wrapped: AsyncGenerator<T, TReturn, TNext> = {+ [Symbol.asyncIterator]() {+ return this;+ },+ next(...[value]: [] | [TNext]) {+ return trace.runInContext(() => (value === undefined ? generator.next() : generator.next(value)));+ },+ return(value: TReturn | PromiseLike<TReturn>) {+ return trace.runInContext(() => generator.return(value));+ },+ throw(e: unknown) {+ return trace.runInContext(() => generator.throw(e));+ },+ [Symbol.asyncDispose]() {+ return generator[Symbol.asyncDispose]();+ },+ };+ return wrapped;+}++interface RootAgentSpanHandle {+ trace: AgentExecutionTrace;+ wrapThreadWithContext(thread: AgentThread, signal?: AbortSignal): AsyncGenerator<AgentThreadEvent>;+ setOutputFromEvent(chunk: AgentThreadEvent): void;+ finalize(thread: AgentThread, error?: unknown): void;+ end(): void;+}++function createRootAgentSpan(mainThread: AgentThread, tracing: AgentTracing): RootAgentSpanHandle {+ const trace = tracing.startRootSpan(+ JSON.stringify({ instructions: mainThread.definition.instruction, messages: mainThread.definition.messages }),+ );+ let rootAgentErrorMessage: string | undefined;+ let rootAgentCompleted = false;++ return {+ trace,+ wrapThreadWithContext(thread: AgentThread, signal?: AbortSignal) {+ return wrapGeneratorWithTrace(trace, thread.execute({ signal }));+ },+ setOutputFromEvent(chunk: AgentThreadEvent) {+ rootAgentCompleted = true;+ if (chunk.type === InternalEventType.AGENT_DONE) {+ if (isInternalThreadDoneError(chunk)) {+ rootAgentErrorMessage = chunk.error;+ trace.setOutput(JSON.stringify({ error: chunk.error }));+ } else {+ const content = assistantMessageContentToStringForSubAgent(chunk.output.content);+ trace.setOutput(JSON.stringify({ result: content }));+ }+ }+ },+ finalize(thread: AgentThread, error?: unknown) {+ trace.setMetrics(thread.getAgentThreadMetrics());+ if (error) {+ trace.setError(error);+ } else if (rootAgentErrorMessage || !rootAgentCompleted) {+ trace.setError(rootAgentErrorMessage ?? 'Agent execution interrupted');+ } else {+ trace.setSuccess();+ }+ },+ end() {+ trace.end();+ },+ };+}++/** @internal Exported for sub-agent span finalization tests. */+export async function* wrapWithSubAgentSpan(+ parentTrace: AgentExecutionTrace,+ currentThread: AgentThread,+ signal?: AbortSignal,+): AsyncGenerator<AgentThreadEvent> {+ const agentInfo = currentThread.agentInfo;+ if (!agentInfo) {+ throw new Error('Sub-agent thread is missing agentInfo');+ }+ const subTrace = parentTrace.startSubAgent(agentInfo.name, JSON.stringify({ instructions: agentInfo.input }));+ const generator = wrapGeneratorWithTrace(subTrace, currentThread.execute({ signal }));++ try {+ for await (const event of generator) {+ if (event.type === InternalEventType.AGENT_DONE) {+ if (isInternalThreadDoneError(event)) {+ subTrace.setOutput(JSON.stringify({ error: event.error }));+ subTrace.setMetrics(currentThread.getAgentThreadMetrics());+ subTrace.setError(event.error);+ } else {+ const content = assistantMessageContentToStringForSubAgent(event.output.content);+ subTrace.setOutput(JSON.stringify({ result: content }));+ subTrace.setMetrics(currentThread.getAgentThreadMetrics());+ subTrace.setSuccess();+ }+ // end() only in finally so every path finalizes exactly once+ }+ yield event;+ }+ } catch (error) {+ subTrace.setError(error);+ throw error;+ } finally {+ subTrace.end();+ }+}++export interface AgentThreadOrchestratorInput {+ agentThreads: Map<string, AgentThread>;+ createDynamicSubAgentThread: CreateDynamicSubAgentThread;+ tracing: AgentTracing;+ logger: Logger;+}++export class AgentThreadOrchestrator {+ private readonly agentThreads: Map<string, AgentThread>;+ private readonly createDynamicSubAgentThread: CreateDynamicSubAgentThread;+ private readonly tracing: AgentTracing;+ private readonly logger: Logger;++ constructor(params: AgentThreadOrchestratorInput) {+ this.agentThreads = params.agentThreads;+ this.createDynamicSubAgentThread = params.createDynamicSubAgentThread;+ this.tracing = params.tracing;+ this.logger = params.logger.child({ module: 'AgentThreadOrchestrator' });+ }++ public async *send(messages: AgentThreadSendBatch): AsyncGenerator<AgentThreadAppendContext, void, unknown> {+ const byThread = new Map<string, AgentThreadRuntimeSendBatch>();+ for (const thread of this.agentThreads.values()) {+ byThread.set(thread.threadId, []);+ }++ if (isUserToolApprovalOrResponseBatch(messages)) {+ const grouped = new Map<string, UserToolApprovalOrResponseBatch[number][]>();+ for (const msg of messages) {+ const threadId = msg.thread_id;+ if (!byThread.has(threadId)) {+ throw new InvalidAgentSendInputError(`unknown thread_id: ${threadId}`);+ }+ const batch = grouped.get(threadId) ?? [];+ batch.push(msg);+ grouped.set(threadId, batch);+ }+ for (const [threadId, batch] of grouped) {+ byThread.set(threadId, batch);+ }+ } else if (messages.length > 0) {+ if (this.agentThreads.size > 1) {+ throw new InvalidAgentSendInputError(+ 'Cannot process user messages while sub agents are running, please send empty input for previous conversation to complete',+ );+ }+ byThread.set(getMainThreadId(this.agentThreads), messages);+ }++ const validationErrors: string[] = [];+ for (const [threadId, batch] of byThread) {+ const thread = this.agentThreads.get(threadId);+ if (!thread) {+ throw new Error(`AgentThreadOrchestrator.send: unknown threadId ${threadId}`);+ }+ try {+ thread.validateSendInput(batch);+ } catch (e) {+ if (e instanceof AgentHarnessError && e.code === 'invalid_send_input') {+ validationErrors.push(`thread ${threadId}: ${e.message}`);+ } else {+ throw e;+ }+ }+ }+ if (validationErrors.length > 0) {+ throw new InvalidAgentSendInputError(validationErrors.join('; '));+ }++ for (const [threadId, batch] of byThread) {+ yield* this.sendToThread(threadId, batch);+ }+ }++ private async *sendToThread(+ threadId: string,+ messages: AgentThreadRuntimeSendBatch,+ ): AsyncGenerator<AgentThreadAppendContext, void, unknown> {+ const thread = this.agentThreads.get(threadId);+ if (!thread) {+ throw new Error(`AgentThreadOrchestrator.sendToThread: unknown threadId ${threadId}`);+ }+ yield* thread.send(messages);+ }++ private async *processAgentStreamChunk(+ chunk: Exclude<AgentThreadEvent, InternalMCPAuthRequiredEvent>,+ signal: AbortSignal,+ ): AsyncGenerator<AgentThreadExecutionEvent, { shouldStopExecution: boolean }, unknown> {+ if (chunk.type === InternalEventType.PASSTHROUGH) {+ yield chunk.event;+ return { shouldStopExecution: false };+ }++ if (!('thread_id' in chunk) || chunk.thread_id == null) {+ yield chunk;+ return { shouldStopExecution: false };+ }++ const currentThread = this.agentThreads.get(chunk.thread_id);+ if (!currentThread) {+ throw new Error('unreachable');+ }++ switch (chunk.type) {+ case EventType.TOOL_APPROVAL_REQUIRED:+ case EventType.TOOL_RESPONSE_REQUIRED:+ yield chunk;+ return { shouldStopExecution: true };+ case InternalEventType.AGENT_DONE: {+ if (chunk.parent) {+ if (!chunk.send_to_parent) throw new Error('unreachable');+ const parentThread = this.agentThreads.get(chunk.parent.thread_id);+ if (!parentThread) throw new Error('unreachable: parent thread missing');+ const subAgentToolIsOpen = parentThread.hasOpenToolCallId(chunk.parent.tool_call_id);+ if (subAgentToolIsOpen) {+ const parentToolResponse: ToolResponseEvent = {+ type: EventType.TOOL_RESPONSE,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: chunk.parent.thread_id,+ tool_call_id: chunk.send_to_parent.tool_call_id,+ content: '',+ };+ yield parentToolResponse;+ yield* this.sendToThread(chunk.parent.thread_id, [chunk.send_to_parent]);+ }+ yield chunk;+ this.agentThreads.delete(chunk.thread_id);+ return { shouldStopExecution: false };+ }+ yield chunk;+ return { shouldStopExecution: true };+ }+ case InternalEventType.AGENT_CREATE_SUBAGENT: {+ const parent = {+ tool_call_id: chunk.tool_call_id,+ thread_id: chunk.thread_id,+ };+ const subAgentThreadId = getThreadId();+ const subAgentThread = await this.createDynamicSubAgentThread({+ parentDefinition: currentThread.definition,+ request: chunk.agent_info,+ threadId: subAgentThreadId,+ parent,+ signal,+ });++ yield {+ type: EventType.THREAD_CREATED,+ id: newEventId(),+ agent_info: {+ type: 'dynamic',+ name: chunk.agent_info.name,+ input: chunk.agent_info.input,+ model: chunk.agent_info.model,+ },+ created_at: new Date().toISOString(),+ parent,+ title: chunk.agent_info.name,+ thread_id: subAgentThreadId,+ };+ this.agentThreads.set(subAgentThreadId, subAgentThread);+ return { shouldStopExecution: false };+ }+ default:+ yield chunk;+ return { shouldStopExecution: false };+ }+ }++ public async *execute({+ signal,+ }: {+ signal: AbortSignal;+ }): AsyncGenerator<AgentThreadExecutionEvent, AgentThreadExecutionResult, unknown> {+ const { agentThreads } = this;+ let shouldStopExecution = false;+ let caughtError: unknown;+ let output: ModelMessageEvent | null = null;+ const requiredActions: ActionRequiredEvent[] = [];+ let rootAgentError: AgentThreadExecutionResult['root_agent_error'];+ const pendingAuthEvents: InternalMCPAuthRequiredEvent[] = [];+ const totalMetrics = getEmptyMetric();+ const mainThread = [...agentThreads.values()].find(e => !e.parent);+ if (!mainThread) {+ throw new Error('Unreachable: no root thread found');+ }+ const rootSpan = createRootAgentSpan(mainThread, this.tracing);++ onSignalAbort(signal, () => {+ shouldStopExecution = true;+ });++ try {+ while (agentThreads.size > 0) {+ if (shouldStopExecution) break;++ const activeThreads = getActiveAgentThreads(agentThreads);++ for (let i = 0; i < activeThreads.length && !shouldStopExecution; i += MAX_PARALLEL_SUB_AGENTS) {+ const batch = activeThreads.slice(i, i + MAX_PARALLEL_SUB_AGENTS);+ const generators = batch.map(thread => {+ if (!thread.parent) {+ return rootSpan.wrapThreadWithContext(thread, signal);+ }+ return wrapWithSubAgentSpan(rootSpan.trace, thread, signal);+ });++ for await (const chunk of mergeAsyncGenerators(generators, this.logger)) {+ if (chunk.type === InternalEventType.MCP_AUTH_REQUIRED) {+ pendingAuthEvents.push(chunk);+ shouldStopExecution = true;+ continue;+ }+ if (chunk.type === InternalEventType.AGENT_DONE) {+ if (chunk.parent) {+ const completedThread = agentThreads.get(chunk.thread_id);+ if (completedThread) {+ addMetrics(totalMetrics, completedThread.getAgentThreadMetrics());+ }+ } else {+ // Root-thread only — sub-agent AGENT_DONE would overwrite root trace output /+ // leave a stale error; sub-agent spans finalize in wrapWithSubAgentSpan.+ rootSpan.setOutputFromEvent(chunk);+ }+ }++ const result = yield* this.processAgentStreamChunk(chunk, signal);+ if (result.shouldStopExecution) {+ shouldStopExecution = true;+ if (+ !rootAgentError &&+ chunk.type === InternalEventType.AGENT_DONE &&+ isInternalThreadDoneError(chunk) &&+ !chunk.parent+ ) {+ rootAgentError = { error: chunk.error, output: chunk.output };+ }+ if (chunk.type !== InternalEventType.PASSTHROUGH) {+ const { output: outputContribution, requiredAction } = agentThreadEventToTerminalFields(chunk);+ if (outputContribution) output = outputContribution;+ if (requiredAction) requiredActions.push(requiredAction);+ }+ }+ }+ }+ }+ } catch (error) {+ caughtError = error;+ throw error;+ } finally {+ addMetrics(totalMetrics, mainThread.getAgentThreadMetrics());+ rootSpan.finalize(mainThread, caughtError);+ rootSpan.end();+ }++ if (pendingAuthEvents.length > 0) {+ const authEvent = mergeAuthEvents(pendingAuthEvents);+ yield authEvent;+ const authRequiredAction: ActionRequiredEvent = {+ type: EventType.MCP_AUTH_REQUIRED,+ id: authEvent.id,+ created_at: authEvent.created_at,+ thread_id: authEvent.thread_id,+ mcp_servers: authEvent.mcp_servers.map(({ thread_ids: _, ...s }) => s),+ };+ requiredActions.push(authRequiredAction);+ }++ return {+ output,+ required_actions: requiredActions,+ root_agent_error: rootAgentError,+ metrics: { total: totalMetrics },+ };+ }+}diff --git a/packages/harness/src/core/runtime/CreateDynamicSubAgentThread.ts b/packages/harness/src/core/runtime/CreateDynamicSubAgentThread.tsnew file mode 100644index 000000000..3914be8f2--- /dev/null+++ b/packages/harness/src/core/runtime/CreateDynamicSubAgentThread.ts@@ -0,0 +1,11 @@+import type { AgentInfo, AgentParent } from '../events/eventSchemas';+import type { AgentDefinition } from './AgentDefinition';+import type { AgentThread } from './AgentThread';++export type CreateDynamicSubAgentThread = (input: {+ parentDefinition: AgentDefinition;+ request: AgentInfo;+ threadId: string;+ parent: AgentParent;+ signal: AbortSignal;+}) => Promise<AgentThread>;diff --git a/packages/harness/src/core/runtime/DeferredTool.ts b/packages/harness/src/core/runtime/DeferredTool.tsnew file mode 100644index 000000000..2898a0a54--- /dev/null+++ b/packages/harness/src/core/runtime/DeferredTool.ts@@ -0,0 +1,339 @@+import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import dedent from 'dedent';+import type { Logger } from 'winston';+import { z } from 'zod';+import type { ApprovalDecision } from '../events/eventSchemas';+import { InstructionBuilder } from '../InstructionBuilder';+import type { InternalToolCallInfo } from '../llm/LLMTypes';+import {+ type AgentToolSchema,+ type CallToolResponse,+ isApprovalRequiredResponse,+ isAuthRequired,+ isCallToolResponseResult,+ type IToolSet,+ type ListToolsResolvedResponse,+ toolResultResponse,+} from '../mcp/IMCPServer';+import { defineTool, LocalToolMCP, type ToolDefinition } from '../mcp/LocalToolMCP';+import type { AgentTracing } from '../tracing/AgentTracing';+import { extractErrorLogFields } from '../util/errorLogFields';++export const DEFERRED_TOOLS_SERVER_ID = 'deferred-tools';+const DEFERRED_TOOLS_INSTRUCTION = 'deferred-tools-instructions';+export const LIST_TOOLS_NAME = 'list_tools';+export const GET_TOOL_INFO_NAME = 'get_tool_info';+export const GET_TOOL_OUTPUT_SCHEMA_NAME = 'get_tool_output_schema';+const CALL_TOOL_NAME = 'call_tool';+const MAX_DESCRIPTION_LENGTH = 200;++const listToolsSchema = z.object({+ mcp_server: z.string().describe('Name of the MCP server to list tools for.'),+});++const getToolInfoSchema = z.object({+ mcp_server: z.string().describe('Name of the MCP server.'),+ tool_name: z.string().describe('Name of the tool to inspect.'),+});++const getToolOutputSchemaSchema = z.object({+ mcp_server: z.string().describe('Name of the MCP server.'),+ tool_name: z.string().describe('Name of the tool to get output schema for.'),+});++const callToolSchema = z.object({+ mcp_server: z.string().describe('Name of the MCP server.'),+ tool_name: z.string().describe('Name of the tool to call.'),+ input: z.record(z.string(), z.unknown()).default({}).describe('Arguments to pass to the tool.'),+});++type ResolvedServerTools = {+ server: IToolSet;+ tools: AgentToolSchema[];+ metadata: Omit<ListToolsResolvedResponse, 'result'>;+};++function isResolvedServerTools(result: CallToolResponse | ResolvedServerTools): result is ResolvedServerTools {+ return 'tools' in result;+}++export class DeferredTool extends LocalToolMCP {+ readonly name = DEFERRED_TOOLS_SERVER_ID;+ readonly displayName = 'DeferredTools';+ override readonly description = 'Deferred tool loading for user MCP servers';++ private readonly serverMap: Map<string, IToolSet>;+ private readonly tools: ToolDefinition[];+ private readonly logger: Logger;++ constructor(+ servers: readonly IToolSet[],+ options: {+ tracing: AgentTracing;+ logger: Logger;+ },+ ) {+ super({ tracing: options.tracing });+ this.logger = options.logger.child({ module: 'DeferredTool' });+ this.serverMap = new Map(servers.map(s => [s.name, s]));+ this.tools = this.buildTools();+ }++ buildInstruction(builder: InstructionBuilder): void {+ const servers = [...this.serverMap.values()];++ // Membership follows `preload` only (origin/main). Selective `preload_tools` /+ // `hasPreloadedTools` must not hide a server from deferred discovery instructions.+ const deferredServers = servers.filter(s => !s.preload);++ if (deferredServers.length === 0) return;++ const deferredList = deferredServers+ .map(s => (s.description ? `- ${s.name}: "${s.description.slice(0, MAX_DESCRIPTION_LENGTH)}"` : `- ${s.name}`))+ .join('\n');++ builder.addSection(+ DEFERRED_TOOLS_INSTRUCTION,+ dedent`+ The following MCP servers have deferred tool loading. Their tools are NOT pre-loaded.+ ${deferredList}++ The Agent MUST use ${LIST_TOOLS_NAME} and ${GET_TOOL_INFO_NAME} to discover tools before calling them.`,+ );+ }++ protected getTools(): ToolDefinition[] {+ return this.tools;+ }++ override async toolCallInfo(+ params: CallToolRequest['params'],+ resolveUnderlyingTool?: boolean,+ ): Promise<InternalToolCallInfo> {+ if (params.name !== CALL_TOOL_NAME) {+ return super.toolCallInfo(params, resolveUnderlyingTool);+ }+ if (resolveUnderlyingTool === false) {+ const base = await super.toolCallInfo(params, resolveUnderlyingTool);+ return { ...base, is_deferred: true };+ }+ const parsed = callToolSchema.safeParse(params.arguments);+ if (!parsed.success) {+ this.logger.warn(`Failed to parse call_tool arguments`, {+ tool: params.name,+ errors: parsed.error.issues,+ });+ return { ...(await super.toolCallInfo(params)), is_deferred: true };+ }+ const server = this.resolveServer(parsed.data.mcp_server);+ if (!server) {+ this.logger.warn(`Server not found for toolCallInfo`, {+ mcpServer: parsed.data.mcp_server,+ toolName: parsed.data.tool_name,+ availableServers: [...this.serverMap.keys()],+ });+ return { ...(await super.toolCallInfo(params)), is_deferred: true };+ }+ const underlying = await server.toolCallInfo({+ name: parsed.data.tool_name,+ arguments: parsed.data.input,+ });+ return { ...underlying, is_deferred: true };+ }++ private resolveServer(name: string): IToolSet | undefined {+ return this.serverMap.get(name);+ }++ private async resolveServerTools(mcpServer: string): Promise<CallToolResponse | ResolvedServerTools> {+ const server = this.resolveServer(mcpServer);+ if (!server) {+ return toolResultResponse({+ text: JSON.stringify({ error: `MCP server '${mcpServer}' not found` }),+ isError: true,+ });+ }++ const listResponse = await server.listTools();+ if (isAuthRequired(listResponse)) {+ return listResponse;+ }+ const { result, ...metadata } = listResponse;+ return { server, tools: result.tools, metadata };+ }++ private buildTools(): ToolDefinition[] {+ return [this.buildListTools(), this.buildGetToolInfo(), this.buildGetToolOutputSchema(), this.buildCallTool()];+ }++ private buildListTools(): ToolDefinition {+ return defineTool({+ name: LIST_TOOLS_NAME,+ description: dedent`+ List tool names available on an MCP server.+ Returns tool names only — use ${GET_TOOL_INFO_NAME} to get full details before calling a tool.`,+ schema: listToolsSchema,+ handler: async (input: { mcp_server: string }) => {+ try {+ const resolved = await this.resolveServerTools(input.mcp_server);+ if (!isResolvedServerTools(resolved)) return resolved;+ const { server, tools, metadata } = resolved;+ return toolResultResponse({+ text: `${server.name}:\n ${tools.map(t => t.name).join(', ')}`,+ overrides: metadata,+ });+ } catch (error) {+ this.logger.error('list_tools failed', {+ ...extractErrorLogFields(error),+ mcpServer: input.mcp_server,+ });+ return toolResultResponse({+ text: JSON.stringify({ error: `Failed to list tools for '${input.mcp_server}'.` }),+ isError: true,+ });+ }+ },+ });+ }++ private buildGetToolInfo(): ToolDefinition {+ return defineTool({+ name: GET_TOOL_INFO_NAME,+ description: dedent`+ Get description, inputSchema and outputSchema for a specific tool on an MCP server.+ If outputSchema is null, it will NOT be present in ${GET_TOOL_OUTPUT_SCHEMA_NAME} as well.+ The Agent MUST call ${LIST_TOOLS_NAME} first to know which tools are available.`,+ schema: getToolInfoSchema,+ handler: async (input: { mcp_server: string; tool_name: string }) => {+ try {+ const resolved = await this.resolveServerTools(input.mcp_server);+ if (!isResolvedServerTools(resolved)) return resolved;+ const { tools, metadata } = resolved;+ const tool = tools.find(t => t.name === input.tool_name);+ if (!tool) {+ return toolResultResponse({+ text: JSON.stringify({ error: `Tool '${input.tool_name}' not found on server '${input.mcp_server}'` }),+ overrides: metadata,+ isError: true,+ });+ }++ return toolResultResponse({+ text: JSON.stringify({+ description: tool.description,+ inputSchema: tool.inputSchema,+ outputSchema: tool.outputSchema ?? null,+ }),+ overrides: metadata,+ });+ } catch (error) {+ this.logger.error('get_tool_info failed', {+ ...extractErrorLogFields(error),+ mcpServer: input.mcp_server,+ toolName: input.tool_name,+ });+ return toolResultResponse({+ text: JSON.stringify({+ error: `Failed to get tool info: ${error instanceof Error ? error.message : 'unknown'}`,+ }),+ isError: true,+ });+ }+ },+ });+ }++ private buildGetToolOutputSchema(): ToolDefinition {+ return defineTool({+ name: GET_TOOL_OUTPUT_SCHEMA_NAME,+ description: dedent`+ Get the outputSchema for a specific tool on an MCP server.+ The Agent MUST not call ${GET_TOOL_OUTPUT_SCHEMA_NAME} and ${GET_TOOL_INFO_NAME} for the same tool.+ The Agent MUST either call ${GET_TOOL_OUTPUT_SCHEMA_NAME} or ${GET_TOOL_INFO_NAME} before entering Code Mode.+ The Agent must NOT assume the structure of a tool's response from its name or description alone.`,+ schema: getToolOutputSchemaSchema,+ handler: async (input: { mcp_server: string; tool_name: string }) => {+ try {+ const resolved = await this.resolveServerTools(input.mcp_server);+ if (!isResolvedServerTools(resolved)) return resolved;+ const { tools, metadata } = resolved;+ const tool = tools.find(t => t.name === input.tool_name);+ if (!tool) {+ return toolResultResponse({+ text: JSON.stringify({ error: `Tool '${input.tool_name}' not found on server '${input.mcp_server}'` }),+ overrides: metadata,+ isError: true,+ });+ }++ return toolResultResponse({+ text: JSON.stringify({+ outputSchema: tool.outputSchema ?? null,+ }),+ overrides: metadata,+ });+ } catch (error) {+ this.logger.error('get_tool_output_schema failed', {+ ...extractErrorLogFields(error),+ mcpServer: input.mcp_server,+ toolName: input.tool_name,+ });+ return toolResultResponse({+ text: JSON.stringify({+ error: `Failed to get output schema: ${error instanceof Error ? error.message : 'unknown'}`,+ }),+ isError: true,+ });+ }+ },+ });+ }++ private buildCallTool(): ToolDefinition {+ return defineTool({+ name: CALL_TOOL_NAME,+ description: dedent`+ Call a tool on an MCP server.+ The Agent MUST call ${LIST_TOOLS_NAME} and ${GET_TOOL_INFO_NAME} before calling a tool.`,+ schema: callToolSchema,+ handler: async (+ input: { mcp_server: string; tool_name: string; input: Record<string, unknown> },+ approvalDecision?: ApprovalDecision,+ ) => {+ const server = this.resolveServer(input.mcp_server);+ if (!server) {+ return toolResultResponse({+ text: JSON.stringify({ error: `MCP server '${input.mcp_server}' not found` }),+ isError: true,+ });+ }++ try {+ const response = await server.callTool({ name: input.tool_name, arguments: input.input }, approvalDecision);++ if (isAuthRequired(response)) {+ return response;+ }++ if (isApprovalRequiredResponse(response)) return response;++ if (!isCallToolResponseResult(response)) {+ throw new Error('Tool call returned an unexpected sub-agent response');+ }++ return response;+ } catch (error) {+ this.logger.error('call_tool failed', {+ ...extractErrorLogFields(error),+ mcpServer: input.mcp_server,+ toolName: input.tool_name,+ });+ return toolResultResponse({+ text: JSON.stringify({ error: `Tool call failed: ${error instanceof Error ? error.message : 'unknown'}` }),+ isError: true,+ });+ }+ },+ });+ }+}diff --git a/packages/harness/src/core/runtime/OpenToolCallCloser.ts b/packages/harness/src/core/runtime/OpenToolCallCloser.tsnew file mode 100644index 000000000..46160d9a1--- /dev/null+++ b/packages/harness/src/core/runtime/OpenToolCallCloser.ts@@ -0,0 +1,92 @@+/**+ * OpenToolCallCloser - Context processor that closes unresolved tool calls.+ *+ * When an assistant message contains tool_calls but corresponding tool response+ * messages are missing (e.g., due to a failed or interrupted tool execution),+ * LLMs will reject the request. This processor detects such cases in the+ * **last** assistant message and appends dummy tool responses so the+ * conversation can continue.+ *+ * Uses is_thread_creation from InternalToolCallInfo to identify sub-agent+ * tool calls (which should remain open); does NOT use SUB_AGENTS_SERVER_ID.+ * Older persisted contexts without is_thread_creation follow the ordinary+ * non-thread-creation path (no compatibility fallback).+ */+import type {+ AgentContextProcessorAppendContext,+ AgentThreadExecutionContext,+ PreSendContextProcessor,+} from '../capabilities/AgentContextProcessor';+import type { InternalEnrichedAssistantMessage, LLMToolMessage } from '../llm/LLMTypes';+import { mergeUsage } from '../llm/usage';+import type { ContextMessage } from './AgentThread.types';+import { InternalEventType } from './AgentThread.types';+import { estimateTokensForContextMessages, isLLMContextMessage } from './contextUtils';++const DUMMY_TOOL_MESSAGE_CONTENT = JSON.stringify({+ error: 'Tool call was not executed. Please retry this tool call.',+});++export function getClosableOpenToolCallIds(context: ContextMessage[]): Set<string> {+ const lastIdx = context.findLastIndex(+ (msg): msg is InternalEnrichedAssistantMessage =>+ isLLMContextMessage(msg) && msg.role === 'assistant' && !!msg.tool_calls?.length,+ );+ if (lastIdx === -1) {+ return new Set();+ }++ const lastAssistant = context[lastIdx]!;+ if (!isLLMContextMessage(lastAssistant) || lastAssistant.role !== 'assistant') {+ throw new Error('Unreachable');+ }+ if (!lastAssistant.tool_calls) {+ return new Set();+ }++ if (lastAssistant.tool_calls.some(tc => tc.tool_info.is_approval_required || tc.tool_info.is_client_side)) {+ return new Set();+ }++ const requestedIds = new Set(+ lastAssistant.tool_calls.filter(tc => tc.tool_info.is_thread_creation !== true).map(tc => tc.id),+ );++ const messagesAfterAssistant = context.slice(lastIdx + 1);+ for (const msg of messagesAfterAssistant) {+ if (isLLMContextMessage(msg) && msg.role === 'tool') {+ requestedIds.delete(msg.tool_call_id);+ }+ }++ return requestedIds;+}++export class OpenToolCallCloser implements PreSendContextProcessor {+ async *processPreSend(+ execution: Readonly<AgentThreadExecutionContext>,+ ): AsyncGenerator<AgentContextProcessorAppendContext, void, unknown> {+ const requestedIds = getClosableOpenToolCallIds(execution.context);+ if (requestedIds.size === 0) {+ return;+ }++ const dummyToolMessages: LLMToolMessage[] = [...requestedIds].map(toolCallId => ({+ role: 'tool',+ tool_call_id: toolCallId,+ content: DUMMY_TOOL_MESSAGE_CONTENT,+ }));++ const currentContextUsage = mergeUsage(+ execution.currentContextUsage,+ estimateTokensForContextMessages(dummyToolMessages),+ );++ yield {+ type: InternalEventType.AGENT_CONTEXT_APPEND,+ context: dummyToolMessages,+ output: [],+ current_context_usage: currentContextUsage,+ };+ }+}diff --git a/packages/harness/src/core/runtime/UserInputMessage.ts b/packages/harness/src/core/runtime/UserInputMessage.tsnew file mode 100644index 000000000..58501c698--- /dev/null+++ b/packages/harness/src/core/runtime/UserInputMessage.ts@@ -0,0 +1,198 @@+import type { ChatCompletionContentPart } from 'openai/resources/chat';+import { AgentSandboxRequiredError, InvalidAgentInputError } from '../errors';+import {+ EventType,+ type AgentInputUserMessage,+ type FileContentPart,+ type TextContentPart,+ type UserContentPart,+} from '../events/eventSchemas';+import type { LLMUserMessage } from '../llm/LLMTypes';+import type { Sandbox, SandboxInfo } from '../sandbox/Sandbox';+import type { AgentSendInput } from './AgentThread.types';+import { internalSystemTag } from './contextUtils';++export type { AgentInputUserMessage, FileContentPart, TextContentPart, UserContentPart };++export type AgentUserMessageContent = AgentInputUserMessage['content'];+export type AgentUserContentPart = UserContentPart;++export function isFileContentPart(part: UserContentPart): part is FileContentPart {+ return part.type === 'file';+}++export function isAgentInputUserMessage(msg: AgentSendInput): msg is AgentInputUserMessage {+ return 'type' in msg && msg.type === EventType.USER_MESSAGE;+}++export function isEmptyMessageContent(content: AgentUserMessageContent): boolean {+ return typeof content === 'string' ? content.trim().length === 0 : content.length === 0;+}++const INLINE_MIME_PREFIXES = ['image/', 'application/pdf'];++function isInlineMime(mime: string): boolean {+ return INLINE_MIME_PREFIXES.some(prefix => mime.startsWith(prefix));+}++function isImageMime(mime: string): boolean {+ return mime.startsWith('image/');+}++function parseMimeFromFileData(fileData: string): string {+ const match = fileData.match(/^data:([^;,]+)/);+ if (!match?.[1]) {+ throw new InvalidAgentInputError('File data URI is missing or has unparseable MIME type');+ }+ return match[1];+}++function extractBase64(dataUri: string): Buffer {+ const commaIndex = dataUri.indexOf(',');+ if (commaIndex === -1) {+ throw new InvalidAgentInputError('File data URI has no base64 payload');+ }+ const raw = dataUri.substring(commaIndex + 1);+ if (!raw) {+ throw new InvalidAgentInputError('File data URI has empty base64 payload');+ }+ const buffer = Buffer.from(raw, 'base64');+ if (buffer.length === 0) {+ throw new InvalidAgentInputError('File data URI decoded to zero bytes');+ }+ return buffer;+}++function validatePublicFilename(filename: string): void {+ if (!filename.length) {+ throw new InvalidAgentInputError('File name must not be empty');+ }+ const normalized = filename.replace(/\\/g, '/');+ const parts = normalized.split('/');+ for (const part of parts) {+ if (part === '..') {+ throw new InvalidAgentInputError(`File name contains path traversal: ${filename}`);+ }+ }+}++function buildUploadedFilesAnnouncement(+ files: { filename: string; path: string; mime: string; size: number }[],+): string {+ const entries = files+ .map(+ (f, i) =>+ `[file_${i + 1}]\n filename: ${f.filename}\n path: ${f.path}\n mime: ${f.mime}\n size: ${f.size} bytes`,+ )+ .join('\n\n');+ return internalSystemTag(`Uploaded files (${files.length}):\n${entries}`);+}++function partitionContent(parts: readonly AgentUserContentPart[]): {+ fileParts: FileContentPart[];+ textParts: TextContentPart[];+} {+ const fileParts: FileContentPart[] = [];+ const textParts: TextContentPart[] = [];++ for (const part of parts) {+ if (isFileContentPart(part)) {+ fileParts.push(part);+ } else {+ textParts.push(part);+ }+ }++ return { fileParts, textParts };+}++export interface ProcessAgentUserInputResult {+ message: LLMUserMessage;+ sandboxCreated?: SandboxInfo | undefined;+}++export async function processAgentUserInput(+ msg: AgentInputUserMessage,+ sandbox: Sandbox | undefined,+): Promise<ProcessAgentUserInputResult> {+ if (typeof msg.content === 'string') {+ return { message: { role: 'user', content: msg.content }, sandboxCreated: undefined };+ }++ const { fileParts, textParts } = partitionContent(msg.content);++ if (fileParts.length === 0) {+ return { message: { role: 'user', content: textParts }, sandboxCreated: undefined };+ }++ const modelParts: ChatCompletionContentPart[] = [];+ const filesToUploadToSandbox: { filename: string; buffer: Buffer; mime: string }[] = [];++ for (const filePart of fileParts) {+ const filename = filePart.name.replace(/^\/+/, '');+ if (!filename.length) {+ throw new InvalidAgentInputError('File name must not be empty');+ }+ validatePublicFilename(filename);++ const file_data = filePart.data;+ const mime = parseMimeFromFileData(file_data);++ if (isInlineMime(mime)) {+ modelParts.push(+ isImageMime(mime)+ ? { type: 'image_url', image_url: { url: file_data } }+ : { type: 'file', file: { filename, file_data } },+ );+ } else {+ const buffer = extractBase64(file_data);+ filesToUploadToSandbox.push({ filename, buffer, mime });+ }+ }++ let sandboxCreated: SandboxInfo | undefined;++ if (filesToUploadToSandbox.length > 0) {+ if (!sandbox) {+ throw new AgentSandboxRequiredError(+ 'File uploads requiring sandbox are not supported: no sandbox configured for this agent',+ );+ }++ const uploadResults = await Promise.allSettled(+ filesToUploadToSandbox.map(file =>+ sandbox.uploadUserFile({+ fileName: file.filename,+ content: file.buffer,+ mime: file.mime,+ }),+ ),+ );++ const uploadedFiles: { filename: string; path: string; mime: string; size: number }[] = [];+ for (let i = 0; i < uploadResults.length; i++) {+ const result = uploadResults[i]!;+ const file = filesToUploadToSandbox[i]!;+ if (result.status === 'fulfilled') {+ if (result.value.sandboxCreated) {+ sandboxCreated = result.value.sandboxCreated;+ }+ uploadedFiles.push({+ filename: file.filename,+ path: result.value.filePath,+ mime: file.mime,+ size: file.buffer.length,+ });+ } else {+ throw (result as PromiseRejectedResult).reason;+ }+ }+ if (uploadedFiles.length > 0) {+ modelParts.push({ type: 'text', text: buildUploadedFilesAnnouncement(uploadedFiles) });+ }+ }++ modelParts.push(...textParts);++ return { message: { role: 'user', content: modelParts }, sandboxCreated };+}diff --git a/packages/harness/src/core/runtime/contextUtils.ts b/packages/harness/src/core/runtime/contextUtils.tsnew file mode 100644index 000000000..be3511819--- /dev/null+++ b/packages/harness/src/core/runtime/contextUtils.ts@@ -0,0 +1,173 @@+import dedent from 'dedent';+import type { ApprovalDecision } from '../events/eventSchemas';+import {+ EventType,+ type AgentApprovalDecisionMessage,+ type UserToolApprovalMessage,+ type UserToolResponseMessage,+} from '../events/eventSchemas';+import type {+ CompletionUsage,+ EnrichedToolCall,+ InternalEnrichedToolCall,+ InternalToolCallInfo,+ LLMToolMessage,+ LLMUserMessage,+ ToolInfo,+} from '../llm/LLMTypes';+import { UNKNOWN_TOOL_NAME } from '../llm/LLMTypes';+import { estimateTokensForString } from '../llm/usage';+import type {+ AgentThreadRuntimeSendInput,+ ContextMessage,+ InternalThreadDoneEvent,+ LLMContextMessage,+} from './AgentThread.types';+import type { AgentInputUserMessage } from './UserInputMessage';++export const SYSTEM_TAG_START = '<tfy-internal>';+const SYSTEM_TAG_END = '</tfy-internal>';+export const INTERNAL_SYSTEM_PROMPT = dedent`+Messages wrapped in tfy-internal tags contain information hidden from the user. The Agent must keep this information in mind when conversing with the user.+The Agent must never generate any content with tfy-internal tags.+The Agent cannot generate any content with tfy-internal tags.+`;++export function internalSystemTag(m: string): string {+ return SYSTEM_TAG_START + m + SYSTEM_TAG_END;+}++export function internalSystemMessage(m: string): LLMUserMessage {+ return { role: 'user' as const, content: internalSystemTag(m) };+}++export function isLLMContextMessage(msg: ContextMessage): msg is LLMContextMessage {+ return 'role' in msg;+}++export function isInternalSystemMessage(m: ContextMessage): boolean {+ if (!isLLMContextMessage(m)) return false;+ return m.role === 'user' && typeof m.content === 'string' && m.content.startsWith(SYSTEM_TAG_START);+}++export function isApprovalDecisionMessage(msg: AgentThreadRuntimeSendInput): msg is UserToolApprovalMessage {+ return 'type' in msg && msg.type === EventType.USER_TOOL_APPROVAL;+}++function isUserToolApprovalDecisionMessage(msg: ContextMessage): msg is AgentApprovalDecisionMessage {+ return 'type' in msg && msg.type === EventType.USER_TOOL_APPROVAL;+}++export function isClientSideToolResponseMessage(msg: AgentThreadRuntimeSendInput): msg is UserToolResponseMessage {+ return 'type' in msg && msg.type === EventType.USER_TOOL_RESPONSE;+}++export function isInputUserMessage(msg: AgentThreadRuntimeSendInput): msg is AgentInputUserMessage {+ return 'type' in msg && msg.type === EventType.USER_MESSAGE;+}++export function isLLMToolMessage(msg: AgentThreadRuntimeSendInput): msg is LLMToolMessage {+ return 'role' in msg && msg.role === 'tool';+}++export function isInternalThreadDoneError(+ event: InternalThreadDoneEvent,+): event is InternalThreadDoneEvent & { status: 'error' } {+ return event.status === 'error';+}++export function scanApprovalDecisions(context: ContextMessage[]): Map<string, ApprovalDecision> {+ const decisions = new Map<string, ApprovalDecision>();+ for (const msg of context) {+ if (isUserToolApprovalDecisionMessage(msg)) {+ decisions.set(msg.tool_call_id, msg.approval);+ }+ }+ return decisions;+}++export function makeUnknownToolInfo(toolName: string): InternalToolCallInfo {+ return {+ type: 'mcp',+ mcp_server_id: UNKNOWN_TOOL_NAME,+ mcp_server_name: UNKNOWN_TOOL_NAME,+ original_tool_name: toolName,+ is_approval_required: false,+ is_client_side: false,+ };+}++export function toToolCallInfo(toolInfo: InternalToolCallInfo): ToolInfo {+ if (toolInfo.type === 'mcp') {+ return {+ type: toolInfo.type,+ name: toolInfo.original_tool_name,+ server_id: toolInfo.mcp_server_id,+ server_name: toolInfo.mcp_server_name,+ };+ }+ return {+ type: toolInfo.type,+ name: toolInfo.original_tool_name,+ };+}++export function toEnrichedToolCall(toolCall: InternalEnrichedToolCall): EnrichedToolCall {+ const { tool_info, ...rest } = toolCall;+ return { ...rest, tool_info: toToolCallInfo(tool_info) };+}++export function assistantMessageContentToStringForSubAgent(+ content: string | Array<{ type?: string; text?: string } | string> | null | undefined,+ errorMessage?: string,+): string {+ let text = '';+ if (typeof content === 'string') {+ text = content;+ } else if (Array.isArray(content)) {+ text = content.map(item => (typeof item === 'string' ? item : JSON.stringify(item))).join('');+ }+ if (errorMessage) {+ return text ? `${errorMessage}\n${text}` : errorMessage;+ }+ return text;+}++export function getThreadId(): string {+ return crypto.randomUUID();+}++export function estimateTokensForContextMessages(messages: ContextMessage[]): CompletionUsage {+ let tokenCount = 0;++ for (const b of messages) {+ if ('content' in b && b.content) {+ if (typeof b.content === 'string') {+ tokenCount += estimateTokensForString(b.content);+ } else if (Array.isArray(b.content)) {+ for (const part of b.content) {+ if ('text' in part && typeof part.text === 'string') {+ tokenCount += estimateTokensForString(part.text);+ }+ }+ }+ }++ if ('tool_calls' in b && b.tool_calls) {+ for (const toolCall of b.tool_calls) {+ tokenCount += estimateTokensForString(toolCall.function.name);+ tokenCount += estimateTokensForString(toolCall.function.arguments);+ }+ }++ if ('tool_call_id' in b && b.tool_call_id) {+ tokenCount += estimateTokensForString(b.tool_call_id);+ }+ }++ return {+ prompt_tokens: tokenCount,+ completion_tokens: 0,+ total_tokens: tokenCount,+ };+}diff --git a/packages/harness/src/core/sandbox/Sandbox.ts b/packages/harness/src/core/sandbox/Sandbox.tsnew file mode 100644index 000000000..858cee6a9--- /dev/null+++ b/packages/harness/src/core/sandbox/Sandbox.ts@@ -0,0 +1,711 @@+import { context, propagation } from '@opentelemetry/api';+import dedent from 'dedent';+import type { Logger } from 'winston';+import { z } from 'zod';+import { InstructionBuilder } from '../InstructionBuilder';+import { estimateTokensForString } from '../llm/usage';+import type { MappedMCPTool } from '../mcp/convertMCPServers';+import { type CallToolResponse, type IToolSet, toolResultResponse } from '../mcp/IMCPServer';+import { defineTool, LocalToolMCP } from '../mcp/LocalToolMCP';+import {+ DEFERRED_TOOLS_SERVER_ID,+ GET_TOOL_INFO_NAME,+ GET_TOOL_OUTPUT_SCHEMA_NAME,+ LIST_TOOLS_NAME,+} from '../runtime/DeferredTool';+import type { AgentTracing } from '../tracing/AgentTracing';+import { extractErrorLogFields } from '../util/errorLogFields';+import { SANDBOX_FILE_UPLOADS_DIR, SANDBOX_NATS_WS_PORT } from './constants';+import { type SandboxProvider, ensureExecSuccess } from './provider/Provider';+import { validateNoPathTraversal, validateSandboxOwnedByTenant } from './SandboxErrors';+import { SandboxNatsBridge } from './SandboxNatsBridge';++export interface SandboxInfo {+ sandbox_id: string;+}++/** Write or clear the git credential-store file at an absolute path (no global git config mutation). */+function buildSyncGitCredentialsCommand(credentialsContent: string | null, credentialsPath: string): string {+ if (credentialsContent === null) {+ return `rm -f ${credentialsPath}`;+ }+ // Base64 avoids interpolating credentials directly into the shell command.+ const b64 = Buffer.from(credentialsContent, 'utf-8').toString('base64');+ return (+ `mkdir -p "$(dirname ${credentialsPath})" && ` ++ `echo '${b64}' | base64 -d > ${credentialsPath} && ` ++ `chmod 600 ${credentialsPath}`+ );+}++/**+ * Process-scoped credential.helper via GIT_CONFIG_* (avoids shared ~/.gitconfig).+ * Required for TFY sandbox where many logical sandboxes share one pod/HOME.+ */+function buildGitCredentialHelperEnv(credentialsPath: string): Record<string, string> {+ return {+ GIT_CONFIG_COUNT: '1',+ GIT_CONFIG_KEY_0: 'credential.helper',+ GIT_CONFIG_VALUE_0: `store --file ${credentialsPath}`,+ };+}++export interface MountedSkill {+ fqn: string;+ name: string;+ description: string;+ skillMdContent: string | null;+}++export interface SandboxStoredFile {+ filePath: string;+ sandboxCreated?: SandboxInfo | undefined;+}++export interface SandboxOptions {+ provider: SandboxProvider;+ existingSandboxId?: string | undefined;+ mountedSkills?: readonly MountedSkill[] | undefined;+ fileDownloadEnabled?: boolean | undefined;+ /** Pre-resolved credential-store file content (null = clear / no git auth). */+ resolvedGitCredentialsContent?: string | null | undefined;+ /**+ * Blocks destructive tools in code mode so they go through the approval flow+ * instead. Must be `true` — approvals are always enabled (the kill switch is gone).+ */+ blockDestructiveToolsInCodeMode: true;+ scripts: {+ mcpClient: string;+ skillDownloader: string;+ };+ execExtraEnv?: Readonly<Record<string, string>> | undefined;+ skillInitEnv?: Readonly<Record<string, string>> | undefined;+ tracing: AgentTracing;+ logger: Logger;+}++export const SANDBOX_EXEC_TOOL_NAME = 'exec';+const SANDBOX_MCP_REMINDER_TAG = 'sandbox-mcp-code-mode';+const SANDBOX_FILE_OUTPUT_TAG = 'sandbox-file-output';+export const SANDBOX_SCHEMA_INFER_TAG = 'sandbox-schema-infer';+const SANDBOX_FILE_UPLOADS_TAG = 'sandbox-file-uploads';++// Stable directory inside the sandbox where the MCP client library is uploaded.+// MCP client upload dir. Two lookup channels:+// - Python imports → PYTHONPATH points here (set by injectMCPClientEnv).+// - Shell `mcp-client` → symlinked into MCP_CLIENT_BIN_SYMLINK (on default PATH);+// basename drops `.py` so the agent doesn't reflexively prefix with `python`.+const MCP_CLIENT_DIR = '/opt/tfy/mcp-client';+const MCP_CLIENT_PATH = `${MCP_CLIENT_DIR}/mcp_client.py`;+const MCP_CLIENT_BIN_SYMLINK = '/usr/local/bin/mcp-client';+const SKILL_DOWNLOADER_PATH = '/opt/tfy/skill_downloader.py';+const SKILLS_DIR = '/opt/tfy/skills';++function getSkillPath(skillName: string): string {+ return `${SKILLS_DIR}/${skillName}`;+}++const SKILLS_PREAMBLE = [+ '1. The skill is present in the `path` directory.',+ '2. SKILL.md file within the directory is the primary file, there can be other files as well.',+ '3. Use `description` to judge whether the Agent needs to use a skill.',+ '4. To use a skill:',+ '4.a. If the `SKILL.md content` is inlined, the Agent must not read `path/SKILL.md`.',+ '4.b. Otherwise the Agent must read `path/SKILL.md` first.',+ '5. The Agent must avoid listing the `path` unless there are references in `SKILL.md` and there is reason to do so given the current conversation.',+].join('\n');++// Per-server config sent to mcp_client.py via TFY_MCP_SERVERS.+type SandboxMcpServerConfig = {+ allowed_tools: string[];+};++// Snapshots the active W3C trace context (`traceparent` + optional `tracestate`) into env+// vars consumed by mcp_client.py. Read with TFY_TRACEPARENT / TFY_TRACESTATE on the sandbox+// side and attached as NATS message headers; the bridge extracts them on each message so the+// resulting MCP spans nest under the originating Sandbox: exec span.+function injectTraceContextEnv(): Record<string, string> {+ const carrier: Record<string, string> = {};+ propagation.inject(context.active(), carrier);+ const env: Record<string, string> = {};+ if (carrier['traceparent']) env['TFY_TRACEPARENT'] = carrier['traceparent'];+ if (carrier['tracestate']) env['TFY_TRACESTATE'] = carrier['tracestate'];+ return env;+}++/**+ * Injects environment variables required for mcp_client.py into sandbox_exec arguments.+ *+ * `natsBridgeSubjectPrefix` MUST be the prefix the gateway-side bridge subscribed to; the+ * sandbox script publishes to `<prefix>.mcp` (operation in the payload's `op` field) and only+ * this bridge receives them. See SandboxNatsBridge.+ */+function injectMCPClientEnv(params: {+ env?: Record<string, string> | undefined;+ mcpServers: Record<string, SandboxMcpServerConfig>;+ execExtraEnv?: Readonly<Record<string, string>> | undefined;+ natsBridgeSubjectPrefix?: string | undefined;+}): Record<string, string> {+ return {+ ...(params.execExtraEnv ?? {}),+ ...(params.env ?? {}),+ PYTHONPATH: MCP_CLIENT_DIR,+ ...(Object.keys(params.mcpServers).length > 0 && {+ TFY_MCP_SERVERS: Buffer.from(JSON.stringify(params.mcpServers)).toString('base64'),+ }),+ ...(params.natsBridgeSubjectPrefix && {+ TFY_NATS_URL: `ws://localhost:${SANDBOX_NATS_WS_PORT}`,+ TFY_NATS_SUBJECT_PREFIX: params.natsBridgeSubjectPrefix,+ // W3C trace context captured per-exec so each NATS request carries the originating+ // Sandbox: exec span as parent. Without this, MCP spans dispatched via the bridge+ // inherit whatever ALS context the NATS callback runs under (stale, shared across execs).+ ...injectTraceContextEnv(),+ }),+ // Approvals are always enabled: destructive tools cannot run in code mode.+ TFY_ENABLE_AGENT_APPROVALS: 'true',+ };+}++function buildSkillInitEnv(+ skillInitEnv: Readonly<Record<string, string>> | undefined,+ skillVersionFqnsCsv?: string,+): Record<string, string> {+ return {+ AGENT_SKILL_VERSION_FQNS: skillVersionFqnsCsv ?? '',+ ...(skillInitEnv ?? {}),+ };+}++const sandboxExecSchema = z.object({+ intent: z+ .string()+ .describe(+ 'A brief, user-facing explanation of the purpose of this command. Avoid technical jargon and code details.',+ ),+ command: z.string().describe('The shell command to execute in the sandbox.'),+ cwd: z.string().optional().describe('Working directory for command execution.'),+ env: z.record(z.string()).optional().describe('Additional environment variables to set.'),+});++const SANDBOX_EXEC_DESCRIPTION = `Execute shell commands in a persistent sandbox environment.+The sandbox persists across calls within the same session, allowing stateful operations.+Pre-installed: Python 3.13, pydantic, git, curl, helm, jq, ripgrep, genson.+IMPORTANT: The Agent must never list, print, or expose environment variables as they contain sensitive credentials.+IMPORTANT: Never read or expose any git credential files or ~/.git-credentials.+`;++export function createSandboxLargeToolResponseGuidance(): string {+ return `For use cases where the Agent needs a subset of fields from the MCP response or needs deterministic processing, write code with the provided MCP client and use <${SANDBOX_MCP_REMINDER_TAG}>.`;+}++export const SANDBOX_MCP_SERVER_ID = 'sandbox';+type SandboxExecInput = z.infer<typeof sandboxExecSchema>;++export class Sandbox extends LocalToolMCP {+ readonly name = SANDBOX_MCP_SERVER_ID;+ readonly displayName = 'Sandbox';+ override readonly description = 'Persistent sandbox environment for code execution';+ static readonly FILE_UPLOADS_DIR = SANDBOX_FILE_UPLOADS_DIR;++ private readonly provider: SandboxProvider;+ private readonly existingSandboxId?: string | undefined;+ private readonly tenantName: string;+ private existingSandboxInfo: SandboxInfo | undefined;+ // Cached promise to prevent concurrent sub-agents from creating duplicate sandboxes.+ private sandboxCreationPromise?: Promise<SandboxInfo> | undefined;+ private sandboxInitPromise?: Promise<void> | undefined;+ private codeExecToolSets: readonly IToolSet[] = [];+ private readonly fileDownloadEnabled: boolean;+ private readonly execExtraEnv?: Readonly<Record<string, string>> | undefined;+ private readonly skillInitEnv?: Readonly<Record<string, string>> | undefined;+ private readonly mountedSkills: readonly MountedSkill[];+ private readonly mcpClientScriptBase64: string;+ private readonly skillDownloaderScriptBase64: string;+ private readonly logger: Logger;+ // Pre-resolved credential-store file content (null = clear / no git auth).+ private readonly resolvedGitCredentialsContent: string | null;+ private natsBridgePromise?: Promise<SandboxNatsBridge | undefined> | undefined;++ private tools = [+ defineTool({+ name: SANDBOX_EXEC_TOOL_NAME,+ description: SANDBOX_EXEC_DESCRIPTION,+ schema: sandboxExecSchema,+ handler: input => this.handleExec(input),+ }),+ ];++ constructor(options: SandboxOptions) {+ super({ tracing: options.tracing });+ this.provider = options.provider;+ this.existingSandboxId = options.existingSandboxId;+ this.tenantName = options.execExtraEnv?.['TFY_TENANT_NAME'] ?? '';+ this.mountedSkills = options.mountedSkills ?? [];+ this.fileDownloadEnabled = options.fileDownloadEnabled ?? false;+ this.execExtraEnv = options.execExtraEnv;+ this.skillInitEnv = options.skillInitEnv;+ this.mcpClientScriptBase64 = Buffer.from(options.scripts.mcpClient, 'utf-8').toString('base64');+ this.skillDownloaderScriptBase64 = Buffer.from(options.scripts.skillDownloader, 'utf-8').toString('base64');+ this.logger = options.logger.child({ module: 'Sandbox' });+ this.resolvedGitCredentialsContent = options.resolvedGitCredentialsContent ?? null;++ if (this.existingSandboxId) {+ validateSandboxOwnedByTenant(this.existingSandboxId, this.tenantName);+ this.existingSandboxInfo = { sandbox_id: this.existingSandboxId };+ }+ }++ private buildMcpServersEnvelope(): Record<string, SandboxMcpServerConfig> {+ const out: Record<string, SandboxMcpServerConfig> = {};+ for (const server of this.codeExecToolSets) {+ const allowedTools = server.getAllowedToolNamesForSandbox?.() ?? [];+ out[server.name] = { allowed_tools: allowedTools };+ }+ return out;+ }++ protected getTools() {+ return this.tools;+ }++ configureCodeMode(servers: readonly IToolSet[]): void {+ if (!servers.length) {+ return;+ }+ this.codeExecToolSets = servers;+ }++ estimateSkillsTokens(): number {+ if (!this.mountedSkills.length) return 0;+ let fullContent = `<skills>\n${SKILLS_PREAMBLE}\n\n`;+ for (const skill of this.mountedSkills) {+ const skillPath = getSkillPath(skill.name);+ const body = skill.skillMdContent+ ? `path: ${skillPath}\nSKILL.md content:\n${skill.skillMdContent}`+ : `path: ${skillPath}\nname: ${skill.name}\ndescription: ${skill.description}`;+ fullContent += `<skill>\n${body}\n</skill>\n\n`;+ }+ fullContent += '</skills>';+ return Math.round(estimateTokensForString(fullContent));+ }++ buildInstruction(builder: InstructionBuilder): void {+ const providerInstructions = this.provider.getAdditionalInstructions();++ const sandboxInstructions = builder.beginSection('sandbox');+ sandboxInstructions.addContent('The Agent has access to a persistent sandbox environment for executing code.');+ sandboxInstructions.addContent('The Agent must NOT read or modify any git credential files.');++ this.buildSchemaSection(sandboxInstructions);+ this.buildSkillsSection(sandboxInstructions);+ this.buildMCPSection(sandboxInstructions);+ this.buildFileUploadsSection(sandboxInstructions);++ if (this.fileDownloadEnabled) {+ this.buildFileOutputSection(sandboxInstructions);+ }++ if (providerInstructions) {+ sandboxInstructions.addContent(providerInstructions);+ }+ }++ private buildFileUploadsSection(builder: InstructionBuilder): void {+ builder.addSection(+ SANDBOX_FILE_UPLOADS_TAG,+ `User-uploaded files are placed in ${Sandbox.FILE_UPLOADS_DIR}/. The Agent must not modify files in this directory. Always create a copy at a different location and work on the copy.`,+ );+ }++ private buildSchemaSection(builder: InstructionBuilder): void {+ builder.addSection(+ SANDBOX_SCHEMA_INFER_TAG,+ dedent`+ To infer the schema of a file, the Agent MUST execute:+ head -c 200 file_path && echo "==" && genson file_path+ This serves two purpose:+ 1. The first 200 characters of the file is printed. Do NOT print more than 200 characters.+ 2. genson infers and returns JSON schema if the file is JSON.+ Even if the file is not JSON, (1) helps to take the next step in less number of turns+ `,+ );+ }++ private buildFileOutputSection(builder: InstructionBuilder): void {+ builder.addSection(+ SANDBOX_FILE_OUTPUT_TAG,+ dedent`+ ## File outputs++ The user does not have direct access to the sandbox filesystem. When the Agent wants to output a file to the user, it MUST:+ 1. Ensure that the file is present in the sandbox.+ 2. Then emit a fenced sandbox_artifacts block referencing the file.++ \`\`\`sandbox_artifacts+ [Human-readable label](/absolute/path/to/file.ext)+ \`\`\`++ For large outputs or content that can be generated through code, prefer writing to a file and emitting the sandbox_artifacts block.++ Rules:+ - Use absolute paths, not ~/ or relative paths.+ - One link per line. Markdown link syntax: [label](path).`,+ );+ }++ private buildSkillsSection(builder: InstructionBuilder): void {+ if (!this.mountedSkills.length) return;++ const skills = builder.beginSection('skills');++ skills.addContent(SKILLS_PREAMBLE);++ for (const skill of this.mountedSkills) {+ const skillPath = getSkillPath(skill.name);+ const content = skill.skillMdContent+ ? `path: ${skillPath}\nSKILL.md content:\n${skill.skillMdContent}`+ : `path: ${skillPath}\nname: ${skill.name}\ndescription: ${skill.description}`;+ skills.addSection('skill', content);+ }+ }++ private buildMCPSection(builder: InstructionBuilder): void {+ const toolSetNames = this.codeExecToolSets.map(m => m.name).join(',');+ if (!toolSetNames) return;++ builder.addSection(+ SANDBOX_MCP_REMINDER_TAG,+ dedent`+ The following MCP servers are accessible for Code Mode from ${SANDBOX_EXEC_TOOL_NAME} via the pre-installed mcp_client module: ${toolSetNames}+ Tool and functions are same.+ Tool and MCP tools are same.++ Use \`from mcp_client import call_tool\` in code, or \`mcp-client\` in shell — both work from any directory with no setup.++ For deferred MCP servers, the Agent MUST:+ 1. Discover tools via ${LIST_TOOLS_NAME} from ${DEFERRED_TOOLS_SERVER_ID}. Never call ${GET_TOOL_OUTPUT_SCHEMA_NAME}.+ 2. Discover inputSchema, outputSchema via ${GET_TOOL_INFO_NAME} for the selected tools.++ For non-deferred MCP servers, the Agent MUST:+ 1. Discover outputSchema via ${GET_TOOL_OUTPUT_SCHEMA_NAME} for the selected tools.++ For both deferred and non-deferred if outputSchema is absent,+ the Agent MUST say: "Given the MCP Server does not define an outputSchema let me figure it out first before entering Code Mode."+ mcp-client call-tool {server} {tool} '{"param":"value"}' > file && ${SANDBOX_SCHEMA_INFER_TAG}.+ the Agent MUST execute a single command for above.+ If the Agent does not get the outputSchema, the Agent will encounters scenarios like:+ Agent: "Let me fix the code - it seems the x might be a string rather than an object in some cases:"+ The Agent MUST not face the above scenario.++ Only after the Agent has the above details, it can enter Code Mode.+ Agent: Now I know the inputSchema and outputSchema of tool_a, let me enter Code Mode.++ CLI: mcp-client call-tool {server} {tool_a} '{"param":"value"}'+ # The output of the above command MUST be passed through tools like jq or head -c+ # or should be written to a file. Goal is to reduce content that the Agent prints.++ Code: from mcp_client import call_tool+ async def main():+ result = await call_tool("{server}", "{tool_a}", body={"param1": "value1"})+ # In most cases, it is safe to assume response is a dict.+ # To know the dict keys, the Agent still needs to figure out the outputSchema.+ # The Agent MUST write the code to a file first before executing it.++ Code Mode MUST be used in following scenarios:++ 1. Reduce structured tool output by executing logic on top of it. Never present raw output.+ Agent: Now I know the inputSchema and outputSchema of tool_a, let me enter Code Mode.++ from mcp_client import call_tool+ from collections import Counter+ result = await call_tool("{server}", "{tool_a}", body={"param1": "value1"})+ print(Counter(r["a"] for r in result["b"] if r["c"])) # Here we need outputSchema to know a, b and c exists.++ 2. Piping result of one tool call to another tool request. Never present raw output.+ Agent: Now I know the inputSchema and outputSchema of tool1, let me enter Code Mode.++ from mcp_client import call_tool+ result1 = await call_tool("{server}", "{tool1}", body={"param1": "value1"})+ result2 = await call_tool("{server}", "{tool2}", body={"param2": result1["value1"]}) # Here we need outputSchema to know value1 exists.+ print(result2) # Note in this case, we do not need outputSchema of result2 as we are not using any fields.++ The Agent MUST NOT use Code Mode just to print the full raw response of a tool. The Agent MUST call the tool directly in this case, there are other mechanisms in place to ensure+ large tool call outputs are not loaded in context.++ The Agent must not use Code Mode in the following patterns:+ from mcp_client import call_tool+ import json+ result = await call_tool("{server}", "{tool}", body={"param1": "value1"})+ print(result) # Never do this. Call tool without Code Mode.+ print(json.dumps(result, ...)) # Never do this. Call tool without Code Mode.+ print(result["a"][:100]) # Never do this. Call tool without Code Mode.++ mcp-client call-tool {server} {tool} '{"param":"value"}' > data && cat data # Never do this. Call tool without Code Mode.+ `,+ );+ }++ private get requiredSandboxInfo(): SandboxInfo {+ if (!this.existingSandboxInfo) {+ throw new Error('Sandbox info not available');+ }+ return this.existingSandboxInfo;+ }++ private async ensureSandboxCreated(): Promise<{+ sandboxInfo: SandboxInfo;+ sandboxCreated: SandboxInfo | undefined;+ }> {+ if (this.existingSandboxInfo) {+ return { sandboxInfo: this.existingSandboxInfo, sandboxCreated: undefined };+ }+ if (!this.sandboxCreationPromise) {+ // Provider returns camelCase `{ sandboxId }`; rename to the snake_case+ // `SandboxInfo` shape used everywhere downstream (Redis JSON, wire event,+ // in-memory state).+ this.sandboxCreationPromise = this.provider+ .createSandbox()+ .then(({ sandboxId }) => {+ validateSandboxOwnedByTenant(sandboxId, this.tenantName);+ return { sandbox_id: sandboxId };+ })+ .catch(e => {+ this.sandboxCreationPromise = undefined;+ throw e;+ });+ }++ const sandboxInfo = await this.sandboxCreationPromise;+ const isNew = !this.existingSandboxInfo;+ this.existingSandboxInfo = sandboxInfo;+ return { sandboxInfo, sandboxCreated: isNew ? sandboxInfo : undefined };+ }++ private async handleExec(input: SandboxExecInput): Promise<CallToolResponse> {+ const { sandboxInfo, sandboxCreated } = await this.ensureSandboxCreated();+ const sandboxCreatedFlag = Boolean(sandboxCreated);+ try {+ await this.ensureSandboxInitialized();+ } catch (e) {+ this.logger.error('Sandbox initialization failed', extractErrorLogFields(e));+ const message = e instanceof Error ? e.message : 'Sandbox initialization failed';+ return toolResultResponse({+ text: `Sandbox initialization failed: ${message}`,+ isError: true,+ overrides: { sandboxCreated: sandboxCreatedFlag, sandboxInfo },+ });+ }+ const bridge = await this.ensureNatsBridgeConnected(sandboxInfo.sandbox_id);+ const mcpClientEnv = injectMCPClientEnv({+ ...(input.env !== undefined ? { env: input.env } : {}),+ mcpServers: this.buildMcpServersEnvelope(),+ ...(this.execExtraEnv !== undefined ? { execExtraEnv: this.execExtraEnv } : {}),+ ...(bridge?.subjectPrefix !== undefined ? { natsBridgeSubjectPrefix: bridge.subjectPrefix } : {}),+ });+ const gitAuthEnv =+ this.resolvedGitCredentialsContent !== null+ ? buildGitCredentialHelperEnv(this.provider.getGitCredentialsPath(sandboxInfo.sandbox_id))+ : {};+ const env = { ...mcpClientEnv, ...gitAuthEnv };++ const result = await this.provider.exec({+ sandboxId: sandboxInfo.sandbox_id,+ command: input.command,+ ...(input.cwd !== undefined ? { cwd: input.cwd } : {}),+ env,+ });++ return {+ result: {+ content: [{ type: 'text', text: JSON.stringify(result) }],+ isError: !result.success,+ },+ wasInitialized: undefined,+ sandboxCreated: sandboxCreatedFlag,+ sandboxInfo,+ };+ }++ async getToolResultDumpDir(): Promise<{ dir: string; sandboxCreated: SandboxInfo | undefined }> {+ const { sandboxCreated } = await this.ensureSandboxCreated();+ const dir = this.provider.getToolResultDumpDir(this.requiredSandboxInfo.sandbox_id).replace(/\/+$/, '');+ return { dir, sandboxCreated };+ }++ async uploadFile(params: {+ targetDir: string;+ fileName: string;+ content: Buffer;+ }): Promise<{ filePath: string; sandboxCreated: SandboxInfo | undefined }> {+ const { sandboxCreated } = await this.ensureSandboxCreated();+ await this.ensureSandboxInitialized();+ const { sandbox_id: sandboxId } = this.requiredSandboxInfo;+ const fileName = params.fileName.replace(/^\/+/, '');+ const targetDir = params.targetDir.replace(/\/+$/, '');+ const filePath = `${targetDir}/${fileName}`;+ await this.provider.uploadFile({ sandboxId, remotePath: filePath, content: params.content });+ return { filePath, sandboxCreated };+ }++ async uploadUserFile(input: { fileName: string; content: Buffer; mime: string }): Promise<SandboxStoredFile> {+ validateNoPathTraversal(input.fileName);+ const result = await this.uploadFile({+ targetDir: Sandbox.FILE_UPLOADS_DIR,+ fileName: input.fileName,+ content: input.content,+ });+ return {+ filePath: result.filePath,+ ...(result.sandboxCreated && { sandboxCreated: result.sandboxCreated }),+ };+ }++ async writeArtifact(input: {+ fileName: string;+ content: Buffer;+ sourceTool?: MappedMCPTool | undefined;+ }): Promise<SandboxStoredFile> {+ validateNoPathTraversal(input.fileName);+ const { dir, sandboxCreated: dumpDirCreated } = await this.getToolResultDumpDir();+ const result = await this.uploadFile({+ targetDir: dir,+ fileName: input.fileName,+ content: input.content,+ });+ const sandboxCreated = dumpDirCreated ?? result.sandboxCreated;+ return {+ filePath: result.filePath,+ ...(sandboxCreated && { sandboxCreated }),+ };+ }++ /**+ * Upload the MCP client Python script to the sandbox on the first tool call.+ * The sandbox filesystem is persistent within a session, so this only needs to run once.+ */+ private async ensureSandboxInitialized(): Promise<void> {+ if (!this.sandboxInitPromise) {+ this.sandboxInitPromise = this.initSandboxEnvironment().catch(e => {+ this.sandboxInitPromise = undefined;+ throw e;+ });+ }+ await this.sandboxInitPromise;+ }++ private async writeGitCredentials(): Promise<void> {+ const sandboxId = this.requiredSandboxInfo.sandbox_id;+ const credentialsPath = this.provider.getGitCredentialsPath(sandboxId);+ const result = await this.provider.exec({+ sandboxId,+ command: buildSyncGitCredentialsCommand(this.resolvedGitCredentialsContent, credentialsPath),+ });+ ensureExecSuccess(result);+ }++ private async initSandboxEnvironment(): Promise<void> {+ const skillVersionFqnsCsv = this.mountedSkills.length ? this.mountedSkills.map(s => s.fqn).join(',') : undefined;+ const toolResultDumpDir = this.provider.getToolResultDumpDir(this.requiredSandboxInfo.sandbox_id);++ this.logger.info('Uploading MCP client script and preparing skills directory in sandbox');++ const initSteps = [+ `mkdir -p ${MCP_CLIENT_DIR} ${Sandbox.FILE_UPLOADS_DIR} ${toolResultDumpDir}`,+ `rm -f ${MCP_CLIENT_PATH}`,+ `echo '${this.mcpClientScriptBase64}' | base64 -d > ${MCP_CLIENT_PATH}`,+ // Make executable + symlink onto PATH so `mcp-client` runs by name.+ `chmod 0555 ${MCP_CLIENT_PATH}`,+ `ln -sf ${MCP_CLIENT_PATH} ${MCP_CLIENT_BIN_SYMLINK}`,+ `rm -f ${SKILL_DOWNLOADER_PATH}`,+ `echo '${this.skillDownloaderScriptBase64}' | base64 -d > ${SKILL_DOWNLOADER_PATH}`,+ `chmod a-w ${SKILL_DOWNLOADER_PATH}`,+ `mkdir -p ${SKILLS_DIR}`,+ `python3 ${SKILL_DOWNLOADER_PATH}`,+ ];+ const script = initSteps.join(' && ');+ const result = await this.provider.exec({+ sandboxId: this.requiredSandboxInfo.sandbox_id,+ command: script,+ env: buildSkillInitEnv(this.skillInitEnv, skillVersionFqnsCsv),+ });+ ensureExecSuccess(result);+ const fqnCount = this.mountedSkills.length;+ this.logger.info(+ `Sandbox initialized: MCP client at ${MCP_CLIENT_PATH} (symlinked to ${MCP_CLIENT_BIN_SYMLINK}); ` ++ `skill downloader at ${SKILL_DOWNLOADER_PATH}; skills dir ${SKILLS_DIR}` ++ `; ran skill downloader with ${fqnCount} FQN(s) input`,+ );+ await this.writeGitCredentials();+ }++ /**+ * Lazily connect the sandbox→gateway NATS bridge. Single-flight and idempotent.+ * Skipped when there are no MCP servers exposed to code mode (nothing to bridge). Connect+ * failures resolve to `undefined` (no NATS env for that exec); mcp_client then errors at call+ * time — there is no HTTPS fallback.+ */+ private async ensureNatsBridgeConnected(sandboxId: string): Promise<SandboxNatsBridge | undefined> {+ // No MCP servers means the bridge has nothing to dispatch to. Avoid the connect cost.+ if (this.codeExecToolSets.length === 0) return undefined;+ if (!this.natsBridgePromise) {+ this.natsBridgePromise = this.connectNatsBridge(sandboxId).catch(e => {+ // Connect-level errors (network, timeout, broker not up) are not sticky: a later exec+ // may succeed (e.g. after sandbox warmup). Wipe the cached promise so retries happen.+ this.logger.error('Sandbox NATS bridge connect failed', {+ ...extractErrorLogFields(e),+ sandboxId,+ });+ this.natsBridgePromise = undefined;+ return undefined;+ });+ }+ return this.natsBridgePromise;+ }++ private async connectNatsBridge(sandboxId: string): Promise<SandboxNatsBridge> {+ const wsUrl = await this.provider.getNatsBridgeUrl(sandboxId);+ const toolSets = new Map<string, IToolSet>();+ for (const server of this.codeExecToolSets) {+ toolSets.set(server.name, server);+ }+ const bridge = await SandboxNatsBridge.connect({ url: wsUrl, toolSets, logger: this.logger });+ this.logger.info('Sandbox NATS bridge connected', {+ sandboxId,+ toolSetCount: toolSets.size,+ });+ this.attachBridgeInvalidationOnClose(bridge, sandboxId);+ return bridge;+ }++ private attachBridgeInvalidationOnClose(bridge: SandboxNatsBridge, sandboxId: string): void {+ const cachedPromise = this.natsBridgePromise;+ // fire and forget+ void bridge.whenClosed().then(() => {+ if (this.natsBridgePromise === cachedPromise) {+ this.natsBridgePromise = undefined;+ this.logger.info('Sandbox NATS bridge closed; cache invalidated, next exec will reconnect', { sandboxId });+ }+ });+ }++ // Tears down per-Sandbox resources. Awaits the in-flight connect (if any) and explicitly+ // closes the bridge — dropping the field alone would leak the WS socket and live+ // subscriptions, and orphan a bridge that finishes connecting after close() returned.+ async close(): Promise<void> {+ const pendingPromise = this.natsBridgePromise;+ this.natsBridgePromise = undefined;+ if (!pendingPromise) return;+ let bridge: SandboxNatsBridge | undefined;+ try {+ bridge = await pendingPromise;+ } catch {+ // Connect-error path already logged inside ensureNatsBridgeConnected's .catch.+ }+ if (!bridge) return;+ try {+ await bridge.close();+ } catch (e) {+ this.logger.warn('Error closing sandbox NATS bridge', extractErrorLogFields(e));+ }+ }+}diff --git a/packages/harness/src/core/sandbox/SandboxErrors.ts b/packages/harness/src/core/sandbox/SandboxErrors.tsnew file mode 100644index 000000000..e41f0b6e6--- /dev/null+++ b/packages/harness/src/core/sandbox/SandboxErrors.ts@@ -0,0 +1,76 @@+export abstract class SandboxError extends Error {+ abstract readonly statusCode: number;+}++export class SandboxFileNotFoundError extends SandboxError {+ readonly statusCode = 404;++ constructor(path: string) {+ super(`File not found: ${path}`);+ this.name = 'SandboxFileNotFoundError';+ }+}++export class SandboxNotAvailableError extends SandboxError {+ readonly statusCode = 410;++ constructor(sandboxId: string) {+ super(`Sandbox '${sandboxId}' no longer exists — it may have been auto-deleted`);+ this.name = 'SandboxNotAvailableError';+ }+}++export class SandboxPathIsDirectoryError extends SandboxError {+ readonly statusCode = 400;++ constructor(path: string) {+ super(`Path is a directory, not a file: ${path}`);+ this.name = 'SandboxPathIsDirectoryError';+ }+}++export class SandboxFileTooLargeError extends SandboxError {+ readonly statusCode = 413;+ readonly fileSize: number;+ readonly maxSize: number;++ constructor(path: string, fileSize: number, maxSize: number) {+ super(`File too large: ${path} (${fileSize} bytes, max ${maxSize})`);+ this.name = 'SandboxFileTooLargeError';+ this.fileSize = fileSize;+ this.maxSize = maxSize;+ }+}++class SandboxTenantMismatchError extends SandboxError {+ readonly statusCode = 403;++ constructor(requestTenant: string) {+ super(`Sandbox does not belong to tenant ${requestTenant}`);+ this.name = 'SandboxTenantMismatchError';+ }+}++class SandboxPathTraversalError extends SandboxError {+ readonly statusCode = 400;++ constructor(path: string) {+ super(`Path must not contain ".." segments: ${path}`);+ this.name = 'SandboxPathTraversalError';+ }+}++export function validateSandboxOwnedByTenant(sandboxId: string, tenantName: string): void {+ const dotIndex = sandboxId.indexOf('.');+ if (dotIndex === -1 || sandboxId.substring(0, dotIndex) !== tenantName) {+ throw new SandboxTenantMismatchError(tenantName);+ }+}++const PATH_TRAVERSAL_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;++export function validateNoPathTraversal(path: string): void {+ if (PATH_TRAVERSAL_RE.test(path)) {+ throw new SandboxPathTraversalError(path);+ }+}diff --git a/packages/harness/src/core/sandbox/SandboxNatsBridge.ts b/packages/harness/src/core/sandbox/SandboxNatsBridge.tsnew file mode 100644index 000000000..01372c3bb--- /dev/null+++ b/packages/harness/src/core/sandbox/SandboxNatsBridge.ts@@ -0,0 +1,271 @@+import { type Msg, type NatsConnection, wsconnect } from '@nats-io/nats-core';+import { context, defaultTextMapGetter } from '@opentelemetry/api';+import { suppressTracing, unsuppressTracing, W3CTraceContextPropagator } from '@opentelemetry/core';+import { randomUUID } from 'node:crypto';+import type { Logger } from 'winston';+import { WebSocket } from 'ws';+import { McpConnectionError } from '../errors';+import {+ isAuthRequired,+ isCallToolResponseCreateSubAgent,+ isCallToolResponseResult,+ type CallToolResolvedResponse,+ type IToolSet,+ type ListToolsResolvedResponse,+} from '../mcp/IMCPServer';+import { extractErrorLogFields } from '../util/errorLogFields';+import { withTimeout } from '../util/promiseUtils';++// `wsconnect` from @nats-io/nats-core relies on a global WebSocket constructor; in Node we+// provide it from `ws`. Same pattern as `src/services/NatsService.ts`.+Object.assign(global, { WebSocket });++const NATS_CONNECT_TIMEOUT_MS = 10_000;+const NATS_CONNECT_RETRIES = 3;+const NATS_CONNECT_BACKOFF_MS = 250;+// Bound on the graceful drain at teardown; on timeout we fall back to nc.close()+const NATS_DRAIN_TIMEOUT_MS = 5_000;++const SANDBOX_NATS_SUBJECT_ROOT = 'sandbox.bridge';+// Single request/reply subject leaf; the operation is carried in the payload's `op` field so the+// bridge maintains one subscription instead of one per operation.+const SANDBOX_NATS_MCP_LEAF = 'mcp';++type BridgeRequest =+ | { op: 'list_tools'; server: string }+ | { op: 'call_tool'; server: string; tool: string; arguments?: Record<string, unknown> };++// Attributes an application-level failure so the sandbox client can tell who is at fault:+// 'agent' (bad generated code: wrong server/tool/args or an unsupported path), 'gateway' (our+// handler failed), or 'bridge' (a NATS bridge lifecycle condition, e.g. the bridge was closed).+// Pure transport failures never produce an envelope, so they're inferred client-side instead.+type BridgeErrorSource = 'gateway' | 'agent' | 'bridge';++// Envelope returned on `msg.reply`. NATS itself always succeeds; the receiver branches on `ok`.+type BridgeReply<T> = { ok: true; result: T } | { ok: false; error: string; source: BridgeErrorSource };++// Caller-caused failure: retrying won't help, so it's attributed to the agent's code, not us.+class InvalidMCPUsageError extends Error {+ override readonly name = 'InvalidMCPUsageError';+}++function isHttpClientError(error: unknown): error is { status: number } {+ if (typeof error !== 'object' || error === null || !('status' in error)) {+ return false;+ }+ const { status } = error;+ return typeof status === 'number' && status >= 400 && status < 500;+}++// An InvalidMCPUsageError, a 4xx HTTP-style exception, or a 4xx-hinted McpConnectionError (e.g. a+// disallowed/unknown tool surfaced by an ToolSet) is caller-caused -> 'agent'; anything else is+// our bug -> 'gateway'.+function classifyErrorSource(e: unknown): BridgeErrorSource {+ if (e instanceof InvalidMCPUsageError) return 'agent';+ if (isHttpClientError(e)) return 'agent';+ // ...remote servers with a 4xx McpConnectionError (has `statusCode`, not `status`). Same meaning.+ if (e instanceof McpConnectionError && e.statusCode >= 400 && e.statusCode < 500) return 'agent';+ return 'gateway';+}++// Direct W3C extractor, NOT the global `propagation` API. The gateway-wide propagator+// (SelectivePropagator in src/tracing.ts) refuses to restore traceparent unless the+// internal-secret headers are present — a deliberate guard against external requests+// forging trace parents. The NATS bridge is intra-process trusted (sender + receiver+// share the same Node process and span store), so we bypass that gate here and+// always honor the trace context the sandbox echoes back.+const _w3cExtractor = new W3CTraceContextPropagator();++function extractTraceCarrier(msg: Msg): Record<string, string> {+ const carrier: Record<string, string> = {};+ const traceparent = msg.headers?.get('traceparent');+ const tracestate = msg.headers?.get('tracestate');+ if (traceparent) carrier['traceparent'] = traceparent;+ if (tracestate) carrier['tracestate'] = tracestate;+ return carrier;+}++/**+ * Per-sandbox NATS subscriber. Bridges sandbox-originated MCP tool calls (sent over wss to the+ * sandbox's local nats-server) into the gateway pod's `IToolSet` registry for this agent.+ * The pod that holds the preview URL is the only NATS subscriber, which gives sandbox→gateway+ * traffic pod-affinity for free.+ */+export class SandboxNatsBridge {+ readonly subjectPrefix: string;++ private readonly nc: NatsConnection;+ private readonly toolSets: Map<string, IToolSet>;+ private readonly logger: Logger;+ private closed = false;++ private constructor(nc: NatsConnection, toolSets: Map<string, IToolSet>, subjectPrefix: string, logger: Logger) {+ this.nc = nc;+ this.toolSets = toolSets;+ this.subjectPrefix = subjectPrefix;+ this.logger = logger;+ }++ static async connect(params: {+ url: string;+ toolSets: Map<string, IToolSet>;+ logger: Logger;+ }): Promise<SandboxNatsBridge> {+ const subjectPrefix = `${SANDBOX_NATS_SUBJECT_ROOT}.${randomUUID()}`;+ const logger = params.logger.child({ module: 'SandboxNatsBridge' });+ let lastErr: unknown;+ for (let attempt = 1; attempt <= NATS_CONNECT_RETRIES; attempt++) {+ try {+ const nc = await context.with(suppressTracing(context.active()), () =>+ wsconnect({ servers: [params.url], timeout: NATS_CONNECT_TIMEOUT_MS }),+ );+ logger.info(`Connected to sandbox NATS (attempt ${attempt})`, { subjectPrefix });+ const bridge = new SandboxNatsBridge(nc, params.toolSets, subjectPrefix, logger);+ bridge.subscribe();+ return bridge;+ } catch (e) {+ lastErr = e;+ logger.warn(`Sandbox NATS connect attempt ${attempt} failed`, extractErrorLogFields(e));+ if (attempt < NATS_CONNECT_RETRIES) {+ await new Promise(resolve => setTimeout(resolve, NATS_CONNECT_BACKOFF_MS));+ }+ }+ }+ throw lastErr instanceof Error ? lastErr : new Error('Sandbox NATS connect failed');+ }++ async close(): Promise<void> {+ if (this.closed) return;+ this.closed = true;+ try {+ // drain() resolves once pending replies are flushed and the connection closes.+ await withTimeout(this.nc.drain(), NATS_DRAIN_TIMEOUT_MS);+ } catch (e) {+ // drain rejected or timed out, nc.close() terminates all pending requests and subscriptions on the connection.+ this.logger.warn('Sandbox NATS drain failed/timed out; forcing close', extractErrorLogFields(e));+ await this.nc.close().catch(() => {});+ }+ }++ async whenClosed(): Promise<void> {+ await this.nc.closed();+ }++ private subscribe(): void {+ this.nc.subscribe(`${this.subjectPrefix}.${SANDBOX_NATS_MCP_LEAF}`, {+ callback: (err, msg) => this.handle(err, msg, m => this.route(m)),+ });+ }++ private route(msg: Msg): Promise<unknown> {+ const req = this.decode<BridgeRequest>(msg);+ switch (req.op) {+ case 'list_tools':+ return this.handleListTools(req);+ case 'call_tool':+ return this.handleCallTool(req);+ default:+ throw new InvalidMCPUsageError(`Unknown sandbox bridge operation`);+ }+ }++ private handle(err: Error | null, msg: Msg, handler: (msg: Msg) => Promise<unknown>): void {+ if (err) {+ this.logger.error('Sandbox NATS subscription error', extractErrorLogFields(err));+ return;+ }+ if (!msg.reply) {+ this.logger.warn(`Sandbox NATS request on '${msg.subject}' has no reply subject; dropping`);+ return;+ }++ // Resume the originating Sandbox: exec span from the per-request traceparent header so+ // downstream MCP spans nest correctly (falls through to the current context if absent).+ // unsuppressTracing is required: connect() runs under suppressTracing (to drop the+ // WS-upgrade span) and nats-core's receive loop reuses that suppressed context, which would+ // otherwise make propagation.inject no-op and leak a stale traceparent.+ const ctx = _w3cExtractor.extract(+ unsuppressTracing(context.active()),+ extractTraceCarrier(msg),+ defaultTextMapGetter,+ );+ context.with(ctx, () => void this.dispatch(msg, handler));+ }++ private async dispatch(msg: Msg, handler: (msg: Msg) => Promise<unknown>): Promise<void> {+ if (this.closed) {+ this.logger.warn(`Sandbox NATS bridge is closed; rejecting request on '${msg.subject}'`);+ try {+ msg.respond(this.encode({ ok: false, error: 'Sandbox NATS bridge is closed', source: 'bridge' }));+ } catch (e) {+ this.logger.warn(`Failed to send bridge-closed reply on '${msg.subject}'`, extractErrorLogFields(e));+ }+ return;+ }+ let reply: BridgeReply<unknown>;+ try {+ reply = { ok: true, result: await handler(msg) };+ } catch (e) {+ const source = classifyErrorSource(e);+ const errorMessage = e instanceof Error ? e.message : 'Unknown sandbox bridge error';+ this.logger.error(+ `Sandbox NATS dispatch failed on '${msg.subject}' (source=${source})`,+ extractErrorLogFields(e),+ );+ reply = { ok: false, error: errorMessage, source };+ }+ try {+ msg.respond(this.encode(reply));+ } catch (e) {+ this.logger.error('Failed to publish sandbox NATS reply', extractErrorLogFields(e));+ }+ }++ private encode(reply: BridgeReply<unknown>): Uint8Array {+ return new TextEncoder().encode(JSON.stringify(reply));+ }++ private decode<T>(msg: Msg): T {+ return JSON.parse(new TextDecoder().decode(msg.data)) as T;+ }++ private getToolSet(serverName: string): IToolSet {+ const server = this.toolSets.get(serverName);+ if (!server) {+ throw new InvalidMCPUsageError(`MCP server '${serverName}' is not available for this agent`);+ }+ return server;+ }++ private async handleListTools(req: { server: string }): Promise<ListToolsResolvedResponse['result']> {+ const { server } = req;+ const mcp = this.getToolSet(server);+ const response = await mcp.listTools();+ if (isAuthRequired(response)) {+ throw new InvalidMCPUsageError(`MCP server '${server}' requires OAuth; cannot list tools from sandbox`);+ }+ return response.result;+ }++ private async handleCallTool(req: {+ server: string;+ tool: string;+ arguments?: Record<string, unknown> | undefined;+ }): Promise<CallToolResolvedResponse['result']> {+ const { server, tool, arguments: args } = req;+ const response = await this.getToolSet(server).callTool({ name: tool, arguments: args ?? {} });+ if (isAuthRequired(response)) {+ throw new InvalidMCPUsageError(`MCP server '${server}' requires OAuth; cannot call tool from sandbox`);+ }+ if (isCallToolResponseCreateSubAgent(response)) {+ throw new InvalidMCPUsageError(`Tool '${server}/${tool}' creates a sub-agent and is not callable from sandbox`);+ }+ if (!isCallToolResponseResult(response)) {+ // Approval / client-side-tool paths are intentionally out of scope currently.+ throw new InvalidMCPUsageError(+ `Tool '${server}/${tool}' requires interactive handling and is not callable from sandbox`,+ );+ }+ return response.result;+ }+}diff --git a/packages/harness/src/core/sandbox/constants.ts b/packages/harness/src/core/sandbox/constants.tsnew file mode 100644index 000000000..38d556096--- /dev/null+++ b/packages/harness/src/core/sandbox/constants.ts@@ -0,0 +1,5 @@+/** Stable directory inside the sandbox for user file uploads (mkdir during sandbox init). */+export const SANDBOX_FILE_UPLOADS_DIR = '/tmp/uploads';++/** Port of the pod-local NATS WebSocket broker used by the sandbox→gateway MCP bridge. */+export const SANDBOX_NATS_WS_PORT = 4444;diff --git a/packages/harness/src/core/sandbox/provider/DaytonaProvider.ts b/packages/harness/src/core/sandbox/provider/DaytonaProvider.tsnew file mode 100644index 000000000..6247aa20f--- /dev/null+++ b/packages/harness/src/core/sandbox/provider/DaytonaProvider.ts@@ -0,0 +1,292 @@+import type { Sandbox } from '@daytona/sdk';+import { Daytona, DaytonaError } from '@daytona/sdk';+import { context } from '@opentelemetry/api';+import { suppressTracing } from '@opentelemetry/core';+import { randomUUID } from 'crypto';+import type { Logger } from 'winston';+import { extractErrorLogFields } from '../../util/errorLogFields';+import {+ SandboxFileNotFoundError,+ SandboxFileTooLargeError,+ SandboxNotAvailableError,+ SandboxPathIsDirectoryError,+} from '../SandboxErrors';+import type { ExecResult, SandboxFileInfo, SandboxProvider } from './Provider';++const SANDBOX_NOT_FOUND_STATUS = 404;+const SANDBOX_STATE_STARTED = 'started';++/** Convert Daytona https preview URLs to wss for the NATS client. */+function httpUrlToWsUrl(url: string): string {+ const parsed = new URL(url);+ if (parsed.protocol === 'https:') parsed.protocol = 'wss:';+ else if (parsed.protocol === 'http:') parsed.protocol = 'ws:';+ return parsed.toString();+}++export interface DaytonaSandboxSettings {+ snapshotName: string;+ timeoutMs: number;+ autoStopIntervalInMinutes: number;+ autoArchiveIntervalInMinutes: number;+ autoDeleteIntervalInMinutes: number;+}++export interface DaytonaSandboxProviderOptions {+ apiKey: string;+ tenantName: string;+ settings: DaytonaSandboxSettings;+ fileMaxBytes: number;+ natsBridgePort: number;+ previewUrlExpirySeconds: number;+ logger: Logger;+}++let daytonaClient: Daytona | undefined;+function getDaytonaClient(apiKey: string): Daytona {+ if (!daytonaClient) {+ daytonaClient = new Daytona({ apiKey });+ }+ return daytonaClient;+}++export class DaytonaSandboxProvider implements SandboxProvider {+ private readonly apiKey: string;+ private readonly tenantName: string;+ private readonly settings: DaytonaSandboxSettings;+ private readonly fileMaxBytes: number;+ private readonly natsBridgePort: number;+ private readonly previewUrlExpirySeconds: number;+ private readonly logger: Logger;+ private readonly daytona: Daytona;+ private static readonly cachedSandboxes = new Map<string, { sandbox: Sandbox; timeoutMs: number }>();+ // De-dupes concurrent recovery attempts on the same sandbox to a single refreshData+start round-trip.+ private static readonly inFlightRecoveries = new Map<string, Promise<boolean>>();++ constructor(options: DaytonaSandboxProviderOptions) {+ this.apiKey = options.apiKey;+ this.tenantName = options.tenantName;+ this.settings = options.settings;+ this.fileMaxBytes = options.fileMaxBytes;+ this.natsBridgePort = options.natsBridgePort;+ this.previewUrlExpirySeconds = options.previewUrlExpirySeconds;+ this.logger = options.logger.child({ module: 'DaytonaProvider' });+ this.daytona = getDaytonaClient(this.apiKey);+ }++ private async getOrCreateSandbox(sandboxId?: string): Promise<{ sandbox: Sandbox; timeoutMs: number }> {+ if (sandboxId) {+ const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);+ if (cached) return cached;+ }++ const sandbox = sandboxId+ ? await this.restoreExistingSandbox(sandboxId)+ : await this.daytona.create({+ name: `${this.tenantName}.${randomUUID()}`,+ snapshot: this.settings.snapshotName,+ autoStopInterval: this.settings.autoStopIntervalInMinutes,+ autoArchiveInterval: this.settings.autoArchiveIntervalInMinutes,+ autoDeleteInterval: this.settings.autoDeleteIntervalInMinutes,+ });++ const entry = { sandbox, timeoutMs: this.settings.timeoutMs };+ DaytonaSandboxProvider.cachedSandboxes.set(sandbox.name, entry);+ return entry;+ }++ // Returns true iff the caller should retry: either we restarted a stopped sandbox, or the cache entry is missing and the retry will rebuild it via the cold path.+ private static recoverSandboxIfStopped(sandboxId: string): Promise<boolean> {+ const existing = DaytonaSandboxProvider.inFlightRecoveries.get(sandboxId);+ if (existing) return existing;++ const cached = DaytonaSandboxProvider.cachedSandboxes.get(sandboxId);+ // Cache may have been evicted by a concurrent error path; signal retry so getOrCreateSandbox rebuilds via restoreExistingSandbox.+ if (!cached) return Promise.resolve(true);++ const recovery = (async () => {+ await cached.sandbox.refreshData();+ if (cached.sandbox.state === SANDBOX_STATE_STARTED) return false;+ // start() covers both stopped and archived per Daytona; throws on unrecoverable states (error/destroyed).+ await cached.sandbox.start();+ return true;+ })().finally(() => {+ DaytonaSandboxProvider.inFlightRecoveries.delete(sandboxId);+ });++ DaytonaSandboxProvider.inFlightRecoveries.set(sandboxId, recovery);+ return recovery;+ }++ private async executeWithSandboxRecovery<T>(sandboxId: string, operation: () => Promise<T>): Promise<T> {+ try {+ return await operation();+ } catch (originalError) {+ // TODO: Narrow to a specific Daytona error code once @daytona/sdk exposes one for "sandbox not running".+ if (!(originalError instanceof DaytonaError)) throw originalError;++ let recovered: boolean;+ try {+ recovered = await DaytonaSandboxProvider.recoverSandboxIfStopped(sandboxId);+ } catch (recoveryError) {+ this.logger.error('Sandbox recovery failed', {+ ...extractErrorLogFields(recoveryError),+ originalError: extractErrorLogFields(originalError),+ });+ throw new Error('Sandbox is unavailable; recovery attempt failed.');+ }++ if (!recovered) throw originalError;++ try {+ return await operation();+ } catch (retryError) {+ this.logger.error('Sandbox operation failed after successful recovery', {+ ...extractErrorLogFields(retryError),+ originalError: extractErrorLogFields(originalError),+ });+ // Rethrow as-is so callers can match domain error types (SandboxPathIsDirectoryError, DaytonaError statusCode mappings, etc.).+ throw retryError;+ }+ }+ }++ private async restoreExistingSandbox(sandboxId: string): Promise<Sandbox> {+ try {+ const sandbox = await this.daytona.get(sandboxId);+ if (sandbox.state !== SANDBOX_STATE_STARTED) {+ await sandbox.start();+ }+ return sandbox;+ } catch (ex) {+ if (ex instanceof DaytonaError && ex.statusCode === SANDBOX_NOT_FOUND_STATUS) {+ throw new SandboxNotAvailableError(sandboxId);+ }+ throw ex;+ }+ }++ async createSandbox(): Promise<{ sandboxId: string }> {+ return context.with(suppressTracing(context.active()), async () => {+ const { sandbox } = await this.getOrCreateSandbox();+ this.logger.debug(`Sandbox created: name=${sandbox.name}`);+ return { sandboxId: sandbox.name };+ });+ }++ async exec(params: {+ sandboxId: string;+ command: string;+ cwd?: string | undefined;+ env?: Record<string, string> | undefined;+ }): Promise<ExecResult> {+ return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {+ try {+ return await this.executeWithSandboxRecovery(params.sandboxId, async () => {+ const { sandbox, timeoutMs } = await this.getOrCreateSandbox(params.sandboxId);+ const response = await sandbox.process.executeCommand(+ params.command,+ params.cwd,+ params.env ?? {},+ timeoutMs / 1000,+ );+ return {+ success: true,+ response: { exitCode: response.exitCode, result: response.result },+ };+ });+ } catch (e: unknown) {+ DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);+ this.logger.error('Sandbox execution error', extractErrorLogFields(e));+ const message = e instanceof Error ? e.message : 'Unknown error';+ return { success: false, error: message };+ }+ });+ }++ private async getFileInfo(sandbox: Sandbox, path: string): Promise<SandboxFileInfo> {+ const details = await sandbox.fs.getFileDetails(path);+ return { size: details.size ?? Infinity, isDir: details.isDir ?? false };+ }++ async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {+ return context.with(suppressTracing(context.active()), async () => {+ try {+ return await this.executeWithSandboxRecovery(params.sandboxId, async () => {+ const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);++ const info = await this.getFileInfo(sandbox, params.path);+ if (info.isDir) {+ throw new SandboxPathIsDirectoryError(params.path);+ }+ if (info.size > this.fileMaxBytes) {+ throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytes);+ }++ return await sandbox.fs.downloadFile(params.path);+ });+ } catch (e: unknown) {+ if (e instanceof SandboxPathIsDirectoryError || e instanceof SandboxFileTooLargeError) throw e;+ if (e instanceof DaytonaError && e.statusCode === SANDBOX_NOT_FOUND_STATUS) {+ throw new SandboxFileNotFoundError(params.path);+ }+ DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);+ throw e;+ }+ });+ }++ async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {+ return context.with(suppressTracing(context.active()), async () => {+ try {+ await this.executeWithSandboxRecovery(params.sandboxId, async () => {+ const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);+ await sandbox.fs.uploadFile(params.content, params.remotePath);+ });+ } catch (e: unknown) {+ DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);+ throw e;+ }+ });+ }++ // Mints a signed, time-limited https preview URL exposing the given sandbox port.+ private async getPreviewUrl(params: { sandboxId: string; port: number; expiresInSeconds: number }): Promise<string> {+ return context.with(suppressTracing(context.active()), async () => {+ try {+ return await this.executeWithSandboxRecovery(params.sandboxId, async () => {+ const { sandbox } = await this.getOrCreateSandbox(params.sandboxId);+ const signed = await sandbox.getSignedPreviewUrl(params.port, params.expiresInSeconds);+ return signed.url;+ });+ } catch (e: unknown) {+ DaytonaSandboxProvider.cachedSandboxes.delete(params.sandboxId);+ this.logger.error('Failed to create signed preview URL', extractErrorLogFields(e));+ throw e;+ }+ });+ }++ async getNatsBridgeUrl(sandboxId: string): Promise<string> {+ // Daytona hands us a signed https preview URL; convert http(s) -> ws(s) for the NATS client.+ const previewUrl = await this.getPreviewUrl({+ sandboxId,+ port: this.natsBridgePort,+ expiresInSeconds: this.previewUrlExpirySeconds,+ });+ return httpUrlToWsUrl(previewUrl);+ }++ getAdditionalInstructions(): string | undefined {+ return undefined;+ }++ getToolResultDumpDir(_sandboxId: string): string {+ return '/tmp/tool-results';+ }++ getGitCredentialsPath(): string {+ // Isolated container per sandbox; absolute path so GIT_CONFIG_* needs no $HOME expansion.+ return '/tmp/.git-credentials';+ }+}diff --git a/packages/harness/src/core/sandbox/provider/Provider.ts b/packages/harness/src/core/sandbox/provider/Provider.tsnew file mode 100644index 000000000..74c5936ca--- /dev/null+++ b/packages/harness/src/core/sandbox/provider/Provider.ts@@ -0,0 +1,49 @@+/** Command executed in sandbox — exitCode may be non-zero but the infra call succeeded. */+export interface ExecSuccessResult {+ success: true;+ response: { exitCode: number; result: string };+}++/** Sandbox infrastructure failure — command never ran (e.g. network error, auth failure). */+export interface ExecErrorResult {+ success: false;+ error: string;+}++export type ExecResult = ExecSuccessResult | ExecErrorResult;++/** Throws if the exec result indicates failure (infra error or non-zero exit code). */+export function ensureExecSuccess(result: ExecResult): void {+ if (!result.success) {+ throw new Error(`${result.error}`);+ }+ if (result.response.exitCode !== 0) {+ throw new Error(`(exit code ${result.response.exitCode}): ${result.response.result}`);+ }+}++export interface SandboxFileInfo {+ size: number;+ isDir: boolean;+}++export interface SandboxProvider {+ createSandbox(): Promise<{ sandboxId: string }>;+ exec(params: { sandboxId: string; command: string; cwd?: string; env?: Record<string, string> }): Promise<ExecResult>;+ /** Provider-specific instructions appended to the agent system prompt. */+ getAdditionalInstructions(): string | undefined;+ /** Directory inside the sandbox where large tool responses are dumped. */+ getToolResultDumpDir(sandboxId: string): string;+ /** Absolute path for the git credential-store file (per logical sandbox when sharing a pod). */+ getGitCredentialsPath(sandboxId: string): string;+ /** Downloads a file from the sandbox as a Buffer. Throws SandboxFileNotFoundError / SandboxNotAvailableError / SandboxPathIsDirectoryError / SandboxFileTooLargeError. */+ downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer>;+ /** Uploads a file to the sandbox. */+ uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void>;++ /**+ * Returns a ready-to-use `ws(s)://` URL for this sandbox's pod-local NATS broker, which the+ * gateway connects to as the MCP responder. Throws on failure (caller retries on a later exec).+ */+ getNatsBridgeUrl(sandboxId: string): Promise<string>;+}diff --git a/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.ts b/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.tsnew file mode 100644index 000000000..c46178841--- /dev/null+++ b/packages/harness/src/core/sandbox/provider/TFYSandboxProvider.ts@@ -0,0 +1,171 @@+import { context } from '@opentelemetry/api';+import { suppressTracing } from '@opentelemetry/core';+import { randomUUID } from 'crypto';+import dedent from 'dedent';+import type { Logger } from 'winston';+import { extractErrorLogFields } from '../../util/errorLogFields';+import { SandboxFileNotFoundError, SandboxFileTooLargeError, SandboxPathIsDirectoryError } from '../SandboxErrors';+import { ensureExecSuccess, type ExecResult, type SandboxFileInfo, type SandboxProvider } from './Provider';++const DEFAULT_TIMEOUT_SECONDS = 60;+// Buffer for network latency + response processing on top of the server-side timeout.+const CLIENT_TIMEOUT_BUFFER_SECONDS = 5;++// Wraps a value in single quotes for safe use in shell commands.+// Inner single quotes are escaped via the standard shell idiom: ' → '\''+function shellEscape(value: string): string {+ return `'${value.replace(/'/g, "'\\''")}'`;+}++export interface TFYSandboxProviderOptions {+ serverUrl: string;+ natsBridgeUrl: string;+ tenantName: string;+ fileMaxBytes: number;+ execTimeoutMs?: number | undefined;+ logger: Logger;+}++interface StatResult {+ size: number;+ type: string;+}++export class TFYSandboxProvider implements SandboxProvider {+ private readonly serverUrl: string;+ private readonly natsBridgeUrl: string;+ private readonly tenantName: string;+ private readonly fileMaxBytes: number;+ private readonly execTimeoutSeconds: number;+ private readonly logger: Logger;++ constructor(options: TFYSandboxProviderOptions) {+ this.serverUrl = options.serverUrl.replace(/\/+$/, '');+ this.natsBridgeUrl = options.natsBridgeUrl;+ this.tenantName = options.tenantName;+ this.fileMaxBytes = options.fileMaxBytes;+ this.execTimeoutSeconds = Math.ceil((options.execTimeoutMs ?? DEFAULT_TIMEOUT_SECONDS * 1000) / 1000);+ this.logger = options.logger.child({ module: 'TFYSandboxProvider' });+ }++ async createSandbox(): Promise<{ sandboxId: string }> {+ const sandboxId = `${this.tenantName}.${randomUUID()}`;+ this.logger.debug(`Sandbox created: id=${sandboxId}`);+ return { sandboxId };+ }++ async exec(params: {+ sandboxId: string;+ command: string;+ cwd?: string | undefined;+ env?: Record<string, string> | undefined;+ }): Promise<ExecResult> {+ return context.with(suppressTracing(context.active()), async (): Promise<ExecResult> => {+ const body = {+ sandbox_id: params.sandboxId,+ command: params.command,+ cwd: params.cwd,+ env: params.env,+ timeout: this.execTimeoutSeconds,+ };++ const controller = new AbortController();+ const clientTimeoutMs = (this.execTimeoutSeconds + CLIENT_TIMEOUT_BUFFER_SECONDS) * 1000;+ const timer = setTimeout(() => controller.abort(), clientTimeoutMs);++ try {+ const response = await fetch(`${this.serverUrl}/exec`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ signal: controller.signal,+ });++ if (!response.ok) {+ const text = await response.text();+ this.logger.error(`Sandbox server returned ${response.status}: ${text}`);+ return { success: false, error: `Sandbox server returned ${response.status}: ${text}` };+ }++ const result = (await response.json()) as ExecResult;+ return result;+ } catch (e: unknown) {+ if (e instanceof Error && e.name === 'AbortError') {+ this.logger.error(`Sandbox exec timed out after ${this.execTimeoutSeconds}s`, extractErrorLogFields(e));+ return { success: false, error: `Sandbox exec timed out after ${this.execTimeoutSeconds}s` };+ }+ this.logger.error('Sandbox exec failed', extractErrorLogFields(e));+ const message = e instanceof Error ? e.message : 'Unknown error';+ return { success: false, error: message };+ } finally {+ clearTimeout(timer);+ }+ });+ }++ private async getFileInfo(params: { sandboxId: string; path: string }): Promise<SandboxFileInfo> {+ const result = await this.exec({+ sandboxId: params.sandboxId,+ command: `stat -L --printf='{"size":%s,"type":"%F"}' ${shellEscape(params.path)}`,+ });++ if (!result.success) throw new Error(`Failed to stat file: ${result.error}`);+ if (result.response.exitCode !== 0) throw new SandboxFileNotFoundError(params.path);++ const parsed = JSON.parse(result.response.result) as StatResult;+ return { size: parsed.size, isDir: parsed.type === 'directory' };+ }++ async downloadFile(params: { sandboxId: string; path: string }): Promise<Buffer> {+ const info = await this.getFileInfo(params);+ if (info.isDir) {+ throw new SandboxPathIsDirectoryError(params.path);+ }+ if (info.size > this.fileMaxBytes) {+ throw new SandboxFileTooLargeError(params.path, info.size, this.fileMaxBytes);+ }++ const result = await this.exec({+ sandboxId: params.sandboxId,+ command: `base64 -w0 ${shellEscape(params.path)}`,+ });++ if (!result.success) throw new Error(`Failed to download file: ${result.error}`);+ if (result.response.exitCode !== 0) throw new SandboxFileNotFoundError(params.path);++ return Buffer.from(result.response.result.trim(), 'base64');+ }++ async uploadFile(params: { sandboxId: string; remotePath: string; content: Buffer }): Promise<void> {+ const encoded = params.content.toString('base64');+ const escapedPath = shellEscape(params.remotePath);++ const result = await this.exec({+ sandboxId: params.sandboxId,+ command: `echo ${shellEscape(encoded)} | base64 -d > ${escapedPath}`,+ });+ ensureExecSuccess(result);+ }++ // The TFY sandbox exposes a static, cluster-internal NATS WebSocket URL (no signed URLs).+ async getNatsBridgeUrl(_sandboxId: string): Promise<string> {+ return this.natsBridgeUrl;+ }++ getAdditionalInstructions(): string {+ return dedent`+ SANDBOX RULES:+ - The Agent's first sandbox command should be \`pwd\` to discover the working directory.+ - ALL file creation and writes MUST stay within that working directory.+ - The Agent must NOT write to /tmp/, ~/, or any absolute path outside the working directory.+ `;+ }++ getToolResultDumpDir(sandboxId: string): string {+ return `/tmp/${sandboxId}/tool-results`;+ }++ getGitCredentialsPath(sandboxId: string): string {+ return `/tmp/${sandboxId}/.git-credentials`;+ }+}diff --git a/packages/harness/src/core/sandbox/provider/createSandboxProvider.ts b/packages/harness/src/core/sandbox/provider/createSandboxProvider.tsnew file mode 100644index 000000000..6f984244d--- /dev/null+++ b/packages/harness/src/core/sandbox/provider/createSandboxProvider.ts@@ -0,0 +1,69 @@+/**+ * Sandbox provider registry: typed settings (discriminated on `type`) and a+ * factory mapping them onto a {@link SandboxProvider}.+ *+ * Adding a provider = add its settings schema to the union + a case to the+ * switch. The switch is exhaustive: since the function declares a+ * `SandboxProvider` return type, a union member without a matching case makes+ * it no longer return on all paths and fails compilation (TS2366).+ */+import type { Logger } from 'winston';+import { z } from 'zod';+import { SANDBOX_NATS_WS_PORT } from '../constants';+import { DaytonaSandboxProvider } from './DaytonaProvider';+import type { SandboxProvider } from './Provider';++/**+ * Daytona-backed sandboxes. Keys and defaults match the gateway's+ * SANDBOX_SETTINGS JSON (sandboxComposition.ts), plus the `type` discriminator.+ */+export const DaytonaSandboxProviderSettingsSchema = z+ .object({+ type: z.literal('daytona'),+ apiKey: z.string().min(1, 'apiKey is required'),+ snapshotName: z.string().min(1, 'snapshotName is required'),+ timeoutMs: z.number().int().positive().default(60_000),+ autoStopIntervalInMinutes: z.number().int().nonnegative().default(5),+ autoArchiveIntervalInMinutes: z.number().int().nonnegative().default(60),+ autoDeleteIntervalInMinutes: z.number().int().nonnegative().default(43_200),+ })+ .strict();++/** All supported sandbox backends, discriminated on `type`. */+export const SandboxProviderSettingsSchema = z.discriminatedUnion('type', [DaytonaSandboxProviderSettingsSchema]);++export type SandboxProviderSettings = z.infer<typeof SandboxProviderSettingsSchema>;++export interface CreateSandboxProviderInput {+ settings: SandboxProviderSettings;+ /** Namespaces sandbox names and ownership checks. */+ tenantName: string;+ /** Max bytes for a single file download out of the sandbox. */+ fileMaxBytes: number;+ /** Lifetime of signed preview URLs minted for the sandbox NATS bridge. */+ previewUrlExpirySeconds: number;+ logger: Logger;+}++/** Builds the provider for the given settings. Construction is cheap and does no I/O. */+export function createSandboxProvider(input: CreateSandboxProviderInput): SandboxProvider {+ const { settings } = input;+ switch (settings.type) {+ case 'daytona':+ return new DaytonaSandboxProvider({+ apiKey: settings.apiKey,+ tenantName: input.tenantName,+ settings: {+ snapshotName: settings.snapshotName,+ timeoutMs: settings.timeoutMs,+ autoStopIntervalInMinutes: settings.autoStopIntervalInMinutes,+ autoArchiveIntervalInMinutes: settings.autoArchiveIntervalInMinutes,+ autoDeleteIntervalInMinutes: settings.autoDeleteIntervalInMinutes,+ },+ fileMaxBytes: input.fileMaxBytes,+ natsBridgePort: SANDBOX_NATS_WS_PORT,+ previewUrlExpirySeconds: input.previewUrlExpirySeconds,+ logger: input.logger,+ });+ }+}diff --git a/packages/harness/src/core/sandbox/scripts/mcp_client.py b/packages/harness/src/core/sandbox/scripts/mcp_client.pynew file mode 100644index 000000000..4289bbac5--- /dev/null+++ b/packages/harness/src/core/sandbox/scripts/mcp_client.py@@ -0,0 +1,312 @@+#!/usr/bin/env python3++# /// script+# dependencies = ["fastmcp==3.2.4", "pydantic==2.12.5", "nats-py==2.15.0"]+# ///+# NOTE: If you change or bump dependencies above, update them in these repos too:+# - https://github.com/truefoundry/tfy-llm-tools+# - https://github.com/truefoundry/tfy-sandbox-server++import os+import sys+import json+import time+import base64+import asyncio+import logging+import argparse+from pathlib import Path+from typing import Any, TypedDict++from pydantic import BaseModel, ValidationError++from mcp.types import CallToolResult, TextContent, Tool++logger = logging.getLogger(__name__)++_NATS_REQUEST_TIMEOUT_SECONDS = 60+_NATS_REQUEST_MAX_ATTEMPTS = 3+_NATS_RETRY_BACKOFF_MS = 250++_nats_url = os.environ.get("TFY_NATS_URL")+_nats_subject_prefix = os.environ.get("TFY_NATS_SUBJECT_PREFIX")+_NATS_SUBJECT = f"{_nats_subject_prefix}.mcp" if _nats_url and _nats_subject_prefix else None+if bool(_nats_url) != bool(_nats_subject_prefix):+ raise RuntimeError(+ "TFY_NATS_URL and TFY_NATS_SUBJECT_PREFIX must be set together; "+ f"got TFY_NATS_URL={'set' if _nats_url else 'unset'}, "+ f"TFY_NATS_SUBJECT_PREFIX={'set' if _nats_subject_prefix else 'unset'}"+ ) from None++_nats_trace_headers: dict[str, str] = {}+if _traceparent := os.environ.get("TFY_TRACEPARENT"):+ _nats_trace_headers["traceparent"] = _traceparent+if _tracestate := os.environ.get("TFY_TRACESTATE"):+ _nats_trace_headers["tracestate"] = _tracestate+++class _ToolsCache(BaseModel):+ fetched_at: float+ tools: list[Tool]+++class _BridgeReply(BaseModel):+ """NATS bridge reply envelope. `result` is left untyped — operation-specific callers+ (Tool / CallToolResult) validate the payload; this model only validates the envelope."""++ ok: bool+ result: Any = None+ error: str = "unknown error"+ source: str = "gateway"+++class _ServerConfig(TypedDict):+ allowed_tools: list[str]+++_TOOLS_CACHE_TTL_SECONDS = 600++_inflight_list_tools: dict[str, asyncio.Task[list[Tool]]] = {}++_raw_servers = os.environ.get("TFY_MCP_SERVERS")+_servers_map: dict[str, _ServerConfig] = json.loads(base64.b64decode(_raw_servers).decode()) if _raw_servers else {}+# Approvals are always enabled (Sandbox always injects TFY_ENABLE_AGENT_APPROVALS=true).+_enable_agent_approvals = os.environ.get("TFY_ENABLE_AGENT_APPROVALS", "true").lower() == "true"+++def _check_tool_allowed(server: str, tool_name: str) -> None:+ server_config = _servers_map.get(server)+ if server_config is None:+ raise RuntimeError(f"Access denied: MCP server '{server}' is not available for this agent") from None+ server_tools = server_config.get("allowed_tools") or []+ if len(server_tools) > 0 and tool_name not in server_tools:+ raise RuntimeError(f"Access denied: tool '{tool_name}' is not enabled on server '{server}'") from None+++def _cache_path(server: str) -> Path:+ return Path(__file__).parent / f"{server}.tools.json"+++def _read_tools_cache(server: str) -> _ToolsCache | None:+ p = _cache_path(server)+ if not p.exists():+ return None+ try:+ cache = _ToolsCache.model_validate_json(p.read_text(encoding="utf-8"))+ except Exception:+ logger.exception("_ToolsCache.model_validate_json")+ p.unlink(missing_ok=True)+ return None+ if time.time() - cache.fetched_at > _TOOLS_CACHE_TTL_SECONDS:+ p.unlink(missing_ok=True)+ return None+ return cache+++def _write_tools_cache(server: str, tools: list[Tool]) -> None:+ try:+ cache = _ToolsCache(fetched_at=time.time(), tools=tools)+ _cache_path(server).write_text(cache.model_dump_json(), encoding="utf-8")+ except Exception:+ logger.exception("_write_tools_cache")+++def _require_nats_subject() -> str:+ if not _NATS_SUBJECT or not _nats_url:+ raise RuntimeError(+ "NATS bridge setup failed; NATS bridge is required for MCP from Code Mode. "+ "Try again."+ ) from None+ return _NATS_SUBJECT+++async def _fetch_tools(server: str) -> list[Tool]:+ result = await _nats_request(_require_nats_subject(), {"op": "list_tools", "server": server})+ if not isinstance(result, dict):+ raise RuntimeError(f"NATS list_tools '{server}' returned unexpected shape: {result!r}") from None+ return [Tool.model_validate(t) for t in result.get("tools", [])]+++async def _fetch_and_cache_tools(server: str) -> list[Tool]:+ tools = await _fetch_tools(server)+ _write_tools_cache(server, tools)+ return tools+++async def _nats_request(subject: str, payload: dict[str, Any]) -> Any:+ """Send one request over a short-lived bridge connection, unwrap { ok, result|error }.++ Connection is per-call (closed in `finally`) to avoid leaking nats-py's aiohttp session.+ Connect and request are retried in separate loops so a successful connection isn't torn+ down and rebuilt on a request-level retry. Retries only failures that prove the request+ never reached a handler (connect failure, NoRespondersError); timeouts and post-delivery+ failures are not retried so a non-idempotent tool can't double-execute.+ """+ import nats+ from nats.errors import NoRespondersError++ data = json.dumps(payload).encode()++ # Phase 1: establish a connection, retrying only connect failures.+ nc = None+ last_connect_error = "unknown error"+ for attempt in range(1, _NATS_REQUEST_MAX_ATTEMPTS + 1):+ if attempt > 1:+ await asyncio.sleep(_NATS_RETRY_BACKOFF_MS / 1000)+ try:+ nc = await nats.connect(_nats_url)+ break+ except Exception as e:+ last_connect_error = f"connect to NATS at {_nats_url} failed: {e}"+ if nc is None:+ raise RuntimeError(+ f"NATS connect failed for '{subject}' after {_NATS_REQUEST_MAX_ATTEMPTS} attempts: {last_connect_error}"+ ) from None++ # Phase 2: request over the established connection, retrying only NoRespondersError.+ try:+ last_transport_error = "unknown error"+ for attempt in range(1, _NATS_REQUEST_MAX_ATTEMPTS + 1):+ if attempt > 1:+ await asyncio.sleep(_NATS_RETRY_BACKOFF_MS / 1000)+ try:+ msg = await nc.request(+ subject,+ data,+ timeout=_NATS_REQUEST_TIMEOUT_SECONDS,+ headers=_nats_trace_headers or None,+ )+ except NoRespondersError as e:+ # Server confirms no subscriber — never delivered, safe to retry.+ last_transport_error = f"no NATS responder for '{subject}': {e}"+ continue+ except Exception as e:+ # Timeout / other: the tool may already have run, so we must not retry.+ raise RuntimeError(f"NATS request '{subject}' failed: {e}") from None+ try:+ reply = _BridgeReply.model_validate_json(msg.data.decode())+ except ValidationError as e:+ raise RuntimeError(f"NATS reply on '{subject}' is malformed: {e}") from None+ if not reply.ok:+ # A well-formed reply means the bridge/transport worked; `source` says who's at fault.+ if reply.source == "agent":+ raise RuntimeError(f"Invalid MCP request on '{subject}': {reply.error}") from None+ if reply.source == "bridge":+ raise RuntimeError(f"NATS bridge error on '{subject}': {reply.error}") from None+ raise RuntimeError(f"Gateway MCP error on '{subject}': {reply.error}") from None+ return reply.result+ raise RuntimeError(+ f"NATS bridge has no responder for '{subject}' after {_NATS_REQUEST_MAX_ATTEMPTS} attempts: {last_transport_error}"+ ) from None+ finally:+ try:+ await nc.close()+ except Exception:+ logger.debug("Error closing NATS connection", exc_info=True)+++async def _get_tools(server: str) -> list[Tool]:+ cache = _read_tools_cache(server)+ if cache is not None:+ return cache.tools+ task = _inflight_list_tools.get(server)+ if task is None:+ task = asyncio.create_task(_fetch_and_cache_tools(server))+ _inflight_list_tools[server] = task+ task.add_done_callback(lambda _t: _inflight_list_tools.pop(server, None))+ return await task+++async def _get_tool(server: str, tool_name: str) -> Tool | None:+ for t in await _get_tools(server):+ if t.name == tool_name:+ return t+ return None+++def _is_destructive(tool: Tool) -> bool:+ annotations = tool.annotations+ if annotations is None:+ return False+ return bool(annotations.destructiveHint) or (not annotations.readOnlyHint and annotations.readOnlyHint is not None)++async def _ensure_non_destructive(server: str, tool_name: str) -> None:+ tool = await _get_tool(server, tool_name)+ if tool is None:+ raise RuntimeError(f"Tool '{tool_name}' not found on MCP server '{server}'") from None+ if _is_destructive(tool):+ raise RuntimeError(+ f"Tool '{tool_name}' on MCP server '{server}' is destructive and cannot be called in Code Mode; "+ f"call it directly so it can go through the user approval flow"+ ) from None+++def _project_call_tool_result(server: str, tool: str, result: CallToolResult) -> Any:+ """Project an MCP-wire CallToolResult into the user-facing Python value."""+ if result.isError:+ text_parts = [c.text for c in result.content if isinstance(c, TextContent) and c.text]+ msg = "; ".join(text_parts) if text_parts else "tool returned an error"+ raise RuntimeError(f"MCP tool error (server={server}, tool={tool}): {msg}") from None++ if result.structuredContent is not None:+ return result.structuredContent++ # Fallback to content blocks (tools without outputSchema / plain text responses)+ if len(result.content) == 1:+ first = result.content[0]+ if isinstance(first, TextContent) and first.text:+ try:+ return json.loads(first.text)+ except Exception:+ pass+ if result.content:+ return result.content+ return None+++async def call_tool(server: str, tool: str, body: dict[str, Any]) -> Any:+ _check_tool_allowed(server, tool)+ if _enable_agent_approvals:+ await _ensure_non_destructive(server, tool)++ raw = await _nats_request(+ _require_nats_subject(),+ {"op": "call_tool", "server": server, "tool": tool, "arguments": body},+ )+ try:+ result = CallToolResult.model_validate(raw)+ except Exception as e:+ raise RuntimeError(f"NATS call_tool reply for '{server}/{tool}' is malformed: {e}") from None++ return _project_call_tool_result(server, tool, result)+++_USAGE = "mcp_client.py call-tool <server> <tool> <args-json>"+++def _build_arg_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="mcp_client.py", usage=_USAGE)+ sub = parser.add_subparsers(dest="cmd", required=True)++ call_tool_p = sub.add_parser("call-tool", help="Invoke an MCP tool")+ call_tool_p.add_argument("server")+ call_tool_p.add_argument("tool")+ # Parsing JSON at the argparse boundary surfaces malformed input as a clean+ # argparse error (with usage) instead of an opaque traceback from inside the handler.+ call_tool_p.add_argument("args_json", metavar="args-json", type=json.loads)++ return parser+++async def _main() -> None:+ args = _build_arg_parser().parse_args()+ try:+ if args.cmd == "call-tool":+ result = await call_tool(args.server, args.tool, args.args_json)+ print(json.dumps(result, default=str))+ except RuntimeError as e:+ sys.exit(str(e))+++if __name__ == "__main__":+ asyncio.run(_main())diff --git a/packages/harness/src/core/sandbox/scripts/skill_downloader.py b/packages/harness/src/core/sandbox/scripts/skill_downloader.pynew file mode 100644index 000000000..b405190f3--- /dev/null+++ b/packages/harness/src/core/sandbox/scripts/skill_downloader.py@@ -0,0 +1,308 @@+#!/usr/bin/env python3++# /// script+# dependencies = ["pydantic==2.12.5", "requests>=2.31,<3"]+# ///++"""Download skill tarballs (presigned URLs) into TFY_SKILLS_DIR (default /opt/tfy/skills).++Required env (only when there are skills to download): TFY_HOST, TFY_API_KEY (caller bearer).+Optional env: TFY_AGENT_NAME, AGENT_SKILL_VERSION_FQNS (comma-separated; empty clears downloads).+"""++from __future__ import annotations++import json+import os+import shutil+import sys+import tarfile+import tempfile+from io import BytesIO+from pathlib import Path++import requests+from pydantic import BaseModel, ConfigDict, Field, ValidationError++DEFAULT_SKILLS_DIR = "/opt/tfy/skills"+STATE_FILE_NAME = ".tfy-skill-downloader-state.json"+DOWNLOAD_TIMEOUT_SECONDS = 30+PRESIGNED_URL_PATH = "/api/svc/v1/llm-gateway/agent-skill-versions/presigned-urls"+SKILLS_ROOT = Path(os.environ.get("TFY_SKILLS_DIR", DEFAULT_SKILLS_DIR))+STATE_PATH = SKILLS_ROOT / STATE_FILE_NAME+++class AgentSkill(BaseModel):+ model_config = ConfigDict(extra="ignore")++ fqn: str+ name: str+++class SkillDownloaderState(BaseModel):+ """Persisted next to skills: {\"downloaded_fqns\": [{\"fqn\": \"agent_skill:...\"]}."""++ model_config = ConfigDict(extra="ignore")++ downloaded_fqns: list[AgentSkill] = Field(+ default_factory=list,+ description="Skills successfully downloaded (fqn + name).",+ )+++class PresignedUrlsRequestItem(BaseModel):+ model_config = ConfigDict(extra="forbid")++ fqn: str+++class PresignedUrlsRequest(BaseModel):+ model_config = ConfigDict(extra="forbid", populate_by_name=True)++ data: list[PresignedUrlsRequestItem]+ agent_name: str | None = Field(default=None, alias="agentName")+++class AgentSkillPresignedRow(AgentSkill):+ model_config = ConfigDict(extra="ignore")++ presigned_url: str+++class PresignedUrlsResponse(BaseModel):+ model_config = ConfigDict(extra="ignore")++ data: list[AgentSkillPresignedRow]+++class ReconcilePartitionResult(BaseModel):+ """Pending downloads, skipped (already satisfied), and FQNs pruned from state."""++ model_config = ConfigDict(extra="forbid")++ pending_fqns: list[str] = Field(+ default_factory=list,+ description="FQNs to download this run.",+ )+ skipped_fqns: list[str] = Field(+ default_factory=list,+ description="FQNs already satisfied (state or on-disk); skipped.",+ )+ removed_fqns: list[str] = Field(+ default_factory=list,+ description="FQNs dropped from desired; removed from state and disk.",+ )+++def skills_from_env(raw: str | None) -> list[str]:+ """Empty or missing env means “no desired skills” (prune all downloaded)."""+ if raw is None or not str(raw).strip():+ return []+ return [s.strip() for s in raw.split(",") if s.strip()]+++def load_state() -> SkillDownloaderState:+ if not STATE_PATH.is_file():+ return SkillDownloaderState()+ try:+ return SkillDownloaderState.model_validate_json(STATE_PATH.read_text(encoding="utf-8"))+ except (OSError, ValidationError) as e:+ return SkillDownloaderState()+++def save_state(state: SkillDownloaderState) -> None:+ STATE_PATH.parent.mkdir(parents=True, exist_ok=True)+ tmp = STATE_PATH.with_name(STATE_PATH.name + ".tmp")+ tmp.write_text(state.model_dump_json(indent=2), encoding="utf-8")+ os.replace(tmp, STATE_PATH)+++def _mark_downloaded(state: SkillDownloaderState, skill: AgentSkill) -> None:+ if any(x.fqn == skill.fqn for x in state.downloaded_fqns):+ return+ state.downloaded_fqns.append(skill)+++def _rmtree(path: Path, ignore_errors: bool = True) -> None:+ try:+ shutil.rmtree(path, ignore_errors=ignore_errors)+ except OSError:+ pass+++def _delete_skill_dir(skill: AgentSkill) -> None:+ dir_ = SKILLS_ROOT / skill.name+ if not dir_.is_dir():+ return+ try:+ shutil.rmtree(dir_)+ except OSError as e:+ sys.exit(f"Could not remove skill directory {dir_} ({skill.fqn}): {e}")+++def reconcile_and_partition(+ skills_fqns: list[str], # list of FQNs+ state: SkillDownloaderState,+ have_downloaded_skills: bool,+) -> ReconcilePartitionResult:+ """Drop skills no longer desired (state + dirs), then pending vs skipped; persist state."""+ requested_fqns = set(skills_fqns)+ pending_fqns: list[str] = []+ skipped_fqns: list[str] = []+ removed = [x for x in state.downloaded_fqns if x.fqn not in requested_fqns]+ removed_fqns = [x.fqn for x in removed]+ if removed:+ for x in removed:+ _delete_skill_dir(x)+ state.downloaded_fqns = [x for x in state.downloaded_fqns if x.fqn in requested_fqns]++ if not have_downloaded_skills:+ pending_fqns = list(skills_fqns)+ else:+ already_downloaded = {x.fqn for x in state.downloaded_fqns}+ for skill_fqn in requested_fqns:+ if skill_fqn in already_downloaded:+ skipped_fqns.append(skill_fqn)+ else:+ pending_fqns.append(skill_fqn)++ save_state(state)+ return ReconcilePartitionResult(+ pending_fqns=pending_fqns,+ skipped_fqns=skipped_fqns,+ removed_fqns=removed_fqns,+ )+++def request_presigned_rows(+ control_plane_url: str,+ token: str,+ agent_name: str | None,+ fqns: list[str],+) -> list[AgentSkillPresignedRow]:+ url = f"{control_plane_url.rstrip('/')}{PRESIGNED_URL_PATH}"+ req = PresignedUrlsRequest(+ data=[PresignedUrlsRequestItem(fqn=fqn) for fqn in fqns],+ agent_name=agent_name,+ )+ try:+ resp = requests.post(+ url,+ json=req.model_dump(by_alias=True, exclude_none=True),+ headers={"Authorization": f"Bearer {token}"},+ timeout=120,+ )+ except requests.RequestException as e:+ sys.exit(f"POST {url} failed: {e}")+ if resp.status_code >= 400:+ try:+ err = resp.json()+ detail = err.get("message", resp.text)+ if code := err.get("error_code"):+ detail = f"{code}: {detail}"+ except (json.JSONDecodeError, ValueError):+ detail = resp.text+ sys.exit(f"POST {url} failed HTTP {resp.status_code}\n{detail}")+ try:+ payload = resp.json()+ except json.JSONDecodeError as e:+ sys.exit(f"POST {url}: invalid JSON in response: {e}")+ try:+ rows = PresignedUrlsResponse.model_validate(payload).data+ except ValidationError as e:+ sys.exit(f"Invalid API response: {e}")++ returned_fqns = {r.fqn for r in rows}+ if miss := [f for f in fqns if f not in returned_fqns]:+ sys.exit(f"API did not return these FQNs: {miss}")+ return rows+++def download_skill(skill_name: str, presigned_url: str, dest: Path) -> None:+ try:+ r = requests.get(presigned_url, timeout=DOWNLOAD_TIMEOUT_SECONDS)+ r.raise_for_status()+ raw = r.content+ except requests.HTTPError as e:+ code = e.response.status_code if e.response is not None else "?"+ sys.exit(f"Download HTTP {code} for skill {skill_name}")+ except requests.RequestException as e:+ sys.exit(f"Download failed for skill {skill_name}: {e}")++ dest.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(+ prefix=".skill-dl-",+ dir=os.fspath(dest.parent),+ ignore_cleanup_errors=True,+ ) as tmp_str:+ tmp_dir = Path(tmp_str)+ try:+ tf = tarfile.open(fileobj=BytesIO(raw), mode="r:*")+ except (tarfile.TarError, OSError, EOFError):+ sys.exit(f"Skill {skill_name}: not a tar archive")+ try:+ with tf:+ tf.extractall(tmp_dir, filter="data")+ except tarfile.TarError as e:+ sys.exit(f"Skill {skill_name}: tar extraction refused or failed ({e})")+ except OSError as e:+ sys.exit(f"Skill {skill_name}: failed to read archive: {e}")++ try:+ if dest.exists():+ shutil.rmtree(dest)+ shutil.move(str(tmp_dir), str(dest))+ except OSError as e:+ _rmtree(dest)+ sys.exit(f"Failed to write downloaded skill {skill_name}: {e}")+++def run_download() -> None:+ skills_fqns = skills_from_env(os.environ.get("AGENT_SKILL_VERSION_FQNS"))+ state = load_state()+ have_downloaded_skills = bool(state.downloaded_fqns)++ part = reconcile_and_partition(+ skills_fqns, state, have_downloaded_skills=have_downloaded_skills+ )+ if not part.pending_fqns:+ if part.removed_fqns:+ n = len(part.removed_fqns)+ print(+ f"Removed {n} skill(s) from state and disk."+ + ("" if skills_fqns else " (AGENT_SKILL_VERSION_FQNS empty.)")+ )+ elif not skills_fqns:+ print("AGENT_SKILL_VERSION_FQNS empty; nothing downloaded.")+ else:+ print("Nothing to download; all listed skills already downloaded.")+ return++ # Credentials are only needed when there is actually something to download,+ # so runtimes with no skills configured (e.g. the public server) can init+ # the sandbox without a control plane.+ control_plane_url = os.environ.get("TFY_HOST")+ if not control_plane_url:+ sys.exit("Set TFY_HOST to the control plane base URL.")+ token = os.environ.get("TFY_API_KEY")+ if not token:+ sys.exit("Set TFY_API_KEY.")+ agent_name = os.environ.get("TFY_AGENT_NAME")++ rows = request_presigned_rows(+ control_plane_url, token, agent_name, part.pending_fqns+ )+ for row in rows:+ download_skill(row.name, row.presigned_url, SKILLS_ROOT / row.name)+ _mark_downloaded(state, AgentSkill(fqn=row.fqn, name=row.name))+ save_state(state)++ print(f"Downloaded {len(rows)} skill(s).")+++def main() -> None:+ run_download()+++if __name__ == "__main__":+ main()diff --git a/packages/harness/src/core/tracing/AgentTracing.ts b/packages/harness/src/core/tracing/AgentTracing.tsnew file mode 100644index 000000000..3beffc529--- /dev/null+++ b/packages/harness/src/core/tracing/AgentTracing.ts@@ -0,0 +1,52 @@+import type { AgentThreadMetric } from '../llm/metrics';++export interface AgentExecutionTrace {+ runInContext<T>(operation: () => T): T;+ startSubAgent(name: string, input: string): AgentExecutionTrace;+ setOutput(output: string): void;+ setMetrics(metrics: AgentThreadMetric): void;+ setError(error: unknown): void;+ setSuccess(): void;+ end(): void;+}++export interface AgentLocalToolTrace {+ setOutput(output: string): void;+ setSandboxId(sandboxId: string): void;+}++export interface AgentRemoteMcpToolTrace {+ setOutput(output: string): void;+ setNumberOfTools(count: number): void;+}++export interface AgentTracing {+ withInitSpan<T>(operation: () => Promise<T>): Promise<T>;++ startRootSpan(input: string): AgentExecutionTrace;++ withLocalToolSpan<T>(+ input: {+ displayName: string;+ toolName: string;+ input?: string | undefined;+ enabled: boolean;+ },+ operation: (span: AgentLocalToolTrace) => Promise<T>,+ ): Promise<T>;++ // Span for a remote (url-based) MCP operation. `serverUrl` must already be redacted (no secrets).+ withRemoteMcpToolSpan<T>(+ input: {+ // MCP method: 'initialize' | 'tools/list' | 'tools/call'.+ method: string;+ serverName: string;+ serverId: string;+ serverUrl: string;+ toolName?: string | undefined;+ input?: string | undefined;+ enabled: boolean;+ },+ operation: (span: AgentRemoteMcpToolTrace) => Promise<T>,+ ): Promise<T>;+}diff --git a/packages/harness/src/core/tracing/NoopAgentTracing.ts b/packages/harness/src/core/tracing/NoopAgentTracing.tsnew file mode 100644index 000000000..cc816988d--- /dev/null+++ b/packages/harness/src/core/tracing/NoopAgentTracing.ts@@ -0,0 +1,75 @@+import type { AgentThreadMetric } from '../llm/metrics';+import type { AgentExecutionTrace, AgentLocalToolTrace, AgentRemoteMcpToolTrace, AgentTracing } from './AgentTracing';++class NoopAgentExecutionTrace implements AgentExecutionTrace {+ runInContext<T>(operation: () => T): T {+ return operation();+ }++ startSubAgent(_name: string, _input: string): AgentExecutionTrace {+ return this;+ }++ setOutput(_output: string): void {}++ setMetrics(_metrics: AgentThreadMetric): void {}++ setError(_error: unknown): void {}++ setSuccess(): void {}++ end(): void {}+}++class NoopAgentLocalToolTrace implements AgentLocalToolTrace {+ setOutput(_output: string): void {}++ setSandboxId(_sandboxId: string): void {}+}++class NoopAgentRemoteMcpToolTrace implements AgentRemoteMcpToolTrace {+ setOutput(_output: string): void {}++ setNumberOfTools(_count: number): void {}+}++const NOOP_EXECUTION_TRACE = new NoopAgentExecutionTrace();+const NOOP_LOCAL_TOOL_TRACE = new NoopAgentLocalToolTrace();+const NOOP_REMOTE_MCP_TOOL_TRACE = new NoopAgentRemoteMcpToolTrace();++export const NOOP_AGENT_TRACING: AgentTracing = {+ async withInitSpan<T>(operation: () => Promise<T>): Promise<T> {+ return operation();+ },++ startRootSpan(_input: string): AgentExecutionTrace {+ return NOOP_EXECUTION_TRACE;+ },++ async withLocalToolSpan<T>(+ _input: {+ displayName: string;+ toolName: string;+ input?: string | undefined;+ enabled: boolean;+ },+ operation: (span: AgentLocalToolTrace) => Promise<T>,+ ): Promise<T> {+ return operation(NOOP_LOCAL_TOOL_TRACE);+ },++ async withRemoteMcpToolSpan<T>(+ _input: {+ method: string;+ serverName: string;+ serverId: string;+ serverUrl: string;+ toolName?: string | undefined;+ input?: string | undefined;+ enabled: boolean;+ },+ operation: (span: AgentRemoteMcpToolTrace) => Promise<T>,+ ): Promise<T> {+ return operation(NOOP_REMOTE_MCP_TOOL_TRACE);+ },+};diff --git a/packages/harness/src/core/util/abort.ts b/packages/harness/src/core/util/abort.tsnew file mode 100644index 000000000..97e884cc4--- /dev/null+++ b/packages/harness/src/core/util/abort.ts@@ -0,0 +1,8 @@+export function onSignalAbort(signal: AbortSignal | undefined, callback: () => void): void {+ if (!signal) return;+ if (signal.aborted) {+ callback();+ return;+ }+ signal.addEventListener('abort', callback, { once: true });+}diff --git a/packages/harness/src/core/util/errorLogFields.ts b/packages/harness/src/core/util/errorLogFields.tsnew file mode 100644index 000000000..da955f705--- /dev/null+++ b/packages/harness/src/core/util/errorLogFields.ts@@ -0,0 +1,11 @@+export interface ErrorLogFields {+ error: string;+ stack?: string | undefined;+}++export function extractErrorLogFields(error: unknown): ErrorLogFields {+ if (error instanceof Error) {+ return { error: error.message, stack: error.stack };+ }+ return { error: String(error) };+}diff --git a/packages/harness/src/core/util/promiseUtils.ts b/packages/harness/src/core/util/promiseUtils.tsnew file mode 100644index 000000000..d1fbba50d--- /dev/null+++ b/packages/harness/src/core/util/promiseUtils.ts@@ -0,0 +1,55 @@+import type { Logger } from 'winston';+import { extractErrorLogFields } from './errorLogFields';++export class PromiseTimeoutError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'PromiseTimeoutError';+ }+}++export function withTimeout<T>(p: Promise<T>, ms: number, label?: string): Promise<T> {+ let timer: ReturnType<typeof setTimeout>;++ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new PromiseTimeoutError(label ? `Timed out after ${ms}ms (${label})` : `Timed out after ${ms}ms`)),+ ms,+ );+ });++ return Promise.race([p, timeout]).finally(() => {+ clearTimeout(timer);+ });+}++export async function* mergeAsyncGenerators<T>(+ generators: AsyncGenerator<T>[],+ logger: Logger,+): AsyncGenerator<T, void, unknown> {+ type PendingResult = { idx: number; result: IteratorResult<T, void> };+ const pending = new Map<number, Promise<PendingResult>>();++ const getNextIteration = (idx: number): Promise<PendingResult> => {+ const nextPromise = generators[idx]!.next().then(result => ({ idx, result }));+ nextPromise.catch(error => {+ logger.error(`Unexpected error in mergeAsyncGenerators generator ${idx}`, extractErrorLogFields(error));+ });+ return nextPromise;+ };++ for (let i = 0; i < generators.length; i++) {+ pending.set(i, getNextIteration(i));+ }++ while (pending.size > 0) {+ const { idx, result } = await Promise.race(pending.values());+ if (result.done) {+ pending.delete(idx);+ continue;+ }++ yield result.value;+ pending.set(idx, getNextIteration(idx));+ }+}diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.tsnew file mode 100644index 000000000..579fd4e3e--- /dev/null+++ b/packages/harness/src/index.ts@@ -0,0 +1,6 @@+/**+ * Root barrel for @truefoundry/utils.+ * Namespaced to avoid colliding event-schema exports between layers.+ */+export * as core from './core';+export * as agentSession from './agentSession';diff --git a/packages/harness/tests/agentSession/capabilityState.test.ts b/packages/harness/tests/agentSession/capabilityState.test.tsnew file mode 100644index 000000000..f2e427663--- /dev/null+++ b/packages/harness/tests/agentSession/capabilityState.test.ts@@ -0,0 +1,228 @@+/**+ * plan-migration proof: tfy.plan-shaped capability fixture over InMemorySessionStore.+ * Does not migrate private Plan / overwriteAgentPlan — gateway adoption is out of scope.+ */+import type { Logger } from 'winston';+import { MAIN_THREAD_ID } from '../../src/agentSession/models/TurnRecord';+import { EventType } from '../../src/agentSession/schemas/events';+import { Sessions } from '../../src/agentSession/Sessions';+import { InMemorySessionStore } from '../../src/agentSession/store/InMemorySessionStore';+import type { AgentCapability } from '../../src/core/capabilities/AgentCapability';+import type { AgentContextProcessorOutput } from '../../src/core/capabilities/AgentContextProcessor';+import { AgentThread } from '../../src/core/runtime/AgentThread';+import { InternalEventType } from '../../src/core/runtime/AgentThread.types';+import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';+import { emptyLlmStream, makeAgentSpec, makeMockILLM, makeSilentLogger, makeTestResolver } from './testHelpers';++type PlanState = { todo: Array<{ title: string; description: string; status: string }> };++function makePlanShapedCapability(options: {+ enabled: boolean;+ emitState?: PlanState;+ onLoad?: (state: unknown) => void;+}): AgentCapability {+ const emitState = options.emitState;+ const processor = {+ async *processPreLLM(): AsyncGenerator<AgentContextProcessorOutput> {+ if (!options.enabled || !emitState) return;+ yield {+ type: InternalEventType.CAPABILITY_STATE,+ key: 'tfy.plan',+ state: emitState,+ };+ },+ };+ return {+ ...(options.enabled+ ? {+ preLLMProcessors: [processor],+ state: {+ key: 'tfy.plan',+ load(state: unknown) {+ options.onLoad?.(state);+ },+ },+ }+ : {}),+ };+}++describe('capability_state (tfy.plan fixture)', () => {+ const tenant = 'tenant-1';++ it('multi-turn: emit → persist → hydrate via AgentThread ctor (resolver never loads)', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });++ const planV1: PlanState = {+ todo: [{ title: 'step', description: 'do it', status: 'wip' }],+ };+ let loads: unknown[] = [];++ const turn1 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'start' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({+ extraCapabilities: [+ makePlanShapedCapability({+ enabled: true,+ emitState: planV1,+ onLoad: s => loads.push(s),+ }),+ ],+ }),+ });+ for await (const _ of turn1.stream()) {+ // drain+ }+ const stored1 = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn1.id,+ });+ expect(stored1?.snapshot.threads[MAIN_THREAD_ID]?.capability_state?.['tfy.plan']).toEqual(planV1);+ // First turn: no prior state to load+ expect(loads).toHaveLength(0);++ loads = [];+ const turn2 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'continue' }],+ previous_turn_id: 'auto',+ signal: new AbortController().signal,+ resolver: makeTestResolver({+ extraCapabilities: [+ makePlanShapedCapability({+ enabled: true,+ // No emit — prove hydration alone+ onLoad: s => loads.push(s),+ }),+ ],+ }),+ });+ // Hydration happens in run() when threads are built (before stream).+ expect(loads).toEqual([planV1]);+ for await (const _ of turn2.stream()) {+ // drain+ }+ const stored2 = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn2.id,+ });+ // Unchanged state carries via toSnapshot with zero CAPABILITY_STATE writes this turn.+ expect(stored2?.snapshot.threads[MAIN_THREAD_ID]?.capability_state?.['tfy.plan']).toEqual(planV1);+ });++ it('capability disabled → unclaimed key dropped + warn; prior turn untouched', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });+ const planV1: PlanState = {+ todo: [{ title: 'step', description: 'do it', status: 'done' }],+ };++ const turn1 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'start' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({+ extraCapabilities: [makePlanShapedCapability({ enabled: true, emitState: planV1 })],+ }),+ });+ for await (const _ of turn1.stream()) {+ // drain+ }++ const logger = makeSilentLogger();+ const warnSpy = jest.spyOn(logger, 'warn');+ const resolver = makeTestResolver({+ extraCapabilities: [makePlanShapedCapability({ enabled: false })],+ });+ // Override logger so AgentThread child warn is observable — wrap resolver to use our logger.+ const wrapped = {+ ...resolver,+ get logger(): Logger {+ return logger;+ },+ createTracing: () => resolver.createTracing(),+ resolveSandbox: (input: Parameters<typeof resolver.resolveSandbox>[0]) => resolver.resolveSandbox(input),+ resolveAgentDefinition: (input: Parameters<typeof resolver.resolveAgentDefinition>[0]) =>+ resolver.resolveAgentDefinition(input),+ close: () => resolver.close(),+ };++ const turn3 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'no plan' }],+ previous_turn_id: 'auto',+ signal: new AbortController().signal,+ resolver: wrapped,+ });+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Dropping unclaimed capability_state key 'tfy.plan'"));++ for await (const _ of turn3.stream()) {+ // drain+ }+ const prior = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn1.id,+ });+ expect(prior?.snapshot.threads[MAIN_THREAD_ID]?.capability_state?.['tfy.plan']).toEqual(planV1);++ const latest = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn3.id,+ });+ expect(latest?.snapshot.threads[MAIN_THREAD_ID]?.capability_state?.['tfy.plan']).toBeUndefined();+ });++ it('emit with undeclared key surfaces capability_state_error (emit-key guard)', async () => {+ const badCapability: AgentCapability = {+ state: { key: 'tfy.plan', load: () => {} },+ preLLMProcessors: [+ {+ async *processPreLLM(): AsyncGenerator<AgentContextProcessorOutput> {+ yield {+ type: InternalEventType.CAPABILITY_STATE,+ key: 'tfy.other',+ state: {},+ };+ },+ },+ ],+ };+ const thread = new AgentThread({+ definition: {+ model: 'test-model',+ modelClient: makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) }),+ },+ threadId: MAIN_THREAD_ID,+ title: 'main',+ capabilities: [badCapability],+ tracing: NOOP_AGENT_TRACING,+ logger: makeSilentLogger(),+ });+ for await (const _ of thread.send([{ type: EventType.USER_MESSAGE, content: 'x' }])) {+ // drain send+ }+ let errorMessage: string | undefined;+ for await (const event of thread.execute({ signal: new AbortController().signal })) {+ if (event.type === InternalEventType.AGENT_DONE && event.status === 'error') {+ errorMessage = event.error;+ }+ }+ expect(errorMessage).toContain('CAPABILITY_STATE');+ expect(errorMessage).toContain('tfy.other');+ });+});diff --git a/packages/harness/tests/agentSession/inMemorySessionStore.test.ts b/packages/harness/tests/agentSession/inMemorySessionStore.test.tsnew file mode 100644index 000000000..8110664ba--- /dev/null+++ b/packages/harness/tests/agentSession/inMemorySessionStore.test.ts@@ -0,0 +1,628 @@+import {+ MAIN_THREAD_ID,+ TURN_SERIALIZATION_VERSION,+} from '../../src/agentSession/models/TurnRecord';+import { CancellationReason } from '../../src/agentSession/schemas/turn';+import type { ISessionStore } from '../../src/agentSession/store/ISessionStore';+import { InMemorySessionStore } from '../../src/agentSession/store/InMemorySessionStore';+import {+ SessionStoreConflictError,+ SessionStoreNotFoundError,+} from '../../src/agentSession/store/SessionStoreErrors';+import { EventType, newEventId } from '../../src/core/events/eventSchemas';+import { getEmptyUsage } from '../../src/core/llm/LLMTypes';+import { makeAgentSpec, makeModelMessageEvent, makeRunningTurnRecord, makeTurnCreatedEvent } from './testHelpers';++/** Store contract suite — factory-injected so other backends can reuse it. */+function runStoreContractSuite(createStore: () => ISessionStore) {+ const tenant = 't1';+ const sessionId = 's1';++ async function seedSession(store: ISessionStore, agentSpec = makeAgentSpec()) {+ await store.createSession({+ tenant_name: tenant,+ session_id: sessionId,+ agent_spec: agentSpec,+ });+ }++ describe('session CRUD + activity', () => {+ it('createSession hydrates agent_spec and sets last_activity_timestamp_ms', async () => {+ const store = createStore();+ const before = Date.now();+ await seedSession(store);+ const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(session).toBeDefined();+ expect(session!.agent_spec.model.name).toBe('test-model');+ expect(session!.last_activity_timestamp_ms).toBeGreaterThanOrEqual(before);+ expect(session!.title).toBeNull();+ });++ it('getSession does not bump last_activity_timestamp_ms', async () => {+ const store = createStore();+ await seedSession(store);+ const first = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ await new Promise(r => setTimeout(r, 5));+ const second = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(second!.last_activity_timestamp_ms).toBe(first!.last_activity_timestamp_ms);+ });++ it('updateSession patches only provided fields and bumps activity', async () => {+ const store = createStore();+ await seedSession(store);+ const before = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ await new Promise(r => setTimeout(r, 5));+ const nextSpec = makeAgentSpec({ instructions: 'updated' });+ await store.updateSession({+ tenant_name: tenant,+ session_id: sessionId,+ agent_spec: nextSpec,+ title: 'Hello',+ });+ const after = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(after!.agent_spec.instructions).toBe('updated');+ expect(after!.title).toBe('Hello');+ expect(after!.last_activity_timestamp_ms).toBeGreaterThan(before!.last_activity_timestamp_ms);+ });++ it('createSession conflict when session already exists', async () => {+ const store = createStore();+ await seedSession(store);+ await expect(seedSession(store)).rejects.toBeInstanceOf(SessionStoreConflictError);+ });+ });++ describe('listSessions', () => {+ async function seedThreeSessions(store: ISessionStore) {+ for (const id of ['sa', 'sb', 'sc']) {+ await store.createSession({ tenant_name: tenant, session_id: id, agent_spec: makeAgentSpec() });+ await new Promise(r => setTimeout(r, 2));+ }+ }++ it('lists newest-first by default, asc on request, scoped to tenant', async () => {+ const store = createStore();+ await seedThreeSessions(store);+ await store.createSession({ tenant_name: 'other', session_id: 'sx', agent_spec: makeAgentSpec() });++ const desc = await store.listSessions({ tenant_name: tenant, limit: 10 });+ expect(desc.data.map(s => s.session_id)).toEqual(['sc', 'sb', 'sa']);++ const asc = await store.listSessions({ tenant_name: tenant, limit: 10, order: 'asc' });+ expect(asc.data.map(s => s.session_id)).toEqual(['sa', 'sb', 'sc']);+ });++ it('paginates with next/previous tokens and filters by created_at bounds', async () => {+ const store = createStore();+ await seedThreeSessions(store);++ const first = await store.listSessions({ tenant_name: tenant, limit: 2 });+ expect(first.data).toHaveLength(2);+ expect(first.pagination.next_page_token).toBeDefined();+ const second = await store.listSessions({+ tenant_name: tenant,+ limit: 2,+ page_token: first.pagination.next_page_token,+ });+ expect(second.data.map(s => s.session_id)).toEqual(['sa']);+ expect(second.pagination.next_page_token).toBeUndefined();++ const all = await store.listSessions({ tenant_name: tenant, limit: 10, order: 'asc' });+ const middleSession = all.data[1];+ if (!middleSession) throw new Error('expected middle session in list');+ const middleCreatedAt = middleSession.created_at;+ const bounded = await store.listSessions({+ tenant_name: tenant,+ limit: 10,+ order: 'asc',+ start_timestamp: middleCreatedAt,+ end_timestamp: middleCreatedAt,+ });+ expect(bounded.data.map(s => s.session_id)).toEqual(['sb']);+ });+ });++ describe('createTurn', () => {+ it('atomically links last_turn_id and bumps activity', async () => {+ const store = createStore();+ await seedSession(store);+ const before = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ await new Promise(r => setTimeout(r, 5));+ const turn = makeRunningTurnRecord({ sessionId, turnId: 'turn-1' });+ await store.createTurn({ tenant_name: tenant, turn });+ const after = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(after!.last_turn_id).toBe('turn-1');+ expect(after!.last_activity_timestamp_ms).toBeGreaterThan(before!.last_activity_timestamp_ms);+ });++ it('update_session_title_if_not_exist sets once and never overwrites', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ update_session_title_if_not_exist: 'First title',+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 'turn-2',+ previousTurnId: 'turn-1',+ firstTurnId: 'turn-1',+ }),+ update_session_title_if_not_exist: 'Second title',+ });+ const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(session!.title).toBe('First title');+ });++ it('rejects unknown previous_turn_id with not-found', async () => {+ const store = createStore();+ await seedSession(store);+ await expect(+ store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 'turn-2',+ previousTurnId: 'missing',+ }),+ }),+ ).rejects.toBeInstanceOf(SessionStoreNotFoundError);+ });++ it('fork from any existing turn succeeds and advances tip', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 'turn-2',+ previousTurnId: 'turn-1',+ firstTurnId: 'turn-1',+ }),+ });+ // Fork from turn-1 (not the tip).+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 'turn-fork',+ previousTurnId: 'turn-1',+ firstTurnId: 'turn-1',+ }),+ });+ const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(session!.last_turn_id).toBe('turn-fork');+ });++ it('new root turn (no previous_turn_id) succeeds on non-empty session', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-root-2' }),+ });+ const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(session!.last_turn_id).toBe('turn-root-2');+ });++ it('concurrent createTurn forking the same tip: both succeed', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'tip' }),+ });+ const a = makeRunningTurnRecord({+ sessionId,+ turnId: 'turn-a',+ previousTurnId: 'tip',+ firstTurnId: 'tip',+ });+ const b = makeRunningTurnRecord({+ sessionId,+ turnId: 'turn-b',+ previousTurnId: 'tip',+ firstTurnId: 'tip',+ });+ const results = await Promise.allSettled([+ store.createTurn({ tenant_name: tenant, turn: a }),+ store.createTurn({ tenant_name: tenant, turn: b }),+ ]);+ expect(results.every(r => r.status === 'fulfilled')).toBe(true);+ const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(['turn-a', 'turn-b']).toContain(session!.last_turn_id);+ const turns = await store.listTurns({+ tenant_name: tenant,+ session_id: sessionId,+ limit: 10,+ });+ expect(turns.data.map(t => t.turn_id).sort()).toEqual(['tip', 'turn-a', 'turn-b']);+ });+ });++ describe('updateTurnState', () => {+ it('allows running → done and rejects second terminal (first-terminal-wins)', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.updateTurnState({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ state: {+ status: 'done',+ output: null,+ required_actions: [],+ completed_at: new Date().toISOString(),+ },+ });+ await expect(+ store.updateTurnState({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ state: {+ status: 'cancelled',+ reason: CancellationReason.ClientCancelled,+ completed_at: new Date().toISOString(),+ },+ }),+ ).rejects.toBeInstanceOf(SessionStoreConflictError);+ });++ it('missing turn → not found', async () => {+ const store = createStore();+ await seedSession(store);+ await expect(+ store.updateTurnState({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'missing',+ state: {+ status: 'done',+ output: null,+ required_actions: [],+ completed_at: new Date().toISOString(),+ },+ }),+ ).rejects.toBeInstanceOf(SessionStoreNotFoundError);+ });+ });++ describe('events + threads + capability_state', () => {+ it('appendToEvents preserves order including lifecycle rows', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ const created = makeTurnCreatedEvent('turn-1');+ const model = makeModelMessageEvent();+ await store.appendToEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ events: [created, model],+ });+ const { data } = await store.listTurnEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ limit: 10,+ });+ expect(data.map(e => e.type)).toEqual(['turn.created', EventType.MODEL_MESSAGE]);+ });++ it('add/remove threads and append/overwrite context', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.addThreads({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ threads: [+ {+ thread_id: 'child',+ context: [],+ current_context_usage: getEmptyUsage(),+ parent: { thread_id: MAIN_THREAD_ID, tool_call_id: 'tc1' },+ agent_info: { type: 'dynamic', name: 'child', input: 'do work' },+ },+ ],+ });+ await store.appendToThreadContext({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ thread_id: 'child',+ context: [{ role: 'user', content: 'hello' }],+ });+ let turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });+ expect(turn?.snapshot.threads['child']?.context).toHaveLength(1);++ await store.overwriteThreadContext({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ event: {+ type: EventType.AGENT_CONTEXT_OVERWRITE,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: 'child',+ reason: 'compaction',+ context: [{ role: 'user', content: 'replaced' }],+ current_context_usage: getEmptyUsage(),+ compaction_llm_usage: getEmptyUsage(),+ },+ });+ turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });+ expect(turn?.snapshot.threads['child']?.context).toEqual([{ role: 'user', content: 'replaced' }]);++ await store.removeThreads({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ thread_ids: ['child'],+ });+ turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });+ expect(turn?.snapshot.threads['child']).toBeUndefined();+ });++ it('patchThreadCapabilityState is LWW per key', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.patchThreadCapabilityState({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ thread_id: MAIN_THREAD_ID,+ key: 'tfy.plan',+ state: { v: 1 },+ });+ await store.patchThreadCapabilityState({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ thread_id: MAIN_THREAD_ID,+ key: 'tfy.plan',+ state: { v: 2 },+ });+ const turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });+ expect(turn?.snapshot.threads[MAIN_THREAD_ID]?.capability_state).toEqual({ 'tfy.plan': { v: 2 } });+ });++ it('patchMCPServers and patchSandboxInfo', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.patchMCPServers({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ mcp_servers: [{ id: 'svc', name: 'svc', session_id: 'mcp-1', transport_type: 'streamable-http' }],+ });+ await store.patchSandboxInfo({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ sandbox_info: { sandbox_id: 'sbx-1' },+ });+ const turn = await store.getTurn({ tenant_name: tenant, session_id: sessionId, turn_id: 'turn-1' });+ expect(turn?.snapshot.mcp_servers?.['svc']?.session_id).toBe('mcp-1');+ expect(turn!.snapshot.sandbox_info?.sandbox_id).toBe('sbx-1');+ });+ });++ describe('pagination', () => {+ it('listTurns paginates with opaque tokens', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 't2',+ previousTurnId: 't1',+ firstTurnId: 't1',+ }),+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 't3',+ previousTurnId: 't2',+ firstTurnId: 't1',+ }),+ });+ const page1 = await store.listTurns({+ tenant_name: tenant,+ session_id: sessionId,+ limit: 2,+ });+ expect(page1.data.map(t => t.turn_id)).toEqual(['t1', 't2']);+ expect(page1.pagination.next_page_token).toBeDefined();+ const page2 = await store.listTurns({+ tenant_name: tenant,+ session_id: sessionId,+ limit: 2,+ page_token: page1.pagination.next_page_token,+ });+ expect(page2.data.map(t => t.turn_id)).toEqual(['t3']);+ });++ it('listTurnEvents supports desc order', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 'turn-1' }),+ });+ await store.appendToEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ events: [makeTurnCreatedEvent('turn-1'), makeModelMessageEvent()],+ });+ const { data } = await store.listTurnEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 'turn-1',+ limit: 10,+ order: 'desc',+ });+ expect(data[0]?.type).toBe(EventType.MODEL_MESSAGE);+ });++ it('listSessionEvents includes running turns and is newest-first', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),+ });+ await store.appendToEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 't1',+ events: [makeTurnCreatedEvent('t1')],+ });+ await store.updateTurnState({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 't1',+ state: {+ status: 'done',+ output: null,+ required_actions: [],+ completed_at: new Date().toISOString(),+ },+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({+ sessionId,+ turnId: 't2',+ previousTurnId: 't1',+ firstTurnId: 't1',+ }),+ });+ await store.appendToEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: 't2',+ events: [makeTurnCreatedEvent('t2')],+ });+ // t2 still running — must appear in the feed.+ const { data } = await store.listSessionEvents({+ tenant_name: tenant,+ session_id: sessionId,+ limit: 10,+ });+ expect(data.map(row => row.turn_id)).toEqual(['t2', 't1']);+ expect(data.every(row => row.event.type === 'turn.created')).toBe(true);+ });++ it('listSessionEvents with last_turn_id scopes to that branch, excluding fork siblings', async () => {+ const store = createStore();+ await seedSession(store);+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 't1' }),+ });+ // Two forks off t1; the sibling is created BEFORE the anchor, so a+ // creation-order prefix would wrongly include it.+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 't2-sibling', previousTurnId: 't1', firstTurnId: 't1' }),+ });+ await store.createTurn({+ tenant_name: tenant,+ turn: makeRunningTurnRecord({ sessionId, turnId: 't2-anchor', previousTurnId: 't1', firstTurnId: 't1' }),+ });+ for (const turnId of ['t1', 't2-sibling', 't2-anchor']) {+ await store.appendToEvents({+ tenant_name: tenant,+ session_id: sessionId,+ turn_id: turnId,+ events: [makeTurnCreatedEvent(turnId)],+ });+ }+ const { data } = await store.listSessionEvents({+ tenant_name: tenant,+ session_id: sessionId,+ limit: 10,+ last_turn_id: 't2-anchor',+ });+ expect(data.map(row => row.turn_id)).toEqual(['t2-anchor', 't1']);++ await expect(+ store.listSessionEvents({+ tenant_name: tenant,+ session_id: sessionId,+ limit: 10,+ last_turn_id: 'missing',+ }),+ ).rejects.toBeInstanceOf(SessionStoreNotFoundError);+ });+ });++ describe('deep-copy boundary', () => {+ it('mutating a returned session does not mutate the store', async () => {+ const store = createStore();+ await seedSession(store);+ const session = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ session!.agent_spec.instructions = 'mutated';+ const again = await store.getSession({ tenant_name: tenant, session_id: sessionId });+ expect(again!.agent_spec.instructions).toBe('You are a test agent.');+ });+ });++ describe('no SSE surface', () => {+ it('ISessionStore has no subscribe* members', () => {+ const store = createStore();+ const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(store)).concat(Object.keys(store));+ expect(keys.some(k => k.startsWith('subscribe'))).toBe(false);+ });+ });++ // Keep serialization_version visible in fixtures+ it('turn records use TURN_SERIALIZATION_VERSION', () => {+ expect(TURN_SERIALIZATION_VERSION).toBe(1);+ });+}++describe('InMemorySessionStore (ISessionStore contract)', () => {+ runStoreContractSuite(() => new InMemorySessionStore());+});diff --git a/packages/harness/tests/agentSession/sessions.test.ts b/packages/harness/tests/agentSession/sessions.test.tsnew file mode 100644index 000000000..df62c844a--- /dev/null+++ b/packages/harness/tests/agentSession/sessions.test.ts@@ -0,0 +1,189 @@+import { EventType } from '../../src/agentSession/schemas/events';+import { Sessions } from '../../src/agentSession/Sessions';+import { InMemorySessionStore } from '../../src/agentSession/store/InMemorySessionStore';+import { makeAgentSpec, makeTestResolver } from './testHelpers';++describe('Sessions / SessionHandle / TurnHandle (storage + run)', () => {+ const tenant = 'tenant-1';++ it('create/get hydrates agent_spec', async () => {+ const store = new InMemorySessionStore<{ tag: string }>();+ const sessions = new Sessions<{ tag: string }>({ sessionStore: store });+ const created = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec({ instructions: 'hydrate-me' }),+ custom: { tag: 'a' },+ });+ expect(created.agent_spec.instructions).toBe('hydrate-me');+ expect(created.custom).toEqual({ tag: 'a' });++ const loaded = await sessions.get({ tenant_name: tenant, session_id: 's1' });+ expect(loaded?.agent_spec.instructions).toBe('hydrate-me');+ expect(loaded?.session_id).toBe('s1');+ });++ it('run() happy path commits a running turn without executing', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ update_session_title_if_not_exist: 'From first message',+ });+ expect(turn.state.status).toBe('running');+ expect(turn.input).toHaveLength(1);++ const stored = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn.id,+ });+ expect(stored?.state.status).toBe('running');+ const sessionRecord = await store.getSession({ tenant_name: tenant, session_id: 's1' });+ expect(sessionRecord?.title).toBe('From first message');+ expect(sessionRecord?.last_turn_id).toBe(turn.id);+ });++ it('custom value vs merge-fn', async () => {+ const store = new InMemorySessionStore<{ tag: string }, { n: number }>();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });+ const t1 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'one' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver<{ n: number }>(),+ custom: { n: 1 },+ });+ expect(t1.custom).toEqual({ n: 1 });++ const t2 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'two' }],+ previous_turn_id: 'auto',+ signal: new AbortController().signal,+ resolver: makeTestResolver<{ n: number }>(),+ custom: prev => ({ n: (prev?.n ?? 0) + 10 }),+ });+ expect(t2.custom).toEqual({ n: 11 });+ });++ it('previous_turn_id null creates a new root on a non-empty session', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });+ const first = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'one' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ });+ for await (const _ of first.stream()) {+ // drain+ }+ const root2 = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'fresh root' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ });+ expect(root2.previous_turn_id).toBeUndefined();+ const sessionRecord = await store.getSession({ tenant_name: tenant, session_id: 's1' });+ expect(sessionRecord?.last_turn_id).toBe(root2.id);+ });++ it('send/validation failure in run() persists no turn', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });+ await expect(+ session.run({+ // Mixed batch — rejected by SessionHandle.toSendBatch / orchestrator validation path.+ input: [+ { type: EventType.USER_MESSAGE, content: 'hi' },+ {+ type: EventType.USER_TOOL_APPROVAL,+ thread_id: 'main',+ tool_call_id: 'tc1',+ approval: { status: 'allow' },+ },+ ],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ }),+ ).rejects.toThrow();+ const turns = await store.listTurns({+ tenant_name: tenant,+ session_id: 's1',+ limit: 10,+ });+ expect(turns.data).toHaveLength(0);+ const sessionRecord = await store.getSession({ tenant_name: tenant, session_id: 's1' });+ expect(sessionRecord?.last_turn_id).toBeUndefined();+ });++ it('run() failure closes the resolver; success defers close() to stream()', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec(),+ });++ // Failure path: resources acquired before the throw must be released.+ const closeOnFailure = jest.fn().mockResolvedValue(undefined);+ await expect(+ session.run({+ // Mixed batch — rejected after sandbox/thread resolution.+ input: [+ { type: EventType.USER_MESSAGE, content: 'hi' },+ {+ type: EventType.USER_TOOL_APPROVAL,+ thread_id: 'main',+ tool_call_id: 'tc1',+ approval: { status: 'allow' },+ },+ ],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({ close: closeOnFailure }),+ }),+ ).rejects.toThrow();+ expect(closeOnFailure).toHaveBeenCalledTimes(1);++ // Success path: run() must NOT close — TurnHandle.stream()'s finally owns it.+ const closeOnSuccess = jest.fn().mockResolvedValue(undefined);+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({ close: closeOnSuccess }),+ });+ expect(closeOnSuccess).not.toHaveBeenCalled();+ for await (const _ of turn.stream()) {+ // drain+ }+ expect(closeOnSuccess).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/harness/tests/agentSession/testHelpers.ts b/packages/harness/tests/agentSession/testHelpers.tsnew file mode 100644index 000000000..436e2322a--- /dev/null+++ b/packages/harness/tests/agentSession/testHelpers.ts@@ -0,0 +1,177 @@+import type { ITurnResourceResolver } from '../../src/agentSession/ITurnResourceResolver';+import {+ MAIN_THREAD_ID,+ TURN_SERIALIZATION_VERSION,+ type TurnRecord,+} from '../../src/agentSession/models/TurnRecord';+import { AgentSpecSchema, type AgentSpec } from '../../src/agentSession/schemas/agentSpec';+import { TurnResourceResolver } from '../../src/agentSession/TurnResourceResolver';+import type { AgentCapability } from '../../src/core/capabilities/AgentCapability';+import { EventType, newEventId } from '../../src/core/events/eventSchemas';+import type {+ ExtendedChatCompletionChunk,+ RawAssistantMessageWithUsage,+} from '../../src/core/llm/LLMTypes';+import { getEmptyUsage } from '../../src/core/llm/LLMTypes';+import type { Sandbox } from '../../src/core/sandbox/Sandbox';+import { makeMockILLM, makeSilentLogger } from '../core/harnessMocks';++export { makeMockILLM, makeSilentLogger };++/** Minimal AgentSpec for session/turn tests — interactive builtins off. */+export function makeAgentSpec(+ overrides: {+ instructions?: string;+ model?: { name: string };+ config?: {+ iteration_limit?: number;+ sandbox?: { enabled: boolean; file_downloads?: boolean };+ ask_user_questions?: { enabled?: boolean };+ dynamic_sub_agents?: { enabled?: boolean };+ generative_ui?: { enabled?: boolean };+ context_management?: {+ compaction?: { enabled?: boolean; compaction_threshold_tokens?: number };+ large_tool_response?: { enabled?: boolean };+ };+ };+ } = {},+): AgentSpec {+ return AgentSpecSchema.parse({+ model: overrides.model ?? { name: 'test-model' },+ instructions: overrides.instructions ?? 'You are a test agent.',+ config: {+ iteration_limit: 5,+ ask_user_questions: { enabled: false },+ dynamic_sub_agents: { enabled: false },+ context_management: {+ compaction: { enabled: false },+ large_tool_response: { enabled: false },+ },+ ...overrides.config,+ },+ });+}++export async function* emptyLlmStream(): AsyncGenerator<+ ExtendedChatCompletionChunk,+ RawAssistantMessageWithUsage,+ unknown+> {+ yield {+ id: 'chunk-1',+ object: 'chat.completion.chunk',+ created: 0,+ model: 'test-model',+ choices: [{ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],+ } as ExtendedChatCompletionChunk;+ return {+ output: { role: 'assistant', content: 'ok' },+ usage: getEmptyUsage(),+ finish_reason: 'stop',+ };+}++export function makeTestResolver<TTurnCustom extends object = Record<string, never>>(options?: {+ extraCapabilities?: AgentCapability[];+ sandbox?: Sandbox;+ close?: () => Promise<void>;+}): ITurnResourceResolver<TTurnCustom> {+ const llm = makeMockILLM({+ create: jest.fn().mockImplementation(() => emptyLlmStream()),+ });+ const base = new TurnResourceResolver<TTurnCustom>({+ llm: () => llm,+ mcp: async name => {+ throw new Error(`unexpected mcp lookup: ${name}`);+ },+ logger: makeSilentLogger(),+ ...(options?.sandbox+ ? {+ sandboxProvider: async () => {+ if (!options.sandbox) {+ throw new Error('sandbox missing');+ }+ return options.sandbox;+ },+ }+ : {}),+ });++ if (!options?.extraCapabilities && !options?.close && !options?.sandbox) {+ return base;+ }++ const wrapped: ITurnResourceResolver<TTurnCustom> = {+ get logger() {+ return base.logger;+ },+ createTracing: () => base.createTracing(),+ resolveSandbox: input => base.resolveSandbox(input),+ resolveAgentDefinition: async input => {+ const resolved = await base.resolveAgentDefinition(input);+ return {+ ...resolved,+ extraCapabilities: [...(resolved.extraCapabilities ?? []), ...(options?.extraCapabilities ?? [])],+ };+ },+ close: async () => {+ if (options?.close) {+ await options.close();+ }+ await base.close();+ },+ };+ return wrapped;+}++export function makeRunningTurnRecord(input: {+ sessionId: string;+ turnId: string;+ previousTurnId?: string;+ firstTurnId?: string;+}): TurnRecord {+ const now = new Date().toISOString();+ return {+ serialization_version: TURN_SERIALIZATION_VERSION,+ turn_id: input.turnId,+ session_id: input.sessionId,+ first_turn_id: input.firstTurnId ?? input.turnId,+ ancestor_ids: input.previousTurnId ? [input.previousTurnId] : [],+ ...(input.previousTurnId !== undefined ? { previous_turn_id: input.previousTurnId } : {}),+ state: { status: 'running' },+ input: [],+ snapshot: {+ threads: {+ [MAIN_THREAD_ID]: {+ thread_id: MAIN_THREAD_ID,+ context: [],+ current_context_usage: getEmptyUsage(),+ },+ },+ },+ created_at: now,+ updated_at: now,+ };+}++export function makeTurnCreatedEvent(turnId: string) {+ return {+ type: 'turn.created' as const,+ id: newEventId(),+ turn_id: turnId,+ previous_turn_id: null,+ state: { status: 'running' as const },+ created_at: new Date().toISOString(),+ thread_id: null,+ };+}++export function makeModelMessageEvent() {+ return {+ type: EventType.MODEL_MESSAGE,+ id: newEventId(),+ created_at: new Date().toISOString(),+ thread_id: MAIN_THREAD_ID,+ content: 'hi',+ };+}diff --git a/packages/harness/tests/agentSession/turnStream.test.ts b/packages/harness/tests/agentSession/turnStream.test.tsnew file mode 100644index 000000000..7f90bd2ed--- /dev/null+++ b/packages/harness/tests/agentSession/turnStream.test.ts@@ -0,0 +1,273 @@+import { EventType } from '../../src/agentSession/schemas/events';+import { CancellationReason } from '../../src/agentSession/schemas/turn';+import { Sessions } from '../../src/agentSession/Sessions';+import { InMemorySessionStore } from '../../src/agentSession/store/InMemorySessionStore';+import { TurnResourceResolver } from '../../src/agentSession/TurnResourceResolver';+import { RemoteMCP } from '../../src/core/mcp/RemoteMCP';+import { makeStubPublicSandbox } from '../core/harnessMocks';+import { emptyLlmStream, makeAgentSpec, makeMockILLM, makeSilentLogger, makeTestResolver } from './testHelpers';++describe('TurnHandle.stream()', () => {+ const tenant = 'tenant-1';++ async function createSession() {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: tenant,+ session_id: 's1',+ agent_spec: makeAgentSpec({+ config: {+ sandbox: { enabled: true, file_downloads: true },+ },+ }),+ });+ return { store, session };+ }++ it('run commits running turn; stream is sole terminal writer → done', async () => {+ const { store, session } = await createSession();+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ });+ expect(turn.state.status).toBe('running');++ const types: string[] = [];+ for await (const event of turn.stream()) {+ types.push(event.type);+ }+ expect(types[0]).toBe(EventType.TURN_CREATED);+ expect(types[types.length - 1]).toBe(EventType.TURN_DONE);+ expect(turn.state.status).toBe('done');++ const { data } = await turn.listEvents({ limit: 50 });+ expect(data.some(e => e.type === EventType.TURN_CREATED)).toBe(true);+ expect(data.some(e => e.type === EventType.TURN_DONE)).toBe(true);++ const stored = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn.id,+ });+ expect(stored?.state.status).toBe('done');+ });++ it('background drain reaches terminal done', async () => {+ const { session } = await createSession();+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ });+ await (async () => {+ for await (const _ of turn.stream()) {+ // drain+ }+ })();+ expect(turn.state.status).toBe('done');+ });++ it('second stream() call throws', async () => {+ const { session } = await createSession();+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver(),+ });+ for await (const _ of turn.stream()) {+ // drain+ }+ await expect(+ (async () => {+ for await (const _ of turn.stream()) {+ // should throw before yielding+ }+ })(),+ ).rejects.toThrow(/single-use/);+ });++ it('consumer break/abandon without abort writes cancelled ClientCancelled', async () => {+ const { store, session } = await createSession();+ let closeCalls = 0;+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({+ close: async () => {+ closeCalls += 1;+ },+ }),+ });+ for await (const event of turn.stream()) {+ expect(event.type).toBe(EventType.TURN_CREATED);+ break;+ }+ expect(turn.state.status).toBe('cancelled');+ if (turn.state.status === 'cancelled') {+ expect(turn.state.reason).toBe(CancellationReason.ClientCancelled);+ }+ expect(closeCalls).toBe(1);+ const stored = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn.id,+ });+ expect(stored?.state.status).toBe('cancelled');+ });++ it('abort mid-drain writes terminal cancelled', async () => {+ const { store, session } = await createSession();+ const controller = new AbortController();+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: controller.signal,+ resolver: makeTestResolver(),+ });+ controller.abort(CancellationReason.ClientCancelled);+ for await (const _ of turn.stream()) {+ // drain+ }+ expect(turn.state.status).toBe('cancelled');+ if (turn.state.status === 'cancelled') {+ expect(turn.state.reason).toBe(CancellationReason.ClientCancelled);+ }+ const stored = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn.id,+ });+ expect(stored?.state.status).toBe('cancelled');+ });++ it('resolver.close() called once in finally; throwing close does not flip terminal state', async () => {+ const { store, session } = await createSession();+ let closeCalls = 0;+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({+ close: async () => {+ closeCalls += 1;+ throw new Error('close boom');+ },+ }),+ });+ for await (const _ of turn.stream()) {+ // drain+ }+ expect(closeCalls).toBe(1);+ expect(turn.state.status).toBe('done');+ const stored = await store.getTurn({+ tenant_name: tenant,+ session_id: 's1',+ turn_id: turn.id,+ });+ expect(stored?.state.status).toBe('done');+ });++ it('TurnResourceResolver.close() closes sandbox handle once and is idempotent', async () => {+ const sandbox = makeStubPublicSandbox();+ const closeSpy = jest.spyOn(sandbox, 'close').mockResolvedValue(undefined);+ const logger = makeSilentLogger();+ const resolver = new TurnResourceResolver({+ llm: () => makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) }),+ mcp: async () => ({ url: 'http://localhost' }),+ sandboxProvider: async () => sandbox,+ logger,+ });+ const { session } = await createSession();+ // Spec already has sandbox.enabled from createSession helper.+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hello' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver,+ });+ for await (const _ of turn.stream()) {+ // drain+ }+ expect(closeSpy).toHaveBeenCalledTimes(1);+ await resolver.close();+ expect(closeSpy).toHaveBeenCalledTimes(1);+ });+});++describe('TurnResourceResolver caches', () => {+ it('getOrCreateToolSource single-flights by id', async () => {+ const logger = makeSilentLogger();+ let creates = 0;+ const resolver = new (class extends TurnResourceResolver {+ async resolveTwice() {+ const create = async () => {+ creates += 1;+ await new Promise(r => setTimeout(r, 10));+ return new RemoteMCP({+ id: 'svc',+ name: 'svc',+ url: 'http://example.invalid',+ headers: {},+ logger,+ tracing: this.createTracing(),+ signal: new AbortController().signal,+ });+ };+ const [a, b] = await Promise.all([+ this.getOrCreateToolSource({ id: 'svc', create }),+ this.getOrCreateToolSource({ id: 'svc', create }),+ ]);+ expect(a).toBe(b);+ }+ })({+ llm: () => makeMockILLM(),+ mcp: async () => ({ url: 'http://example.invalid' }),+ logger,+ });+ await resolver.resolveTwice();+ expect(creates).toBe(1);+ });++ it('resolveSandbox called once per run via SessionHandle.run', async () => {+ const sandbox = makeStubPublicSandbox();+ jest.spyOn(sandbox, 'close').mockResolvedValue(undefined);+ let sandboxCreates = 0;+ const logger = makeSilentLogger();+ const resolver = new TurnResourceResolver({+ llm: () => makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) }),+ mcp: async () => ({ url: 'http://localhost' }),+ sandboxProvider: async () => {+ sandboxCreates += 1;+ return sandbox;+ },+ logger,+ });+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_name: 't',+ session_id: 's',+ agent_spec: makeAgentSpec({+ config: {+ sandbox: { enabled: true, file_downloads: true },+ },+ }),+ });+ const turn = await session.run({+ input: [{ type: EventType.USER_MESSAGE, content: 'hi' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver,+ });+ for await (const _ of turn.stream()) {+ // drain+ }+ expect(sandboxCreates).toBe(1);+ });+});diff --git a/packages/harness/tests/core/connectRemoteMcp.test.ts b/packages/harness/tests/core/connectRemoteMcp.test.tsnew file mode 100644index 000000000..7ada52f38--- /dev/null+++ b/packages/harness/tests/core/connectRemoteMcp.test.ts@@ -0,0 +1,114 @@+import { McpConnectionError } from '../../src/core/errors';+import { connectRemoteMcp } from '../../src/core/mcp/remoteMcpClient';++// Records every transport type client.connect() was attempted with, in order.+const mockConnectAttempts: string[] = [];+// Per-test hook: throw to fail a given transport, return to succeed.+let mockConnectImpl: (type: string) => void = () => {};++jest.mock('@modelcontextprotocol/sdk/client/index.js', () => ({+ Client: class {+ onclose?: () => void;+ onerror?: (e: Error) => void;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ async connect(transport: any): Promise<void> {+ const type = transport.__type as string;+ mockConnectAttempts.push(type);+ mockConnectImpl(type);+ }+ async close(): Promise<void> {}+ async listTools(): Promise<{ tools: [] }> {+ return { tools: [] };+ }+ async callTool(): Promise<{ content: [] }> {+ return { content: [] };+ }+ },+}));++jest.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({+ StreamableHTTPClientTransport: class {+ sessionId?: string;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ constructor(_url: URL, opts?: any) {+ this.sessionId = opts?.sessionId;+ (this as unknown as { __type: string }).__type = 'streamable-http';+ }+ },+}));++jest.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({+ SSEClientTransport: class {+ constructor() {+ (this as unknown as { __type: string }).__type = 'sse';+ }+ },+}));++const baseParams = () => ({+ url: 'https://mcp.example.com/mcp',+ headers: {},+ signal: new AbortController().signal,+});++describe('connectRemoteMcp transport selection', () => {+ beforeEach(() => {+ mockConnectAttempts.length = 0;+ mockConnectImpl = () => {};+ });++ it('falls back to the other transport when the known hint is stale/wrong', async () => {+ // Hint says sse, but the server is actually streamable-http (sse connect fails).+ mockConnectImpl = type => {+ if (type === 'sse') throw new Error('not an SSE endpoint');+ };++ const conn = await connectRemoteMcp({ ...baseParams(), knownTransportType: 'sse' });++ expect(conn.transportType).toBe('streamable-http');+ // Hint tried first, then fell back to the remaining transport.+ expect(mockConnectAttempts).toEqual(['sse', 'streamable-http']);+ });++ it('uses the known hint directly when it works (no fallback attempt)', async () => {+ const conn = await connectRemoteMcp({ ...baseParams(), knownTransportType: 'sse' });++ expect(conn.transportType).toBe('sse');+ expect(mockConnectAttempts).toEqual(['sse']);+ });++ it('probes in order when there is no hint', async () => {+ mockConnectImpl = type => {+ if (type === 'streamable-http') throw new Error('no streamable-http');+ };++ const conn = await connectRemoteMcp(baseParams());++ expect(conn.transportType).toBe('sse');+ expect(mockConnectAttempts).toEqual(['streamable-http', 'sse']);+ });++ it('throws immediately on a 401 without trying the fallback transport', async () => {+ mockConnectImpl = () => {+ throw new Error('HTTP 401 Unauthorized');+ };++ await expect(connectRemoteMcp({ ...baseParams(), knownTransportType: 'streamable-http' })).rejects.toMatchObject({+ constructor: McpConnectionError,+ statusCode: 401,+ });+ expect(mockConnectAttempts).toEqual(['streamable-http']);+ });++ it('surfaces a session-expiry on the hinted transport without falling back (caller resets the session)', async () => {+ mockConnectImpl = () => {+ throw new Error('HTTP 404 session not found');+ };++ await expect(+ connectRemoteMcp({ ...baseParams(), knownTransportType: 'streamable-http', sessionId: 'sess-1' }),+ ).rejects.toMatchObject({ constructor: McpConnectionError });+ // Session-expiry short-circuits: no fallback to sse with a stale session.+ expect(mockConnectAttempts).toEqual(['streamable-http']);+ });+});diff --git a/packages/harness/tests/core/createSandboxProvider.test.ts b/packages/harness/tests/core/createSandboxProvider.test.tsnew file mode 100644index 000000000..ac0994b6f--- /dev/null+++ b/packages/harness/tests/core/createSandboxProvider.test.ts@@ -0,0 +1,79 @@+/**+ * Library-level sandbox provider registry: settings union parsing and the+ * settings → provider factory (public harness, no gateway config involved).+ */+import {+ createSandboxProvider,+ SandboxProviderSettingsSchema,+} from '../../src/core/sandbox/provider/createSandboxProvider';+import { DaytonaSandboxProvider } from '../../src/core/sandbox/provider/DaytonaProvider';+import { makeSilentLogger } from './harnessMocks';++describe('SandboxProviderSettingsSchema', () => {+ it('parses minimal daytona settings and applies defaults', () => {+ const settings = SandboxProviderSettingsSchema.parse({+ type: 'daytona',+ apiKey: 'key-1',+ snapshotName: 'snap-1',+ });+ expect(settings).toEqual({+ type: 'daytona',+ apiKey: 'key-1',+ snapshotName: 'snap-1',+ timeoutMs: 60_000,+ autoStopIntervalInMinutes: 5,+ autoArchiveIntervalInMinutes: 60,+ autoDeleteIntervalInMinutes: 43_200,+ });+ });++ it('keeps explicit overrides', () => {+ const settings = SandboxProviderSettingsSchema.parse({+ type: 'daytona',+ apiKey: 'key-1',+ snapshotName: 'snap-1',+ timeoutMs: 5_000,+ autoStopIntervalInMinutes: 0,+ });+ expect(settings.timeoutMs).toBe(5_000);+ expect(settings.autoStopIntervalInMinutes).toBe(0);+ });++ it('rejects an unknown provider type', () => {+ expect(() => SandboxProviderSettingsSchema.parse({ type: 'e2b', apiKey: 'k', snapshotName: 's' })).toThrow();+ });++ it('rejects missing apiKey / snapshotName', () => {+ expect(() => SandboxProviderSettingsSchema.parse({ type: 'daytona', snapshotName: 's' })).toThrow();+ expect(() => SandboxProviderSettingsSchema.parse({ type: 'daytona', apiKey: 'k' })).toThrow();+ expect(() => SandboxProviderSettingsSchema.parse({ type: 'daytona', apiKey: '', snapshotName: 's' })).toThrow();+ });++ it('rejects unknown keys (strict schema)', () => {+ expect(() =>+ SandboxProviderSettingsSchema.parse({+ type: 'daytona',+ apiKey: 'k',+ snapshotName: 's',+ snapshot_name: 'typo',+ }),+ ).toThrow();+ });+});++describe('createSandboxProvider', () => {+ it('builds a DaytonaSandboxProvider for type "daytona"', () => {+ const provider = createSandboxProvider({+ settings: SandboxProviderSettingsSchema.parse({+ type: 'daytona',+ apiKey: 'key-1',+ snapshotName: 'snap-1',+ }),+ tenantName: 'tenant-1',+ fileMaxBytes: 1024,+ previewUrlExpirySeconds: 60,+ logger: makeSilentLogger(),+ });+ expect(provider).toBeInstanceOf(DaytonaSandboxProvider);+ });+});diff --git a/packages/harness/tests/core/deferredLoading.test.ts b/packages/harness/tests/core/deferredLoading.test.tsnew file mode 100644index 000000000..3a73c316f--- /dev/null+++ b/packages/harness/tests/core/deferredLoading.test.ts@@ -0,0 +1,55 @@+import { InstructionBuilder } from '../../src/core/InstructionBuilder';+import type { IToolSet } from '../../src/core/mcp/IMCPServer';+import { DeferredTool } from '../../src/core/runtime/DeferredTool';+import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';+import './harnessMocks';+import { makeMockIMCPServer, makeSilentLogger } from './harnessMocks';++const DEFERRED_TOOLS_INSTRUCTION = 'deferred-tools-instructions';++const silentLogger = makeSilentLogger();++function deferredInstructionText(servers: IToolSet[]): string {+ const builder = InstructionBuilder.createSystemPrompt('test');+ const capabilities = builder.beginSection('agent-capabilities');+ new DeferredTool(servers, { tracing: NOOP_AGENT_TRACING, logger: silentLogger }).buildInstruction(capabilities);+ return builder.build();+}++describe('DeferredTool deferred loading behavior', () => {+ it('includes preload:false servers in deferred-tools instructions', () => {+ const text = deferredInstructionText([+ makeMockIMCPServer({ name: 'eager-server', preload: true }),+ makeMockIMCPServer({ name: 'lazy-server', preload: false }),+ ]);+ expect(text).toContain(`<${DEFERRED_TOOLS_INSTRUCTION}>`);+ expect(text).toContain('lazy-server');+ expect(text).not.toContain('eager-server');+ });++ it('omits deferred-tools instructions when every server is preload:true', () => {+ const text = deferredInstructionText([makeMockIMCPServer({ name: 'all-eager', preload: true })]);+ expect(text).not.toContain(`<${DEFERRED_TOOLS_INSTRUCTION}>`);+ });++ it('lists preload:false servers even when hasPreloadedTools is true (selective preload)', () => {+ const text = deferredInstructionText([+ makeMockIMCPServer({+ name: 'partial-preload-server',+ preload: false,+ hasPreloadedTools: true,+ preloadTools: ['tool_a'],+ }),+ ]);+ expect(text).toContain('partial-preload-server');+ });++ it('lists preload:false with no preloads and omits preload:true', () => {+ const text = deferredInstructionText([+ makeMockIMCPServer({ name: 'lazy-empty', preload: false, hasPreloadedTools: false }),+ makeMockIMCPServer({ name: 'eager', preload: true, hasPreloadedTools: true }),+ ]);+ expect(text).toContain('lazy-empty');+ expect(text).not.toContain('eager');+ });+});diff --git a/packages/harness/tests/core/fixtures/baseline-build-lint.json b/packages/harness/tests/core/fixtures/baseline-build-lint.jsonnew file mode 100644index 000000000..04f13ec59--- /dev/null+++ b/packages/harness/tests/core/fixtures/baseline-build-lint.json@@ -0,0 +1,32 @@+{+ "recordedAt": "2026-07-19",+ "commands": {+ "build": {+ "command": "npm run build:ci",+ "exitCode": 2,+ "errors": [+ {+ "classification": "canonical-pre-existing",+ "file": "src/routers/inference.ts",+ "line": 216,+ "message": "Object literal may only specify known properties, and 'enableMetrics' does not exist in type 'AuthCacheConfig'."+ }+ ]+ },+ "lint": {+ "command": "npm run lint:ci",+ "exitCode": 0,+ "errors": []+ }+ },+ "publicTry1Diagnostics": {+ "buildErrors": 0,+ "lintErrors": 0,+ "note": "public-try-1 is compiled via tsconfig src/**/* but produces no distinct build/lint diagnostics beyond canonical sources at baseline time."+ },+ "notes": [+ "Baseline recorded before public harness extraction.",+ "Do not fix canonical-pre-existing inference.ts error during extraction unless required for unrelated reasons.",+ "Re-run the same commands at verify-build-lint and classify any new diagnostics."+ ]+}diff --git a/packages/harness/tests/core/fixtures/boundary-valid.ts b/packages/harness/tests/core/fixtures/boundary-valid.tsnew file mode 100644index 000000000..545575e74--- /dev/null+++ b/packages/harness/tests/core/fixtures/boundary-valid.ts@@ -0,0 +1,14 @@+/**+ * Public-boundary smoke fixture: npm + intra-harness imports only.+ * Lint with the harness fixtures eslint override; expect zero diagnostics.+ */+import { z } from 'zod';+import { EventType } from '../../../src/core/events/eventSchemas';+import { NOOP_AGENT_TRACING } from '../../../src/core/tracing/NoopAgentTracing';++export const BoundaryValidSchema = z.object({+ type: z.literal(EventType.USER_MESSAGE),+ tracingOk: z.literal(true),+});++export const boundaryValidTracing = NOOP_AGENT_TRACING;diff --git a/packages/harness/tests/core/harnessMocks.ts b/packages/harness/tests/core/harnessMocks.tsnew file mode 100644index 000000000..8335fdbc4--- /dev/null+++ b/packages/harness/tests/core/harnessMocks.ts@@ -0,0 +1,102 @@+import type { Logger } from 'winston';+import winston from 'winston';+import type { ILLM } from '../../src/core/llm/ILLM';+import type { AgentToolSchema, IToolSet, ListToolsResponse } from '../../src/core/mcp/IMCPServer';+import type { SandboxProvider } from '../../src/core/sandbox/provider/Provider';+import { Sandbox } from '../../src/core/sandbox/Sandbox';+import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';++export const OBJECT_INPUT_SCHEMA = { type: 'object' as const, properties: {} };++/** Minimal typed ILLM stub — both methods required by the interface. */+export function makeMockILLM(overrides: Partial<ILLM> = {}): ILLM {+ return {+ create: jest.fn(),+ createNonStream: jest.fn(),+ ...overrides,+ };+}++/**+ * Real Winston logger (silent). Prefer this over structural casts.+ * `child` is wired to return the same instance so spies on the root logger still fire.+ */+export function makeSilentLogger(): Logger {+ const logger = winston.createLogger({ silent: true, transports: [] });+ logger.child = (() => logger) as Logger['child'];+ return logger;+}++export function makeMockIMCPServer(params: {+ name: string;+ preload: boolean;+ /** When set, overrides default `hasPreloadedTools` (defaults to `preload`). */+ hasPreloadedTools?: boolean | undefined;+ preloadTools?: string[] | undefined;+ tools?: AgentToolSchema[] | undefined;+}): IToolSet {+ return {+ name: params.name,+ id: params.name,+ preload: params.preload,+ hasPreloadedTools: params.hasPreloadedTools ?? params.preload,+ listTools: jest.fn(+ async (): Promise<ListToolsResponse> => ({+ result: {+ tools: params.tools ?? [+ { name: 'tool_a', description: 'A', inputSchema: OBJECT_INPUT_SCHEMA, preload: params.preload },+ ],+ },+ wasInitialized: undefined,+ }),+ ),+ callTool: jest.fn(),+ toolCallInfo: jest.fn(),+ };+}++export function makeStubPublicSandbox(tenantName = 'test-tenant'): Sandbox {+ const provider: SandboxProvider = {+ createSandbox: jest.fn(),+ exec: jest.fn(),+ getAdditionalInstructions: () => undefined,+ getToolResultDumpDir: () => '/tmp/tool-results',+ getGitCredentialsPath: () => '/tmp/.git-credentials',+ downloadFile: jest.fn(),+ uploadFile: jest.fn(),+ getNatsBridgeUrl: jest.fn(),+ };+ return new Sandbox({+ provider,+ blockDestructiveToolsInCodeMode: true,+ execExtraEnv: { TFY_TENANT_NAME: tenantName },+ scripts: { mcpClient: '# mcp', skillDownloader: '# skills' },+ logger: makeSilentLogger(),+ tracing: NOOP_AGENT_TRACING,+ });+}++/** Extract `mcp server: <name>` labels from an LLM tools array (public create() body). */+export function mcpServerNamesFromTools(tools: unknown): string[] {+ if (!Array.isArray(tools)) return [];+ const names: string[] = [];+ for (const tool of tools) {+ const description =+ tool &&+ typeof tool === 'object' &&+ 'function' in tool &&+ tool.function &&+ typeof tool.function === 'object' &&+ 'description' in tool.function &&+ typeof tool.function.description === 'string'+ ? tool.function.description+ : undefined;+ if (!description) continue;+ const match = /^mcp server: ([^\n]+)/.exec(description);+ const serverName = match?.[1];+ if (serverName !== undefined && !names.includes(serverName)) {+ names.push(serverName);+ }+ }+ return names;+}diff --git a/packages/harness/tests/core/helperOwnership.test.ts b/packages/harness/tests/core/helperOwnership.test.tsnew file mode 100644index 000000000..95e838243--- /dev/null+++ b/packages/harness/tests/core/helperOwnership.test.ts@@ -0,0 +1,56 @@+import { ToolNameCollisionError } from '../../src/core/errors';+import { getUniqueSanitizedToolName, MAX_DUP_SUFFIX } from '../../src/core/mcp/toolNames';+import {+ assistantMessageContentToStringForSubAgent,+ INTERNAL_SYSTEM_PROMPT,+ makeUnknownToolInfo,+} from '../../src/core/runtime/contextUtils';+import { extractErrorLogFields } from '../../src/core/util/errorLogFields';+import { PromiseTimeoutError, withTimeout } from '../../src/core/util/promiseUtils';++describe('canonical helper ownership fidelity', () => {+ it('extractErrorLogFields matches Error and non-Error shapes', () => {+ const err = new Error('x');+ expect(extractErrorLogFields(err)).toEqual({ error: 'x', stack: err.stack });+ expect(extractErrorLogFields('plain')).toEqual({ error: 'plain' });+ });++ it('DaytonaProvider owns http→ws URL conversion (no shared helper module)', () => {+ // Folded into DaytonaProvider per ISSUE-042; assert the conversion contract via URL API.+ const https = new URL('https://example.com/path');+ https.protocol = 'wss:';+ expect(https.toString()).toBe('wss://example.com/path');+ const http = new URL('http://example.com/path');+ http.protocol = 'ws:';+ expect(http.toString()).toBe('ws://example.com/path');+ });++ it('withTimeout rejects with PromiseTimeoutError', async () => {+ await expect(withTimeout(new Promise(() => undefined), 5)).rejects.toBeInstanceOf(PromiseTimeoutError);+ });++ it('preserves canonical prompt and unknown-tool bytes', () => {+ expect(INTERNAL_SYSTEM_PROMPT).toContain('tfy-internal tags contain information hidden from the user');+ expect(makeUnknownToolInfo('foo')).toEqual({+ type: 'mcp',+ mcp_server_id: 'unknown',+ mcp_server_name: 'unknown',+ original_tool_name: 'foo',+ is_approval_required: false,+ is_client_side: false,+ });+ expect(assistantMessageContentToStringForSubAgent('body', 'ERR')).toBe('ERR\nbody');+ expect(assistantMessageContentToStringForSubAgent('', 'ERR')).toBe('ERR');+ });++ it('enforces tool-name collision limit 50', () => {+ const existing = new Set<string>();+ existing.add('tool');+ for (let i = 1; i <= MAX_DUP_SUFFIX; i++) existing.add(`tool${i}`);+ expect(MAX_DUP_SUFFIX).toBe(50);+ expect(() => getUniqueSanitizedToolName('tool', existing)).toThrow(ToolNameCollisionError);+ expect(() => getUniqueSanitizedToolName('tool', existing)).toThrow(+ `Tool name collision limit exceeded for "tool": more than ${MAX_DUP_SUFFIX} duplicates across MCP servers`,+ );+ });+});diff --git a/packages/harness/tests/core/mcpInitializeAggregation.test.ts b/packages/harness/tests/core/mcpInitializeAggregation.test.tsnew file mode 100644index 000000000..19d1987d0--- /dev/null+++ b/packages/harness/tests/core/mcpInitializeAggregation.test.ts@@ -0,0 +1,90 @@+import type { MCPServerInitInfo } from '../../src/core/events/eventSchemas';+import { EventType } from '../../src/core/events/eventSchemas';+import type { AgentToolSchema, IToolSet, ListToolsResponse } from '../../src/core/mcp/IMCPServer';+import { convertMCPServersToTools } from '../../src/core/mcp/convertMCPServers';+import './harnessMocks';+import { OBJECT_INPUT_SCHEMA, makeMockIMCPServer } from './harnessMocks';++function makeServer(params: { name: string; initInfo?: MCPServerInitInfo; tools?: AgentToolSchema[] | undefined }): IToolSet {+ const base = makeMockIMCPServer({+ name: params.name,+ preload: true,+ ...(params.tools !== undefined ? { tools: params.tools } : {}),+ });+ return {+ ...base,+ listTools: jest.fn(+ async (): Promise<ListToolsResponse> => ({+ result: {+ tools: params.tools ?? [+ { name: 'do_thing', description: 'Does a thing', inputSchema: OBJECT_INPUT_SCHEMA, preload: true },+ ],+ },+ wasInitialized: params.initInfo,+ }),+ ),+ };+}++describe('convertMCPServersToTools initialization aggregation', () => {+ it('aggregates wasInitialized info from each server into initializationInfo', async () => {+ const alphaInit: MCPServerInitInfo = {+ id: 'alpha-id',+ name: 'alpha',+ session_id: 'sess-alpha',+ };+ const betaInit: MCPServerInitInfo = {+ id: 'beta-id',+ name: 'beta',+ session_id: 'sess-beta',+ };++ const { initializationInfo, convertedTools } = await convertMCPServersToTools({+ tfyManagedServers: [makeServer({ name: 'alpha', initInfo: alphaInit })],+ userServers: [makeServer({ name: 'beta', initInfo: betaInit })],+ });++ expect(initializationInfo).toEqual([alphaInit, betaInit]);+ expect(convertedTools.tools.length).toBe(2);+ });++ it('skips initialization entries for OAuth-required servers', async () => {+ const oauthServer: IToolSet = {+ name: 'oauth-server',+ id: 'oauth-server',+ preload: true,+ hasPreloadedTools: true,+ listTools: jest.fn(async () => ({+ authRequired: {+ servers: [{ id: 'oauth-server', name: 'oauth-server', auth_url: 'https://auth.example' }],+ },+ })),+ callTool: jest.fn(),+ toolCallInfo: jest.fn(),+ };++ const readyInit: MCPServerInitInfo = {+ id: 'ready-id',+ name: 'ready',+ session_id: 'sess-ready',+ };+ const { initializationInfo, authRequirementInfo } = await convertMCPServersToTools({+ tfyManagedServers: [makeServer({ name: 'ready', initInfo: readyInit })],+ userServers: [oauthServer],+ });++ expect(initializationInfo).toEqual([readyInit]);+ expect(authRequirementInfo).toHaveLength(1);+ });++ it('matches mcp.initialize event shape when init info is wrapped', () => {+ const initInfo: MCPServerInitInfo[] = [{ id: 'srv-1', name: 'srv-1', session_id: 'abc' }];+ const event = {+ type: EventType.MCP_INITIALIZE,+ thread_id: 'thread-1',+ mcp_servers: initInfo,+ };+ expect(event.type).toBe('mcp.initialize');+ expect(event.mcp_servers).toEqual(initInfo);+ });+});diff --git a/packages/harness/tests/core/openToolCallCloser.test.ts b/packages/harness/tests/core/openToolCallCloser.test.tsnew file mode 100644index 000000000..2e2edac20--- /dev/null+++ b/packages/harness/tests/core/openToolCallCloser.test.ts@@ -0,0 +1,107 @@+import type {+ InternalEnrichedAssistantMessage,+ InternalEnrichedToolCall,+} from '../../src/core/llm/LLMTypes';+import type { ContextMessage } from '../../src/core/runtime/AgentThread.types';+import { getClosableOpenToolCallIds } from '../../src/core/runtime/OpenToolCallCloser';+import './harnessMocks';++function makeToolCall(+ id: string,+ toolInfo: Partial<InternalEnrichedToolCall['tool_info']> = {},+): InternalEnrichedToolCall {+ return {+ id,+ type: 'function',+ function: { name: 'test_tool', arguments: '{}' },+ tool_info: {+ type: 'mcp',+ mcp_server_id: 'test-server',+ mcp_server_name: 'test-server',+ original_tool_name: 'test_tool',+ is_approval_required: false,+ is_client_side: false,+ ...toolInfo,+ },+ };+}++function assistantWithToolCalls(toolCalls: InternalEnrichedToolCall[]): ContextMessage[] {+ const assistant: InternalEnrichedAssistantMessage = {+ role: 'assistant',+ content: '',+ tool_calls: toolCalls,+ };+ return [assistant];+}++describe('getClosableOpenToolCallIds', () => {+ it('closes ordinary dangling tool calls on the last assistant message', () => {+ const context = assistantWithToolCalls([makeToolCall('tc-1'), makeToolCall('tc-2')]);+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set(['tc-1', 'tc-2']));+ });++ it('excludes tool calls that already have a matching tool response', () => {+ const context: ContextMessage[] = [+ ...assistantWithToolCalls([makeToolCall('tc-1'), makeToolCall('tc-2')]),+ { role: 'tool', tool_call_id: 'tc-1', content: 'done' },+ ];+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set(['tc-2']));+ });++ it('returns empty when any open call requires approval', () => {+ const context = assistantWithToolCalls([+ makeToolCall('tc-ordinary'),+ makeToolCall('tc-approval', { is_approval_required: true }),+ ]);+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set());+ });++ it('returns empty when any open call is client-side', () => {+ const context = assistantWithToolCalls([+ makeToolCall('tc-ordinary'),+ makeToolCall('tc-client', { is_client_side: true }),+ ]);+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set());+ });++ it('excludes thread-creation tool calls (is_thread_creation)', () => {+ const context = assistantWithToolCalls([+ makeToolCall('tc-regular'),+ makeToolCall('tc-sub-agent', { is_thread_creation: true }),+ ]);+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set(['tc-regular']));+ });++ it('treats legacy sub-agent calls without is_thread_creation as ordinary closable calls', () => {+ const context = assistantWithToolCalls([+ makeToolCall('tc-legacy-sub-agent', {+ mcp_server_id: 'legacy-sub-agents',+ mcp_server_name: 'legacy-sub-agents',+ original_tool_name: 'create_sub_agent',+ }),+ ]);+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set(['tc-legacy-sub-agent']));+ });++ it('only inspects tool calls on the last assistant message', () => {+ const context: ContextMessage[] = [+ {+ role: 'assistant',+ content: '',+ tool_calls: [makeToolCall('old-tc')],+ },+ { role: 'tool', tool_call_id: 'old-tc', content: 'resolved' },+ {+ role: 'assistant',+ content: '',+ tool_calls: [makeToolCall('new-tc')],+ },+ ];+ expect(getClosableOpenToolCallIds(context)).toEqual(new Set(['new-tc']));+ });++ it('returns empty when there is no assistant message with tool calls', () => {+ expect(getClosableOpenToolCallIds([{ role: 'user', content: 'hello' }])).toEqual(new Set());+ });+});diff --git a/packages/harness/tests/core/passthroughIdentity.test.ts b/packages/harness/tests/core/passthroughIdentity.test.tsnew file mode 100644index 000000000..3fd76dee4--- /dev/null+++ b/packages/harness/tests/core/passthroughIdentity.test.ts@@ -0,0 +1,11 @@+import { InternalEventType } from '../../src/core/runtime/AgentThread.types';++describe('passthrough event identity (public harness)', () => {+ it('includes PASSTHROUGH in public InternalEventType', () => {+ expect(InternalEventType.PASSTHROUGH).toBe('agent.passthrough');+ });++ it('keeps plan.overwrite as a passthrough event type, not a wire InternalEventType constant', () => {+ expect(Object.values(InternalEventType)).not.toContain('internal.agent.plan.overwrite');+ });+});diff --git a/packages/harness/tests/core/remoteMcpServer.test.ts b/packages/harness/tests/core/remoteMcpServer.test.tsnew file mode 100644index 000000000..8b641452c--- /dev/null+++ b/packages/harness/tests/core/remoteMcpServer.test.ts@@ -0,0 +1,356 @@+import type { Logger } from 'winston';+import { McpConnectionError, RemoteMCP, ToolSet } from '../../src/core';+import {+ isApprovalRequiredResponse,+ isCallToolResponseResult,+ type MCPAuthRequired,+ type ToolSchema,+} from '../../src/core/mcp/IMCPServer';+import type { RemoteMcpHeaders } from '../../src/core/mcp/RemoteMCP';+import { connectRemoteMcp } from '../../src/core/mcp/remoteMcpClient';+import type { ToolSelectorConfig } from '../../src/core/mcp/ToolSelectorPolicy';+import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';++// RemoteMCP connects itself via connectRemoteMcp; mock it so the split RemoteMCP (connection) ++// ToolSet (policy) can be exercised without real networking. isSessionExpiredError stays real.+jest.mock('../../src/core/mcp/remoteMcpClient', () => {+ const actual = jest.requireActual('../../src/core/mcp/remoteMcpClient');+ return { __esModule: true, ...actual, connectRemoteMcp: jest.fn() };+});++const mockConnect = connectRemoteMcp as jest.MockedFunction<typeof connectRemoteMcp>;++const noopLogger = { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() } as unknown as Logger;++const READ_TOOL: ToolSchema = {+ name: 'read_thing',+ inputSchema: { type: 'object' },+ annotations: { readOnlyHint: true },+} as ToolSchema;+const WRITE_TOOL: ToolSchema = {+ name: 'write_thing',+ inputSchema: { type: 'object' },+ annotations: { readOnlyHint: false },+} as ToolSchema;++const DEFAULT_SELECTORS: ToolSelectorConfig = {+ enableTools: ['@all'],+ disableTools: [],+ preloadTools: [],+ requireApprovalForTools: [],+};++// Shared, mutable state backing the mocked connection so tests can assert connect/callTool/close+// counts and queue errors, mirroring the previous FakeTransport.+interface FakeConnectionState {+ connectCalls: number;+ callToolCalls: number;+ closes: number;+ queueCallToolError(error: unknown): void;+}++function installFakeConnection(+ opts: { tools?: ToolSchema[]; sessionId?: string | null; connectError?: unknown } = {},+): FakeConnectionState {+ const callToolErrors: unknown[] = [];+ const state: FakeConnectionState = {+ connectCalls: 0,+ callToolCalls: 0,+ closes: 0,+ queueCallToolError: (error: unknown) => callToolErrors.push(error),+ };++ mockConnect.mockImplementation(async () => {+ state.connectCalls += 1;+ if (opts.connectError) throw opts.connectError;+ return {+ transportType: 'streamable-http',+ sessionId: opts.sessionId ?? null,+ listTools: async () => ({ tools: opts.tools ?? [READ_TOOL, WRITE_TOOL] }),+ callTool: async callParams => {+ state.callToolCalls += 1;+ const queued = callToolErrors.shift();+ if (queued) throw queued;+ return { content: [{ type: 'text', text: `called ${callParams.name}` }] };+ },+ close: async () => {+ state.closes += 1;+ },+ };+ });++ return state;+}++function makeServer(params: {+ selectors?: ToolSelectorConfig | undefined;+ preload?: boolean | undefined;+ sessionId?: string | undefined;+ transportType?: 'streamable-http' | 'sse' | undefined;+ headers?: RemoteMcpHeaders | undefined;+}): ToolSet {+ const remote = new RemoteMCP({+ name: 'my-inline',+ id: 'inline-id-123',+ url: 'https://mcp.example.com/mcp',+ headers: params.headers ?? {},+ logger: noopLogger,+ tracing: NOOP_AGENT_TRACING,+ sessionId: params.sessionId,+ transportType: params.transportType,+ signal: new AbortController().signal,+ });+ return new ToolSet({+ source: remote,+ selectors: params.selectors ?? DEFAULT_SELECTORS,+ preload: params.preload ?? false,+ });+}++describe('RemoteMCP + ToolSet', () => {+ it('connects once, emits init info with session id, and caches across listTools calls', async () => {+ const state = installFakeConnection({ sessionId: 'sess-1' });+ const server = makeServer({});++ const first = await server.listTools();+ if ('authRequired' in first) throw new Error('unexpected oauth');+ expect(first.wasInitialized).toEqual({+ id: 'inline-id-123',+ name: 'my-inline',+ session_id: 'sess-1',+ transport_type: 'streamable-http',+ });+ expect(first.result.tools.map(t => t.name).sort()).toEqual(['read_thing', 'write_thing']);++ const second = await server.listTools();+ if ('authRequired' in second) throw new Error('unexpected oauth');+ // Cached: no re-connect and no duplicate init emission.+ expect(second.wasInitialized).toBeUndefined();+ expect(state.connectCalls).toBe(1);+ });++ it('seeds a persisted transport type as knownTransportType so the connect skips the probe', async () => {+ installFakeConnection({ sessionId: 'sess-1' });+ const server = makeServer({ sessionId: 'sess-1', transportType: 'sse' });++ await server.listTools();+ expect(mockConnect).toHaveBeenCalledWith(expect.objectContaining({ knownTransportType: 'sse' }));+ });++ it('probes (no knownTransportType) when there is no persisted transport type', async () => {+ installFakeConnection({ sessionId: 'sess-1' });+ const server = makeServer({ sessionId: 'sess-1' });++ await server.listTools();+ expect(mockConnect.mock.calls[0]![0]).not.toHaveProperty('knownTransportType');+ });++ it('applies enable/disable selectors and preload annotation', async () => {+ installFakeConnection();+ const server = makeServer({+ selectors: { enableTools: ['@read-only'], disableTools: [], preloadTools: ['read_thing'] },+ });++ const res = await server.listTools();+ if ('authRequired' in res) throw new Error('unexpected oauth');+ expect(res.result.tools.map(t => t.name)).toEqual(['read_thing']);+ expect(res.result.tools[0]?.preload).toBe(true);+ expect(server.getAllowedToolNamesForSandbox()).toEqual(['read_thing']);+ });++ it('throws a 400 McpConnectionError when a literal enable tool is missing', async () => {+ installFakeConnection();+ const server = makeServer({+ selectors: { enableTools: ['does_not_exist'], disableTools: [], preloadTools: [] },+ });+ await expect(server.listTools()).rejects.toMatchObject({+ constructor: McpConnectionError,+ statusCode: 400,+ });+ });++ it('does not throw the missing-enable-literal 400 during annotation lookups (only explicit listTools)', async () => {+ const state = installFakeConnection();+ const server = makeServer({+ selectors: { enableTools: ['does_not_exist'], disableTools: [], preloadTools: [] },+ });+ // Annotation lookups (toolCallInfo / callTool preflight) fetch the raw tool list and+ // must not run the missing-literal guard, so deferred paths behave like the pre-refactor inner cache.+ await expect(server.toolCallInfo({ name: 'read_thing', arguments: {} })).resolves.toMatchObject({+ original_tool_name: 'read_thing',+ });+ expect(state.connectCalls).toBe(1);+ // The guard still fires on an explicit listTools().+ await expect(server.listTools()).rejects.toMatchObject({ statusCode: 400 });+ });++ it('rejects a disallowed tool call with a 403 McpConnectionError', async () => {+ const state = installFakeConnection();+ const server = makeServer({+ selectors: { enableTools: ['@read-only'], disableTools: [], preloadTools: [] },+ });+ await server.listTools();+ await expect(server.callTool({ name: 'write_thing', arguments: {} })).rejects.toMatchObject({+ statusCode: 403,+ });+ expect(state.callToolCalls).toBe(0);+ });++ it('returns approvalRequired for an approval-gated tool when no decision is supplied', async () => {+ const state = installFakeConnection();+ const server = makeServer({+ selectors: { enableTools: ['@all'], disableTools: [], preloadTools: [], requireApprovalForTools: ['@write'] },+ });+ await server.listTools();++ const res = await server.callTool({ name: 'write_thing', arguments: {} });+ expect(isApprovalRequiredResponse(res)).toBe(true);+ expect(state.callToolCalls).toBe(0);+ });++ it('enforces the write/destructive approval floor even when the agent narrows require_approval_for_tools', async () => {+ const state = installFakeConnection();+ // Agent explicitly clears its approval selectors; the write/destructive floor must still apply.+ const server = makeServer({+ selectors: { enableTools: ['@all'], disableTools: [], preloadTools: [], requireApprovalForTools: [] },+ });+ await server.listTools();++ const res = await server.callTool({ name: 'write_thing', arguments: {} });+ expect(isApprovalRequiredResponse(res)).toBe(true);+ expect(state.callToolCalls).toBe(0);+ });++ it('short-circuits a denied tool call without hitting the transport', async () => {+ const state = installFakeConnection();+ const server = makeServer({});+ await server.listTools();++ const res = await server.callTool({ name: 'write_thing', arguments: {} }, { status: 'deny', reason: 'nope' });+ if (!isCallToolResponseResult(res)) throw new Error('expected result response');+ expect(res.result.isError).toBe(true);+ expect(state.callToolCalls).toBe(0);+ });++ it('retries once on an expired session, reconnecting transparently', async () => {+ const state = installFakeConnection({ sessionId: 'sess-1' });+ const server = makeServer({});+ await server.listTools();+ expect(state.connectCalls).toBe(1);++ state.queueCallToolError(new Error('session-expired'));+ const res = await server.callTool({ name: 'read_thing', arguments: {} });+ if (!isCallToolResponseResult(res)) throw new Error('expected result response');+ // First attempt failed with expiry, reset + reconnect, second attempt succeeded.+ expect(state.connectCalls).toBe(2);+ expect(state.callToolCalls).toBe(2);+ });++ it('wraps a non-auth connect failure in a server-named McpConnectionError preserving the status hint', async () => {+ installFakeConnection({ connectError: new McpConnectionError('upstream down', 502) });+ const server = makeServer({});+ await expect(server.listTools()).rejects.toMatchObject({+ constructor: McpConnectionError,+ statusCode: 502,+ message: expect.stringContaining("remote MCP server 'my-inline'"),+ });+ });++ it('wraps a 401 on connect as a server-named McpConnectionError (inline never enters auth-required)', async () => {+ const state = installFakeConnection({ connectError: new McpConnectionError('upstream 401', 401) });+ const server = makeServer({});++ await expect(server.listTools()).rejects.toMatchObject({+ constructor: McpConnectionError,+ statusCode: 401,+ message: expect.stringContaining("remote MCP server 'my-inline'"),+ });+ expect(state.connectCalls).toBe(1);+ });++ it('short-circuits with authRequired when the headers resolver signals auth-required', async () => {+ const state = installFakeConnection();+ const authRequired: MCPAuthRequired = {+ servers: [{ id: 'inline-id-123', name: 'my-inline', auth_url: 'https://auth.example' }],+ };+ const headers: RemoteMcpHeaders = async () => ({ authRequired });+ const server = makeServer({+ headers,+ selectors: { enableTools: ['@read-only'], disableTools: [], preloadTools: [] },+ });++ const listRes = await server.listTools();+ expect(listRes).toEqual({ authRequired });++ // callTool surfaces auth-required before the annotation-based allow/approval checks.+ const callRes = await server.callTool({ name: 'read_thing', arguments: {} });+ expect(callRes).toEqual({ authRequired });++ // The resolver signalled auth before any network use.+ expect(state.connectCalls).toBe(0);+ expect(state.callToolCalls).toBe(0);+ });++ it('re-checks auth on every op: a mid-session auth revocation surfaces authRequired on the next callTool', async () => {+ const state = installFakeConnection({ sessionId: 'sess-1' });+ const authRequired: MCPAuthRequired = {+ servers: [{ id: 'inline-id-123', name: 'my-inline', auth_url: 'https://auth.example' }],+ };+ // Headers resolve fine at connect time, then flip to auth-required (e.g. token revoked mid-request).+ const headers = jest+ .fn<Promise<{ headers: Record<string, string> } | { authRequired: MCPAuthRequired }>, []>()+ .mockResolvedValueOnce({ headers: {} })+ .mockResolvedValue({ authRequired });+ const server = makeServer({ headers });++ const first = await server.listTools();+ if ('authRequired' in first) throw new Error('expected successful first connect');+ expect(state.connectCalls).toBe(1);++ // Already connected, but auth is re-checked: the revocation must surface instead of a tool result.+ const callRes = await server.callTool({ name: 'read_thing', arguments: {} });+ expect(callRes).toEqual({ authRequired });+ expect(state.callToolCalls).toBe(0);+ });++ it('emits init for a stateless (SSE) server on connect (matches gateway strict-compare behavior)', async () => {+ // Stateless connection reports a null session id.+ installFakeConnection({ sessionId: null });++ // First turn: never-connected (undefined) -> stateless (null) counts as a change, so init is+ // emitted once, carrying transport_type so a later turn can skip the probe. session_id is absent.+ const firstTurn = makeServer({});+ const first = await firstTurn.listTools();+ if ('authRequired' in first) throw new Error('unexpected oauth');+ expect(first.wasInitialized).toEqual({+ id: 'inline-id-123',+ name: 'my-inline',+ session_id: undefined,+ transport_type: 'streamable-http',+ });++ // A resume turn (hydrated with no session id) still emits, mirroring the gateway.+ const secondTurn = makeServer({ sessionId: undefined });+ const second = await secondTurn.listTools();+ if ('authRequired' in second) throw new Error('unexpected oauth');+ expect(second.wasInitialized).toMatchObject({ id: 'inline-id-123', name: 'my-inline' });+ });++ it('resolves dynamic headers from the resolver and connects normally', async () => {+ const state = installFakeConnection({ sessionId: 'sess-1' });+ const headers = jest+ .fn<Promise<{ headers: Record<string, string> }>, []>()+ .mockResolvedValue({ headers: { Authorization: 'Bearer live-token' } });+ const server = makeServer({ headers });++ const res = await server.listTools();+ if ('authRequired' in res) throw new Error('unexpected auth-required');+ expect(res.result.tools.map(t => t.name).sort()).toEqual(['read_thing', 'write_thing']);+ expect(headers).toHaveBeenCalled();++ // Second (cached) listTools does not re-resolve headers — resolution happens only at connect.+ await server.listTools();+ expect(headers).toHaveBeenCalledTimes(1);+ expect(state.connectCalls).toBe(1);+ });+});diff --git a/packages/harness/tests/core/sandboxObjectIdentity.test.ts b/packages/harness/tests/core/sandboxObjectIdentity.test.tsnew file mode 100644index 000000000..390fa24d3--- /dev/null+++ b/packages/harness/tests/core/sandboxObjectIdentity.test.ts@@ -0,0 +1,55 @@+import { largeToolResponse } from '../../src/core/capabilities/builtins/LargeToolResponse';+import { getEmptyUsage } from '../../src/core/llm/LLMTypes';+import type { IToolSet } from '../../src/core/mcp/IMCPServer';+import type { ToolCallResult } from '../../src/core/mcp/executeToolCalls';+import { makeMockIMCPServer, makeSilentLogger, makeStubPublicSandbox } from './harnessMocks';++const silentLogger = makeSilentLogger();++const LARGE_CONTENT = 'x'.repeat(50_000);++function makeToolResult(toolSet: IToolSet, name: string): ToolCallResult {+ return {+ message: {+ role: 'tool',+ tool_call_id: 'call-1',+ content: LARGE_CONTENT,+ },+ info: {+ toolSet,+ originalToolName: name,+ },+ failure: false,+ isStructuredContent: false,+ completedAt: new Date().toISOString(),+ };+}++describe('LargeToolResponse sandbox object identity (ISSUE-035)', () => {+ it('classifies only the exact Sandbox instance as sandbox category', async () => {+ const sandbox = makeStubPublicSandbox();+ const sandboxNamedMcp = makeMockIMCPServer({ name: 'sandbox', preload: true });++ const processor = largeToolResponse({+ dynamicSubAgentsPresent: false,+ settings: { individualTokenThreshold: 100, totalTokenThreshold: 200 },+ logger: silentLogger,+ }).toolResponseProcessors?.[0];+ expect(processor).toBeDefined();+ if (!processor) throw new Error('expected largeToolResponse processor');++ const sandboxResult = makeToolResult(sandbox, 'exec');+ const mcpResult = makeToolResult(sandboxNamedMcp, 'search');++ await processor.process([sandboxResult, mcpResult], {+ threadId: 'main',+ sandbox,+ currentContextUsage: getEmptyUsage(),+ context: [],+ });++ expect(sandboxResult.message.content).toContain('write to a file');+ expect(mcpResult.message.content).not.toContain('write to a file');+ expect(mcpResult.message.content).toContain('Content too big');+ });+});diff --git a/packages/harness/tests/core/sendBatchTypes.compile.test.ts b/packages/harness/tests/core/sendBatchTypes.compile.test.tsnew file mode 100644index 000000000..70aec92c8--- /dev/null+++ b/packages/harness/tests/core/sendBatchTypes.compile.test.ts@@ -0,0 +1,53 @@+/**+ * Compile-time ownership of public vs runtime send batches.+ * Accepts the three homogeneous modes; rejects mixed pairs via @ts-expect-error.+ */+import type {+ UserToolApprovalMessage,+ UserToolResponseMessage,+} from '../../src/core/events/eventSchemas';+import type { LLMToolMessage } from '../../src/core/llm/LLMTypes';+import type {+ AgentThreadRuntimeSendBatch,+ AgentThreadSendBatch,+} from '../../src/core/runtime/AgentThread.types';+import type { AgentInputUserMessage } from '../../src/core/runtime/UserInputMessage';++const userMsg = { type: 'user.message' as const, content: 'hi' } satisfies AgentInputUserMessage;+const approval = {+ type: 'user.tool_approval' as const,+ thread_id: 'main',+ tool_call_id: 'tc1',+ approval: { status: 'allow' as const },+} satisfies UserToolApprovalMessage;+const toolResponse = {+ type: 'user.tool_response' as const,+ thread_id: 'main',+ tool_call_id: 'tc1',+ content: 'ok',+} satisfies UserToolResponseMessage;+const llmTool: LLMToolMessage = { role: 'tool', tool_call_id: 'tc1', content: 'ok' };++const _userBatch: AgentThreadSendBatch = [userMsg];+const _approvalBatch: AgentThreadSendBatch = [approval, toolResponse];+const _runtimeLlmBatch: AgentThreadRuntimeSendBatch = [llmTool];+const _runtimePublicBatch: AgentThreadRuntimeSendBatch = _userBatch;+void _userBatch;+void _approvalBatch;+void _runtimeLlmBatch;+void _runtimePublicBatch;++// @ts-expect-error mixed user + approval is not a public send batch+const _mixedUserApproval: AgentThreadSendBatch = [userMsg, approval];+// @ts-expect-error mixed user + LLM tool is not a public send batch+const _mixedUserLlm: AgentThreadSendBatch = [userMsg, llmTool];+// @ts-expect-error mixed approval + LLM tool is not a public send batch+const _mixedApprovalLlm: AgentThreadSendBatch = [approval, llmTool];+// @ts-expect-error mixed user + LLM tool is not a runtime send batch either+const _mixedRuntime: AgentThreadRuntimeSendBatch = [userMsg, llmTool];++describe('send batch type ownership', () => {+ it('compiles homogeneous modes and rejects mixed pairs', () => {+ expect(true).toBe(true);+ });+});diff --git a/packages/harness/tests/core/unknownToolLogging.test.ts b/packages/harness/tests/core/unknownToolLogging.test.tsnew file mode 100644index 000000000..2aaa7af3b--- /dev/null+++ b/packages/harness/tests/core/unknownToolLogging.test.ts@@ -0,0 +1,120 @@+import type { ILLM } from '../../src/core/llm/ILLM';+import type {+ ExtendedChatCompletionChunk,+ RawAssistantMessageWithUsage,+} from '../../src/core/llm/LLMTypes';+import { getEmptyUsage } from '../../src/core/llm/LLMTypes';+import { AgentThread } from '../../src/core/runtime/AgentThread';+import { makeUnknownToolInfo, toToolCallInfo } from '../../src/core/runtime/contextUtils';+import { NOOP_AGENT_TRACING } from '../../src/core/tracing/NoopAgentTracing';+import './harnessMocks';+import { makeSilentLogger } from './harnessMocks';++const silentLogger = makeSilentLogger();+const warn = jest.spyOn(silentLogger, 'warn');++async function* unknownToolStream(): AsyncGenerator<+ ExtendedChatCompletionChunk,+ RawAssistantMessageWithUsage,+ unknown+> {+ yield {+ id: 'chunk-1',+ object: 'chat.completion.chunk',+ created: 0,+ model: 'test-model',+ choices: [+ {+ index: 0,+ delta: {+ role: 'assistant',+ tool_calls: [+ {+ index: 0,+ id: 'call-unknown',+ type: 'function',+ function: { name: 'totally_unknown_tool', arguments: '{}' },+ },+ ],+ },+ finish_reason: 'tool_calls',+ },+ ],+ } as ExtendedChatCompletionChunk;++ return {+ output: {+ role: 'assistant',+ content: null,+ tool_calls: [+ {+ id: 'call-unknown',+ type: 'function',+ function: { name: 'totally_unknown_tool', arguments: '{}' },+ },+ ],+ },+ usage: getEmptyUsage(),+ finish_reason: 'tool_calls',+ };+}++async function* finalAnswerStream(): AsyncGenerator<+ ExtendedChatCompletionChunk,+ RawAssistantMessageWithUsage,+ unknown+> {+ yield {+ id: 'chunk-2',+ object: 'chat.completion.chunk',+ created: 0,+ model: 'test-model',+ choices: [{ index: 0, delta: { role: 'assistant', content: 'done' }, finish_reason: 'stop' }],+ } as ExtendedChatCompletionChunk;++ return {+ output: { role: 'assistant', content: 'done' },+ usage: getEmptyUsage(),+ finish_reason: 'stop',+ };+}++describe('AgentThread unknown tool logging', () => {+ it('warns once with the canonical message and emits unknown tool_info', async () => {+ const modelClient: ILLM = {+ create: jest+ .fn()+ .mockImplementationOnce(() => unknownToolStream())+ .mockImplementation(() => finalAnswerStream()),+ createNonStream: jest.fn(),+ };++ const thread = new AgentThread({+ threadId: 'main',+ title: 'Main',+ tracing: NOOP_AGENT_TRACING,+ logger: silentLogger,+ definition: {+ model: 'test-model',+ modelClient,+ instruction: 'test',+ toolSets: [],+ },+ context: [{ role: 'user', content: 'hi' }],+ });++ const deltas: Array<{ tool_calls?: Array<{ tool_info?: unknown }> | undefined }> = [];+ for await (const event of thread.execute({ signal: new AbortController().signal })) {+ if (event.type === 'model.message.delta') {+ deltas.push(event);+ }+ }++ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledWith('LLM called unknown tool: Tool totally_unknown_tool not found in tool mapping.');++ const unknownInfo = toToolCallInfo(makeUnknownToolInfo('totally_unknown_tool'));+ const emitted = deltas.flatMap(d => d.tool_calls ?? []).find(tc => tc.tool_info);+ expect(emitted?.tool_info).toEqual(unknownInfo);+ });+});diff --git a/packages/harness/tests/core/userInputMessage.test.ts b/packages/harness/tests/core/userInputMessage.test.tsnew file mode 100644index 000000000..5aa53a372--- /dev/null+++ b/packages/harness/tests/core/userInputMessage.test.ts@@ -0,0 +1,96 @@+import { AgentSandboxRequiredError, InvalidAgentInputError } from '../../src/core/errors';+import { EventType } from '../../src/core/events/eventSchemas';+import {+ isEmptyMessageContent,+ processAgentUserInput,+ type AgentInputUserMessage,+ type FileContentPart,+} from '../../src/core/runtime/UserInputMessage';+import './harnessMocks';+import { makeStubPublicSandbox } from './harnessMocks';++describe('UserInputMessage validation', () => {+ const sandbox = makeStubPublicSandbox();++ it('detects empty string content', () => {+ expect(isEmptyMessageContent(' ')).toBe(true);+ expect(isEmptyMessageContent('hello')).toBe(false);+ });++ it('detects empty multipart content', () => {+ expect(isEmptyMessageContent([])).toBe(true);+ expect(isEmptyMessageContent([{ type: 'text', text: 'hi' }])).toBe(false);+ });++ it('rejects file uploads when sandbox is unavailable', async () => {+ const msg: AgentInputUserMessage = {+ type: EventType.USER_MESSAGE,+ content: [+ {+ type: 'file',+ name: 'notes.txt',+ data: 'data:text/plain;base64,bm90ZXM=',+ } satisfies FileContentPart,+ ],+ };++ await expect(processAgentUserInput(msg, undefined)).rejects.toBeInstanceOf(AgentSandboxRequiredError);+ await expect(processAgentUserInput(msg, undefined)).rejects.toMatchObject({+ message: 'File uploads requiring sandbox are not supported: no sandbox configured for this agent',+ });+ });++ it('rejects empty file names', async () => {+ const msg: AgentInputUserMessage = {+ type: EventType.USER_MESSAGE,+ content: [+ {+ type: 'file',+ name: '',+ data: 'data:text/plain;base64,bm90ZXM=',+ } satisfies FileContentPart,+ ],+ };++ await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidAgentInputError);+ await expect(processAgentUserInput(msg, sandbox)).rejects.toMatchObject({+ message: 'File name must not be empty',+ });+ });++ it('rejects path traversal in file names', async () => {+ const msg: AgentInputUserMessage = {+ type: EventType.USER_MESSAGE,+ content: [+ {+ type: 'file',+ name: '../secrets.txt',+ data: 'data:text/plain;base64,c2VjcmV0',+ } satisfies FileContentPart,+ ],+ };++ await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidAgentInputError);+ await expect(processAgentUserInput(msg, sandbox)).rejects.toMatchObject({+ message: 'File name contains path traversal: ../secrets.txt',+ });+ });++ it('rejects malformed file data URIs', async () => {+ const msg: AgentInputUserMessage = {+ type: EventType.USER_MESSAGE,+ content: [+ {+ type: 'file',+ name: 'broken.txt',+ data: 'not-a-data-uri',+ } satisfies FileContentPart,+ ],+ };++ await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidAgentInputError);+ await expect(processAgentUserInput(msg, sandbox)).rejects.toMatchObject({+ message: 'File data URI is missing or has unparseable MIME type',+ });+ });+});diff --git a/packages/harness/tests/setup.ts b/packages/harness/tests/setup.tsnew file mode 100644index 000000000..dc08d416e--- /dev/null+++ b/packages/harness/tests/setup.ts@@ -0,0 +1,16 @@+// Suppress console.log / console.warn / console.error during tests+const originalConsoleLog = console.log;+const originalConsoleWarn = console.warn;+const originalConsoleError = console.error;++beforeAll(() => {+ console.log = jest.fn();+ console.warn = jest.fn();+ console.error = jest.fn();+});++afterAll(() => {+ console.log = originalConsoleLog;+ console.warn = originalConsoleWarn;+ console.error = originalConsoleError;+});diff --git a/packages/harness/tsconfig.build.json b/packages/harness/tsconfig.build.jsonnew file mode 100644index 000000000..1e87d59e8--- /dev/null+++ b/packages/harness/tsconfig.build.json@@ -0,0 +1,14 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": false,+ "emitDeclarationOnly": true,+ "declaration": true,+ "declarationMap": true,+ "rootDir": "./src",+ "outDir": "./dist",+ "types": ["node"]+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/harness/tsconfig.json b/packages/harness/tsconfig.jsonnew file mode 100644index 000000000..02e928950--- /dev/null+++ b/packages/harness/tsconfig.json@@ -0,0 +1,17 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "types": ["node", "jest"],+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "rootDir": ".",+ "outDir": "./dist",+ "noEmit": true,+ "paths": {+ "openai/resources/chat": ["./node_modules/openai/resources/chat/index.d.ts"]+ }+ },+ "include": ["src/**/*", "tests/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/harness/tsup.config.ts b/packages/harness/tsup.config.tsnew file mode 100644index 000000000..247bc64e3--- /dev/null+++ b/packages/harness/tsup.config.ts@@ -0,0 +1,31 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ entry: {+ index: 'src/index.ts',+ 'core/index': 'src/core/index.ts',+ 'agentSession/index': 'src/agentSession/index.ts',+ },+ format: ['esm'],+ dts: false,+ splitting: false,+ sourcemap: true,+ clean: true,+ target: 'esnext',+ outDir: 'dist',+ external: [+ '@daytona/sdk',+ '@hono/zod-openapi',+ '@modelcontextprotocol/sdk',+ '@nats-io/nats-core',+ '@opentelemetry/api',+ '@opentelemetry/core',+ 'dedent',+ 'openai',+ 'ulid',+ 'winston',+ 'ws',+ 'zod',+ 'zod-to-json-schema',+ ],+});diff --git a/packages/server/package.json b/packages/server/package.jsonnew file mode 100644index 000000000..1a9d0ec6e--- /dev/null+++ b/packages/server/package.json@@ -0,0 +1,32 @@+{+ "name": "@truefoundry/server",+ "version": "0.1.0",+ "description": "TrueFoundry agent server (CLI/HTTP). Not published yet.",+ "author": "Truefoundry",+ "license": "UNLICENSED",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "tsup",+ "dev": "tsx --env-file=src/config/.env src/main.ts",+ "typecheck": "tsc --noEmit",+ "start": "node dist/main.js"+ },+ "dependencies": {+ "@hono/node-server": "^1.19.14",+ "@hono/swagger-ui": "^0.2.1",+ "@hono/zod-openapi": "^0.19.10",+ "@truefoundry/utils": "workspace:*",+ "hono": "^4.12.31",+ "ulid": "^3.0.2",+ "winston": "^3.13.0",+ "yaml": "^2.9.0",+ "zod": "^3.24.3"+ },+ "devDependencies": {+ "@types/node": "^24.12.0",+ "tsup": "^8.5.0",+ "tsx": "^4.16.2",+ "typescript": "^7.0.2"+ }+}diff --git a/packages/server/src/apis/mcp.ts b/packages/server/src/apis/mcp.tsnew file mode 100644index 000000000..d483f3e2e--- /dev/null+++ b/packages/server/src/apis/mcp.ts@@ -0,0 +1,69 @@+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';+import type { Logger } from 'winston';+import { McpConnectionError } from '@truefoundry/utils/core';+import { isAuthRequired } from '@truefoundry/utils/core';+import { RemoteMCP } from '@truefoundry/utils/core';+import { extractErrorLogFields } from '@truefoundry/utils/core';+import { listMcpServersRoute, listMcpToolsRoute } from '../routes/mcpRoutes';+import type { McpStore } from '../store/McpStore';++export interface McpRouterDeps {+ mcpStore: McpStore;+ logger: Logger;+}++/** Omits keys whose value is `undefined` so wire objects satisfy JSONValue index signatures. */+function omitUndefinedEntries(obj: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(obj)) {+ if (value !== undefined) {+ out[key] = value;+ }+ }+ return out;+}++export function createMcpRouter(deps: McpRouterDeps) {+ const listMcpServersHandler: RouteHandler<typeof listMcpServersRoute> = c => {+ return c.json({ data: deps.mcpStore.list() }, 200);+ };++ // Live MCP `tools/list` call against the configured server, no selectors applied.+ const listMcpToolsHandler: RouteHandler<typeof listMcpToolsRoute> = async c => {+ const { name } = c.req.valid('param');+ const entry = deps.mcpStore.get(name);+ if (!entry) {+ return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);+ }+ const remote = new RemoteMCP({+ id: name,+ name,+ url: entry.url,+ headers: deps.mcpStore.getHeaders(name),+ logger: deps.logger,+ signal: c.req.raw.signal,+ });+ try {+ const response = await remote.listTools();+ if (isAuthRequired(response)) {+ return c.json({ error: { message: `MCP server "${name}" requires authentication` } }, 401);+ }+ const data = response.result.tools.map(tool => omitUndefinedEntries({ ...tool }));+ return c.json({ data }, 200);+ } catch (error) {+ if (error instanceof McpConnectionError) {+ deps.logger.warn(`MCP tools/list failed for "${name}"`, extractErrorLogFields(error));+ if (error.statusCode === 401) {+ return c.json({ error: { message: error.message } }, 401);+ }+ return c.json({ error: { message: error.message } }, 502);+ }+ throw error;+ }+ };++ const router = new OpenAPIHono();+ router.openapi(listMcpServersRoute, listMcpServersHandler);+ router.openapi(listMcpToolsRoute, listMcpToolsHandler);+ return router;+}diff --git a/packages/server/src/apis/models.ts b/packages/server/src/apis/models.tsnew file mode 100644index 000000000..32c33906e--- /dev/null+++ b/packages/server/src/apis/models.ts@@ -0,0 +1,9 @@+import { OpenAPIHono } from '@hono/zod-openapi';+import { listModelsRoute } from '../routes/modelRoutes';+import type { ModelStore } from '../store/ModelStore';++export function createModelsRouter(store: ModelStore) {+ const router = new OpenAPIHono();+ router.openapi(listModelsRoute, c => c.json({ data: store.list() }, 200));+ return router;+}diff --git a/packages/server/src/apis/sessions.ts b/packages/server/src/apis/sessions.tsnew file mode 100644index 000000000..0d07bffe8--- /dev/null+++ b/packages/server/src/apis/sessions.ts@@ -0,0 +1,178 @@+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';+import { ulid } from 'ulid';+import type { SessionRecord } from '@truefoundry/utils/agent-session';+import type { AgentSpec } from '@truefoundry/utils/agent-session';+import { CancellationReason } from '@truefoundry/utils/agent-session';+import type { Sessions } from '@truefoundry/utils/agent-session';+import type { ISessionStore } from '@truefoundry/utils/agent-session';+import { SessionStoreConflictError, SessionStoreNotFoundError } from '@truefoundry/utils/agent-session';+import {+ cancelSessionRoute,+ createSessionRoute,+ listSessionEventsRoute,+ listSessionsRoute,+ updateSessionRoute,+} from '../routes/sessionRoutes';+import type { ActiveTurnRegistry } from '../runtime/activeTurns';+import type { Session } from '../schemas/session';+import type { McpStore } from '../store/McpStore';+import type { ModelStore } from '../store/ModelStore';++/** The server is single-tenant; every record lives under one fixed tenant scope. */+export const TENANT_NAME = 'default';++/**+ * Cross-checks an AgentSpec against the YAML catalogs and the server's+ * capabilities before a session is created or updated, so misconfigured specs+ * fail at admission instead of at turn time. Returns an error message, or+ * undefined when the spec is usable.+ */+function validateAgentSpec(+ spec: AgentSpec,+ deps: { modelStore: ModelStore; mcpStore: McpStore; sandboxSupported: boolean },+): string | undefined {+ if (!deps.modelStore.get(spec.model.name)) {+ return `Unknown model "${spec.model.name}" — not declared in models.yaml`;+ }+ for (const server of spec.mcp_servers ?? []) {+ if (!deps.mcpStore.get(server.name)) {+ return `Unknown MCP server "${server.name}" — not declared in mcp.yaml`;+ }+ }+ if (spec.config?.sandbox?.enabled && !deps.sandboxSupported) {+ return 'sandbox is enabled in the agent spec but this server has no sandbox provider configured — set SANDBOX_SETTINGS (and SANDBOX_API_KEY)';+ }+ if (spec.skills?.length) {+ return 'skills are not supported by this server yet';+ }+ return undefined;+}++export interface SessionsRouterDeps {+ sessions: Sessions;+ sessionStore: ISessionStore;+ activeTurns: ActiveTurnRegistry;+ modelStore: ModelStore;+ mcpStore: McpStore;+ /** Whether a sandbox provider is configured (SANDBOX_SETTINGS); gates spec admission. */+ sandboxSupported: boolean;+}++function toWireSession(record: SessionRecord): Session {+ return {+ id: record.session_id,+ agent_spec: record.agent_spec,+ title: record.title ?? null,+ created_at: record.created_at,+ updated_at: record.updated_at,+ };+}++export function createSessionsRouter(deps: SessionsRouterDeps) {+ const createSessionHandler: RouteHandler<typeof createSessionRoute> = async c => {+ const body = c.req.valid('json');+ const specError = validateAgentSpec(body.agent_spec, deps);+ if (specError) {+ return c.json({ error: { message: specError } }, 400);+ }+ const session = await deps.sessions.create({+ tenant_name: TENANT_NAME,+ session_id: ulid().toLowerCase(),+ agent_spec: body.agent_spec,+ });+ return c.json({ data: toWireSession(session.record) }, 201);+ };++ const updateSessionHandler: RouteHandler<typeof updateSessionRoute> = async c => {+ const { sessionId } = c.req.valid('param');+ const body = c.req.valid('json');+ if (body.agent_spec) {+ const specError = validateAgentSpec(body.agent_spec, deps);+ if (specError) {+ return c.json({ error: { message: specError } }, 400);+ }+ }+ try {+ await deps.sessionStore.updateSession({+ tenant_name: TENANT_NAME,+ session_id: sessionId,+ ...(body.agent_spec ? { agent_spec: body.agent_spec } : {}),+ });+ } catch (error) {+ if (error instanceof SessionStoreNotFoundError) {+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);+ }+ throw error;+ }+ const record = await deps.sessionStore.getSession({ tenant_name: TENANT_NAME, session_id: sessionId });+ if (!record) {+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);+ }+ return c.json({ data: toWireSession(record) }, 200);+ };++ const listSessionsHandler: RouteHandler<typeof listSessionsRoute> = async c => {+ const query = c.req.valid('query');+ try {+ const { data, pagination } = await deps.sessionStore.listSessions({+ tenant_name: TENANT_NAME,+ limit: query.limit,+ ...(query.page_token !== undefined ? { page_token: query.page_token } : {}),+ ...(query.order !== undefined ? { order: query.order } : {}),+ ...(query.start_timestamp !== undefined ? { start_timestamp: query.start_timestamp } : {}),+ ...(query.end_timestamp !== undefined ? { end_timestamp: query.end_timestamp } : {}),+ });+ return c.json({ data: data.map(toWireSession), pagination }, 200);+ } catch (error) {+ if (error instanceof SessionStoreConflictError) {+ return c.json({ error: { message: error.message } }, 400);+ }+ throw error;+ }+ };++ // Cancelling with no running turn is a 200 no-op, matching the turn state+ // machine (first terminal write wins).+ const cancelSessionHandler: RouteHandler<typeof cancelSessionRoute> = async c => {+ const { sessionId } = c.req.valid('param');+ const record = await deps.sessionStore.getSession({ tenant_name: TENANT_NAME, session_id: sessionId });+ if (!record) {+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);+ }+ deps.activeTurns.cancelIfRunning({ sessionId, abortReason: CancellationReason.ClientCancelled });+ return c.json({}, 200);+ };++ const listSessionEventsHandler: RouteHandler<typeof listSessionEventsRoute> = async c => {+ const { sessionId } = c.req.valid('param');+ const query = c.req.valid('query');+ const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });+ if (!session) {+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);+ }+ try {+ const { data, pagination } = await session.listEvents({+ limit: query.limit,+ ...(query.page_token !== undefined ? { page_token: query.page_token } : {}),+ ...(query.last_turn_id !== undefined ? { last_turn_id: query.last_turn_id } : {}),+ });+ return c.json({ data, pagination }, 200);+ } catch (error) {+ if (error instanceof SessionStoreConflictError) {+ return c.json({ error: { message: error.message } }, 400);+ }+ if (error instanceof SessionStoreNotFoundError) {+ return c.json({ error: { message: error.message } }, 404);+ }+ throw error;+ }+ };++ const router = new OpenAPIHono();+ router.openapi(createSessionRoute, createSessionHandler);+ router.openapi(updateSessionRoute, updateSessionHandler);+ router.openapi(listSessionsRoute, listSessionsHandler);+ router.openapi(cancelSessionRoute, cancelSessionHandler);+ router.openapi(listSessionEventsRoute, listSessionEventsHandler);+ return router;+}diff --git a/packages/server/src/apis/skills.ts b/packages/server/src/apis/skills.tsnew file mode 100644index 000000000..8db54bf41--- /dev/null+++ b/packages/server/src/apis/skills.ts@@ -0,0 +1,9 @@+import { OpenAPIHono } from '@hono/zod-openapi';+import { listSkillsRoute } from '../routes/skillRoutes';+import type { SkillStore } from '../store/SkillStore';++export function createSkillsRouter(store: SkillStore) {+ const router = new OpenAPIHono();+ router.openapi(listSkillsRoute, c => c.json({ data: store.list() }, 200));+ return router;+}diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.tsnew file mode 100644index 000000000..1b7abb259--- /dev/null+++ b/packages/server/src/apis/turns.ts@@ -0,0 +1,194 @@+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';+import { streamSSE } from 'hono/streaming';+import { Readable } from 'stream';+import type { Logger } from 'winston';+import { CancellationReason, type TurnInputItem } from '@truefoundry/utils/agent-session';+import type { Sessions } from '@truefoundry/utils/agent-session';+import { SessionStoreNotFoundError } from '@truefoundry/utils/agent-session';+import type { TurnStreamingEvent } from '@truefoundry/utils/agent-session';+import { TurnResourceResolver, type TurnSandboxFactory } from '@truefoundry/utils/agent-session';+import { AgentHarnessError, McpConnectionError } from '@truefoundry/utils/core';+import { OpenAILLM } from '@truefoundry/utils/core';+import { isAgentInputUserMessage, isFileContentPart } from '@truefoundry/utils/core';+import { extractErrorLogFields } from '@truefoundry/utils/core';+import { createTurnRoute } from '../routes/turnRoutes';+import type { ActiveTurnRegistry } from '../runtime/activeTurns';+import type { McpStore } from '../store/McpStore';+import type { ModelStore } from '../store/ModelStore';+import { TENANT_NAME } from './sessions';++export interface TurnsRouterDeps {+ sessions: Sessions;+ activeTurns: ActiveTurnRegistry;+ modelStore: ModelStore;+ mcpStore: McpStore;+ /** Built at boot from SANDBOX_SETTINGS; undefined = sandbox unsupported. */+ sandboxFactory?: TurnSandboxFactory;+ logger: Logger;+}++/**+ * Per-run resource wiring: maps the YAML catalogs onto the agentSession+ * TurnResourceResolver. Models are served by one OpenAI-compatible API+ * (models.yaml base_url); MCP servers resolve to url + env-configured headers;+ * the sandbox factory (when configured) creates/reattaches the run's Sandbox.+ */+function createTurnResolver(deps: {+ modelStore: ModelStore;+ mcpStore: McpStore;+ sandboxFactory?: TurnSandboxFactory;+ logger: Logger;+ signal: AbortSignal;+}): TurnResourceResolver {+ const { modelStore, mcpStore, logger, signal } = deps;+ return new TurnResourceResolver({+ llm: name =>+ new OpenAILLM({+ baseURL: modelStore.baseUrl,+ apiKey: modelStore.getApiKey(name),+ headers: modelStore.getHeaders(name),+ logger,+ signal,+ }),+ mcp: async name => {+ const entry = mcpStore.get(name);+ if (!entry) {+ throw new Error(`MCP server not declared in mcp.yaml: ${name}`);+ }+ return { url: entry.url, headers: mcpStore.getHeaders(name) };+ },+ ...(deps.sandboxFactory ? { sandboxProvider: deps.sandboxFactory } : {}),+ logger,+ });+}++const MAX_SESSION_TITLE_LENGTH = 50;++/**+ * Derives a session title from the first user message of the first turn. Returns the+ * trimmed text (capped at {@link MAX_SESSION_TITLE_LENGTH}) or `undefined` when no usable+ * text is present (e.g. file-only or tool-approval input).+ */+function deriveSessionTitle(input: TurnInputItem[] | undefined): string | undefined {+ const firstUserMessage = input?.find(isAgentInputUserMessage);+ if (!firstUserMessage) {+ return undefined;+ }++ const text =+ typeof firstUserMessage.content === 'string'+ ? firstUserMessage.content+ : firstUserMessage.content+ .filter(part => !isFileContentPart(part))+ .map(part => part.text)+ .join(' ');++ const trimmed = text.trim();+ if (!trimmed) {+ return undefined;+ }+ return trimmed.slice(0, MAX_SESSION_TITLE_LENGTH);+}++/**+ * SSE payload for one turn event. The `id` field carries the per-stream+ * sequence number; the event body itself is not numbered (yield order is+ * persist order, so the transport boundary stamps).+ */+function turnEventSsePayload(event: TurnStreamingEvent, sequenceNumber: number): { id: string; data: string } {+ return {+ id: String(sequenceNumber),+ data: JSON.stringify(event),+ };+}++export function createTurnsRouter(deps: TurnsRouterDeps) {+ const createTurnHandler: RouteHandler<typeof createTurnRoute> = async c => {+ const { sessionId } = c.req.valid('param');+ const body = c.req.valid('json');++ const session = await deps.sessions.get({ tenant_name: TENANT_NAME, session_id: sessionId });+ if (!session) {+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);+ }++ // Starting a new turn supersedes the session's running turn, if any.+ deps.activeTurns.cancelIfRunning({ sessionId, abortReason: CancellationReason.CancelledForNextTurn });++ const abortController = new AbortController();+ const resolver = createTurnResolver({+ modelStore: deps.modelStore,+ mcpStore: deps.mcpStore,+ ...(deps.sandboxFactory ? { sandboxFactory: deps.sandboxFactory } : {}),+ logger: deps.logger,+ signal: abortController.signal,+ });++ // First turn only: derive the title from the first user message. The store+ // never overwrites an existing title.+ const title = session.record.last_turn_id ? undefined : deriveSessionTitle(body.input);++ let turn;+ try {+ turn = await session.run({+ ...(body.input !== undefined ? { input: body.input } : {}),+ previous_turn_id: body.previous_turn_id,+ signal: abortController.signal,+ resolver,+ ...(title !== undefined ? { update_session_title_if_not_exist: title } : {}),+ });+ } catch (error) {+ // Unknown previous_turn_id (nothing was persisted).+ if (error instanceof SessionStoreNotFoundError) {+ return c.json({ error: { message: error.message } }, 404);+ }+ // Input/spec validation failures from the harness. MCP failures carry+ // their own status but the wire contract only declares 400 here.+ if (error instanceof AgentHarnessError && !(error instanceof McpConnectionError)) {+ return c.json({ error: { message: error.message } }, 400);+ }+ throw error;+ }++ deps.activeTurns.register({ sessionId, turnId: turn.id, abortController });++ // Buffer the run behind a Readable so a slow or disconnected client cannot+ // stall execution; the SSE loop below drains it independently.+ const generator = Readable.from(turn.stream(), { objectMode: true, highWaterMark: 128000 });++ let shouldWriteToSSEStream = true;+ let sequenceNumber = -1;+ return streamSSE(c, async stream => {+ // On client disconnect stop writing but keep draining, so the turn+ // completes and its events persist.+ stream.onAbort(() => {+ shouldWriteToSSEStream = false;+ });+ try {+ for await (const event of generator) {+ sequenceNumber += 1;+ if (!stream.closed && !stream.aborted && shouldWriteToSSEStream) {+ try {+ await stream.writeSSE(turnEventSsePayload(event, sequenceNumber));+ } catch (error) {+ deps.logger.error('SSE stream write error', extractErrorLogFields(error));+ shouldWriteToSSEStream = false;+ }+ }+ }+ } catch (error) {+ deps.logger.error('Unexpected error in turn SSE stream loop', extractErrorLogFields(error));+ } finally {+ deps.activeTurns.finish({ sessionId, turnId: turn.id });+ await stream.close();+ }+ });+ };++ const router = new OpenAPIHono();+ router.openapi(createTurnRoute, createTurnHandler);+ // subscribeTurnRoute (routes/turnRoutes.ts) is defined but not registered:+ // re-subscribing to a running turn needs a live-stream registry that this+ // single-process server does not have yet.+ return router;+}diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsnew file mode 100644index 000000000..d4482dd59--- /dev/null+++ b/packages/server/src/app.ts@@ -0,0 +1,88 @@+/**+ * HTTP application: composes the resource routers and serves the OpenAPI+ * document (/openapi.json) and Swagger UI (/docs).+ */+import { swaggerUI } from '@hono/swagger-ui';+import { OpenAPIHono } from '@hono/zod-openapi';+import { HTTPException } from 'hono/http-exception';+import type { Logger } from 'winston';+import type { Sessions } from '@truefoundry/utils/agent-session';+import type { ISessionStore } from '@truefoundry/utils/agent-session';+import type { TurnSandboxFactory } from '@truefoundry/utils/agent-session';+import { createMcpRouter } from './apis/mcp';+import { createModelsRouter } from './apis/models';+import { createSessionsRouter } from './apis/sessions';+import { createSkillsRouter } from './apis/skills';+import { createTurnsRouter } from './apis/turns';+import type { ActiveTurnRegistry } from './runtime/activeTurns';+import type { McpStore } from './store/McpStore';+import type { ModelStore } from './store/ModelStore';+import type { SkillStore } from './store/SkillStore';++export const openApiDocConfig = {+ openapi: '3.0.0',+ info: {+ title: 'Agent Server',+ description: 'Agent server exposing models, MCP servers and skills from local YAML config.',+ version: '0.1.0',+ },+};++export interface ServerDeps {+ modelStore: ModelStore;+ mcpStore: McpStore;+ skillStore: SkillStore;+ sessionStore: ISessionStore;+ sessions: Sessions;+ activeTurns: ActiveTurnRegistry;+ /** Built at boot from SANDBOX_SETTINGS; undefined = sandbox unsupported. */+ sandboxFactory?: TurnSandboxFactory;+ logger: Logger;+}++export function createServerApp(deps: ServerDeps) {+ const app = new OpenAPIHono();++ app.get('/', c => c.text('OK!'));++ app.route('/v1/models', createModelsRouter(deps.modelStore));+ app.route('/v1/mcp-servers', createMcpRouter({ mcpStore: deps.mcpStore, logger: deps.logger }));+ app.route('/v1/skills', createSkillsRouter(deps.skillStore));+ app.route(+ '/v1/sessions',+ createSessionsRouter({+ sessions: deps.sessions,+ sessionStore: deps.sessionStore,+ activeTurns: deps.activeTurns,+ modelStore: deps.modelStore,+ mcpStore: deps.mcpStore,+ sandboxSupported: deps.sandboxFactory !== undefined,+ }),+ );+ app.route(+ '/v1/sessions',+ createTurnsRouter({+ sessions: deps.sessions,+ activeTurns: deps.activeTurns,+ modelStore: deps.modelStore,+ mcpStore: deps.mcpStore,+ ...(deps.sandboxFactory ? { sandboxFactory: deps.sandboxFactory } : {}),+ logger: deps.logger,+ }),+ );++ app.get('/docs', swaggerUI({ url: '/openapi.json' }));+ app.get('/openapi.json', c => c.json(app.getOpenAPIDocument(openApiDocConfig)));++ app.notFound(c => c.json({ error: { message: `Route not found: ${c.req.method} ${c.req.path}` } }, 404));++ app.onError((error, c) => {+ if (error instanceof HTTPException) {+ return c.json({ error: { message: error.message } }, error.status);+ }+ deps.logger.error('Unhandled error', { message: error.message, stack: error.stack });+ return c.json({ error: { message: 'Internal server error' } }, 500);+ });++ return app;+}diff --git a/packages/server/src/config/.env.example b/packages/server/src/config/.env.examplenew file mode 100644index 000000000..6df7a6c70--- /dev/null+++ b/packages/server/src/config/.env.example@@ -0,0 +1,63 @@+# ---------------------------------------------------------------------------+# Public agent server environment+#+# Copy to .env and fill in the values. The server validates all of these at+# startup and refuses to boot on any invalid value (bad JSON, bad URL, etc.).+# ---------------------------------------------------------------------------++# HTTP port the server listens on. Optional, defaults to 8790.+PORT=8790++# Note: models.yaml, mcp.yaml and skills.yaml are always read from ./config+# (relative to the working directory). The model API base URL is the+# base_url field in models.yaml; only its API key lives here.++# Required. Default API key for the OpenAI-compatible API at models.yaml's+# base_url, sent as "Authorization: Bearer <key>" on every model request.+# Per-model overrides use MODEL_{NAME}_API_KEY with the same {NAME} rules as+# MODEL_{NAME}_HEADERS below.+MODEL_API_KEY=<your-api-key>+# MODEL_OPENAI_MAIN_GPT_5_API_KEY=<gpt-5-specific-key>++# ---------------------------------------------------------------------------+# Extra model headers (JSON objects of string values). Optional.+#+# MODEL_HEADERS is added to every model request. Per-model overrides use+# MODEL_{NAME}_HEADERS, where {NAME} is the model name from models.yaml,+# uppercased with every run of non-alphanumeric characters replaced by "_".+# Example: model "openai-main/gpt-5" -> MODEL_OPENAI_MAIN_GPT_5_HEADERS+# ---------------------------------------------------------------------------+# MODEL_HEADERS={"x-custom-header":"value"}+# MODEL_OPENAI_MAIN_GPT_5_HEADERS={"x-custom-header":"gpt-5-specific-value"}++# ---------------------------------------------------------------------------+# MCP server auth headers. Same rules as model headers: MCP_HEADERS applies to+# every MCP server in mcp.yaml; MCP_{NAME}_HEADERS overrides per server.+# Example: MCP server "github" -> MCP_GITHUB_HEADERS+# ---------------------------------------------------------------------------+# MCP_HEADERS={}+# MCP_GITHUB_HEADERS={"Authorization":"Bearer <github-mcp-token>"}++# ---------------------------------------------------------------------------+# Sandbox (optional). When unset, agent specs with config.sandbox.enabled are+# rejected at session creation.+#+# SANDBOX_SETTINGS is a JSON object discriminated on "type". Supported today:+# {"type":"daytona","snapshotName":"<daytona-snapshot>"}+# Optional daytona fields (defaults): timeoutMs (60000),+# autoStopIntervalInMinutes (5), autoArchiveIntervalInMinutes (60),+# autoDeleteIntervalInMinutes (43200).+#+# The provider API key goes in SANDBOX_API_KEY (recommended, keeps the+# credential out of the JSON blob) or as "apiKey" inside SANDBOX_SETTINGS;+# SANDBOX_API_KEY wins when both are set.+# ---------------------------------------------------------------------------+# SANDBOX_API_KEY=<daytona-api-key>+# SANDBOX_SETTINGS={"type":"daytona","snapshotName":"my-snapshot"}++# Max bytes for a single file download out of the sandbox. Default 20 MB.+# SANDBOX_FILE_MAX_BYTES=20971520++# Lifetime of the signed preview URL minted for the sandbox NATS bridge+# (effectively the max duration of one turn's sandbox connection). Default 1 hour.+# SANDBOX_PREVIEW_URL_EXPIRY_SECONDS=3600diff --git a/packages/server/src/config/config.ts b/packages/server/src/config/config.tsnew file mode 100644index 000000000..ba4394303--- /dev/null+++ b/packages/server/src/config/config.ts@@ -0,0 +1,232 @@+/**+ * Server configuration.+ *+ * Environment variables are read once at module load into a typed+ * `configuration` object exported as default. Any invalid value throws at+ * import time, so a misconfigured server fails fast at boot instead of+ * mid-run.+ */+import path from 'node:path';++// ============================================================================+// CONFIG FILES+// ============================================================================++/** Directory containing the YAML config files: `./config` relative to the working directory. */+export const CONFIG_DIR = path.resolve('config');++/** YAML files the stores load from CONFIG_DIR at startup. */+export const CONFIG_FILES = {+ models: 'models.yaml',+ mcpServers: 'mcp.yaml',+ skills: 'skills.yaml',+} as const;++// ============================================================================+// HELPER FUNCTIONS+// ============================================================================++export interface GetEnvOptions {+ defaultValue?: string;+ required?: boolean;+}++export const getEnv = (key: string, options?: GetEnvOptions): string | undefined => {+ const value = process.env[key];+ if (value !== undefined) {+ return value;+ }++ // Checking for undefined as value can also be 0 or ""+ if (options?.defaultValue !== undefined) {+ return options.defaultValue;+ }++ if (process.env['NODE_ENV'] !== 'test' && options?.required) {+ throw new Error(`Environment variable ${key} is required but was not specified.`);+ }++ return undefined;+};++/**+ * Normalizes a model/MCP name to the `{NAME}` segment of its env var:+ * uppercase, with every run of non-alphanumeric characters collapsed to `_`.+ * Example: model `gpt-5` -> `GPT_5` -> env var `MODEL_GPT_5_HEADERS`.+ */+export function normalizeEnvName(name: string): string {+ return name.replace(/[^a-zA-Z0-9]+/g, '_').toUpperCase();+}++/**+ * Parses a headers env var: must be a JSON object with string values.+ * Malformed values throw so a typo'd credential block fails at startup+ * instead of surfacing as auth errors mid-run. Unset values yield an empty+ * record.+ */+export const parseHeaders = (envKey: string, raw: string | undefined): Record<string, string> => {+ if (raw === undefined) {+ return {};+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ throw new Error(+ `Environment variable ${envKey} must be valid JSON: ${error instanceof Error ? error.message : String(error)}`,+ { cause: error },+ );+ }+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error(`Environment variable ${envKey} must be a JSON object of string values`);+ }+ const headers: Record<string, string> = {};+ for (const [key, value] of Object.entries(parsed)) {+ if (typeof value !== 'string') {+ throw new Error(`Environment variable ${envKey} must only contain string values (key "${key}" is not a string)`);+ }+ headers[key] = value;+ }+ return headers;+};++/**+ * Collects `{PREFIX}_{NAME}_HEADERS` env vars into a map keyed by the+ * normalized `{NAME}` — the same normalization lookups use, so any casing of+ * the env var name works. The default `{PREFIX}_HEADERS` var never matches+ * (the regex requires a non-empty `{NAME}` segment).+ */+export const parseHeadersByName = (prefix: 'MODEL' | 'MCP'): Record<string, Record<string, string>> => {+ const pattern = new RegExp(`^${prefix}_(.+)_HEADERS$`);+ const byName: Record<string, Record<string, string>> = {};+ for (const [envKey, raw] of Object.entries(process.env)) {+ const match = envKey.match(pattern);+ if (!match || raw === undefined) continue;+ const name = match[1];+ if (name === undefined) continue;+ byName[normalizeEnvName(name)] = parseHeaders(envKey, raw);+ }+ return byName;+};++/**+ * Collects `MODEL_{NAME}_API_KEY` env vars into a map keyed by the normalized+ * `{NAME}`. The default `MODEL_API_KEY` var never matches (the regex requires+ * a non-empty `{NAME}` segment).+ */+export const parseApiKeysByName = (): Record<string, string> => {+ const pattern = /^MODEL_(.+)_API_KEY$/;+ const byName: Record<string, string> = {};+ for (const [envKey, raw] of Object.entries(process.env)) {+ const match = envKey.match(pattern);+ if (!match || raw === undefined) continue;+ const name = match[1];+ if (name === undefined) continue;+ byName[normalizeEnvName(name)] = raw;+ }+ return byName;+};++export const parsePort = (raw: string | undefined): number => {+ if (raw === undefined || raw.trim() === '') {+ return DEFAULT_PORT;+ }+ const port = Number(raw);+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ throw new Error(`Environment variable PORT must be an integer between 1 and 65535, got "${raw}"`);+ }+ return port;+};++/** Parses a positive-integer env var, falling back to `defaultValue` when unset/blank. */+export const parsePositiveInt = (envKey: string, raw: string | undefined, defaultValue: number): number => {+ if (raw === undefined || raw.trim() === '') {+ return defaultValue;+ }+ const value = Number(raw);+ if (!Number.isInteger(value) || value < 1) {+ throw new Error(`Environment variable ${envKey} must be a positive integer, got "${raw}"`);+ }+ return value;+};++// ============================================================================+// CONFIGURATION INTERFACE+// ============================================================================++export const DEFAULT_PORT = 8790;++export interface ServerConfiguration {+ /** HTTP port the server listens on. Env: `PORT`. */+ PORT: number;+ /**+ * Default API key for the OpenAI-compatible API at models.yaml's base_url,+ * sent as `Authorization: Bearer <key>` on every model request.+ * Env: `MODEL_API_KEY` (required).+ */+ MODEL_API_KEY: string;+ /**+ * Per-model API key overrides keyed by normalized model name.+ * Env: `MODEL_{NAME}_API_KEY` (see `normalizeEnvName`).+ */+ MODEL_API_KEY_BY_NAME: Record<string, string>;+ /** Extra headers applied to every model request. Env: `MODEL_HEADERS`. */+ MODEL_HEADERS: Record<string, string>;+ /**+ * Per-model header overrides keyed by normalized model name.+ * Env: `MODEL_{NAME}_HEADERS` (see `normalizeEnvName`).+ */+ MODEL_HEADERS_BY_NAME: Record<string, Record<string, string>>;+ /** Default headers applied to every MCP server request. Env: `MCP_HEADERS`. */+ MCP_HEADERS: Record<string, string>;+ /**+ * Per-MCP-server header overrides keyed by normalized server name.+ * Env: `MCP_{NAME}_HEADERS` (see `normalizeEnvName`).+ */+ MCP_HEADERS_BY_NAME: Record<string, Record<string, string>>;+ /**+ * Sandbox provider settings as a JSON object discriminated on `type`+ * (see SandboxProviderSettingsSchema in the harness; today: "daytona").+ * Unset = sandbox unsupported: specs with `config.sandbox.enabled` are+ * rejected at session creation. Validated at boot by the sandbox factory.+ * Env: `SANDBOX_SETTINGS`.+ */+ SANDBOX_SETTINGS: string | undefined;+ /**+ * Provider API key, kept out of the SANDBOX_SETTINGS JSON blob; overrides+ * an inline `apiKey` when both are set. Env: `SANDBOX_API_KEY`.+ */+ SANDBOX_API_KEY: string | undefined;+ /** Max bytes for a single file download out of the sandbox. Env: `SANDBOX_FILE_MAX_BYTES`. Default 20 MB. */+ SANDBOX_FILE_MAX_BYTES: number;+ /**+ * Lifetime of the signed preview URL minted for the sandbox NATS bridge;+ * effectively the max duration of one turn's sandbox connection.+ * Env: `SANDBOX_PREVIEW_URL_EXPIRY_SECONDS`. Default 1 hour.+ */+ SANDBOX_PREVIEW_URL_EXPIRY_SECONDS: number;+}++// ============================================================================+// CONFIGURATION VALUES+// ============================================================================++const configuration: ServerConfiguration = {+ PORT: parsePort(getEnv('PORT')),+ MODEL_API_KEY: getEnv('MODEL_API_KEY', { required: true })!,+ MODEL_API_KEY_BY_NAME: parseApiKeysByName(),+ MODEL_HEADERS: parseHeaders('MODEL_HEADERS', getEnv('MODEL_HEADERS')),+ MODEL_HEADERS_BY_NAME: parseHeadersByName('MODEL'),+ MCP_HEADERS: parseHeaders('MCP_HEADERS', getEnv('MCP_HEADERS')),+ MCP_HEADERS_BY_NAME: parseHeadersByName('MCP'),+ SANDBOX_SETTINGS: getEnv('SANDBOX_SETTINGS'),+ SANDBOX_API_KEY: getEnv('SANDBOX_API_KEY'),+ SANDBOX_FILE_MAX_BYTES: parsePositiveInt('SANDBOX_FILE_MAX_BYTES', getEnv('SANDBOX_FILE_MAX_BYTES'), 20_971_520),+ SANDBOX_PREVIEW_URL_EXPIRY_SECONDS: parsePositiveInt(+ 'SANDBOX_PREVIEW_URL_EXPIRY_SECONDS',+ getEnv('SANDBOX_PREVIEW_URL_EXPIRY_SECONDS'),+ 3600,+ ),+} as const;++export default configuration;diff --git a/packages/server/src/config/mcp.yaml b/packages/server/src/config/mcp.yamlnew file mode 100644index 000000000..b9c4bd72a--- /dev/null+++ b/packages/server/src/config/mcp.yaml@@ -0,0 +1,9 @@+# MCP servers available to agents.+#+# Auth headers are configured via env vars, never in this file:+# MCP_HEADERS - default headers for every MCP server+# MCP_{NAME}_HEADERS - per-server overrides ({NAME} = server name,+# uppercased, non-alphanumerics replaced by "_")+mcp_servers:+ - name: github-remote+ url: https://internal.devtest.truefoundry.tech/api/llm/truefoundry/mcp/github-remote/serverdiff --git a/packages/server/src/config/models.yaml b/packages/server/src/config/models.yamlnew file mode 100644index 000000000..1de9c84fe--- /dev/null+++ b/packages/server/src/config/models.yaml@@ -0,0 +1,13 @@+# Models reachable through the OpenAI-compatible API at base_url.+#+# Auth headers are configured via env vars, never in this file:+# MODEL_API_KEY - default API key for base_url (required)+# MODEL_{NAME}_API_KEY - per-model API key override+# MODEL_HEADERS - extra default headers for every model+# MODEL_{NAME}_HEADERS - per-model overrides ({NAME} = model name,+# uppercased, non-alphanumerics replaced by "_")+base_url: https://internal.devtest.truefoundry.tech/api/llm++models:+ - name: anthropic/claude-sonnet-4-6+ max_output_tokens: 32768diff --git a/packages/server/src/config/skills.yaml b/packages/server/src/config/skills.yamlnew file mode 100644index 000000000..e67bbd546--- /dev/null+++ b/packages/server/src/config/skills.yaml@@ -0,0 +1,10 @@+# Agent skills, each a directory with a SKILL.md in a public git repository.+# url - public git repository+# path - directory containing SKILL.md (optional, repo root if omitted)+# reference - commit SHA, tag or branch to pin (optional, default branch if omitted)+skills:+ - name: pr-review+ url: https://github.com/acme/agent-skills+ path: skills/pr-review+ reference: v1.2.0+ description: Reviews pull requests for style and correctness.diff --git a/packages/server/src/main.ts b/packages/server/src/main.tsnew file mode 100644index 000000000..01b26b32b--- /dev/null+++ b/packages/server/src/main.ts@@ -0,0 +1,62 @@+/**+ * Server entry point: validates config, loads the YAML stores, wires the+ * in-memory session runtime and starts the HTTP server. Any config or store+ * error aborts startup.+ */+import { serve } from '@hono/node-server';+import winston from 'winston';++try {+ const [+ { createServerApp },+ { default: configuration },+ { ModelStore },+ { McpStore },+ { SkillStore },+ { Sessions, InMemorySessionStore },+ { ActiveTurnRegistry },+ { createServerSandboxFactory },+ ] = await Promise.all([+ import('./app'),+ import('./config/config'),+ import('./store/ModelStore'),+ import('./store/McpStore'),+ import('./store/SkillStore'),+ import('@truefoundry/utils/agent-session'),+ import('./runtime/activeTurns'),+ import('./runtime/sandboxFactory'),+ ]);++ // Console logger shared by the server runtime (harness components require one).+ const logger = winston.createLogger({+ level: process.env['LOG_LEVEL'] ?? 'info',+ format: winston.format.combine(winston.format.timestamp(), winston.format.json()),+ transports: [new winston.transports.Console()],+ });++ const sessionStore = new InMemorySessionStore();+ // Throws on malformed SANDBOX_SETTINGS; undefined when sandbox is not configured.+ const sandboxFactory = createServerSandboxFactory({ logger });+ const app = createServerApp({+ modelStore: ModelStore.load(),+ mcpStore: McpStore.load(),+ skillStore: SkillStore.load(),+ sessionStore,+ sessions: new Sessions({ sessionStore }),+ activeTurns: new ActiveTurnRegistry(),+ ...(sandboxFactory ? { sandboxFactory } : {}),+ logger,+ });++ const server = serve({ fetch: app.fetch, port: configuration.PORT }, info => {+ console.log(`Agent server listening on http://localhost:${info.port} (docs at /docs)`);+ });++ server.on('error', error => {+ console.error('Failed to start server:', error instanceof Error ? error.message : error);+ process.exit(1);+ });+} catch (error) {+ console.error('Failed to start server:', error instanceof Error ? error.message : error);+ process.exit(1);+}diff --git a/packages/server/src/routes/mcpRoutes.ts b/packages/server/src/routes/mcpRoutes.tsnew file mode 100644index 000000000..43b19460a--- /dev/null+++ b/packages/server/src/routes/mcpRoutes.ts@@ -0,0 +1,72 @@+import { createRoute, z } from '@hono/zod-openapi';+import { RequestErrorResponseSchema } from '../schemas/errors';+import { McpServerEntrySchema } from '../store/schemas';++const MCP_SERVERS_TAG = 'MCP Servers';++const ListMcpServersResponseSchema = z+ .object({+ data: z.array(McpServerEntrySchema),+ })+ .openapi('ListMcpServersResponse');++export const listMcpServersRoute = createRoute({+ method: 'get',+ path: '/',+ tags: [MCP_SERVERS_TAG],+ summary: 'List MCP servers',+ description: 'MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.',+ responses: {+ 200: {+ content: { 'application/json': { schema: ListMcpServersResponseSchema } },+ description: 'All configured MCP servers.',+ },+ },+});++// Tools are passed through verbatim from the MCP server's `tools/list`+// response (name, description, inputSchema, outputSchema, annotations, ...),+// so they are documented as opaque objects rather than a copied MCP schema —+// the MCP spec owns the tool shape. The SDK's own ToolSchema can't be reused+// here: it is Zod v4, while @hono/zod-openapi is Zod v3.+const ListMcpToolsResponseSchema = z+ .object({+ data: z+ .array(z.record(z.unknown()))+ .describe('MCP `tools/list` entries, passed through verbatim from the MCP server.'),+ })+ .openapi('ListMcpToolsResponse');++const McpServerNameParamsSchema = z.object({+ name: z.string().min(1).describe('MCP server name from mcp.yaml.'),+});++export const listMcpToolsRoute = createRoute({+ method: 'get',+ path: '/{name}/tools',+ tags: [MCP_SERVERS_TAG],+ summary: 'List tools of an MCP server',+ description:+ 'All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.',+ request: {+ params: McpServerNameParamsSchema,+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: ListMcpToolsResponseSchema } },+ description: 'All tools of the MCP server.',+ },+ 401: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'The MCP server requires authentication (configure MCP_HEADERS / MCP_{NAME}_HEADERS).',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'MCP server not declared in mcp.yaml.',+ },+ 502: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'The MCP server could not be reached or returned an error.',+ },+ },+});diff --git a/packages/server/src/routes/modelRoutes.ts b/packages/server/src/routes/modelRoutes.tsnew file mode 100644index 000000000..5cb5cd251--- /dev/null+++ b/packages/server/src/routes/modelRoutes.ts@@ -0,0 +1,22 @@+import { createRoute, z } from '@hono/zod-openapi';+import { ModelEntrySchema } from '../store/schemas';++const ListModelsResponseSchema = z+ .object({+ data: z.array(ModelEntrySchema),+ })+ .openapi('ListModelsResponse');++export const listModelsRoute = createRoute({+ method: 'get',+ path: '/',+ tags: ['Models'],+ summary: 'List models',+ description: "Models declared in models.yaml, reachable through the OpenAI-compatible API at the file's base_url.",+ responses: {+ 200: {+ content: { 'application/json': { schema: ListModelsResponseSchema } },+ description: 'All configured models.',+ },+ },+});diff --git a/packages/server/src/routes/sessionRoutes.ts b/packages/server/src/routes/sessionRoutes.tsnew file mode 100644index 000000000..45dc2e4a9--- /dev/null+++ b/packages/server/src/routes/sessionRoutes.ts@@ -0,0 +1,152 @@+/**+ * Session route definitions (mounted at /v1/sessions). A session holds an+ * inline agent spec. Handlers are registered in apis/sessions.ts.+ */+import { createRoute, z } from '@hono/zod-openapi';+import { RequestErrorResponseSchema } from '../schemas/errors';+import { ListSessionEventsRequestQuerySchema, ListSessionEventsResponseSchema } from '../schemas/events';+import {+ CreateSessionRequestSchema,+ GetSessionResponseSchema,+ ListSessionsRequestQuerySchema,+ ListSessionsResponseSchema,+ UpdateSessionRequestSchema,+} from '../schemas/session';+import { CancelSessionRequestSchema, CancelSessionResponseSchema } from '../schemas/turn';++const SESSIONS_TAG = 'Sessions';++export const SessionIdParamsSchema = z.object({+ sessionId: z.string().min(1).max(64).describe('Session identifier.'),+});++export const createSessionRoute = createRoute({+ method: 'post',+ path: '/',+ tags: [SESSIONS_TAG],+ summary: 'Create a session',+ description: 'Create a session holding an inline agent spec. Turns are executed against this spec.',+ request: {+ body: {+ content: { 'application/json': { schema: CreateSessionRequestSchema } },+ required: true,+ },+ },+ responses: {+ 201: {+ content: { 'application/json': { schema: GetSessionResponseSchema } },+ description: 'Session created.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body.',+ },+ },+});++export const updateSessionRoute = createRoute({+ method: 'patch',+ path: '/{sessionId}',+ tags: [SESSIONS_TAG],+ summary: 'Update a session',+ description: "Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.",+ request: {+ params: SessionIdParamsSchema,+ body: {+ content: { 'application/json': { schema: UpdateSessionRequestSchema } },+ required: true,+ },+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: GetSessionResponseSchema } },+ description: 'Session updated.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Session not found.',+ },+ },+});++export const listSessionsRoute = createRoute({+ method: 'get',+ path: '/',+ tags: [SESSIONS_TAG],+ summary: 'List sessions',+ description:+ 'List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.',+ request: {+ query: ListSessionsRequestQuerySchema,+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: ListSessionsResponseSchema } },+ description: 'Paginated sessions.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid query parameters or page token.',+ },+ },+});++export const cancelSessionRoute = createRoute({+ method: 'post',+ path: '/{sessionId}/cancel',+ tags: [SESSIONS_TAG],+ summary: 'Cancel a running turn in a session',+ description: 'Cancel the running last turn for a session.',+ request: {+ params: SessionIdParamsSchema,+ body: {+ content: { 'application/json': { schema: CancelSessionRequestSchema } },+ required: false,+ },+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: CancelSessionResponseSchema } },+ description: 'Turn cancelled.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Session not found.',+ },+ 412: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Requested action cannot be performed on the session because it is no longer usable.',+ },+ },+});++export const listSessionEventsRoute = createRoute({+ method: 'get',+ path: '/{sessionId}/events',+ tags: [SESSIONS_TAG],+ summary: 'List session events',+ description:+ 'List session events as `{ turn_id, event }` across the turn chain (newest first). Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done; streaming deltas are not included. If the newest turn is still running, its events are excluded — subscribe to the running turn for live events. Use `page_token` to paginate backward toward older events.',+ request: {+ params: SessionIdParamsSchema,+ query: ListSessionEventsRequestQuerySchema,+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: ListSessionEventsResponseSchema } },+ description: 'Paginated session events.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid page token.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Session not found.',+ },+ },+});diff --git a/packages/server/src/routes/skillRoutes.ts b/packages/server/src/routes/skillRoutes.tsnew file mode 100644index 000000000..699787529--- /dev/null+++ b/packages/server/src/routes/skillRoutes.ts@@ -0,0 +1,22 @@+import { createRoute, z } from '@hono/zod-openapi';+import { SkillEntrySchema } from '../store/schemas';++const ListSkillsResponseSchema = z+ .object({+ data: z.array(SkillEntrySchema),+ })+ .openapi('ListSkillsResponse');++export const listSkillsRoute = createRoute({+ method: 'get',+ path: '/',+ tags: ['Skills'],+ summary: 'List skills',+ description: 'Agent skills declared in skills.yaml.',+ responses: {+ 200: {+ content: { 'application/json': { schema: ListSkillsResponseSchema } },+ description: 'All configured skills.',+ },+ },+});diff --git a/packages/server/src/routes/turnRoutes.ts b/packages/server/src/routes/turnRoutes.tsnew file mode 100644index 000000000..9cd4b5440--- /dev/null+++ b/packages/server/src/routes/turnRoutes.ts@@ -0,0 +1,92 @@+/**+ * Turn route definitions (mounted at /v1/sessions). Creating a turn responds+ * with a Server-Sent Events stream; a running turn can be re-subscribed to+ * with resume support. Handlers are registered in apis/turns.ts.+ */+import { createRoute, z } from '@hono/zod-openapi';+import { RequestErrorResponseSchema } from '../schemas/errors';+import { TurnStreamingEventSchema } from '../schemas/events';+import { CreateTurnRequestSchema, SubscribeTurnRequestSchema } from '../schemas/turn';+import { SessionIdParamsSchema } from './sessionRoutes';++const SESSIONS_TAG = 'Sessions';++export const TurnIdParamsSchema = SessionIdParamsSchema.extend({+ turnId: z.string().min(1).describe('Turn identifier.'),+});++export const createTurnRoute = createRoute({+ method: 'post',+ path: '/{sessionId}/turns',+ tags: [SESSIONS_TAG],+ summary: 'Create a turn in a session',+ description: `Start or continue a turn within a session. Responds with a Server-Sent Events stream.+Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto\`).`,+ request: {+ params: SessionIdParamsSchema,+ body: {+ content: { 'application/json': { schema: CreateTurnRequestSchema } },+ required: true,+ },+ },+ responses: {+ 200: {+ content: {+ 'text/event-stream': {+ schema: TurnStreamingEventSchema,+ },+ },+ description: 'Server-Sent Events stream of turn events.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Session or prior turn not found.',+ },+ 412: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Requested action cannot be performed on the session because it is no longer usable.',+ },+ },+});++export const subscribeTurnRoute = createRoute({+ method: 'post',+ path: '/{sessionId}/turns/{turnId}/subscribe',+ tags: [SESSIONS_TAG],+ summary: 'Subscribe to a running turn',+ description:+ 'Subscribe to the live SSE stream for a turn. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).',+ request: {+ params: TurnIdParamsSchema,+ body: {+ content: { 'application/json': { schema: SubscribeTurnRequestSchema } },+ required: true,+ },+ },+ responses: {+ 200: {+ content: {+ 'text/event-stream': {+ schema: TurnStreamingEventSchema,+ },+ },+ description: 'Server-Sent Events stream of turn events (deltas and lifecycle).',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Turn not found.',+ },+ 412: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Cannot subscribe — the live stream no longer exists.',+ },+ },+});diff --git a/packages/server/src/runtime/activeTurns.ts b/packages/server/src/runtime/activeTurns.tsnew file mode 100644index 000000000..f90c02c02--- /dev/null+++ b/packages/server/src/runtime/activeTurns.ts@@ -0,0 +1,43 @@+/**+ * In-memory registry of running turns, at most one per session. Cancel and+ * turn-creation code abort a run through its AbortController; TurnHandle.stream()+ * writes the terminal state when the signal fires.+ */+interface ActiveTurn {+ turnId: string;+ abortController: AbortController;+}++export class ActiveTurnRegistry {+ private readonly runs = new Map<string, ActiveTurn>();++ /** Registers the session's running turn. The previous entry, if any, must already be cancelled. */+ register(input: { sessionId: string; turnId: string; abortController: AbortController }): void {+ this.runs.set(input.sessionId, { turnId: input.turnId, abortController: input.abortController });+ }++ /** Removes the entry once the turn's stream has fully drained. */+ finish(input: { sessionId: string; turnId: string }): void {+ const active = this.runs.get(input.sessionId);+ if (active?.turnId === input.turnId) {+ this.runs.delete(input.sessionId);+ }+ }++ /**+ * Aborts the session's running turn if there is one. Returns true when a+ * run was found (already-aborted runs are not re-aborted). Cancelling a+ * session with no running turn is a no-op, mirroring the store's+ * first-terminal-write-wins rule.+ */+ cancelIfRunning(input: { sessionId: string; abortReason?: string }): boolean {+ const active = this.runs.get(input.sessionId);+ if (!active) {+ return false;+ }+ if (!active.abortController.signal.aborted) {+ active.abortController.abort(input.abortReason);+ }+ return true;+ }+}diff --git a/packages/server/src/runtime/sandboxFactory.ts b/packages/server/src/runtime/sandboxFactory.tsnew file mode 100644index 000000000..3ab9223d5--- /dev/null+++ b/packages/server/src/runtime/sandboxFactory.ts@@ -0,0 +1,105 @@+/**+ * Boot-time sandbox composition: parses `SANDBOX_SETTINGS` into the harness's+ * provider-settings union, builds the provider once, and returns the per-run+ * {@link TurnSandboxFactory} handed to TurnResourceResolver. Returns undefined+ * when the server has no sandbox configuration — admission then rejects specs+ * with `config.sandbox.enabled`.+ *+ * Called from main.ts so a malformed SANDBOX_SETTINGS aborts startup instead+ * of failing mid-turn.+ */+import { readFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import { dirname, join } from 'node:path';+import type { Logger } from 'winston';+import { ZodError } from 'zod';+import type { TurnSandboxFactory } from '@truefoundry/utils/agent-session';+import { createSandboxProvider, Sandbox, SandboxProviderSettingsSchema } from '@truefoundry/utils/core';+import { TENANT_NAME } from '../apis/sessions';+import configuration from '../config/config';++// Python helpers ship with @truefoundry/utils under dist/sandbox-scripts.+const require = createRequire(import.meta.url);+const UTILS_ROOT = dirname(require.resolve('@truefoundry/utils/package.json'));+const SCRIPTS_DIR = join(UTILS_ROOT, 'dist/sandbox-scripts');++function loadSandboxScripts(): { mcpClient: string; skillDownloader: string } {+ return {+ mcpClient: readFileSync(join(SCRIPTS_DIR, 'mcp_client.py'), 'utf-8'),+ skillDownloader: readFileSync(join(SCRIPTS_DIR, 'skill_downloader.py'), 'utf-8'),+ };+}++function parseSandboxSettings(rawJson: string) {+ let raw: unknown;+ try {+ raw = JSON.parse(rawJson);+ } catch (error) {+ throw new Error(+ `Environment variable SANDBOX_SETTINGS must be valid JSON: ${error instanceof Error ? error.message : String(error)}`,+ { cause: error },+ );+ }+ // SANDBOX_API_KEY overrides an inline `apiKey` so the credential can stay out+ // of the settings blob (mirrors the gateway's SANDBOX_API_KEY + SANDBOX_SETTINGS split).+ const merged =+ typeof raw === 'object' && raw !== null && !Array.isArray(raw)+ ? { ...raw, ...(configuration.SANDBOX_API_KEY !== undefined ? { apiKey: configuration.SANDBOX_API_KEY } : {}) }+ : raw;+ try {+ return SandboxProviderSettingsSchema.parse(merged);+ } catch (error) {+ if (error instanceof ZodError) {+ throw new Error(`Environment variable SANDBOX_SETTINGS is invalid: ${error.message}`, { cause: error });+ }+ throw error;+ }+}++/**+ * Builds the per-run sandbox factory from the environment, or undefined when+ * sandbox is not configured. Throws on any misconfiguration.+ */+export function createServerSandboxFactory(deps: { logger: Logger }): TurnSandboxFactory | undefined {+ if (configuration.SANDBOX_SETTINGS === undefined) {+ if (configuration.SANDBOX_API_KEY !== undefined) {+ throw new Error(+ 'SANDBOX_API_KEY is set but SANDBOX_SETTINGS is missing. ' ++ 'Set SANDBOX_SETTINGS (e.g. {"type":"daytona","snapshotName":"..."}) or unset SANDBOX_API_KEY.',+ );+ }+ return undefined;+ }++ const settings = parseSandboxSettings(configuration.SANDBOX_SETTINGS);+ const logger = deps.logger.child({ module: 'sandboxFactory' });+ const provider = createSandboxProvider({+ settings,+ tenantName: TENANT_NAME,+ fileMaxBytes: configuration.SANDBOX_FILE_MAX_BYTES,+ previewUrlExpirySeconds: configuration.SANDBOX_PREVIEW_URL_EXPIRY_SECONDS,+ logger,+ });+ const scripts = loadSandboxScripts();++ // TODO(skills): wire the complete skills flow. Spec-declared skills (from+ // skills.yaml) should be resolved to MountedSkill[] and passed as+ // `mountedSkills`, with `skillInitEnv` carrying the credentials+ // skill_downloader.py needs (TFY_HOST, TFY_API_KEY, TFY_AGENT_NAME) to+ // download tarballs into the sandbox — mirroring the private gateway's+ // sandboxComposition.ts. Until then sandbox sessions run without skills.+ return async ({ spec, existingSandboxId, tracing }) =>+ new Sandbox({+ provider,+ ...(existingSandboxId !== undefined ? { existingSandboxId } : {}),+ fileDownloadEnabled: spec.config?.sandbox?.file_downloads ?? false,+ blockDestructiveToolsInCodeMode: true,+ scripts,+ // Sandbox reads its tenant from TFY_TENANT_NAME (see Sandbox constructor)+ // for the ownership check against provider-created sandbox ids+ // (`<tenant>.<uuid>`). Must match the tenantName given to the provider.+ execExtraEnv: { TFY_TENANT_NAME: TENANT_NAME },+ tracing,+ logger,+ });+}diff --git a/packages/server/src/schemas/errors.ts b/packages/server/src/schemas/errors.tsnew file mode 100644index 000000000..957f13726--- /dev/null+++ b/packages/server/src/schemas/errors.ts@@ -0,0 +1,15 @@+/** Error response wire schema. */+import { z } from '@hono/zod-openapi';++export const RequestErrorResponseSchema = z+ .object({+ error: z.object({+ message: z.string(),+ type: z.string().optional(),+ code: z.string().nullable().optional(),+ param: z.string().nullable().optional(),+ }),+ })+ .openapi('RequestErrorResponse');++export type RequestErrorResponse = z.infer<typeof RequestErrorResponseSchema>;diff --git a/packages/server/src/schemas/events.ts b/packages/server/src/schemas/events.tsnew file mode 100644index 000000000..3b9c54d5d--- /dev/null+++ b/packages/server/src/schemas/events.ts@@ -0,0 +1,82 @@+/**+ * Server event wire schemas: SSE streaming union + list-query envelopes.+ * Lifecycle / persisted event schemas live in agentSession.+ */+import { z } from '@hono/zod-openapi';+import {+ EventType,+ SessionEventItemSchema,+ TurnCreatedEventSchema,+ TurnDoneEventSchema,+} from '@truefoundry/utils/agent-session';+import { TokenPaginationSchema } from '@truefoundry/utils/agent-session';+import {+ MCPAuthRequiredEventSchema,+ MCPInitializeEventSchema,+ ModelMessageDeltaEventSchema,+ ModelMessageEventSchema,+ SandboxCreatedEventSchema,+ ThreadCreatedEventSchema,+ ThreadDoneEventSchema,+ ToolApprovalRequiredEventSchema,+ ToolResponseEventSchema,+ ToolResponseRequiredEventSchema,+} from '@truefoundry/utils/core';++export type { TurnCreatedEvent } from '@truefoundry/utils/agent-session';+export { EventType };++/** Live SSE stream for session turns — content events, deltas and lifecycle. */+export const TurnStreamingEventSchema = z+ .discriminatedUnion('type', [+ ModelMessageEventSchema,+ ModelMessageDeltaEventSchema,+ ToolResponseEventSchema,+ ThreadCreatedEventSchema,+ ThreadDoneEventSchema,+ MCPAuthRequiredEventSchema,+ MCPInitializeEventSchema,+ SandboxCreatedEventSchema,+ ToolApprovalRequiredEventSchema,+ ToolResponseRequiredEventSchema,+ TurnCreatedEventSchema,+ TurnDoneEventSchema,+ ])+ .openapi('TurnStreamingEvent');++/** Max events per session-events page. */+export const SESSION_EVENTS_LIMIT = 100;++export const ListSessionEventsRequestQuerySchema = z+ .object({+ page_token: z+ .string()+ .optional()+ .describe(+ 'Pagination cursor from `pagination.next_page_token`. Returns older events before the cursor (toward session start).',+ ),+ last_turn_id: z+ .string()+ .optional()+ .describe(+ 'Newest turn in the listing window (initial load only; ignored when `page_token` is set). Lists that turn and its ancestors, newest events first. Omit to use the session last turn. If the resolved turn is still running, its events are excluded — subscribe to the running turn for live events.',+ ),+ limit: z.coerce+ .number()+ .int()+ .min(1)+ .max(SESSION_EVENTS_LIMIT)+ .optional()+ .default(SESSION_EVENTS_LIMIT)+ .describe(`Max events per response. Default ${SESSION_EVENTS_LIMIT}, max ${SESSION_EVENTS_LIMIT}.`),+ })+ .openapi('ListSessionEventsRequestQuery');++export const ListSessionEventsResponseSchema = z+ .object({+ data: z.array(SessionEventItemSchema),+ pagination: TokenPaginationSchema,+ })+ .openapi('ListSessionEventsResponse');++export type TurnStreamingEvent = z.infer<typeof TurnStreamingEventSchema>;diff --git a/packages/server/src/schemas/session.ts b/packages/server/src/schemas/session.tsnew file mode 100644index 000000000..f82ae96c1--- /dev/null+++ b/packages/server/src/schemas/session.ts@@ -0,0 +1,49 @@+/** Server session wire schemas. Core Session/Create/Update live in agentSession. */+import { z } from '@hono/zod-openapi';+import { TokenPaginationSchema } from '@truefoundry/utils/agent-session';+import {+ CreateSessionRequestSchema,+ SessionSchema,+ UpdateSessionRequestSchema,+} from '@truefoundry/utils/agent-session';++export type { Session } from '@truefoundry/utils/agent-session';+export { CreateSessionRequestSchema, UpdateSessionRequestSchema };++export const DEFAULT_SESSIONS_LIMIT = 10;+export const SESSIONS_MAX_LIMIT = 100;++export const ListSessionsRequestQuerySchema = z+ .object({+ limit: z.coerce+ .number()+ .int()+ .min(1)+ .max(SESSIONS_MAX_LIMIT)+ .optional()+ .default(DEFAULT_SESSIONS_LIMIT)+ .describe(`Page size. Defaults to ${DEFAULT_SESSIONS_LIMIT}, max ${SESSIONS_MAX_LIMIT}.`),+ order: z+ .enum(['asc', 'desc'])+ .optional()+ .default('desc')+ .describe('Sort sessions by creation time. Defaults to "desc".')+ .openapi('ListSessionsOrder'),+ page_token: z.string().optional().describe('Opaque token from a previous response `next_page_token`.'),+ start_timestamp: z.string().optional().describe('Inclusive lower bound on `created_at` (ISO-8601).'),+ end_timestamp: z.string().optional().describe('Inclusive upper bound on `created_at` (ISO-8601).'),+ })+ .openapi('ListSessionsRequestQuery');++export const GetSessionResponseSchema = z+ .object({+ data: SessionSchema,+ })+ .openapi('GetSessionResponse');++export const ListSessionsResponseSchema = z+ .object({+ data: z.array(SessionSchema),+ pagination: TokenPaginationSchema,+ })+ .openapi('ListSessionsResponse');diff --git a/packages/server/src/schemas/turn.ts b/packages/server/src/schemas/turn.tsnew file mode 100644index 000000000..832bc430c--- /dev/null+++ b/packages/server/src/schemas/turn.ts@@ -0,0 +1,13 @@+/** Server-only turn wire schemas (SSE resume / cancel). Core turn schemas live in agentSession. */+import { z } from '@hono/zod-openapi';++export { CreateTurnRequestSchema } from '@truefoundry/utils/agent-session';++export const SubscribeTurnRequestSchema = z+ .object({+ after_sequence_number: z.number().int().nonnegative().optional(),+ })+ .openapi('SubscribeTurnRequest');++export const CancelSessionRequestSchema = z.object({}).openapi('CancelSessionRequest');+export const CancelSessionResponseSchema = z.object({}).openapi('CancelSessionResponse');diff --git a/packages/server/src/store/McpStore.ts b/packages/server/src/store/McpStore.tsnew file mode 100644index 000000000..df9a8ef1b--- /dev/null+++ b/packages/server/src/store/McpStore.ts@@ -0,0 +1,37 @@+/**+ * Catalog of MCP servers from mcp.yaml. Auth headers come from the+ * MCP_HEADERS / MCP_{NAME}_HEADERS env vars and are never exposed in list+ * output.+ */+import configuration, { CONFIG_FILES, normalizeEnvName } from '../config/config';+import { loadYamlFile } from './loadYaml';+import { McpFileSchema, type McpServerEntry } from './schemas';++export class McpStore {+ private readonly mcpServers: McpServerEntry[];++ constructor(mcpServers: McpServerEntry[]) {+ this.mcpServers = mcpServers;+ }++ /** Loads and validates mcp.yaml. Throws on any error. */+ static load(): McpStore {+ return new McpStore(loadYamlFile(CONFIG_FILES.mcpServers, McpFileSchema).mcp_servers);+ }++ list(): McpServerEntry[] {+ return this.mcpServers;+ }++ get(name: string): McpServerEntry | undefined {+ return this.mcpServers.find(server => server.name === name);+ }++ /** Headers for requests to the given MCP server: defaults overlaid with per-server overrides. */+ getHeaders(name: string): Record<string, string> {+ return {+ ...configuration.MCP_HEADERS,+ ...configuration.MCP_HEADERS_BY_NAME[normalizeEnvName(name)],+ };+ }+}diff --git a/packages/server/src/store/ModelStore.ts b/packages/server/src/store/ModelStore.tsnew file mode 100644index 000000000..72658729c--- /dev/null+++ b/packages/server/src/store/ModelStore.ts@@ -0,0 +1,51 @@+/**+ * Catalog of models from models.yaml. Every model is reached through the+ * OpenAI-compatible API at the file's base_url, authenticated with+ * MODEL_API_KEY (or a per-model MODEL_{NAME}_API_KEY override);+ * MODEL_HEADERS / MODEL_{NAME}_HEADERS add extra headers. Credentials are+ * never exposed in list output.+ */+import configuration, { CONFIG_FILES, normalizeEnvName } from '../config/config';+import { loadYamlFile } from './loadYaml';+import { ModelsFileSchema, type ModelEntry } from './schemas';++export class ModelStore {+ readonly baseUrl: string;+ private readonly models: ModelEntry[];++ constructor(baseUrl: string, models: ModelEntry[]) {+ this.baseUrl = baseUrl;+ this.models = models;+ }++ /** Loads and validates models.yaml. Throws on any error. */+ static load(): ModelStore {+ const file = loadYamlFile(CONFIG_FILES.models, ModelsFileSchema);+ return new ModelStore(file.base_url, file.models);+ }++ list(): ModelEntry[] {+ return this.models;+ }++ get(name: string): ModelEntry | undefined {+ return this.models.find(model => model.name === name);+ }++ /** API key for the given model: MODEL_{NAME}_API_KEY override, else MODEL_API_KEY. */+ getApiKey(name: string): string {+ return configuration.MODEL_API_KEY_BY_NAME[normalizeEnvName(name)] ?? configuration.MODEL_API_KEY;+ }++ /**+ * Extra headers for requests to the given model: MODEL_HEADERS plus+ * per-model MODEL_{NAME}_HEADERS overrides. Auth is not included — the API+ * key from getApiKey() is passed to the LLM client separately.+ */+ getHeaders(name: string): Record<string, string> {+ return {+ ...configuration.MODEL_HEADERS,+ ...configuration.MODEL_HEADERS_BY_NAME[normalizeEnvName(name)],+ };+ }+}diff --git a/packages/server/src/store/SkillStore.ts b/packages/server/src/store/SkillStore.tsnew file mode 100644index 000000000..52a0d1039--- /dev/null+++ b/packages/server/src/store/SkillStore.ts@@ -0,0 +1,27 @@+/**+ * Catalog of agent skills from skills.yaml (git-based skills).+ */+import { CONFIG_FILES } from '../config/config';+import { loadYamlFile } from './loadYaml';+import { SkillsFileSchema, type SkillEntry } from './schemas';++export class SkillStore {+ private readonly skills: SkillEntry[];++ constructor(skills: SkillEntry[]) {+ this.skills = skills;+ }++ /** Loads and validates skills.yaml. Throws on any error. */+ static load(): SkillStore {+ return new SkillStore(loadYamlFile(CONFIG_FILES.skills, SkillsFileSchema).skills);+ }++ list(): SkillEntry[] {+ return this.skills;+ }++ get(name: string): SkillEntry | undefined {+ return this.skills.find(skill => skill.name === name);+ }+}diff --git a/packages/server/src/store/loadYaml.ts b/packages/server/src/store/loadYaml.tsnew file mode 100644index 000000000..312cc973b--- /dev/null+++ b/packages/server/src/store/loadYaml.ts@@ -0,0 +1,42 @@+/**+ * Reads and validates a YAML config file. Any failure (missing file, invalid+ * YAML, schema violation) throws, so callers fail at startup with a message+ * pointing at the offending file.+ */+import fs from 'node:fs';+import path from 'node:path';+import { parse } from 'yaml';+import type { z } from 'zod';+import { CONFIG_DIR } from '../config/config';++export function loadYamlFile<Schema extends z.ZodTypeAny>(fileName: string, schema: Schema): z.infer<Schema> {+ const filePath = path.join(CONFIG_DIR, fileName);++ let raw: string;+ try {+ raw = fs.readFileSync(filePath, 'utf8');+ } catch (error) {+ throw new Error(+ `Failed to read config file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,+ { cause: error },+ );+ }++ let document: unknown;+ try {+ document = parse(raw);+ } catch (error) {+ throw new Error(`Invalid YAML in ${filePath}: ${error instanceof Error ? error.message : String(error)}`, {+ cause: error,+ });+ }++ const result = schema.safeParse(document);+ if (!result.success) {+ const issues = result.error.issues+ .map(issue => ` - ${issue.path.length > 0 ? issue.path.join('.') : '(root)'}: ${issue.message}`)+ .join('\n');+ throw new Error(`Invalid config in ${filePath}:\n${issues}`);+ }+ return result.data;+}diff --git a/packages/server/src/store/schemas.ts b/packages/server/src/store/schemas.tsnew file mode 100644index 000000000..55a94cc38--- /dev/null+++ b/packages/server/src/store/schemas.ts@@ -0,0 +1,107 @@+/**+ * Zod schemas for the YAML config files (models.yaml, mcp.yaml, skills.yaml).+ * Validation is strict: unknown keys, duplicate names, or missing fields make+ * the server fail at startup.+ */+import { z } from 'zod';+import { normalizeEnvName } from '../config/config';++/** Adds a validation issue if two entries share a name. */+function uniqueNames(entries: Array<{ name: string }>, ctx: z.RefinementCtx): void {+ const seen = new Set<string>();+ for (const entry of entries) {+ if (seen.has(entry.name)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Duplicate name "${entry.name}" — names must be unique`,+ });+ }+ seen.add(entry.name);+ }+}++/**+ * Adds a validation issue if two distinct names normalize to the same+ * `{NAME}` env var segment (e.g. "foo-bar" and "foo_bar"), since they could+ * not be given separate per-name overrides (headers, API keys). Only applied+ * to entries with per-name env vars (models, MCP servers).+ */+function uniqueEnvNames(entries: Array<{ name: string }>, ctx: z.RefinementCtx): void {+ const seenByEnvName = new Map<string, string>();+ for (const entry of entries) {+ const envName = normalizeEnvName(entry.name);+ const existing = seenByEnvName.get(envName);+ if (existing && existing !== entry.name) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Names "${existing}" and "${entry.name}" both map to the "${envName}" env var segment — rename one so they can be configured separately`,+ });+ } else {+ seenByEnvName.set(envName, entry.name);+ }+ }+}++export const ModelEntrySchema = z+ .object({+ name: z.string().min(1),+ supported_reasoning_efforts: z.array(z.string().min(1)).optional(),+ max_output_tokens: z.number().int().positive(),+ })+ .strict();++export const ModelsFileSchema = z+ .object({+ base_url: z+ .string()+ .url()+ .transform(url => url.replace(/\/$/, '')),+ models: z.array(ModelEntrySchema),+ })+ .strict()+ .superRefine((file, ctx) => {+ uniqueNames(file.models, ctx);+ uniqueEnvNames(file.models, ctx);+ });++export const McpServerEntrySchema = z+ .object({+ name: z.string().min(1),+ url: z.string().url(),+ })+ .strict();++export const McpFileSchema = z+ .object({+ mcp_servers: z.array(McpServerEntrySchema),+ })+ .strict()+ .superRefine((file, ctx) => {+ uniqueNames(file.mcp_servers, ctx);+ uniqueEnvNames(file.mcp_servers, ctx);+ });++export const SkillEntrySchema = z+ .object({+ name: z.string().min(1),+ // Public git repository containing the skill.+ url: z.string().url(),+ // Directory inside the repository containing SKILL.md. Repo root if omitted.+ path: z.string().min(1).optional(),+ // Commit SHA, tag or branch to pin. Default branch if omitted.+ reference: z.string().min(1).optional(),+ // Injected into the agent context so it can judge when to use the skill.+ description: z.string().min(1),+ })+ .strict();++export const SkillsFileSchema = z+ .object({+ skills: z.array(SkillEntrySchema),+ })+ .strict()+ .superRefine((file, ctx) => uniqueNames(file.skills, ctx));++export type ModelEntry = z.infer<typeof ModelEntrySchema>;+export type McpServerEntry = z.infer<typeof McpServerEntrySchema>;+export type SkillEntry = z.infer<typeof SkillEntrySchema>;diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.jsonnew file mode 100644index 000000000..996260be9--- /dev/null+++ b/packages/server/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "types": ["node"],+ "noEmit": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.tsnew file mode 100644index 000000000..050f32f12--- /dev/null+++ b/packages/server/tsup.config.ts@@ -0,0 +1,23 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ entry: { main: 'src/main.ts' },+ format: ['esm'],+ dts: false,+ splitting: false,+ sourcemap: true,+ clean: true,+ target: 'esnext',+ outDir: 'dist',+ external: [+ '@hono/node-server',+ '@hono/swagger-ui',+ '@hono/zod-openapi',+ '@truefoundry/utils',+ 'hono',+ 'ulid',+ 'winston',+ 'yaml',+ 'zod',+ ],+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlnew file mode 100644index 000000000..407b28848--- /dev/null+++ b/pnpm-lock.yaml@@ -0,0 +1,6538 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .: {}++ packages/harness:+ dependencies:+ '@daytona/sdk':+ specifier: ^0.190.0+ '@hono/zod-openapi':+ specifier: ^0.19.10+ version: 0.19.10([email protected])([email protected])+ '@modelcontextprotocol/sdk':+ specifier: ^1.29.0+ version: 1.29.0([email protected])([email protected])+ '@nats-io/nats-core':+ specifier: 3.0.2+ version: 3.0.2+ '@opentelemetry/api':+ specifier: ^1.9.0+ version: 1.9.1+ '@opentelemetry/core':+ specifier: ^2.9.0+ version: 2.10.0(@opentelemetry/[email protected])+ dedent:+ specifier: ^1.7.2+ version: 1.7.2+ openai:+ specifier: ^4.104.0+ version: 4.104.0([email protected])([email protected])+ ulid:+ specifier: ^3.0.2+ version: 3.0.2+ winston:+ specifier: ^3.13.0+ version: 3.19.0+ ws:+ specifier: ^8.21.0+ version: 8.21.1+ zod:+ specifier: ^3.24.3+ version: 3.25.76+ zod-to-json-schema:+ specifier: ^3.25.1+ version: 3.25.2([email protected])+ devDependencies:+ '@swc/core':+ specifier: ^1.11.0+ version: 1.15.46+ '@swc/jest':+ specifier: ^0.2.37+ version: 0.2.39(@swc/[email protected])+ '@types/jest':+ specifier: ^29.5.14+ version: 29.5.14+ '@types/node':+ specifier: ^24.12.0+ version: 24.13.3+ '@types/ws':+ specifier: ^8.5.10+ version: 8.18.1+ jest:+ specifier: ^29.7.0+ version: 29.7.0(@types/[email protected])([email protected])+ tsup:+ specifier: ^8.5.0+ version: 8.5.1(@swc/[email protected])([email protected])([email protected])([email protected])([email protected])+ typescript:+ specifier: ^7.0.2+ version: 7.0.2++ packages/server:+ dependencies:+ '@hono/node-server':+ specifier: ^1.19.14+ version: 1.19.14([email protected])+ '@hono/swagger-ui':+ specifier: ^0.2.1+ version: 0.2.2([email protected])+ '@hono/zod-openapi':+ specifier: ^0.19.10+ version: 0.19.10([email protected])([email protected])+ '@truefoundry/utils':+ specifier: workspace:*+ version: link:../harness+ hono:+ specifier: ^4.12.31+ version: 4.12.31+ ulid:+ specifier: ^3.0.2+ version: 3.0.2+ winston:+ specifier: ^3.13.0+ version: 3.19.0+ yaml:+ specifier: ^2.9.0+ version: 2.9.0+ zod:+ specifier: ^3.24.3+ version: 3.25.76+ devDependencies:+ '@types/node':+ specifier: ^24.12.0+ version: 24.13.3+ tsup:+ specifier: ^8.5.0+ version: 8.5.1(@swc/[email protected])([email protected])([email protected])([email protected])([email protected])+ tsx:+ specifier: ^4.16.2+ version: 4.23.1+ typescript:+ specifier: ^7.0.2+ version: 7.0.2++packages:++ '@asteasolutions/[email protected]':+ resolution: {integrity: sha512-/2rThQ5zPi9OzVwes6U7lK1+Yvug0iXu25olp7S0XsYmOqnyMfxH7gdSQjn/+DSOHRg7wnotwGJSyL+fBKdnEA==}+ peerDependencies:+ zod: ^3.20.2++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-Hc4N100RdkuWshKBnhPzmpdftfi9mCLz+OHFELHM1QIgMH4QRUUWyWgfiebta/YX2Bd62wTcm3EqAP8TeXv0gA==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-7452vEdp/nihIBWijnmcTBujXEFfbs4F02wyBDGqmNr6pwyo5GmQorx0zQIVg8QGFLXiBvsWKXBhCdiBcxNnGA==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-0cjRaEdlVoOrsNb9pP5q1Syyc8pXw5xSj2Np2ryReRTr9FppIIRVSdZK4lbnfmc2Hvgux/xBOUU6baB7z8//uA==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-BAkxdoe7tpDDqCghGpuOeHQRbm/2znVvOQm0AvpQbA2tbfMN46doN4zx65fv85ImP3KADwc2zQPmbrlI9MPfMg==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-g/0fGqKTb9xpKdd9AtpmV5Eo3DFKbnkpA2+w0peISSlu7NfAoWOuYBFxsu+yWBtxU89ka55ezoZBCbFaS8pjYQ==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-ylubazcRfq2TVus/qXucSXeC42Qdjp5HQxTu68K/BsdMiZlcSLD1zkpoCgApXZX1Y6YJhtGGs7ZHhO/GuIgBlw==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-CCygIKJ9YbI3n84OClSaSppkgKKHVj2TGT33c6FRORZrYNZQ1POmD+ip0FLYokiJAK7sSdc3YVkOsBm90oxWMQ==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-HIg7Q2osBzajQwL+1Vkyh2E7Gim3eTNb9RHIsOxDGjW0eZg4oEKtRs5sioCnc73ilhaOm4gX2lHVF8J7+nt2rg==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-YIo3f99hM43QdYG8hDzwGemnR/pU95b0kramqSJUTleCqaB7+HwKf7YZFHqvOgTqZTPx/mRmNIqoDRr3U0Z3Tw==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-BPdmL8sSBOCv4ngZ+3LHxyc3CNqDCEK37CHioCk7zGrTMY5sUtkH8q+o6qA80nn6w3/fyBPGNE7OIRlmoOxRQA==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-kSAziJboOmZmsR9/MTbiNjowl2BPes1bQuJpne4qAZ62ubi8fjfr/aupJSQje6udBoYxXTQbsL0e0kby2la3ng==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-F8+7VfqQW/rCBr3g8JvEyg4YF8K+HicVIxv/5XlDIdBK1DgcznJh0NzR3qfvizR78Fi3yXtET11PQEaGVdppLg==}+ engines: {node: '>=20.0.0'}+ peerDependencies:+ '@aws-sdk/client-s3': ^3.1093.0++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-udwNhRfDTfCB98mAHjjgsnKQlxygB4e0X+Obne/XjJpvVsF0YCQC8ZErd/8Z6IPoLQjtiKHzwqEDbZiLrJEnOg==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-Y9REVrSwmLM+Qy6sZJ7ofMC2S3Hr3tPP/4CzL5U1olPP7OGoF+6+Px0E49cVQBtSxJtyeLJMf0UaBErfeSahAA==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-QMUytg+FQMGouc8gHS00KoYih3+N6cqmVI/pQGOIo7Nr7OpQaiXjSYOuL+vsPZ1tymY4LAQ8MYcHJmws5LRxng==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-hBYUAr6iBLNFcsiWTgtBb0stdSw39VOUq4Sp4A5caCNf66BAZplWN4FleKrVpJx5li2YgdnK2DqoFSMWC642FQ==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-3W6IUtSxFbH6X7Wb7DzGCV5QiFQsd0g8bOfntpmDxQlzBoKWUMBu/JPQR0DwkE+Hpnxd6db1tXbOwdeHddG6cA==}+ engines: {node: '>=20.0.0'}++ '@aws-sdk/[email protected]':+ resolution: {integrity: sha512-RdGmS1GLrtaTOLE1ElSluMldNrpk9Emq6uYs8SS8iHlu5xTAmM9rRkM91o48+rIRryBtyO9t+uLYCoMG6jVMVA==}+ engines: {node: '>=20.0.0'}++ '@aws/[email protected]':+ resolution: {integrity: sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==}+ engines: {node: '>=18.0.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0++ '@babel/[email protected]':+ resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ '@babel/[email protected]':+ resolution: {integrity: sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-zGYcYfq/WmZ4V+kBIXQon9dSSc8ircGZqw9ZaNhhGj9nZkeBu1jHLBDQqYYi5WA9uawvA2sIMbry2nCFhf5Djg==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}+ engines: {node: '>=6.9.0'}++ '@bcoe/[email protected]':+ resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==}++ '@colors/[email protected]':+ resolution: {integrity: sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==}+ engines: {node: '>=0.1.90'}++ '@dabh/[email protected]':+ resolution: {integrity: sha512-R4MSXTVnuMzGD7bzHdW2ZhhdPC/igELENcq5IjEverBvq5hn1SXCWcsi6eSsdWP0/Ur+SItRRjAktmdoX/8R/Q==}++ '@daytona/[email protected]':+ resolution: {integrity: sha512-69/J9B1YuJIVa4DT4/r5zSzy6vKpV7Cz2l6xZYhYyAjiLunqn7nlAxbDOXE08pmhuOK38C/8g/4SeBHdkARFQg==}++ '@daytona/[email protected]':+ resolution: {integrity: sha512-AWQRlgNiauh2o33+SjuQFhwr6xqaEZhofKtok151FcB7+UAMxqhSd5cNDsODM4nmzxt+by8oAKOYmHncg7DxWQ==}++ '@daytona/[email protected]':+ resolution: {integrity: sha512-vObFluXvY7tJpU4en58TrZHdjueUDpTD7yZlDnYHypPUdGsTUdyWbAJUOSs0WyV9HHWBzwEzauOdif0e5Xytkg==}++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@grpc/[email protected]':+ resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}+ engines: {node: '>=12.10.0'}++ '@grpc/[email protected]':+ resolution: {integrity: sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==}+ engines: {node: '>=6'}+ hasBin: true++ '@hono/[email protected]':+ resolution: {integrity: sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==}+ engines: {node: '>=18.14.1'}+ peerDependencies:+ hono: ^4++ '@hono/[email protected]':+ resolution: {integrity: sha512-Bco6XdKkTP7yIVWXpquLQayvjwzDmsmsESjF7VcrU/ZPTYafGvvpHf7Z6PHTWyp+JpdYORZXlyZ75T3At2KfAA==}+ peerDependencies:+ hono: '*'++ '@hono/[email protected]':+ resolution: {integrity: sha512-dpoS6DenvoJyvxtQ7Kd633FRZ/Qf74+4+o9s+zZI8pEqnbjdF/DtxIib08WDpCaWabMEJOL5TXpMgNEZvb7hpA==}+ engines: {node: '>=16.0.0'}+ peerDependencies:+ hono: '>=4.3.6'+ zod: '>=3.0.0'++ '@hono/[email protected]':+ resolution: {integrity: sha512-Io1B6d011Gj1KknV4rXYz4le5+5EubcWEU/speUjuw9XMMIaP3n78yXLhjd2A3PXaXaUwEAluOiAyLqhBEJgsw==}+ peerDependencies:+ hono: '>=3.9.0'+ zod: ^3.25.0 || ^4.0.0++ '@iarna/[email protected]':+ resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==}++ '@isaacs/[email protected]':+ resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}+ engines: {node: '>=18.0.0'}++ '@istanbuljs/[email protected]':+ resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==}+ engines: {node: '>=8'}++ '@istanbuljs/[email protected]':+ resolution: {integrity: sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==}+ engines: {node: '>=8'}++ '@jest/[email protected]':+ resolution: {integrity: sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ peerDependencies:+ node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0+ peerDependenciesMeta:+ node-notifier:+ optional: true++ '@jest/[email protected]':+ resolution: {integrity: sha512-R+xGEtzA95NIsvpXJSROG4t01956dDOt17KpamguY4XOnGvdHNFFXE7Er0C1OAsRjOwiIxpKqOvGlznIGZIQlQ==}+ engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-RAWn3+f9u8BsHijKJ71uHcFp6vmyEt6VvoWXkl6hKF3qVIuWNmudVjg12DlBPGup/frIl5UcUlH5HfEuvHpEXg==}+ engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ peerDependencies:+ node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0+ peerDependenciesMeta:+ node-notifier:+ optional: true++ '@jest/[email protected]':+ resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==}+ engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ '@jest/[email protected]':+ resolution: {integrity: sha512-f1x/vJXIfjOlEmejYpbkbgw1gOqpPECwMvMEtBqe47j7H2Hg8h8w3o3ikhSXq3MI15kg+oQ0exWO0uCtTNJLoQ==}+ engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}++ '@js-sdsl/[email protected]':+ resolution: {integrity: sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==}++ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==}+ engines: {node: '>=18'}+ peerDependencies:+ '@cfworker/json-schema': ^4.1.1+ zod: ^3.25 || ^4.0+ peerDependenciesMeta:+ '@cfworker/json-schema':+ optional: true++ '@nats-io/[email protected]':+ resolution: {integrity: sha512-gACbRIhY3yQTO+5C4E1LY/qO2e5EhGUBeDsnPDT8Hd3qY9mfhNtluY6R7d7WX7/JMGsXRPbYdSLSADr/ECSy3w==}++ '@nats-io/[email protected]':+ resolution: {integrity: sha512-JVt56GuE6Z89KUkI4TXUbSI9fmIfAmk6PMPknijmuL72GcD+UgIomTcRWiNvvJKxA01sBbmIPStqJs5cMRBC3A==}+ engines: {node: '>=18.0.0'}++ '@nats-io/[email protected]':+ resolution: {integrity: sha512-TpA3HEBna/qMVudy+3HZr5M3mo/L1JPofpVT4t0HkFGkz2Cn9wrlrQC8tvR8Md5Oa9//GtGG26eN0qEWF5Vqew==}+ engines: {node: '>= 18.x'}++ '@nodelib/[email protected]':+ resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}+ engines: {node: '>= 8'}++ '@nodelib/[email protected]':+ resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==}+ engines: {node: '>= 8'}++ '@nodelib/[email protected]':+ resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}+ engines: {node: '>= 8'}++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-Cdq0jW2lknrNfrAm92MyEAvpe2cRsKjdnQLHUL6xRA4IVUnsWx6P65E7NcUO0Y+L4w1Aee5iV8FvjSwd+lrs9A==}+ engines: {node: '>=8.0.0'}++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}+ engines: {node: '>=8.0.0'}++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-xCtrYOhBqdy6ZOMfe0Oa73ZKF+2LMhoOv4L5vmwAHVvOXUg+V3fvKuEIr9ZyD0Ow+vxllEjWO6PV1wd0DOtyvw==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.9.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-OPFBYuXEn1E4ja3Y6eeA7O+ZnLBNcXTV5Cgsn1VaqBZ6hC5FnpZPLBNme1LJY8ZtF4aOujPKFoeWN4ik487KuQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-vC5S0Dc+noxD86CVtNu1+awCHPA5Kewi1Sg23ps+9lh4YifwsKXh3pe4XTNEKtUJiAcjpJ5dqStGakLbrSE+YQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-KfLAdt1uilVE+3FxbgVnp2ZrzqbIawzcesnRoi+Kh9ckB5Ld5D8btUgoBvwTbdmuNx1j6b132Wsh72azq+pPNQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-Se0GG/ZO24mQTlQj7zprR4pNI0nKe4lPDPBsuJmi6508b9TlZEuUd3EfyuHk6oJxzL7fGyDFYAbxNigQvRP2ZQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-0GpJKnCoVaVA1rKBMVPHziznfOQlXgH72S9ktjBAF1AnAVPzX7vVEBGrhwiSxxHDAiefXk+J8znApsMb/K6Z3w==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-1zkMzzhiNJdVmLxuwkltqWGw4fOOam47bqRxmuQNjyKJe/9NmY5cIrZ4kiQV7sVGxoOgT0ZvGUfLcjvtpC/b9Q==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-nfxt/KxVGFkjkO/M+58y1ugHu/dwPtxG4eYq0KApcQ7xk5CHzhdn+IuLZfDSvNDrJ3Uy5q++Fj/wbK7i8yryfQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-U9MCXxJu0sBCh5aEkylYRR4xVIL8D1CW6dGwvYXbfFr0qveSorfD0XJchCAWoW6QfAAIcY/yxjf4Dj8OgkHBPw==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-fPZs2fw7veLH3pEKu8vSepUa2fQpAE2P7al6qU10aH9GrEJJ8YaPgsd5xON7by5rbcEVS71FOU2aWyK6nzB7VQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-38YQoqtYjglz2GV94LGUN/djLvxtvGIQO68o6qAFPVshjmwSdX1F2i0c7vn3lEl1L5B/YqjB/bgKXaVx7KO+RQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-nPV8gKHUiSuTZpQcnZU3/pBlK7crSyEGpZuh5MtWySB0vv6NNG0QvvfKitQt+Fc2Mc6qfyU54KlZcurwoTbrVg==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-mfsD9bKAxcKrh5+y08TPodvClBO0CznBE3p79YAGnO81WI4LrdsGA65T53e4iTSbCalW4WaUpkbeJcbpyIUHfg==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.0.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-B88Y7k5A9a60pHUboFoeJlgVwXq2T0rsZKj6dTwzSMKSOsNXR4Jz5ovwprVn3kHLAZrkyLEjQtBJ34DYHs1U4Q==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-24ucQMjz7Y34Kw3trbxL2ZrssbtgWnR+Clpaa+YdeWuuyH3Cvk23Q03PcQvqiZrDvt8AmQmjgg9v6Y9PHoxG7w==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-eYfqnB3UhKu/5frhd1R6+FprKygbhkomuaceMXDyzxbfXB9tKgZOVmjaJ02CkLA6Tdzumxl+e2H+vo2a8jiMPQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-7RTAdZuOsCDnsyqTCG4+bDzrfnsWdzkRs7z0AVi/V3tEQx0oKeyc+OuRWYxnRsmaJXgxcmB8vb/lfxn58Dj6Ag==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-MKK8UHKFUOGAvbZRWh90MhwHG+Fxm6OROBdjKPCF+HQobjuJ/Kuf8Chs8CR45X1aqotxrMj7OxTdsXe8sXuGVA==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': ^1.3.0++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-RJid6E2CKyeGfKBzXKF21ejabGMHypFkPAh3qZ+NvI+SGjuIye79t3PmiqcDgtRzdKH6ynXzbfslQ8DfpRUg2A==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-KMjVBHzP4N60bOzxja76M1F1hZZ43lGPga5ix+mkv9+kk1nx9SbkxSvJsMbuVUxdPQmsPTqGShmhN8ulrMOg6Q==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.3.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-DeT6KKolmC4e/dRQvMQ/RwlnzhaqeiFOXY5ngoOPJ07GgVVKxZOg9EcrNZb5aTzUn+iCrJldAgOfQm1O/QfPAQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.3.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-BB+PcHItcZDL63dPMW+mJvwN9rk37wuIDjRxbVlg6pPDvDR/7GL7UJHbGsllgoggOoTimsKgENaWPoGch/oE1A==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.4.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-MpDJdkiFDs3Pm1RHO3KByuZbuBdJEXEAkiC0+yJdsZGVCdf1RpHR6n+LHDcS7ffmfrt5kVCzJSCfm4z2C7v0uQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.9.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-K/60pSv42+NQiZKy1pAH18nYDkxltsDV4O3SJ233J0E9raU1ksyL9gsKuS8p30bYBb4AMPCfDuutHQaHYpcv0Q==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.3.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-GuYQQT7QD2EeO8lcZLRQzcbOyhqAzL+6WWTKTU9mSUBYBazkEDl+VrQcXQhbB08OWM9anD1aHleVadzulpOaUQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.3.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-NAYIlsF8MPUsKqJMiDQJTMPOmlbawC1Iz/omMLygZ1C9am8fTKYjTaI+OZM+WTY3t3Glo0wnOg/6/pac6RGPPw==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.3.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-pCpQxU68lV+I9s9svqMyVu5iHdDDUnqUpSxqwyCU8A9ejEsSnMPCbearwsUO4yk08ZJzAIUCFuReMdVQvHrdvg==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-MfQGq3GRmTh5fM/y+OjaO0vj6+luCB1XO2gfXCalKCfgKw0eHL++sm75DNweC6ohlp+aFvACqeE0fYayqdRaoQ==}+ engines: {node: ^18.19.0 || >=20.6.0}+ peerDependencies:+ '@opentelemetry/api': '>=1.3.0 <1.10.0'++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==}+ engines: {node: '>=14'}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==}++ '@protobufjs/[email protected]':+ resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==}++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==}+ cpu: [arm]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==}+ cpu: [loong64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==}+ cpu: [loong64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==}+ cpu: [ppc64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==}+ cpu: [riscv64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==}+ cpu: [x64]+ os: [win32]++ '@sinclair/[email protected]':+ resolution: {integrity: sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==}++ '@sinclair/[email protected]':+ resolution: {integrity: sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==}++ '@sinonjs/[email protected]':+ resolution: {integrity: sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==}++ '@sinonjs/[email protected]':+ resolution: {integrity: sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==}++ '@smithy/[email protected]':+ resolution: {integrity: sha512-BiEE2bnnGoPKdlGe3L+gOYORDHFGPuYVRLP7iUow/Sflm0B4hC4XY3FC1MRuc7ltzpW2xNnXopKi34TTkULlKQ==}+ engines: {node: '>=18.0.0'}++ '@smithy/[email protected]':+ resolution: {integrity: sha512-ZZPDbl/aRp77aycuoMlo3BTayT4CE2a3uoqETYZU5ySnVbhpl5IJiY7dCZedn+ZusyDLqVv44IvKBiXd2/nK0Q==}+ engines: {node: '>=18.0.0'}++ '@smithy/[email protected]':+ resolution: {integrity: sha512-EJktha5m5MXCwzdXrlWyqb9UCNHNFKlg+PmTpRsdX3dncJPTiqYleM9OKj2mLgdVJHR01d2tU4alG+z2NdH5rQ==}+ engines: {node: '>=18.0.0'}++ '@smithy/[email protected]':+ resolution: {integrity: sha512-xVBZ3hptB99iNO9XyWqEhC7KD9bP9UPXhuy3h5Y2ItCfBv160D9IIC/Fmmp3EbnWwit4C+KVqlSE+E29Nk/pPg==}+ engines: {node: '>=18.0.0'}++ '@smithy/[email protected]':+ resolution: {integrity: sha512-iGBm6hIwD2MGvVRSgrjVWa4FXtXDq3akxu0DCpnkmBo0xtEHZ/siMRt7ycfZAefYr2UdywUgmGtoRLaq5u56pg==}+ engines: {node: '>=18.0.0'}++ '@smithy/[email protected]':+ resolution: {integrity: sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==}+ engines: {node: '>=18.0.0'}++ '@so-ric/[email protected]':+ resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==}++ '@swc/[email protected]':+ resolution: {integrity: sha512-IsISIT22EfktVJrlvIpnAxG2u/A9aob9l99HMlx80x72WlFmFPk1V3UhkEzx86eJP8hw049KTFv/RISho2cq2Q==}+ engines: {node: '>=10'}+ cpu: [arm64]+ os: [darwin]++ '@swc/[email protected]':+ resolution: {integrity: sha512-4Tj4ppVIPCmUMpmGFiGtyEriwLyJ+yi/US4WfBrP/ok8COGddDZXLEzQETnKyK46mjvr1v0jevrS23zjoff7vA==}+ engines: {node: '>=10'}+ cpu: [x64]+ os: [darwin]++ '@swc/[email protected]':+ resolution: {integrity: sha512-i8tUGnNjyOgMmfmgFSg4aeJLQoFyfpIHK5FjpQAwpRyQIqEUB2w1e8zIDQzY1WhOxx8NoS1S5iUL813Un4Sf5A==}+ engines: {node: '>=10'}+ cpu: [arm]+ os: [linux]++ '@swc/[email protected]':+ resolution: {integrity: sha512-c0OnhqzdhfOvv6qhNCcByepB+sNYOGZyhtr2Qa6ZCHvAWTYhSRw4j/u92Stue9PbZ/6q74b9nHzi76+kVzqQHQ==}+ engines: {node: '>=10'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@swc/[email protected]':+ resolution: {integrity: sha512-imyRpNEcUzFQFV2LE4jL68ErvmKEuZCbvZru77iQREunJ+bR4i658cupTgtG1mLYM3F1Tzy3Sb9xYb02KghWTg==}+ engines: {node: '>=10'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@swc/[email protected]':+ resolution: {integrity: sha512-ctEfcl/HcUeomK33cbySiHZm98GEDIxTm1EkpBsYCiHxElYBzvTXVeuQT2YwbUXn9XCrjiw4ipyUNk33k26qRg==}+ engines: {node: '>=10'}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@swc/[email protected]':+ resolution: {integrity: sha512-DxlMdnt84TtRVTv7WL/thWyz9+QU8QZNNoAP9rrk0P68LziuhfePp8MjQ44zIprpTHTsEwyziIuGUUN5iSC1bQ==}+ engines: {node: '>=10'}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@swc/[email protected]':+ resolution: {integrity: sha512-SKxI7J6t90XPl8hRUqtJi9NfGdunN/E/vZMc7Bc0figeRdOPDBT+Tm8g7cx9xM0T0mewh2l+8dewa3Am27/P+A==}+ engines: {node: '>=10'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@swc/[email protected]':+ resolution: {integrity: sha512-qj9T6B7bosI0VEsrWOVXZN1OXxS8Tp63ywyrLxNdOycnUtLdkgYcoBsN5y8ImnDDsnwrEWZOy1e+J4xSe7mA3Q==}+ engines: {node: '>=10'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@swc/[email protected]':+ resolution: {integrity: sha512-8p7l4c3LU+eA5g9Et1JPhNeMC1oQwXTGU+uah8DPIBX7YXzqswvaBtyKVmXefVGi/DJU1x3YJsc3mbAp9aWzSQ==}+ engines: {node: '>=10'}+ cpu: [arm64]+ os: [win32]++ '@swc/[email protected]':+ resolution: {integrity: sha512-tUEnfr3Bn9u6FOjUb3PN9p+09qZC2j+wNDLKHzXXZn22rqGcUqR/ohCRSS+nG9B9+X+U+3FewNEHJkTmdIvMjQ==}+ engines: {node: '>=10'}+ cpu: [ia32]+ os: [win32]++ '@swc/[email protected]':+ resolution: {integrity: sha512-Vux7UDzBJYQggSuPfcl2w9iu+IJpgpRCxHzgCaVkELnAXAE4XZMOTX9HNcaNiwfeIDqdu2rkr69RuDm6wY8neA==}+ engines: {node: '>=10'}+ cpu: [x64]+ os: [win32]++ '@swc/[email protected]':+ resolution: {integrity: sha512-Ri3em2mBpq3h2zSPliCYl63otDGqek8PPEfv2nWgRQEbZ/VBCNyypVTVQ6cEbTCXBhy+WE2T3fQb08moIyuYaw==}+ engines: {node: '>=10'}+ peerDependencies:+ '@swc/helpers': '>=0.5.17'+ peerDependenciesMeta:+ '@swc/helpers':+ optional: true++ '@swc/[email protected]':+ resolution: {integrity: sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==}++ '@swc/[email protected]':+ resolution: {integrity: sha512-eyokjOwYd0Q8RnMHri+8/FS1HIrIUKK/sRrFp8c1dThUOfNeCWbLmBP1P5VsKdvmkd25JaH+OKYwEYiAYg9YAA==}+ engines: {npm: '>= 7.0.0'}+ peerDependencies:+ '@swc/core': '*'++ '@swc/[email protected]':+ resolution: {integrity: sha512-K6h3iUlqeM946U4sXFYeahefR1YBbXJvko+hv8WS8/0BNJ4OHiHRywMnQUJCqkR7Y9+hqQ1TvEpiKqUhz7NEFg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}++ '@types/[email protected]':+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==}++ '@types/[email protected]':+ resolution: {integrity: sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==}++ '@typescript/[email protected]':+ resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [aix]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [darwin]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [freebsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==}+ engines: {node: '>=16.20.0'}+ cpu: [loong64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==}+ engines: {node: '>=16.20.0'}+ cpu: [mips64el]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==}+ engines: {node: '>=16.20.0'}+ cpu: [ppc64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==}+ engines: {node: '>=16.20.0'}+ cpu: [riscv64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==}+ engines: {node: '>=16.20.0'}+ cpu: [s390x]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [linux]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [netbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [openbsd]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [sunos]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==}+ engines: {node: '>=16.20.0'}+ cpu: [arm64]+ os: [win32]++ '@typescript/[email protected]':+ resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==}+ engines: {node: '>=16.20.0'}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}+ engines: {node: '>=6.5'}++ resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==}+ engines: {node: '>=0.4.0'}+ hasBin: true++ resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}+ engines: {node: '>= 6.0.0'}++ resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==}+ engines: {node: '>= 8.0.0'}++ resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}+ peerDependencies:+ ajv: ^8.0.0+ peerDependenciesMeta:+ ajv:+ optional: true++ resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}++ resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==}++ resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==}++ resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}++ resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}++ resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==}++ resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ peerDependencies:+ '@babel/core': ^7.8.0++ resolution: {integrity: sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==}+ peerDependencies:+ '@babel/core': ^7.0.0 || ^8.0.0-0++ resolution: {integrity: sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ peerDependencies:+ '@babel/core': ^7.0.0++ resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}++ resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}++ resolution: {integrity: sha512-HYXq73DDpCtNzOmrFsm9eSwCvWCql0RzqjpDzXN9EadiLJ4DNat0nsZ/Bzmy+Ud12mb4/zKDY0cQ805ZzN+i0A==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}++ resolution: {integrity: sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==}++ resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==}+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}+ hasBin: true++ resolution: {integrity: sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==}++ resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}++ resolution: {integrity: sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==}++ resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+ peerDependencies:+ esbuild: '>=0.18'++ resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==}+ engines: {node: '>=10.16.0'}++ resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==}++ resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}+ engines: {node: '>= 14.16.0'}++ resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==}++ resolution: {integrity: sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ==}++ resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==}+ engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'}++ resolution: {integrity: sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==}++ resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}+ engines: {node: '>=7.0.0'}++ resolution: {integrity: sha512-fasDH2ont2GqF5HpyO4w0+BcewlhHEZOFn9c1ckZdHpJ56Qb7MHhH/IcJZbBGgvdtwdwNbLvxiBEdg336iA9Sg==}+ engines: {node: '>=14.6'}++ resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}++ resolution: {integrity: sha512-p2FdgwVx1a9yWBHP2wI0VgShkDpgN4kZISkxdNipGBJWpa5G6b04OINlVWCyJj0JmfvcPrgqt95E9k8yvaOJFg==}+ engines: {node: '>=12.20'}++ resolution: {integrity: sha512-Bb6Cq8oq0IjDOe8wJmi4JeNn763Xs9cfrBcaylK1tPypWzyoy2G3l90v9k64kjphl/ZJjPIShFztenRomi8WTg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-ezmVcLR3xAVp8kYOm4GS45ZLLgIE6SPAFoduLr6hTDajwb3KZ2F46gulK3XpcwRFb5KKGCSezCBAY4Dw4HsyXA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}++ resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}++ resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}+ engines: {node: ^14.18.0 || >=16.10.0}++ resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}++ resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}+ engines: {node: '>=6.6.0'}++ resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ hasBin: true++ resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==}+ peerDependencies:+ babel-plugin-macros: ^3.1.0+ peerDependenciesMeta:+ babel-plugin-macros:+ optional: true++ resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}+ engines: {node: '>=0.4.0'}++ resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}++ resolution: {integrity: sha512-7zt9Aw+SrmxLWLN0zhaTWZQiCdryLVrYTq5R7iZakLvi2UQPYMMsROYV/2qVCzMeCiSXHwKOU+sZ4zOVVlrtKA==}++ resolution: {integrity: sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}++ resolution: {integrity: sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==}++ resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}++ resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==}++ resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}++ resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==}+ engines: {node: '>=4'}+ hasBin: true++ resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}+ engines: {node: '>=0.8.x'}++ resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==}+ engines: {node: '>= 0.8.0'}++ resolution: {integrity: sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-XKJXDsASUOo0LLtFwW5hCcQGH0N4WQc/Rn8/Pvoia+TJFOkkFPvrtW9lZOeeNcxQJspvOIERMwiRLsVFlhHEkA==}+ engines: {node: '>= 16'}+ peerDependencies:+ express: '>= 4.11'++ resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}++ resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}+ engines: {node: '>=8.6.0'}++ resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}++ resolution: {integrity: sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==}++ resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}++ resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==}++ resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}+ engines: {node: '>= 18.0.0'}++ resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}++ resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==}++ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}+ engines: {node: '>=4.0'}+ peerDependencies:+ debug: '*'+ peerDependenciesMeta:+ debug:+ optional: true++ resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==}++ resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==}+ engines: {node: '>= 12.20'}++ resolution: {integrity: sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==}++ resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}++ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}+ engines: {node: '>=6.9.0'}++ resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}+ engines: {node: 6.* || 8.* || >= 10.*}++ resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==}+ engines: {node: '>=8.0.0'}++ resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]++ resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}++ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-zJIHFrl6bq3RDd2YusFNCDlM8qUprxKswyi/OPzPyzKDdyBXDqWx8bZlZ7R+saTdSTatUmb3O7K4SspGPaEOQg==}+ engines: {node: '>=16.9.0'}++ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}++ resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}+ engines: {node: '>=10.17.0'}++ resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==}++ resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}++ resolution: {integrity: sha512-jTd2FfOgOWOdgjkHuk/1Ms8VKFXkPs15ymYBETw1sAOrO/dY3XeGVRWir9qBbw7pXr0T2eTFwfCZ+N02HmiNGA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==}+ engines: {node: '>=8'}+ hasBin: true++ resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}+ engines: {node: '>=0.8.19'}++ resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}+ deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.++ resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}++ resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==}++ resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}+ engines: {node: '>=0.12.0'}++ resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}++ resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}++ resolution: {integrity: sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw==}+ peerDependencies:+ ws: '*'++ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ hasBin: true+ peerDependencies:+ node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0+ peerDependenciesMeta:+ node-notifier:+ optional: true++ resolution: {integrity: sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ peerDependencies:+ '@types/node': '*'+ ts-node: '>=9.0.0'+ peerDependenciesMeta:+ '@types/node':+ optional: true+ ts-node:+ optional: true++ resolution: {integrity: sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==}+ engines: {node: '>=6'}+ peerDependencies:+ jest-resolve: '*'+ peerDependenciesMeta:+ jest-resolve:+ optional: true++ resolution: {integrity: sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-mWlvLviKIgIQ8VCuM1xRdD0TWp3zlzionlmDBjuXVBs+VkmXq6FgW9T4Emr7oGz/Rk6feDCGyiugolcQEyp3mg==}+ engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}++ resolution: {integrity: sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}+ hasBin: true+ peerDependencies:+ node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0+ peerDependenciesMeta:+ node-notifier:+ optional: true++ resolution: {integrity: sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==}++ resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}++ resolution: {integrity: sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==}+ hasBin: true++ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==}++ resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}++ resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}++ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==}++ resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==}++ resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}++ resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==}++ resolution: {integrity: sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==}+ engines: {node: '>= 12.0.0'}++ resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}++ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}++ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}++ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==}++ resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}++ resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}+ engines: {node: '>=8.6'}++ resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}++ resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}+ engines: {node: '>=16 || 14 >=14.17'}++ resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}++ resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}++ resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}++ resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}+ engines: {node: '>=10.5.0'}+ deprecated: Use your platform's native DOMException instead++ resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}+ engines: {node: 4.x || >=6.0.0}+ peerDependencies:+ encoding: ^0.1.0+ peerDependenciesMeta:+ encoding:+ optional: true++ resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}++ resolution: {integrity: sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}++ resolution: {integrity: sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==}++ resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==}+ hasBin: true+ peerDependencies:+ ws: ^8.18.0+ zod: ^3.23.8+ peerDependenciesMeta:+ ws:+ optional: true+ zod:+ optional: true++ resolution: {integrity: sha512-a4sfn6L2sIShhtzJqmjGrARvxAW/3F2BJDdyRVvNF9VhAsZSh5hSyI3a9TNvmzBxXmq66nY5LNT5bQcBxYAZZg==}++ resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}++ resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}++ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==}+ engines: {node: '>=8.6'}++ resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}+ engines: {node: '>=16.20.0'}++ resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}++ resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}+ engines: {node: '>= 18'}+ peerDependencies:+ jiti: '>=1.21.0'+ postcss: '>=8.0.9'+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ jiti:+ optional: true+ postcss:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==}+ engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}++ resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-NWWCCscLjs+cOKF/s/XVNFRW7Yih0fdH+9brffR5NZCy8k42yRdl5KlWKMVXuI1vfCoy4o1z80XR/W/QUb3V3w==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==}++ resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}+ engines: {node: '>=0.6'}++ resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}++ resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}++ resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}+ engines: {node: '>= 14.18.0'}++ resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==}+ engines: {node: '>=9.3.0 || >=8.10.0 <9.0.0'}++ resolution: {integrity: sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==}+ engines: {node: '>= 0.4'}+ hasBin: true++ resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}+ engines: {iojs: '>=1.0.0', node: '>=0.10.0'}++ resolution: {integrity: sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}++ resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}++ resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}++ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}+ hasBin: true++ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}++ resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}++ resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}++ resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==}++ resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==}++ resolution: {integrity: sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==}++ resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==}++ resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==}+ engines: {node: '>=10.0.0'}++ resolution: {integrity: sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}++ resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}+ engines: {node: '>=16 || 14 >=14.17'}+ hasBin: true++ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-XdhtCvlMywwxpCW8YEq3lOXBJpUPTR2OHHcwLPO3HwsJqOHa2Ok/oJ7ruGzp+JrKoRPVCzJwAdEjqLW/vNRPHA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==}++ resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}+ engines: {node: '>=0.8'}++ resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}++ resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==}++ resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}+ engines: {node: '>=8.0'}++ resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}+ engines: {node: '>=0.6'}++ resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}++ resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}+ hasBin: true++ resolution: {integrity: sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==}+ engines: {node: '>= 14.0.0'}++ resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==}+ engines: {node: '>=18'}+ hasBin: true+ peerDependencies:+ '@microsoft/api-extractor': ^7.36.0+ '@swc/core': ^1+ postcss: ^8.4.12+ typescript: '>=4.5.0'+ peerDependenciesMeta:+ '@microsoft/api-extractor':+ optional: true+ '@swc/core':+ optional: true+ postcss:+ optional: true+ typescript:+ optional: true++ resolution: {integrity: sha512-GQHnkIfxyx1wYCOS/wonik5MVRZU9hi1TEZmzGZSCJB1y9YgoZ8H6itNE/u4suE+yLmOzuE4E5S4TZ/ZX2wcWQ==}+ engines: {node: '>=18.0.0'}+ hasBin: true++ resolution: {integrity: sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==}++ resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==}+ engines: {node: '>=4'}++ resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}+ engines: {node: '>=16.20.0'}+ hasBin: true++ resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==}++ resolution: {integrity: sha512-yu26mwteFYzBAot7KVMqFGCVpsF6g8wXfJzQUHvu1no3+rRRSFcSV2nKeYvNPLD2J4b08jYBDhHUjeH0ygIl9w==}+ hasBin: true++ resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}++ resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}++ resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}+ hasBin: true+ peerDependencies:+ browserslist: '>= 4.21.0'++ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}++ resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==}+ engines: {node: '>=10.12.0'}++ resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==}++ resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}++ resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}++ resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}+ engines: {node: '>= 8'}+ hasBin: true++ resolution: {integrity: sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==}+ engines: {node: '>= 12.0.0'}++ resolution: {integrity: sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA==}+ engines: {node: '>= 12.0.0'}++ resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}++ resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==}+ engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}++ resolution: {integrity: sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++ resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}++ resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}+ engines: {node: '>= 14.6'}+ hasBin: true++ resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}+ peerDependencies:+ zod: ^3.25.28 || ^4++ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}++snapshots:++ '@asteasolutions/[email protected]([email protected])':+ dependencies:+ openapi3-ts: 4.6.0+ zod: 3.25.76++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/checksums': 3.1000.19+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/credential-provider-node': 3.972.71+ '@aws-sdk/middleware-sdk-s3': 3.972.65+ '@aws-sdk/signature-v4-multi-region': 3.996.41+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/fetch-http-handler': 5.6.9+ '@smithy/node-http-handler': 4.9.9+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.974.2+ '@aws-sdk/xml-builder': 3.972.36+ '@aws/lambda-invoke-store': 0.3.0+ '@smithy/core': 3.29.7+ '@smithy/signature-v4': 5.6.8+ '@smithy/types': 4.16.1+ bowser: 2.14.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/fetch-http-handler': 5.6.9+ '@smithy/node-http-handler': 4.9.9+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/credential-provider-env': 3.972.60+ '@aws-sdk/credential-provider-http': 3.972.62+ '@aws-sdk/credential-provider-login': 3.972.67+ '@aws-sdk/credential-provider-process': 3.972.60+ '@aws-sdk/credential-provider-sso': 3.973.4+ '@aws-sdk/credential-provider-web-identity': 3.972.66+ '@aws-sdk/nested-clients': 3.997.34+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/credential-provider-imds': 4.4.12+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/nested-clients': 3.997.34+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/credential-provider-env': 3.972.60+ '@aws-sdk/credential-provider-http': 3.972.62+ '@aws-sdk/credential-provider-ini': 3.973.5+ '@aws-sdk/credential-provider-process': 3.972.60+ '@aws-sdk/credential-provider-sso': 3.973.4+ '@aws-sdk/credential-provider-web-identity': 3.972.66+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/credential-provider-imds': 4.4.12+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/nested-clients': 3.997.34+ '@aws-sdk/token-providers': 3.1092.0+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/nested-clients': 3.997.34+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected](@aws-sdk/[email protected])':+ dependencies:+ '@aws-sdk/client-s3': 3.1093.0+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ buffer: 5.6.0+ events: 3.3.0+ stream-browserify: 3.0.0+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/signature-v4-multi-region': 3.996.41+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/signature-v4-multi-region': 3.996.41+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/fetch-http-handler': 5.6.9+ '@smithy/node-http-handler': 4.9.9+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/types': 3.974.2+ '@smithy/signature-v4': 5.6.8+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@aws-sdk/core': 3.976.0+ '@aws-sdk/nested-clients': 3.997.34+ '@aws-sdk/types': 3.974.2+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws-sdk/[email protected]':+ dependencies:+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@aws/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-validator-identifier': 7.29.7+ js-tokens: 4.0.0+ picocolors: 1.1.1++ '@babel/[email protected]': {}++ '@babel/[email protected]([email protected])':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.7+ '@babel/helper-compilation-targets': 7.29.7+ '@babel/helper-module-transforms': 7.29.7(@babel/[email protected]([email protected]))([email protected])+ '@babel/helpers': 7.29.7+ '@babel/parser': 7.29.7+ '@babel/template': 7.29.7+ '@babel/traverse': 7.29.7([email protected])+ '@babel/types': 7.29.7+ '@jridgewell/remapping': 2.3.5+ convert-source-map: 2.0.0+ debug: 4.4.3([email protected])+ gensync: 1.0.0-beta.2+ json5: 2.2.3+ semver: 6.3.1+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/parser': 7.29.7+ '@babel/types': 7.29.7+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31+ jsesc: 3.1.0++ '@babel/[email protected]':+ dependencies:+ '@babel/compat-data': 7.29.7+ '@babel/helper-validator-option': 7.29.7+ browserslist: 4.28.7+ lru-cache: 5.1.1+ semver: 6.3.1++ '@babel/[email protected]': {}++ '@babel/[email protected]([email protected])':+ dependencies:+ '@babel/traverse': 7.29.7([email protected])+ '@babel/types': 7.29.7+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-module-imports': 7.29.7([email protected])+ '@babel/helper-validator-identifier': 7.29.7+ '@babel/traverse': 7.29.7([email protected])+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/template': 7.29.7+ '@babel/types': 7.29.7++ '@babel/[email protected]':+ dependencies:+ '@babel/types': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/parser': 7.29.7+ '@babel/types': 7.29.7++ '@babel/[email protected]([email protected])':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.7+ '@babel/helper-globals': 7.29.7+ '@babel/parser': 7.29.7+ '@babel/template': 7.29.7+ '@babel/types': 7.29.7+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-string-parser': 7.29.7+ '@babel/helper-validator-identifier': 7.29.7++ '@bcoe/[email protected]': {}++ '@colors/[email protected]': {}++ '@dabh/[email protected]':+ dependencies:+ '@so-ric/colorspace': 1.1.6+ enabled: 2.0.0+ kuler: 2.0.0++ dependencies:+ transitivePeerDependencies:+ - debug+ - supports-color++ '@daytona/[email protected]([email protected]([email protected]))([email protected])([email protected])':+ dependencies:+ '@aws-sdk/client-s3': 3.1093.0+ '@aws-sdk/lib-storage': 3.1093.0(@aws-sdk/[email protected])+ '@iarna/toml': 2.2.5+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/exporter-trace-otlp-http': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation-http': 0.217.0(@opentelemetry/[email protected])([email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-node': 0.217.0(@opentelemetry/[email protected])([email protected])+ '@opentelemetry/sdk-trace-base': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+ busboy: 1.6.0+ dotenv: 17.4.2+ expand-tilde: 2.0.2+ fast-glob: 3.3.3+ form-data: 4.0.6+ isomorphic-ws: 5.0.0([email protected])+ pathe: 2.0.3+ shell-quote: 1.10.0+ tar: 7.5.21+ transitivePeerDependencies:+ - debug+ - supports-color+ - ws++ dependencies:+ transitivePeerDependencies:+ - debug+ - supports-color++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@grpc/[email protected]':+ dependencies:+ '@grpc/proto-loader': 0.8.1+ '@js-sdsl/ordered-map': 4.4.2++ '@grpc/[email protected]':+ dependencies:+ lodash.camelcase: 4.3.0+ long: 5.3.2+ protobufjs: 7.6.5+ yargs: 17.7.3++ '@hono/[email protected]([email protected])':+ dependencies:+ hono: 4.12.31++ '@hono/[email protected]([email protected])':+ dependencies:+ hono: 4.12.31++ dependencies:+ '@asteasolutions/zod-to-openapi': 7.3.4([email protected])+ '@hono/zod-validator': 0.7.6([email protected])([email protected])+ hono: 4.12.31+ openapi3-ts: 4.6.0+ zod: 3.25.76++ dependencies:+ hono: 4.12.31+ zod: 3.25.76++ '@iarna/[email protected]': {}++ '@isaacs/[email protected]':+ dependencies:+ minipass: 7.1.3++ '@istanbuljs/[email protected]':+ dependencies:+ camelcase: 5.3.1+ find-up: 4.1.0+ get-package-type: 0.1.0+ js-yaml: 3.15.0+ resolve-from: 5.0.0++ '@istanbuljs/[email protected]': {}++ '@jest/[email protected]':+ dependencies:+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ chalk: 4.1.2+ jest-message-util: 29.7.0+ jest-util: 29.7.0+ slash: 3.0.0++ '@jest/[email protected]([email protected])':+ dependencies:+ '@jest/console': 29.7.0+ '@jest/reporters': 29.7.0([email protected])+ '@jest/test-result': 29.7.0+ '@jest/transform': 29.7.0([email protected])+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ ansi-escapes: 4.3.2+ chalk: 4.1.2+ ci-info: 3.9.0+ exit: 0.1.2+ graceful-fs: 4.2.11+ jest-changed-files: 29.7.0+ jest-config: 29.7.0(@types/[email protected])([email protected])+ jest-haste-map: 29.7.0+ jest-message-util: 29.7.0+ jest-regex-util: 29.6.3+ jest-resolve: 29.7.0+ jest-resolve-dependencies: 29.7.0([email protected])+ jest-runner: 29.7.0([email protected])+ jest-runtime: 29.7.0([email protected])+ jest-snapshot: 29.7.0([email protected])+ jest-util: 29.7.0+ jest-validate: 29.7.0+ jest-watcher: 29.7.0+ micromatch: 4.0.8+ pretty-format: 29.7.0+ slash: 3.0.0+ strip-ansi: 6.0.1+ transitivePeerDependencies:+ - babel-plugin-macros+ - supports-color+ - ts-node++ '@jest/[email protected]':+ dependencies:+ '@jest/types': 30.4.1++ '@jest/[email protected]':+ dependencies:+ '@jest/fake-timers': 29.7.0+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ jest-mock: 29.7.0++ '@jest/[email protected]':+ dependencies:+ jest-get-type: 29.6.3++ '@jest/[email protected]([email protected])':+ dependencies:+ expect: 29.7.0+ jest-snapshot: 29.7.0([email protected])+ transitivePeerDependencies:+ - supports-color++ '@jest/[email protected]':+ dependencies:+ '@jest/types': 29.6.3+ '@sinonjs/fake-timers': 10.3.0+ '@types/node': 24.13.3+ jest-message-util: 29.7.0+ jest-mock: 29.7.0+ jest-util: 29.7.0++ '@jest/[email protected]([email protected])':+ dependencies:+ '@jest/environment': 29.7.0+ '@jest/expect': 29.7.0([email protected])+ '@jest/types': 29.6.3+ jest-mock: 29.7.0+ transitivePeerDependencies:+ - supports-color++ '@jest/[email protected]':+ dependencies:+ '@types/node': 24.13.3+ jest-regex-util: 30.4.0++ '@jest/[email protected]([email protected])':+ dependencies:+ '@bcoe/v8-coverage': 0.2.3+ '@jest/console': 29.7.0+ '@jest/test-result': 29.7.0+ '@jest/transform': 29.7.0([email protected])+ '@jest/types': 29.6.3+ '@jridgewell/trace-mapping': 0.3.31+ '@types/node': 24.13.3+ chalk: 4.1.2+ collect-v8-coverage: 1.0.3+ exit: 0.1.2+ glob: 7.2.3+ graceful-fs: 4.2.11+ istanbul-lib-coverage: 3.2.2+ istanbul-lib-instrument: 6.0.3([email protected])+ istanbul-lib-report: 3.0.1+ istanbul-lib-source-maps: 4.0.1([email protected])+ istanbul-reports: 3.2.0+ jest-message-util: 29.7.0+ jest-util: 29.7.0+ jest-worker: 29.7.0+ slash: 3.0.0+ string-length: 4.0.2+ strip-ansi: 6.0.1+ v8-to-istanbul: 9.3.0+ transitivePeerDependencies:+ - supports-color++ '@jest/[email protected]':+ dependencies:+ '@sinclair/typebox': 0.27.12++ '@jest/[email protected]':+ dependencies:+ '@sinclair/typebox': 0.34.52++ '@jest/[email protected]':+ dependencies:+ '@jridgewell/trace-mapping': 0.3.31+ callsites: 3.1.0+ graceful-fs: 4.2.11++ '@jest/[email protected]':+ dependencies:+ '@jest/console': 29.7.0+ '@jest/types': 29.6.3+ '@types/istanbul-lib-coverage': 2.0.6+ collect-v8-coverage: 1.0.3++ '@jest/[email protected]':+ dependencies:+ '@jest/test-result': 29.7.0+ graceful-fs: 4.2.11+ jest-haste-map: 29.7.0+ slash: 3.0.0++ '@jest/[email protected]([email protected])':+ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@jest/types': 29.6.3+ '@jridgewell/trace-mapping': 0.3.31+ babel-plugin-istanbul: 6.1.1([email protected])+ chalk: 4.1.2+ convert-source-map: 2.0.0+ fast-json-stable-stringify: 2.1.0+ graceful-fs: 4.2.11+ jest-haste-map: 29.7.0+ jest-regex-util: 29.6.3+ jest-util: 29.7.0+ micromatch: 4.0.8+ pirates: 4.0.7+ slash: 3.0.0+ write-file-atomic: 4.0.2+ transitivePeerDependencies:+ - supports-color++ '@jest/[email protected]':+ dependencies:+ '@jest/schemas': 29.6.3+ '@types/istanbul-lib-coverage': 2.0.6+ '@types/istanbul-reports': 3.0.4+ '@types/node': 24.13.3+ '@types/yargs': 17.0.35+ chalk: 4.1.2++ '@jest/[email protected]':+ dependencies:+ '@jest/pattern': 30.4.0+ '@jest/schemas': 30.4.1+ '@types/istanbul-lib-coverage': 2.0.6+ '@types/istanbul-reports': 3.0.4+ '@types/node': 24.13.3+ '@types/yargs': 17.0.35+ chalk: 4.1.2++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.5.5++ '@js-sdsl/[email protected]': {}++ dependencies:+ '@hono/node-server': 1.19.14([email protected])+ ajv: 8.20.0+ ajv-formats: 3.0.1([email protected])+ content-type: 1.0.5+ cors: 2.8.6+ cross-spawn: 7.0.6+ eventsource: 3.0.7+ eventsource-parser: 3.1.0+ express: 5.2.1([email protected])+ hono: 4.12.31+ jose: 6.2.4+ json-schema-typed: 8.0.2+ pkce-challenge: 5.0.1+ raw-body: 3.0.2+ zod: 3.25.76+ zod-to-json-schema: 3.25.2([email protected])+ transitivePeerDependencies:+ - supports-color++ '@nats-io/[email protected]':+ dependencies:+ '@nats-io/nkeys': 2.0.3+ '@nats-io/nuid': 2.0.3++ '@nats-io/[email protected]':+ dependencies:+ tweetnacl: 1.0.3++ '@nats-io/[email protected]': {}++ '@nodelib/[email protected]':+ dependencies:+ '@nodelib/fs.stat': 2.0.5+ run-parallel: 1.2.0++ '@nodelib/[email protected]': {}++ '@nodelib/[email protected]':+ dependencies:+ '@nodelib/fs.scandir': 2.1.5+ fastq: 1.20.1++ '@opentelemetry/[email protected]':+ dependencies:+ '@opentelemetry/api': 1.9.1++ '@opentelemetry/[email protected]': {}++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ yaml: 2.9.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@grpc/grpc-js': 1.14.4+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-grpc-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.217.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/api-logs': 0.217.0+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.217.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/api-logs': 0.217.0+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@grpc/grpc-js': 1.14.4+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/exporter-metrics-otlp-http': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-grpc-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/exporter-metrics-otlp-http': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@grpc/grpc-js': 1.14.4+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-grpc-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/[email protected])([email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+ forwarded-parse: 2.1.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/api-logs': 0.217.0+ import-in-the-middle: 3.3.2+ require-in-the-middle: 8.0.1([email protected])+ transitivePeerDependencies:+ - supports-color++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@grpc/grpc-js': 1.14.4+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/otlp-transformer': 0.217.0(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/api-logs': 0.217.0+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])+ protobufjs: 8.0.1++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/api-logs': 0.217.0+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])++ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/api-logs': 0.217.0+ '@opentelemetry/configuration': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/exporter-logs-otlp-grpc': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-logs-otlp-http': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-logs-otlp-proto': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-metrics-otlp-grpc': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-metrics-otlp-http': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-metrics-otlp-proto': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-prometheus': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-trace-otlp-grpc': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-trace-otlp-http': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-trace-otlp-proto': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/exporter-zipkin': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/instrumentation': 0.217.0(@opentelemetry/[email protected])([email protected])+ '@opentelemetry/otlp-exporter-base': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/propagator-b3': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/propagator-jaeger': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-logs': 0.217.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-metrics': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-node': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0+ transitivePeerDependencies:+ - supports-color++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/context-async-hooks': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/core': 2.7.1(@opentelemetry/[email protected])+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])++ '@opentelemetry/[email protected](@opentelemetry/[email protected])':+ dependencies:+ '@opentelemetry/api': 1.9.1+ '@opentelemetry/core': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/resources': 2.10.0(@opentelemetry/[email protected])+ '@opentelemetry/semantic-conventions': 1.43.0++ '@opentelemetry/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]':+ dependencies:+ '@protobufjs/aspromise': 1.1.2++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@protobufjs/[email protected]': {}++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@sinclair/[email protected]': {}++ '@sinclair/[email protected]': {}++ '@sinonjs/[email protected]':+ dependencies:+ type-detect: 4.0.8++ '@sinonjs/[email protected]':+ dependencies:+ '@sinonjs/commons': 3.0.1++ '@smithy/[email protected]':+ dependencies:+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.29.7+ '@smithy/types': 4.16.1+ tslib: 2.8.1++ '@smithy/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@so-ric/[email protected]':+ dependencies:+ color: 5.0.3+ text-hex: 1.0.0++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ optional: true++ '@swc/[email protected]':+ dependencies:+ '@swc/counter': 0.1.3+ '@swc/types': 0.1.27+ optionalDependencies:+ '@swc/core-darwin-arm64': 1.15.46+ '@swc/core-darwin-x64': 1.15.46+ '@swc/core-linux-arm-gnueabihf': 1.15.46+ '@swc/core-linux-arm64-gnu': 1.15.46+ '@swc/core-linux-arm64-musl': 1.15.46+ '@swc/core-linux-ppc64-gnu': 1.15.46+ '@swc/core-linux-s390x-gnu': 1.15.46+ '@swc/core-linux-x64-gnu': 1.15.46+ '@swc/core-linux-x64-musl': 1.15.46+ '@swc/core-win32-arm64-msvc': 1.15.46+ '@swc/core-win32-ia32-msvc': 1.15.46+ '@swc/core-win32-x64-msvc': 1.15.46++ '@swc/[email protected]': {}++ '@swc/[email protected](@swc/[email protected])':+ dependencies:+ '@jest/create-cache-key-function': 30.4.1+ '@swc/core': 1.15.46+ '@swc/counter': 0.1.3+ jsonc-parser: 3.3.1++ '@swc/[email protected]':+ dependencies:+ '@swc/counter': 0.1.3++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.7+ '@babel/types': 7.29.7+ '@types/babel__generator': 7.27.0+ '@types/babel__template': 7.4.4+ '@types/babel__traverse': 7.28.0++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.7++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.7+ '@babel/types': 7.29.7++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.7++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.3++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/istanbul-lib-coverage': 2.0.6++ '@types/[email protected]':+ dependencies:+ '@types/istanbul-lib-report': 3.0.3++ '@types/[email protected]':+ dependencies:+ expect: 29.7.0+ pretty-format: 29.7.0++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.3+ form-data: 4.0.6++ '@types/[email protected]':+ dependencies:+ undici-types: 5.26.5++ '@types/[email protected]':+ dependencies:+ undici-types: 7.18.2++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.3++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/yargs-parser': 21.0.3++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ '@typescript/[email protected]':+ optional: true++ dependencies:+ event-target-shim: 5.0.1++ dependencies:+ mime-types: 3.0.2+ negotiator: 1.0.0++ [email protected]: {}++ dependencies:+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ humanize-ms: 1.2.1++ optionalDependencies:+ ajv: 8.20.0++ dependencies:+ fast-deep-equal: 3.1.3+ fast-uri: 3.1.4+ json-schema-traverse: 1.0.0+ require-from-string: 2.0.2++ dependencies:+ type-fest: 0.21.3++ [email protected]: {}++ dependencies:+ color-convert: 2.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ normalize-path: 3.0.0+ picomatch: 2.3.2++ dependencies:+ sprintf-js: 1.0.3++ [email protected]: {}++ [email protected]: {}++ dependencies:+ follow-redirects: 1.16.0([email protected]([email protected]))+ form-data: 4.0.6+ https-proxy-agent: 5.0.1([email protected])+ proxy-from-env: 2.1.0+ transitivePeerDependencies:+ - debug+ - supports-color++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@jest/transform': 29.7.0([email protected])+ '@types/babel__core': 7.20.5+ babel-plugin-istanbul: 6.1.1([email protected])+ babel-preset-jest: 29.6.3(@babel/[email protected]([email protected]))+ chalk: 4.1.2+ graceful-fs: 4.2.11+ slash: 3.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@babel/helper-plugin-utils': 7.29.7+ '@istanbuljs/load-nyc-config': 1.1.0+ '@istanbuljs/schema': 0.1.6+ istanbul-lib-instrument: 5.2.1([email protected])+ test-exclude: 6.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@babel/template': 7.29.7+ '@babel/types': 7.29.7+ '@types/babel__core': 7.20.5+ '@types/babel__traverse': 7.28.0++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/plugin-syntax-async-generators': 7.8.4(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-bigint': 7.8.3(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-class-properties': 7.12.13(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-import-attributes': 7.29.7(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-import-meta': 7.10.4(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-json-strings': 7.8.3(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/[email protected]([email protected]))++ dependencies:+ '@babel/core': 7.29.7([email protected])+ babel-plugin-jest-hoist: 29.6.3+ babel-preset-current-node-syntax: 1.2.0(@babel/[email protected]([email protected]))++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ bytes: 3.1.2+ content-type: 2.0.0+ debug: 4.4.3([email protected])+ http-errors: 2.0.1+ iconv-lite: 0.7.3+ on-finished: 2.4.1+ qs: 6.15.3+ raw-body: 3.0.2+ type-is: 2.1.0+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ balanced-match: 1.0.2+ concat-map: 0.0.1++ dependencies:+ fill-range: 7.1.1++ dependencies:+ baseline-browser-mapping: 2.11.1+ caniuse-lite: 1.0.30001806+ electron-to-chromium: 1.5.395+ node-releases: 2.0.51+ update-browserslist-db: 1.2.3([email protected])++ dependencies:+ node-int64: 0.4.0++ [email protected]: {}++ dependencies:+ base64-js: 1.5.1+ ieee754: 1.2.1++ dependencies:+ esbuild: 0.27.7+ load-tsconfig: 0.2.5++ dependencies:+ streamsearch: 1.1.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0+ function-bind: 1.1.2++ dependencies:+ call-bind-apply-helpers: 1.0.2+ get-intrinsic: 1.3.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ansi-styles: 4.3.0+ supports-color: 7.2.0++ [email protected]: {}++ dependencies:+ readdirp: 4.1.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ string-width: 4.2.3+ strip-ansi: 6.0.1+ wrap-ansi: 7.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ color-name: 1.1.4++ dependencies:+ color-name: 2.1.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ color-name: 2.1.1++ dependencies:+ color-convert: 3.1.3+ color-string: 2.1.4++ dependencies:+ delayed-stream: 1.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ object-assign: 4.1.1+ vary: 1.1.2++ dependencies:+ '@jest/types': 29.6.3+ chalk: 4.1.2+ exit: 0.1.2+ graceful-fs: 4.2.11+ jest-config: 29.7.0(@types/[email protected])([email protected])+ jest-util: 29.7.0+ prompts: 2.4.2+ transitivePeerDependencies:+ - '@types/node'+ - babel-plugin-macros+ - supports-color+ - ts-node++ dependencies:+ path-key: 3.1.1+ shebang-command: 2.0.0+ which: 2.0.2++ dependencies:+ ms: 2.1.3+ optionalDependencies:+ supports-color: 8.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ call-bind-apply-helpers: 1.0.2+ es-errors: 1.3.0+ gopd: 1.2.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ is-arrayish: 0.2.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0++ dependencies:+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ has-tostringtag: 1.0.2+ hasown: 2.0.4++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.27.7+ '@esbuild/android-arm': 0.27.7+ '@esbuild/android-arm64': 0.27.7+ '@esbuild/android-x64': 0.27.7+ '@esbuild/darwin-arm64': 0.27.7+ '@esbuild/darwin-x64': 0.27.7+ '@esbuild/freebsd-arm64': 0.27.7+ '@esbuild/freebsd-x64': 0.27.7+ '@esbuild/linux-arm': 0.27.7+ '@esbuild/linux-arm64': 0.27.7+ '@esbuild/linux-ia32': 0.27.7+ '@esbuild/linux-loong64': 0.27.7+ '@esbuild/linux-mips64el': 0.27.7+ '@esbuild/linux-ppc64': 0.27.7+ '@esbuild/linux-riscv64': 0.27.7+ '@esbuild/linux-s390x': 0.27.7+ '@esbuild/linux-x64': 0.27.7+ '@esbuild/netbsd-arm64': 0.27.7+ '@esbuild/netbsd-x64': 0.27.7+ '@esbuild/openbsd-arm64': 0.27.7+ '@esbuild/openbsd-x64': 0.27.7+ '@esbuild/openharmony-arm64': 0.27.7+ '@esbuild/sunos-x64': 0.27.7+ '@esbuild/win32-arm64': 0.27.7+ '@esbuild/win32-ia32': 0.27.7+ '@esbuild/win32-x64': 0.27.7++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.28.1+ '@esbuild/android-arm': 0.28.1+ '@esbuild/android-arm64': 0.28.1+ '@esbuild/android-x64': 0.28.1+ '@esbuild/darwin-arm64': 0.28.1+ '@esbuild/darwin-x64': 0.28.1+ '@esbuild/freebsd-arm64': 0.28.1+ '@esbuild/freebsd-x64': 0.28.1+ '@esbuild/linux-arm': 0.28.1+ '@esbuild/linux-arm64': 0.28.1+ '@esbuild/linux-ia32': 0.28.1+ '@esbuild/linux-loong64': 0.28.1+ '@esbuild/linux-mips64el': 0.28.1+ '@esbuild/linux-ppc64': 0.28.1+ '@esbuild/linux-riscv64': 0.28.1+ '@esbuild/linux-s390x': 0.28.1+ '@esbuild/linux-x64': 0.28.1+ '@esbuild/netbsd-arm64': 0.28.1+ '@esbuild/netbsd-x64': 0.28.1+ '@esbuild/openbsd-arm64': 0.28.1+ '@esbuild/openbsd-x64': 0.28.1+ '@esbuild/openharmony-arm64': 0.28.1+ '@esbuild/sunos-x64': 0.28.1+ '@esbuild/win32-arm64': 0.28.1+ '@esbuild/win32-ia32': 0.28.1+ '@esbuild/win32-x64': 0.28.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ eventsource-parser: 3.1.0++ dependencies:+ cross-spawn: 7.0.6+ get-stream: 6.0.1+ human-signals: 2.1.0+ is-stream: 2.0.1+ merge-stream: 2.0.0+ npm-run-path: 4.0.1+ onetime: 5.1.2+ signal-exit: 3.0.7+ strip-final-newline: 2.0.0++ [email protected]: {}++ dependencies:+ homedir-polyfill: 1.0.3++ dependencies:+ '@jest/expect-utils': 29.7.0+ jest-get-type: 29.6.3+ jest-matcher-utils: 29.7.0+ jest-message-util: 29.7.0+ jest-util: 29.7.0++ dependencies:+ debug: 4.4.3([email protected])+ express: 5.2.1([email protected])+ ip-address: 10.2.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ accepts: 2.0.0+ body-parser: 2.3.0([email protected])+ content-disposition: 1.1.0+ content-type: 1.0.5+ cookie: 0.7.2+ cookie-signature: 1.2.2+ debug: 4.4.3([email protected])+ depd: 2.0.0+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ finalhandler: 2.1.1([email protected])+ fresh: 2.0.0+ http-errors: 2.0.1+ merge-descriptors: 2.0.0+ mime-types: 3.0.2+ on-finished: 2.4.1+ once: 1.4.0+ parseurl: 1.3.3+ proxy-addr: 2.0.7+ qs: 6.15.3+ range-parser: 1.3.0+ router: 2.2.0([email protected])+ send: 1.2.1([email protected])+ serve-static: 2.2.1([email protected])+ statuses: 2.0.2+ type-is: 2.1.0+ vary: 1.1.2+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ '@nodelib/fs.stat': 2.0.5+ '@nodelib/fs.walk': 1.2.8+ glob-parent: 5.1.2+ merge2: 1.4.1+ micromatch: 4.0.8++ [email protected]: {}++ [email protected]: {}++ dependencies:+ reusify: 1.1.0++ dependencies:+ bser: 2.1.1++ optionalDependencies:+ picomatch: 4.0.5++ [email protected]: {}++ dependencies:+ to-regex-range: 5.0.1++ dependencies:+ debug: 4.4.3([email protected])+ encodeurl: 2.0.0+ escape-html: 1.0.3+ on-finished: 2.4.1+ parseurl: 1.3.3+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ locate-path: 5.0.0+ path-exists: 4.0.0++ dependencies:+ magic-string: 0.30.21+ mlly: 1.8.2+ rollup: 4.62.2++ [email protected]: {}++ optionalDependencies:+ debug: 4.4.3([email protected])++ [email protected]: {}++ dependencies:+ asynckit: 0.4.0+ combined-stream: 1.0.8+ es-set-tostringtag: 2.1.0+ hasown: 2.0.4+ mime-types: 2.1.35++ dependencies:+ node-domexception: 1.0.0+ web-streams-polyfill: 4.0.0-beta.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ call-bind-apply-helpers: 1.0.2+ es-define-property: 1.0.1+ es-errors: 1.3.0+ es-object-atoms: 1.1.2+ function-bind: 1.1.2+ get-proto: 1.0.1+ gopd: 1.2.0+ has-symbols: 1.1.0+ hasown: 2.0.4+ math-intrinsics: 1.1.0++ [email protected]: {}++ dependencies:+ dunder-proto: 1.0.1+ es-object-atoms: 1.1.2++ [email protected]: {}++ dependencies:+ is-glob: 4.0.3++ dependencies:+ fs.realpath: 1.0.0+ inflight: 1.0.6+ inherits: 2.0.4+ minimatch: 3.1.5+ once: 1.4.0+ path-is-absolute: 1.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ has-symbols: 1.1.0++ dependencies:+ function-bind: 1.1.2++ dependencies:+ parse-passwd: 1.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ depd: 2.0.0+ inherits: 2.0.4+ setprototypeof: 1.2.0+ statuses: 2.0.2+ toidentifier: 1.0.1++ dependencies:+ agent-base: 6.0.2([email protected])+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ ms: 2.1.3++ dependencies:+ safer-buffer: 2.1.2++ [email protected]: {}++ dependencies:+ cjs-module-lexer: 2.2.0+ es-module-lexer: 2.3.1+ module-details-from-path: 1.0.4++ dependencies:+ pkg-dir: 4.2.0+ resolve-cwd: 3.0.0++ [email protected]: {}++ dependencies:+ once: 1.4.0+ wrappy: 1.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ hasown: 2.0.4++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ is-extglob: 2.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ws: 8.21.1++ [email protected]: {}++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/parser': 7.29.7+ '@istanbuljs/schema': 0.1.6+ istanbul-lib-coverage: 3.2.2+ semver: 6.3.1+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/parser': 7.29.7+ '@istanbuljs/schema': 0.1.6+ istanbul-lib-coverage: 3.2.2+ semver: 7.8.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ istanbul-lib-coverage: 3.2.2+ make-dir: 4.0.0+ supports-color: 7.2.0++ dependencies:+ debug: 4.4.3([email protected])+ istanbul-lib-coverage: 3.2.2+ source-map: 0.6.1+ transitivePeerDependencies:+ - supports-color++ dependencies:+ html-escaper: 2.0.2+ istanbul-lib-report: 3.0.1++ dependencies:+ execa: 5.1.1+ jest-util: 29.7.0+ p-limit: 3.1.0++ dependencies:+ '@jest/environment': 29.7.0+ '@jest/expect': 29.7.0([email protected])+ '@jest/test-result': 29.7.0+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ chalk: 4.1.2+ co: 4.6.0+ dedent: 1.7.2+ is-generator-fn: 2.1.0+ jest-each: 29.7.0+ jest-matcher-utils: 29.7.0+ jest-message-util: 29.7.0+ jest-runtime: 29.7.0([email protected])+ jest-snapshot: 29.7.0([email protected])+ jest-util: 29.7.0+ p-limit: 3.1.0+ pretty-format: 29.7.0+ pure-rand: 6.1.0+ slash: 3.0.0+ stack-utils: 2.0.6+ transitivePeerDependencies:+ - babel-plugin-macros+ - supports-color++ dependencies:+ '@jest/core': 29.7.0([email protected])+ '@jest/test-result': 29.7.0+ '@jest/types': 29.6.3+ chalk: 4.1.2+ create-jest: 29.7.0(@types/[email protected])([email protected])+ exit: 0.1.2+ import-local: 3.2.0+ jest-config: 29.7.0(@types/[email protected])([email protected])+ jest-util: 29.7.0+ jest-validate: 29.7.0+ yargs: 17.7.3+ transitivePeerDependencies:+ - '@types/node'+ - babel-plugin-macros+ - supports-color+ - ts-node++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@jest/test-sequencer': 29.7.0+ '@jest/types': 29.6.3+ chalk: 4.1.2+ ci-info: 3.9.0+ deepmerge: 4.3.1+ glob: 7.2.3+ graceful-fs: 4.2.11+ jest-circus: 29.7.0([email protected])+ jest-environment-node: 29.7.0+ jest-get-type: 29.6.3+ jest-regex-util: 29.6.3+ jest-resolve: 29.7.0+ jest-runner: 29.7.0([email protected])+ jest-util: 29.7.0+ jest-validate: 29.7.0+ micromatch: 4.0.8+ parse-json: 5.2.0+ pretty-format: 29.7.0+ slash: 3.0.0+ strip-json-comments: 3.1.1+ optionalDependencies:+ '@types/node': 24.13.3+ transitivePeerDependencies:+ - babel-plugin-macros+ - supports-color++ dependencies:+ chalk: 4.1.2+ diff-sequences: 29.6.3+ jest-get-type: 29.6.3+ pretty-format: 29.7.0++ dependencies:+ detect-newline: 3.1.0++ dependencies:+ '@jest/types': 29.6.3+ chalk: 4.1.2+ jest-get-type: 29.6.3+ jest-util: 29.7.0+ pretty-format: 29.7.0++ dependencies:+ '@jest/environment': 29.7.0+ '@jest/fake-timers': 29.7.0+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ jest-mock: 29.7.0+ jest-util: 29.7.0++ [email protected]: {}++ dependencies:+ '@jest/types': 29.6.3+ '@types/graceful-fs': 4.1.9+ '@types/node': 24.13.3+ anymatch: 3.1.3+ fb-watchman: 2.0.2+ graceful-fs: 4.2.11+ jest-regex-util: 29.6.3+ jest-util: 29.7.0+ jest-worker: 29.7.0+ micromatch: 4.0.8+ walker: 1.0.8+ optionalDependencies:+ fsevents: 2.3.3++ dependencies:+ jest-get-type: 29.6.3+ pretty-format: 29.7.0++ dependencies:+ chalk: 4.1.2+ jest-diff: 29.7.0+ jest-get-type: 29.6.3+ pretty-format: 29.7.0++ dependencies:+ '@babel/code-frame': 7.29.7+ '@jest/types': 29.6.3+ '@types/stack-utils': 2.0.3+ chalk: 4.1.2+ graceful-fs: 4.2.11+ micromatch: 4.0.8+ pretty-format: 29.7.0+ slash: 3.0.0+ stack-utils: 2.0.6++ dependencies:+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ jest-util: 29.7.0++ optionalDependencies:+ jest-resolve: 29.7.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ jest-regex-util: 29.6.3+ jest-snapshot: 29.7.0([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ chalk: 4.1.2+ graceful-fs: 4.2.11+ jest-haste-map: 29.7.0+ jest-pnp-resolver: 1.2.3([email protected])+ jest-util: 29.7.0+ jest-validate: 29.7.0+ resolve: 1.22.12+ resolve.exports: 2.0.3+ slash: 3.0.0++ dependencies:+ '@jest/console': 29.7.0+ '@jest/environment': 29.7.0+ '@jest/test-result': 29.7.0+ '@jest/transform': 29.7.0([email protected])+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ chalk: 4.1.2+ emittery: 0.13.1+ graceful-fs: 4.2.11+ jest-docblock: 29.7.0+ jest-environment-node: 29.7.0+ jest-haste-map: 29.7.0+ jest-leak-detector: 29.7.0+ jest-message-util: 29.7.0+ jest-resolve: 29.7.0+ jest-runtime: 29.7.0([email protected])+ jest-util: 29.7.0+ jest-watcher: 29.7.0+ jest-worker: 29.7.0+ p-limit: 3.1.0+ source-map-support: 0.5.13+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@jest/environment': 29.7.0+ '@jest/fake-timers': 29.7.0+ '@jest/globals': 29.7.0([email protected])+ '@jest/source-map': 29.6.3+ '@jest/test-result': 29.7.0+ '@jest/transform': 29.7.0([email protected])+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ chalk: 4.1.2+ cjs-module-lexer: 1.4.3+ collect-v8-coverage: 1.0.3+ glob: 7.2.3+ graceful-fs: 4.2.11+ jest-haste-map: 29.7.0+ jest-message-util: 29.7.0+ jest-mock: 29.7.0+ jest-regex-util: 29.6.3+ jest-resolve: 29.7.0+ jest-snapshot: 29.7.0([email protected])+ jest-util: 29.7.0+ slash: 3.0.0+ strip-bom: 4.0.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/generator': 7.29.7+ '@babel/plugin-syntax-jsx': 7.29.7(@babel/[email protected]([email protected]))+ '@babel/plugin-syntax-typescript': 7.29.7(@babel/[email protected]([email protected]))+ '@babel/types': 7.29.7+ '@jest/expect-utils': 29.7.0+ '@jest/transform': 29.7.0([email protected])+ '@jest/types': 29.6.3+ babel-preset-current-node-syntax: 1.2.0(@babel/[email protected]([email protected]))+ chalk: 4.1.2+ expect: 29.7.0+ graceful-fs: 4.2.11+ jest-diff: 29.7.0+ jest-get-type: 29.6.3+ jest-matcher-utils: 29.7.0+ jest-message-util: 29.7.0+ jest-util: 29.7.0+ natural-compare: 1.4.0+ pretty-format: 29.7.0+ semver: 7.8.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ chalk: 4.1.2+ ci-info: 3.9.0+ graceful-fs: 4.2.11+ picomatch: 2.3.2++ dependencies:+ '@jest/types': 29.6.3+ camelcase: 6.3.0+ chalk: 4.1.2+ jest-get-type: 29.6.3+ leven: 3.1.0+ pretty-format: 29.7.0++ dependencies:+ '@jest/test-result': 29.7.0+ '@jest/types': 29.6.3+ '@types/node': 24.13.3+ ansi-escapes: 4.3.2+ chalk: 4.1.2+ emittery: 0.13.1+ jest-util: 29.7.0+ string-length: 4.0.2++ dependencies:+ '@types/node': 24.13.3+ jest-util: 29.7.0+ merge-stream: 2.0.0+ supports-color: 8.1.1++ dependencies:+ '@jest/core': 29.7.0([email protected])+ '@jest/types': 29.6.3+ import-local: 3.2.0+ jest-cli: 29.7.0(@types/[email protected])([email protected])+ transitivePeerDependencies:+ - '@types/node'+ - babel-plugin-macros+ - supports-color+ - ts-node++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ argparse: 1.0.10+ esprima: 4.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ p-locate: 4.1.0++ [email protected]: {}++ dependencies:+ '@colors/colors': 1.6.0+ '@types/triple-beam': 1.3.5+ fecha: 4.2.3+ ms: 2.1.3+ safe-stable-stringify: 2.5.0+ triple-beam: 1.4.1++ [email protected]: {}++ dependencies:+ yallist: 3.1.1++ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5++ dependencies:+ semver: 7.8.5++ dependencies:+ tmpl: 1.0.5++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ braces: 3.0.3+ picomatch: 2.3.2++ [email protected]: {}++ [email protected]: {}++ dependencies:+ mime-db: 1.52.0++ dependencies:+ mime-db: 1.54.0++ [email protected]: {}++ dependencies:+ brace-expansion: 1.1.16++ [email protected]: {}++ dependencies:+ minipass: 7.1.3++ dependencies:+ acorn: 8.17.0+ pathe: 2.0.3+ pkg-types: 1.3.1+ ufo: 1.6.4++ [email protected]: {}++ [email protected]: {}++ dependencies:+ any-promise: 1.3.0+ object-assign: 4.1.1+ thenify-all: 1.6.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ whatwg-url: 5.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ path-key: 3.1.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ee-first: 1.1.1++ dependencies:+ wrappy: 1.0.2++ dependencies:+ fn.name: 1.1.0++ dependencies:+ mimic-fn: 2.1.0++ dependencies:+ '@types/node': 18.19.130+ '@types/node-fetch': 2.6.13+ abort-controller: 3.0.0+ agentkeepalive: 4.6.0+ form-data-encoder: 1.7.2+ formdata-node: 4.4.1+ node-fetch: 2.7.0+ optionalDependencies:+ ws: 8.21.1+ zod: 3.25.76+ transitivePeerDependencies:+ - encoding++ dependencies:+ yaml: 2.9.0++ dependencies:+ p-try: 2.2.0++ dependencies:+ yocto-queue: 0.1.0++ dependencies:+ p-limit: 2.3.0++ [email protected]: {}++ dependencies:+ '@babel/code-frame': 7.29.7+ error-ex: 1.3.4+ json-parse-even-better-errors: 2.3.1+ lines-and-columns: 1.2.4++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ find-up: 4.1.0++ dependencies:+ confbox: 0.1.8+ mlly: 1.8.2+ pathe: 2.0.3++ dependencies:+ lilconfig: 3.1.3+ optionalDependencies:+ tsx: 4.23.1+ yaml: 2.9.0++ dependencies:+ '@jest/schemas': 29.6.3+ ansi-styles: 5.2.0+ react-is: 18.3.1++ dependencies:+ kleur: 3.0.3+ sisteransi: 1.0.5++ dependencies:+ '@protobufjs/aspromise': 1.1.2+ '@protobufjs/base64': 1.1.2+ '@protobufjs/codegen': 2.0.5+ '@protobufjs/eventemitter': 1.1.1+ '@protobufjs/fetch': 1.1.1+ '@protobufjs/float': 1.0.2+ '@protobufjs/path': 1.1.2+ '@protobufjs/pool': 1.1.0+ '@protobufjs/utf8': 1.1.2+ '@types/node': 24.13.3+ long: 5.3.2++ dependencies:+ '@protobufjs/aspromise': 1.1.2+ '@protobufjs/base64': 1.1.2+ '@protobufjs/codegen': 2.0.5+ '@protobufjs/eventemitter': 1.1.1+ '@protobufjs/fetch': 1.1.1+ '@protobufjs/float': 1.0.2+ '@protobufjs/inquire': 1.1.2+ '@protobufjs/path': 1.1.2+ '@protobufjs/pool': 1.1.0+ '@protobufjs/utf8': 1.1.2+ '@types/node': 24.13.3+ long: 5.3.2++ dependencies:+ forwarded: 0.2.0+ ipaddr.js: 1.9.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-define-property: 1.0.1+ side-channel: 1.1.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ bytes: 3.1.2+ http-errors: 2.0.1+ iconv-lite: 0.7.3+ unpipe: 1.0.0++ [email protected]: {}++ dependencies:+ inherits: 2.0.4+ string_decoder: 1.3.0+ util-deprecate: 1.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ debug: 4.4.3([email protected])+ module-details-from-path: 1.0.4+ transitivePeerDependencies:+ - supports-color++ dependencies:+ resolve-from: 5.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0+ is-core-module: 2.16.2+ path-parse: 1.0.7+ supports-preserve-symlinks-flag: 1.0.0++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.9+ optionalDependencies:+ '@rollup/rollup-android-arm-eabi': 4.62.2+ '@rollup/rollup-android-arm64': 4.62.2+ '@rollup/rollup-darwin-arm64': 4.62.2+ '@rollup/rollup-darwin-x64': 4.62.2+ '@rollup/rollup-freebsd-arm64': 4.62.2+ '@rollup/rollup-freebsd-x64': 4.62.2+ '@rollup/rollup-linux-arm-gnueabihf': 4.62.2+ '@rollup/rollup-linux-arm-musleabihf': 4.62.2+ '@rollup/rollup-linux-arm64-gnu': 4.62.2+ '@rollup/rollup-linux-arm64-musl': 4.62.2+ '@rollup/rollup-linux-loong64-gnu': 4.62.2+ '@rollup/rollup-linux-loong64-musl': 4.62.2+ '@rollup/rollup-linux-ppc64-gnu': 4.62.2+ '@rollup/rollup-linux-ppc64-musl': 4.62.2+ '@rollup/rollup-linux-riscv64-gnu': 4.62.2+ '@rollup/rollup-linux-riscv64-musl': 4.62.2+ '@rollup/rollup-linux-s390x-gnu': 4.62.2+ '@rollup/rollup-linux-x64-gnu': 4.62.2+ '@rollup/rollup-linux-x64-musl': 4.62.2+ '@rollup/rollup-openbsd-x64': 4.62.2+ '@rollup/rollup-openharmony-arm64': 4.62.2+ '@rollup/rollup-win32-arm64-msvc': 4.62.2+ '@rollup/rollup-win32-ia32-msvc': 4.62.2+ '@rollup/rollup-win32-x64-gnu': 4.62.2+ '@rollup/rollup-win32-x64-msvc': 4.62.2+ fsevents: 2.3.3++ dependencies:+ debug: 4.4.3([email protected])+ depd: 2.0.0+ is-promise: 4.0.0+ parseurl: 1.3.3+ path-to-regexp: 8.4.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ queue-microtask: 1.2.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ debug: 4.4.3([email protected])+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ fresh: 2.0.0+ http-errors: 2.0.1+ mime-types: 3.0.2+ ms: 2.1.3+ on-finished: 2.4.1+ range-parser: 1.3.0+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ encodeurl: 2.0.0+ escape-html: 1.0.3+ parseurl: 1.3.3+ send: 1.2.1([email protected])+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ shebang-regex: 3.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4+ side-channel-map: 1.0.1++ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4+ side-channel-list: 1.0.1+ side-channel-map: 1.0.1+ side-channel-weakmap: 1.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ buffer-from: 1.1.2+ source-map: 0.6.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ escape-string-regexp: 2.0.0++ [email protected]: {}++ dependencies:+ inherits: 2.0.4+ readable-stream: 3.6.2++ [email protected]: {}++ dependencies:+ char-regex: 1.0.2+ strip-ansi: 6.0.1++ dependencies:+ emoji-regex: 8.0.0+ is-fullwidth-code-point: 3.0.0+ strip-ansi: 6.0.1++ dependencies:+ safe-buffer: 5.2.1++ dependencies:+ ansi-regex: 5.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ commander: 4.1.1+ lines-and-columns: 1.2.4+ mz: 2.7.0+ pirates: 4.0.7+ tinyglobby: 0.2.17+ ts-interface-checker: 0.1.13++ dependencies:+ has-flag: 4.0.0++ dependencies:+ has-flag: 4.0.0++ [email protected]: {}++ dependencies:+ '@isaacs/fs-minipass': 4.0.1+ chownr: 3.0.0+ minipass: 7.1.3+ minizlib: 3.1.0+ yallist: 5.0.0++ dependencies:+ '@istanbuljs/schema': 0.1.6+ glob: 7.2.3+ minimatch: 3.1.5++ [email protected]: {}++ dependencies:+ thenify: 3.3.1++ dependencies:+ any-promise: 1.3.0++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.5++ [email protected]: {}++ dependencies:+ is-number: 7.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected](@swc/[email protected])([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ bundle-require: 5.1.0([email protected])+ cac: 6.7.14+ chokidar: 4.0.3+ consola: 3.4.2+ debug: 4.4.3([email protected])+ esbuild: 0.27.7+ fix-dts-default-cjs-exports: 1.0.1+ joycon: 3.1.1+ picocolors: 1.1.1+ postcss-load-config: 6.0.1([email protected])([email protected])+ resolve-from: 5.0.0+ rollup: 4.62.2+ source-map: 0.7.6+ sucrase: 3.35.1+ tinyexec: 0.3.2+ tinyglobby: 0.2.17+ tree-kill: 1.2.2+ optionalDependencies:+ '@swc/core': 1.15.46+ typescript: 7.0.2+ transitivePeerDependencies:+ - jiti+ - supports-color+ - tsx+ - yaml++ dependencies:+ esbuild: 0.28.1+ optionalDependencies:+ fsevents: 2.3.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ content-type: 2.0.0+ media-typer: 1.1.0+ mime-types: 3.0.2++ optionalDependencies:+ '@typescript/typescript-aix-ppc64': 7.0.2+ '@typescript/typescript-darwin-arm64': 7.0.2+ '@typescript/typescript-darwin-x64': 7.0.2+ '@typescript/typescript-freebsd-arm64': 7.0.2+ '@typescript/typescript-freebsd-x64': 7.0.2+ '@typescript/typescript-linux-arm': 7.0.2+ '@typescript/typescript-linux-arm64': 7.0.2+ '@typescript/typescript-linux-loong64': 7.0.2+ '@typescript/typescript-linux-mips64el': 7.0.2+ '@typescript/typescript-linux-ppc64': 7.0.2+ '@typescript/typescript-linux-riscv64': 7.0.2+ '@typescript/typescript-linux-s390x': 7.0.2+ '@typescript/typescript-linux-x64': 7.0.2+ '@typescript/typescript-netbsd-arm64': 7.0.2+ '@typescript/typescript-netbsd-x64': 7.0.2+ '@typescript/typescript-openbsd-arm64': 7.0.2+ '@typescript/typescript-openbsd-x64': 7.0.2+ '@typescript/typescript-sunos-x64': 7.0.2+ '@typescript/typescript-win32-arm64': 7.0.2+ '@typescript/typescript-win32-x64': 7.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ browserslist: 4.28.7+ escalade: 3.2.0+ picocolors: 1.1.1++ [email protected]: {}++ dependencies:+ '@jridgewell/trace-mapping': 0.3.31+ '@types/istanbul-lib-coverage': 2.0.6+ convert-source-map: 2.0.0++ [email protected]: {}++ dependencies:+ makeerror: 1.0.12++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tr46: 0.0.3+ webidl-conversions: 3.0.1++ dependencies:+ isexe: 2.0.0++ dependencies:+ logform: 2.7.0+ readable-stream: 3.6.2+ triple-beam: 1.4.1++ dependencies:+ '@colors/colors': 1.6.0+ '@dabh/diagnostics': 2.0.8+ async: 3.2.6+ is-stream: 2.0.1+ logform: 2.7.0+ one-time: 1.0.0+ readable-stream: 3.6.2+ safe-stable-stringify: 2.5.0+ stack-trace: 0.0.10+ triple-beam: 1.4.1+ winston-transport: 4.9.0++ dependencies:+ ansi-styles: 4.3.0+ string-width: 4.2.3+ strip-ansi: 6.0.1++ [email protected]: {}++ dependencies:+ imurmurhash: 0.1.4+ signal-exit: 3.0.7++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ cliui: 8.0.1+ escalade: 3.2.0+ get-caller-file: 2.0.5+ require-directory: 2.1.1+ string-width: 4.2.3+ y18n: 5.0.8+ yargs-parser: 21.1.1++ [email protected]: {}++ dependencies:+ zod: 3.25.76++ [email protected]: {}diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlnew file mode 100644index 000000000..d78483bb8--- /dev/null+++ b/pnpm-workspace.yaml@@ -0,0 +1,10 @@+packages:+ - packages/*++minimumReleaseAge: 0+trustLockfile: true+confirmModulesPurge: false+allowBuilds:+ '@swc/core': true+ esbuild: true+ protobufjs: truediff --git a/tsconfig.base.json b/tsconfig.base.jsonnew file mode 100644index 000000000..0f3c829f9--- /dev/null+++ b/tsconfig.base.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "noImplicitOverride": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noPropertyAccessFromIndexSignature": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "allowUnreachableCode": false,+ "allowUnusedLabels": false,+ "verbatimModuleSyntax": true,+ "isolatedModules": true,+ "noUncheckedSideEffectImports": true,+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "esModuleInterop": true,+ "resolveJsonModule": true,+ "lib": ["ESNext"],+ "skipLibCheck": true+ }+}