Merge remote-tracking branch 'origin/master' into code-mode-tools

# Conflicts:
#	examples/AGENTS.md
#	examples/README.md
#	package.json
#	packages/core/tools/tests/gen-tool-catalog.spec.ts
This commit is contained in:
Tianyi Cui
2026-07-09 22:58:58 +08:00
86 changed files with 5758 additions and 274 deletions

View File

@@ -21,6 +21,7 @@ A keyless smoke that spawns the example from a temp cwd must set `TSX_TSCONFIG_P
|---|---|---|
| `echo-agent` | `tests/echo.e2e.ts` — boots the real `cordis.yml`, drives the echo tool round-trip and the direct canned reply | **N/A — keyless by nature** (the `mock-echo` model has no real provider) |
| `coding-agent` | `tests/keyless-smoke.e2e.ts` — boots the full real tree (dummy key, no prompt → no model call), asserts banner + clean exit; `tests/code-mode-keyless-smoke.e2e.ts` — the same boot guard for the Code Mode overlay | `tests/{full-loop,coding-task,resume,compaction,todo-write}.e2e.ts` — real model + real bash + real todo_write, world-verified; `tests/code-mode.e2e.ts` — a real model composes two bash calls in one `run_code` program; collapsed header, dispatch events, written file all verified |
| `cordis-agent` | `tests/keyless-smoke.e2e.ts` — boots the real tree incl. `@deepseek-ai/dsh-tool-cordis` by package name; the tool logic is unit-tested in `packages/cordis/tool-cordis` | `tests/cordis-tools.e2e.ts` — real model mounts a listener (tagged line fires), builds+calls its own tool, composes two mounts via provide/inject |
| `acp-agent` | `pnpm run test:snapshot` — boots the real ACP subprocess and replays a recorded session keyless (incl. the hook matrix: a scenario per hook point × outcome for BOTH the Claude and Codex bridges — block, deny, ask, context-fold, force-continue); `tests/acp.e2e.ts` also asserts stdout purity without a key | `tests/acp.e2e.ts` — real ACP prompt, verifies a file the agent wrote; `tests/hooks.e2e.ts` — a real `PreToolUse` hook blocks bash, verifies the file is NOT written |
See [the root AGENTS.md](../AGENTS.md) for repo-wide conventions and [docs/architecture.md](../docs/architecture.md) for the design.

View File

@@ -21,6 +21,12 @@ Run with: `pnpm run demo:repl` (needs `DEEPSEEK_API_KEY` in the environment or a
Its `code-mode.cordis.yml` overlay flips the same tree to **Code Mode**: the worker-thread code runtime is loaded and the tool registry runs `mode: code`, so the model gets exactly one wire tool — `run_code` — plus a generated TypeScript SDK section, and composes the other tools by writing a program whose output it curates. Run with: `pnpm run demo:code-mode` (the REPL is the default UI; `acp` as the argument serves the acp-agent example's same-shaped overlay instead) — see the [Code Mode section](coding-agent/README.md#code-mode) for what to try.
## cordis-agent
The **self-referential** demo: the coding spine plus [`@deepseek-ai/dsh-tool-cordis`](../packages/cordis/tool-cordis), whose three tools (`cordis_inspect` / `cordis_mount` / `cordis_unmount`) let the agent inspect the live cordis runtime it runs inside, mount model-written plugins into it (an event listener, a brand-new tool for itself, or a service another mount injects), and dispose them again — all dynamic mounts grouped under one `cordis-dynamic` fiber subtree. The `ctx.fs`/`ctx.web` services ride along provider-only, as the capabilities those plugins build on.
Run with: `pnpm run demo:cordis` (needs `DEEPSEEK_API_KEY`). See [cordis-agent/README.md](cordis-agent/README.md) for the staged demo script and [the toolset RFC](../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md) for the design and sandbox caveats.
## acp-agent
An agent demo exposed as an **Agent Client Protocol (ACP)** server over JSON-RPC stdio, via the [`@deepseek-ai/dsh-acp-agent`](../packages/ui/acp-agent) app — drive it from Zed or any other ACP client. Also the home of the keyless snapshot tests.

View File

@@ -0,0 +1,33 @@
# cordis-agent
The self-referential harness demo: the coding-agent spine (DeepSeek V4 + local bash on the stdio chat app) plus [`@deepseek-ai/dsh-tool-cordis`](../../packages/cordis/tool-cordis/README.md), which hands the model three tools over the **live cordis runtime it is running inside** — inspect it, mount new plugins into it, and dispose them again. The `ctx.fs` and `ctx.web` services are mounted (provider-only, no model-facing file/web tools) so the plugins the agent writes have real capabilities to build on; Node built-ins are trapped in the sandbox and redirect to those services. The design (sandbox semantics, mount lifecycle, cross-mount composition, caveats) lives in [the toolset RFC](../../docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md).
## Run it
```sh
# repo root .env (gitignored) or exported env:
# DEEPSEEK_API_KEY=sk-…
# DEEPSEEK_BASE_URL=https://… # optional; defaults to the public API
pnpm run demo:cordis
```
The intended demo is staged — verify the listener link first, then let the agent extend itself:
```
> Mount a plugin that listens to the 'agent/status' event and logs every status change, then run `echo hi` with bash.
[tool call] cordis_mount({"code": "return { name: 'status-logger', apply(ctx) { ctx.on('agent/status', (agent, status) => console.log('status →', status)) } }"})
[tool result] mounted dyn-1 (plugin "status-logger", state: active)
[tool call] bash({"command": "echo hi"})
[cordis:dyn-1] status → … ← the mounted listener firing, live
> Now give yourself a reverse_text tool and use it on "harness".
[tool call] cordis_mount({"code": "return { name: 'reverse-text', inject: ['tools'], apply(ctx) { ctx.tools.register(harness.defineTool({ name: 'reverse_text', … })) } }"})
[tool call] reverse_text({"text": "harness"}) ← a tool the agent built for itself, one step earlier
> Unmount both.
[tool call] cordis_unmount({"id": "dyn-1"})
```
Ask for `cordis_inspect` with `what: "api"` or `what: "events"` to see the generated service/event reference the agent writes plugin code against, and try two cooperating mounts (`ctx.provide` in one, `inject` in the other) to watch cordis park and revive the consumer.
## End-to-end tests
`tests/keyless-smoke.e2e.ts` boots the real `cordis.yml` through the Loader with a dummy key and asserts the banner + clean EOF exit (the export-shape / real-load-path guard, now across the package-name resolution). `tests/cordis-tools.e2e.ts` is the with-key smoke: a real model mounts a status listener (asserting the tagged console line actually fires — the world, not the agent's claim), builds itself a `reverse_text` tool and uses it, and composes two mounts via provide/inject. The tool logic itself is unit-tested in [`packages/cordis/tool-cordis`](../../packages/cordis/tool-cordis) under the per-file 100% coverage gate.

View File

@@ -0,0 +1,49 @@
<!-- Generated by scripts/gen-doc-graphs.ts - do not edit by hand.
Run `pnpm run gen-doc-graphs` to regenerate. -->
# Cordis Agent App Composition
The self-referential demo puts @deepseek-ai/dsh-tool-cordis on the coding spine, letting the agent inspect its own runtime and mount/unmount plugins into it.
```mermaid
flowchart LR
cfg["examples/cordis-agent<br/>cordis.yml"]
plugin_cordis_hmr["hmr<br/>@cordisjs/plugin-hmr"]
cfg --> plugin_cordis_hmr
plugin_cordis_llm_deepseek["llm-deepseek<br/>@deepseek-ai/dsh-llm-deepseek"]
cfg --> plugin_cordis_llm_deepseek
plugin_cordis_bash["bash<br/>@deepseek-ai/dsh-bash-local"]
cfg --> plugin_cordis_bash
plugin_cordis_fs_local["fs-local<br/>@deepseek-ai/dsh-fs-local"]
cfg --> plugin_cordis_fs_local
plugin_cordis_web["web<br/>@deepseek-ai/dsh-web"]
cfg --> plugin_cordis_web
plugin_cordis_web_fetch_local["web-fetch-local<br/>@deepseek-ai/dsh-web-fetch-local"]
cfg --> plugin_cordis_web_fetch_local
plugin_cordis_stdio_agent["stdio-agent<br/>@deepseek-ai/dsh-stdio-agent"]
cfg --> plugin_cordis_stdio_agent
plugin_cordis_stdio_agent --> bundle_agent_core["@deepseek-ai/dsh-agent-core"]
plugin_cordis_stdio_agent --> bundle_jsonl["@deepseek-ai/dsh-session-persistence-jsonl"]
plugin_cordis_stdio_agent --> frontdoor_stdio["readline UI<br/>console logger<br/>pre-created main agent"]
bundle_agent_core --> spine_llm["ctx.llm"]
bundle_agent_core --> spine_sessions["ctx.sessions"]
bundle_agent_core --> spine_tools["ctx.tools + tool-bash"]
bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"]
plugin_cordis_tool_cordis["tool-cordis<br/>@deepseek-ai/dsh-tool-cordis"]
cfg --> plugin_cordis_tool_cordis
```
| Plugin id | Package / module |
| --- | --- |
| `hmr` | `@cordisjs/plugin-hmr` |
| `llm-deepseek` | `@deepseek-ai/dsh-llm-deepseek` |
| `bash` | `@deepseek-ai/dsh-bash-local` |
| `fs-local` | `@deepseek-ai/dsh-fs-local` |
| `web` | `@deepseek-ai/dsh-web` |
| `web-fetch-local` | `@deepseek-ai/dsh-web-fetch-local` |
| `stdio-agent` | `@deepseek-ai/dsh-stdio-agent` |
| `tool-cordis` | `@deepseek-ai/dsh-tool-cordis` |
Source config: [`examples/cordis-agent/cordis.yml`](cordis.yml).
Maintenance mode: hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source.

View File

@@ -0,0 +1,83 @@
# The cordis-agent plugin tree: the SELF-REFERENTIAL harness demo. Same spine
# as coding-agent (DeepSeek V4 + local bash on @deepseek-ai/dsh-stdio-agent),
# plus @deepseek-ai/dsh-tool-cordis, which gives the model three tools over the
# live cordis runtime it is running inside: cordis_inspect (services / plugin
# tree / tools / dynamic mounts / api / events), cordis_mount (evaluate
# model-written code in a vm sandbox and mount the returned plugin under the
# `cordis-dynamic` group), and cordis_unmount (dispose one mount by id).
# Requires DEEPSEEK_API_KEY (and optionally DEEPSEEK_BASE_URL) — the
# dsh-stdio-agent bin loads the gitignored repo-root .env first.
#
# Trust stance (docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md):
# the mounted code gets the REAL ctx — the
# vm sandbox only prevents accidental global pollution. Load the toolset as
# deliberately as you would grant a bash tool.
# Hot-module reload for the dev/demo loop (needs `node --expose-internals`).
- id: hmr
name: '@cordisjs/plugin-hmr'
config:
root: ['.']
# The DeepSeek adapter.
- id: llm-deepseek
name: '@deepseek-ai/dsh-llm-deepseek'
config:
apiKey: !!js process.env.DEEPSEEK_API_KEY
baseURL: !!js process.env.DEEPSEEK_BASE_URL
models:
- deepseek-v4-pro
- deepseek-v4-flash
# Local bash executor for agent-core's tool-bash schema — gives the agent an
# ordinary tool whose calls make the mounted listeners observably fire.
- id: bash
name: '@deepseek-ai/dsh-bash-local'
config:
timeoutMs: 60000
# Filesystem service for mounted plugins (ctx.fs) — the local provider only.
# The model-facing read/write/edit tools stay unmounted on purpose: this demo
# is about the agent building its own tools over the services.
- id: fs-local
name: '@deepseek-ai/dsh-fs-local'
config:
cwd: !!js process.cwd()
# Web service for mounted plugins (ctx.web): the seam plus the anonymous local
# fetch provider (keyless). No search provider is loaded — ctx.web search
# calls fail loud until a deployment adds one.
- id: web
name: '@deepseek-ai/dsh-web'
- id: web-fetch-local
name: '@deepseek-ai/dsh-web-fetch-local'
# The stdio chat app: the whole spine + front-door cluster, configured for the
# self-referential demo driving a pre-created `main` agent.
- id: stdio-agent
name: '@deepseek-ai/dsh-stdio-agent'
config:
model: deepseek-v4-flash
resumeSessionId: !!js process.env.RESUME_SESSION_ID
persistenceRoot: './.sessions'
welcome: 'cordis-agent ready. Ask it to inspect its runtime, mount a listener, or invent a tool for itself.'
persona: |
You are cordis-agent, a self-referential harness demo powered by the
{{model}} model.
You run INSIDE a cordis plugin runtime, and your cordis_* tools operate
on that live runtime: cordis_inspect to look around (its `api` and
`events` sections document the service methods, type shapes, and events
your plugin code can use), cordis_mount to add a plugin (an event
listener, a brand-new tool for yourself, or a service other mounts
inject), cordis_unmount to clean one up. In mounted code, NEVER use Node
built-ins (require/setTimeout/fetch) — use the runtime's cordis services
via inject: fs, web, bash, and timer (ctx.setTimeout). Prefer small
single-purpose plugins, prefer plain notification events over waterfall
events unless you intend to intercept, and unmount what you no longer
need. Report results briefly.
# The self-referential cordis toolset (loaded after the app so ctx.tools exists).
- id: tool-cordis
name: '@deepseek-ai/dsh-tool-cordis'

View File

@@ -0,0 +1,7 @@
{
"name": "cordis-agent-example",
"private": true,
"version": "0.0.1",
"type": "module",
"description": "Runnable demo: the self-referential harness — an agent that inspects and modifies its own cordis runtime"
}

View File

@@ -0,0 +1,156 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { Context } from 'cordis'
import { CallId } from '@deepseek-ai/dsh-llm'
import { AgentId } from '@deepseek-ai/dsh-agent'
import { cordisHarness, waitForIdle } from './harness.ts'
/**
* With-key smoke for the self-referential cordis tools: a REAL model drives
* cordis_mount/cordis_unmount against the live context the test observes.
* World-verified, not self-reported: the mounted listener must actually WRITE
* its tagged console line, the self-made tool must actually EXIST in the
* registry and appear as a real `tool/call`, the cross-mount service must
* actually LAND in the reflect store. Key-gated (see vitest.e2e.config.ts).
*/
let ctx: Context | undefined
afterEach(async () => {
vi.restoreAllMocks()
// Always dispose the harness, even on failure/retry/timeout: agent-loop
// teardown stops the loop, and disposing the tree unwinds every dynamic
// mount the model left behind.
await ctx?.fiber.dispose()
ctx = undefined
})
/** The tagged write-through lines (`[cordis:dyn-n] …`) captured by a console spy. */
function taggedCalls(log: { mock: { calls: unknown[][] } }): unknown[][] {
return log.mock.calls.filter(call => typeof call[0] === 'string' && /^\[cordis:dyn-\d+\]$/.test(call[0]))
}
/** Model-facing text of one tool result, concatenated. */
function resultText(result: { content: { type: string; text?: string }[] }): string {
return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
}
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('cordis tools: a real model modifies its own runtime', () => {
it('mounts a status listener whose tagged output actually fires, then unmounts it', async () => {
ctx = await cordisHarness()
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const agent = ctx.agentLoop.create(AgentId('cordis-e2e-listener'), { model: 'deepseek-v4-flash' })
agent.send([{
type: 'text',
text: 'Use cordis_mount to mount a plugin that listens to the \'agent/status\' '
+ 'cordis event and logs every change with console.log. Reply "mounted" once done.',
}])
await waitForIdle(ctx, agent)
// The WORLD check: the turn's own running→idle transition must have driven
// the mounted listener through the tagged sandbox console.
expect(taggedCalls(log).length).toBeGreaterThan(0)
const mid = await ctx.tools.execute({
callId: CallId('verify-mounted'), name: 'cordis_inspect', arguments: { what: 'dynamic' },
})
expect(resultText(mid)).toContain('dyn-')
agent.send([{ type: 'text', text: 'Now unmount the plugin you just mounted.' }])
await waitForIdle(ctx, agent)
const after = await ctx.tools.execute({
callId: CallId('verify-unmounted'), name: 'cordis_inspect', arguments: { what: 'dynamic' },
})
expect(resultText(after)).toContain('(no dynamic plugins mounted)')
}, 120_000)
it('builds itself a reverse_text tool and actually calls it', async () => {
ctx = await cordisHarness()
const agent = ctx.agentLoop.create(AgentId('cordis-e2e-selftool'), { model: 'deepseek-v4-flash' })
agent.send([{
type: 'text',
text: 'Give yourself a new tool: use cordis_mount to mount a plugin with '
+ 'inject ["tools"] that calls harness.registerTool(ctx, harness.defineTool({...})) '
+ 'to register a tool named reverse_text with one required string parameter '
+ '"text", returning the text reversed. Then CALL reverse_text with the '
+ 'exact text "harness" and report its exact output.',
}])
await waitForIdle(ctx, agent)
// World checks: the tool exists in the registry, was invoked as a real
// tool call, and its RESULT (the self-made execute actually running) is the
// reversed string. The model's prose is not asserted — the tool result is
// the world; the summary sentence is just the self-report.
expect(ctx.tools.get('reverse_text')).toBeDefined()
const events = [...agent.session.events]
const calls = events.filter(event => event.type === 'tool/call')
expect(calls.some(event => event.data.name === 'cordis_mount')).toBe(true)
const reverseCalls = calls.filter(event => event.data.name === 'reverse_text')
expect(reverseCalls.length).toBeGreaterThan(0)
const reverseResults = events
.filter(event => event.type === 'tool/result')
.filter(event => reverseCalls.some(call => call.data.callId === event.data.callId))
.flatMap(event => event.data.content.filter(block => block.type === 'text').map(block => block.text))
// On failure, surface what the model actually mounted and what the tool
// returned — an e2e failing at a distance is undebuggable without it.
const mountCode = calls
.filter(event => event.data.name === 'cordis_mount')
.map(event => event.data.arguments)
.join('\n---\n')
const trace = events.map((event) => {
switch (event.type) {
case 'tool/call': return `tool/call:${event.data.name}`
case 'tool/result': return `tool/result:${event.data.isError ? 'ERR:' + JSON.stringify(event.data.content).slice(0, 200) : 'ok'}`
case 'turn/end': return `turn/end:${JSON.stringify(event.data.reason)}`
default: return event.type
}
}).join('\n')
expect(
reverseResults.some(text => text.includes('ssenrah')),
`no reversed output in reverse_text results.\nresults: ${JSON.stringify(reverseResults)}\nmount code: ${mountCode}\ntrace:\n${trace}`,
).toBe(true)
}, 120_000)
it('composes two mounts through provide/inject, and unmounting the provider parks the consumer', async () => {
ctx = await cordisHarness()
const agent = ctx.agentLoop.create(AgentId('cordis-e2e-compose'), { model: 'deepseek-v4-flash' })
agent.send([{
type: 'text',
text: 'Mount TWO separate plugins with cordis_mount. First a provider: apply calls '
+ 'ctx.provide(\'shouter\', { shout: (s) => s.toUpperCase() }). Second a consumer with '
+ 'inject ["shouter", "tools"] that registers (via harness.registerTool + harness.defineTool) '
+ 'a tool named shout_text with one required string parameter "text" whose execute returns '
+ 'ctx.shouter.shout(args.text) as a text content block. Then CALL shout_text with "quiet" '
+ 'and report the exact output.',
}])
await waitForIdle(ctx, agent)
// World checks: the service is really in the store, the tool really ran.
expect(ctx.get('shouter')).toBeDefined()
expect(ctx.tools.get('shout_text')).toBeDefined()
const events = [...agent.session.events]
const shoutCalls = events
.filter(event => event.type === 'tool/call')
.filter(event => event.data.name === 'shout_text')
expect(shoutCalls.length).toBeGreaterThan(0)
const shoutResults = events
.filter(event => event.type === 'tool/result')
.filter(event => shoutCalls.some(call => call.data.callId === event.data.callId))
.flatMap(event => event.data.content.filter(block => block.type === 'text').map(block => block.text))
expect(shoutResults.some(text => text.includes('QUIET'))).toBe(true)
agent.send([{ type: 'text', text: 'Now unmount ONLY the provider plugin (the one that provided shouter).' }])
await waitForIdle(ctx, agent)
// The consumer must have been parked by cordis itself: service gone,
// dependent tool unregistered, dynamic table naming the missing service.
expect(ctx.get('shouter')).toBeUndefined()
expect(ctx.tools.get('shout_text')).toBeUndefined()
const after = await ctx.tools.execute({
callId: CallId('verify-parked'), name: 'cordis_inspect', arguments: { what: 'dynamic' },
})
expect(resultText(after)).toContain('waiting for: shouter')
}, 120_000)
})

View File

@@ -0,0 +1,46 @@
import { Context } from 'cordis'
import LlmService from '@deepseek-ai/dsh-llm'
import SessionStore from '@deepseek-ai/dsh-session'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
/**
* Shared harness for the cordis-agent e2e suite: the agent spine with the real
* DeepSeek adapter and the real `@deepseek-ai/dsh-tool-cordis` plugin, so a
* live model can mount plugins into the very context the test observes. Lives
* outside the *.e2e.ts pattern so importing it never re-registers another
* file's tests.
*/
const PERSONA = 'You are cordis-agent, a self-referential harness demo. '
+ 'Your cordis_* tools operate on the live cordis runtime you run inside: '
+ 'cordis_inspect to look around, cordis_mount to add a plugin, cordis_unmount '
+ 'to clean one up. Follow the tool descriptions exactly and report results briefly.'
export async function cordisHarness(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(LlmService)
await ctx.plugin(SessionStore)
await ctx.plugin(SystemPrompt, { persona: PERSONA })
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(LlmDeepSeek, { models: ['deepseek-v4-flash'] })
await ctx.plugin(ToolCordis)
return ctx
}
export function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
return new Promise((resolve) => {
const dispose = ctx.on('agent/status', (subject, status) => {
if (subject === agent && status === 'idle') {
dispose()
resolve()
}
})
})
}

View File

@@ -0,0 +1,94 @@
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
/**
* Keyless Loader-path smoke for examples/cordis-agent: boot the REAL example
* through the `@deepseek-ai/dsh-stdio-agent` bin against its `cordis.yml` —
* the cordis Loader, `unwrapExports`, the full plugin tree INCLUDING the
* `@deepseek-ai/dsh-tool-cordis` package resolved by name (whose `inject`
* would crash a collapsed export shape at load, see docs/postmortem/0001) —
* then close stdin with no prompt and assert the ready banner + a clean exit.
*
* No prompt is ever sent, so the model is NEVER called — that is why it runs
* without a real key: `llm-deepseek`'s apply() only requires a key to be
* PRESENT, and the absence of any prompt guarantees no network call. The
* with-key product proof lives in cordis-tools.e2e.ts.
*/
// The dsh-stdio-agent bin (the demo:cordis entry) and this example's cordis.yml.
// The bin resolves its config-path arg from CWD; the test spawns from a temp
// cwd, so we pass the example config's ABSOLUTE path.
const binScript = fileURLToPath(new URL('../../../packages/ui/stdio-agent/src/bin.ts', import.meta.url))
const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url))
const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
// Dev/test run UNBUILT: resolve `@deepseek-ai/dsh-*` through the root tsconfig
// `paths` map; tsx searches UP from cwd, and we spawn from a temp dir outside
// the repo, so point it at the repo tsconfig (root is three levels up).
const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
let child: ChildProcessWithoutNullStreams | undefined
let workdir: string | undefined
afterEach(async () => {
if (child !== undefined && child.exitCode === null) child.kill('SIGKILL')
child = undefined
if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
workdir = undefined
})
async function bootAndEof(): Promise<{ stdout: string; code: number }> {
workdir = await mkdtemp(join(tmpdir(), 'cordis-smoke-'))
const cwd = workdir
return new Promise((resolve, reject) => {
const proc = spawn(
process.execPath,
// --expose-internals: cordis.yml loads the HMR plugin (mirrors demo:cordis).
['--expose-internals', '--import', tsxLoader, binScript, configPath],
{
cwd,
env: {
...process.env,
TSX_TSCONFIG_PATH: repoTsconfig,
// A dummy key so llm-deepseek's apply() (key-PRESENT check only) boots.
// No prompt is sent, so the adapter never streams — no network call.
DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
},
stdio: ['pipe', 'pipe', 'pipe'],
},
)
child = proc
let stdout = ''
let stderr = ''
proc.stdout.setEncoding('utf8')
proc.stdout.on('data', (chunk: string) => { stdout += chunk })
proc.stderr.setEncoding('utf8')
proc.stderr.on('data', (chunk: string) => { stderr += chunk })
const timer = setTimeout(() => {
proc.kill('SIGKILL')
reject(new Error(`cordis-agent did not exit within 10s. stdout:\n${stdout}\nstderr:\n${stderr}`))
}, 10_000)
proc.on('exit', (code) => {
clearTimeout(timer)
if (code === 0) resolve({ stdout, code })
else reject(new Error(`cordis-agent exited ${code}. stderr:\n${stderr}`))
})
proc.on('error', (err) => { clearTimeout(timer); reject(err) })
// No prompt — just EOF, so the stdio UI exits without ever running a turn.
proc.stdin.end()
})
}
describe('cordis-agent keyless smoke (real cordis.yml via the Loader)', () => {
it('boots the full plugin tree incl. tool-cordis, prints its banner, and exits cleanly on EOF', async () => {
const { stdout, code } = await bootAndEof()
expect(code).toBe(0)
expect(stdout).toContain('cordis-agent ready.')
}, 15_000)
})