Merge current master and refresh the CI merge baseline

This commit is contained in:
creatixchu committed 2026-11-19 16:09:10 +08:00
commit 6d652b3c77
19 files changed
+629 -16

No files matched your search

+10 -1
View File
@@ -3347,7 +3347,7 @@ export interface Config {
- `inject`: `agents` · `workingDirectory`
- `refs`: `Readable` (`node:stream`) · `Writable` (`node:stream`)
- `source`: [`packages/sdk/server/src/index.ts:24`](../packages/sdk/server/src/index.ts)
- `source`: [`packages/sdk/server/src/index.ts:25`](../packages/sdk/server/src/index.ts)
```ts config-catalog
/** JSON-RPC deployment config plus runtime-only test hooks. */
@@ -3360,6 +3360,15 @@ export interface JsonRpcConfig {
output?: Writable
/** Process-exit override; production uses `process.exit`. */
exit?: (code: number) => void
/** Process-event override; production uses `process`. */
processEvents?: RuntimeProcessEvents
}
/** The slice of `process` this module observes; `node:events` emitters satisfy it. */
export interface RuntimeProcessEvents {
listenerCount(event: string): number
prependListener(event: string, listener: (...args: unknown[]) => void): unknown
off(event: string, listener: (...args: unknown[]) => void): unknown
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-sdk-jsonrpc-server -->
+10 -1
View File
@@ -3349,7 +3349,7 @@ export interface Config {
- `inject`: `agents` · `workingDirectory`
- `refs`: `Readable` (`node:stream`) · `Writable` (`node:stream`)
- `source`: [`packages/sdk/server/src/index.ts:24`](../packages/sdk/server/src/index.ts)
- `source`: [`packages/sdk/server/src/index.ts:25`](../packages/sdk/server/src/index.ts)
```ts config-catalog
/** JSON-RPC deployment config plus runtime-only test hooks. */
@@ -3362,6 +3362,15 @@ export interface JsonRpcConfig {
output?: Writable
/** Process-exit override; production uses `process.exit`. */
exit?: (code: number) => void
/** Process-event override; production uses `process`. */
processEvents?: RuntimeProcessEvents
}
/** The slice of `process` this module observes; `node:events` emitters satisfy it. */
export interface RuntimeProcessEvents {
listenerCount(event: string): number
prependListener(event: string, listener: (...args: unknown[]) => void): unknown
off(event: string, listener: (...args: unknown[]) => void): unknown
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-sdk-jsonrpc-server -->
+1 -1
View File
@@ -123,7 +123,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/service` | - | `client-ui-forge`, `gateway` |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `server`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `locale/change` | `locale` (`emit`) | `locale` |
| `slots/changed` | `ui-renderer` (`emit`) | - |
+1 -1
View File
@@ -125,7 +125,7 @@
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), [`mcp-manager`](../packages/mcp/mcp-manager), `modules` |
| `internal/service` | - | `client-ui-forge`, `gateway` |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `translator`, [`web`](../packages/web/web) |
| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `modules`, `server`, `translator`, [`web`](../packages/web/web) |
| `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`mcp-manager`](../packages/mcp/mcp-manager), `modules`, [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text`, [`timeline`](../packages/experimental/timeline) |
| `locale/change` | `locale` (`emit`) | `locale` |
| `slots/changed` | `ui-renderer` (`emit`) | - |
+7 -4
View File
@@ -33,8 +33,11 @@
en: 5100c311c8476f93
zh: 60d4bc3165731246
/deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package/shutdown-and-exit:
en: 08c3858f53090f39
zh: dfae960e11515b06
en: bce68765edfb2234
zh: f6ebd47a067b5d90
/deepseek-ai-dsh-sdk-jsonrpc-server/use-this-package/requests-for-a-disposed-agent:
en: 88e3905a28a5bf59
zh: 1a204018ca53d5fb
/deepseek-ai-dsh-sdk-jsonrpc-server/understand-the-implementation:
en: eca39e7027d67d8f
zh: dd3f494276322857
@@ -42,8 +45,8 @@
en: fb2166e245c705f5
zh: df0b1583fe6520f5
/deepseek-ai-dsh-sdk-jsonrpc-server/understand-the-implementation/source-map:
en: 783bd2b6628c0680
zh: ca5b6b730893ddec
en: ac30da58386e08c3
zh: d33b972f0d341c5e
/deepseek-ai-dsh-sdk-jsonrpc-server/understand-the-implementation/request-flow:
en: 2658804b2f90b135
zh: 085aa00c8f0bbbcd
+14
View File
@@ -90,6 +90,19 @@ An initialized client advertising `capabilities.userQuestions` handles questions
The plugin answers `shutdown`, flushes the response, disposes the root context so SDK-owned agents, subscriptions, and persistence reach quiescence, then exits 0. EOF and signal exits belong to the app bin, which also disposes the root context. Unloading only this plugin stops serving without exiting the process.
### Requests for a disposed agent
A request for a session whose agent has left the agent registry fails with `session agent was disposed outside the server: <sessionId>; <context>`. The context states what the server observed:
| Context | Meaning |
|---|---|
| `the runtime is shutting down; last process event before teardown: <event> at <time>` | The whole runtime is being disposed. `<event>` is `SIGTERM`, `SIGINT`, `uncaught exception: <first line>`, `unhandled rejection: <first line>`, or `stdin closed`. It is the last such event seen before disposal began, not an established cause. |
| `the runtime is shutting down; no process event was observed before teardown` | The whole runtime is being disposed and none of those events preceded it. |
| `the SDK server is shutting down` | This plugin is unloading or answering `shutdown`. |
| `the agent loop was unloaded at <time> while the runtime keeps running; first plugin unloading at that time: "<name>"` | Only the agent loop went away; the process stays up. `<name>` is the plugin whose unload began first among those in progress, usually the agent loop or a service it requires; when unloads overlap it can be an unrelated plugin. The time and plugin are omitted when the server did not observe the removal. |
A signal or an unhandled rejection is recorded only when another listener already handles that event, so mounting this plugin never changes whether the process terminates. Failure text is the first line of the message, at most 200 characters, or `<unprintable>` for a value without a string form; the full report stays on stderr.
-----
<a id="understand-the-implementation"></a>
@@ -109,6 +122,7 @@ The plugin is a thin presentation adapter: [`HarnessSdkJsonRpcServer`](src/serve
| File | Role |
|---|---|
| [`src/index.ts`](src/index.ts) | Plugin entry: `Config` schema, stdio wiring, request dispatch, shared shutdown/exit task |
| [`src/process-events.ts`](src/process-events.ts) | Record of the last signal, fatal failure, or input end seen before runtime teardown |
| [`src/user-questions.ts`](src/user-questions.ts) | Native question adapter: host forwarding, answer validation, cancellation |
| [`src/server.ts`](src/server.ts) | `HarnessSdkJsonRpcServer`: protocol methods, per-session agent creation, lifecycle subscriptions, teardown |
+14
View File
@@ -90,6 +90,19 @@ Stdout 只承载 JSON-RPC 帧,客户端可以逐字节解析;诊断信息应
插件应答 `shutdown`,刷新响应并 dispose 根上下文,使 SDK 持有的 agent、订阅与持久化达到完全停稳,然后以 0 退出。EOF 与信号退出归 app bin 负责,后者也会 dispose 根上下文。仅卸载此插件会停止服务,但不会退出进程。
### 针对已销毁 agent 的请求
当会话的 agent 已离开 agent 注册表时,针对该会话的请求以 `session agent was disposed outside the server: <sessionId>; <context>` 失败。其中 context 说明服务端观察到的情况:
| Context | 含义 |
|---|---|
| `the runtime is shutting down; last process event before teardown: <event> at <time>` | 整个运行时正在被 dispose。`<event>` 为 `SIGTERM`、`SIGINT`、`uncaught exception: <首行>`、`unhandled rejection: <首行>` 或 `stdin closed`。它是 dispose 开始前最后观察到的此类事件,不是已确认的原因。 |
| `the runtime is shutting down; no process event was observed before teardown` | 整个运行时正在被 dispose,且此前没有出现上述事件。 |
| `the SDK server is shutting down` | 此插件正在卸载,或正在应答 `shutdown`。 |
| `the agent loop was unloaded at <time> while the runtime keeps running; first plugin unloading at that time: "<name>"` | 只有 agent loop 被卸载,进程仍在运行。`<name>` 是当时正在进行的卸载中最先开始的插件,通常是 agent loop 或它依赖的某个服务;多个卸载重叠时可能是无关插件。服务端未观察到移除过程时,省略时间和插件名。 |
只有当某个信号或未处理的 Promise 拒绝已有其他监听者处理时,才会记录该事件,因此挂载此插件不会改变进程是否终止。失败文本取消息首行,最多 200 个字符;没有字符串形式的值记为 `<unprintable>`;完整报告仍在 stderr。
-----
<a id="understand-the-implementation"></a>
@@ -109,6 +122,7 @@ Stdout 只承载 JSON-RPC 帧,客户端可以逐字节解析;诊断信息应
| 文件 | 职责 |
|---|---|
| [`src/index.ts`](src/index.ts) | 插件入口:`Config` schema、stdio 接线、请求分发、共享关闭与退出任务 |
| [`src/process-events.ts`](src/process-events.ts) | 记录运行时拆除前最后出现的信号、致命失败或输入结束 |
| [`src/user-questions.ts`](src/user-questions.ts) | 原生问答适配器:宿主转发、答案校验、取消 |
| [`src/server.ts`](src/server.ts) | `HarnessSdkJsonRpcServer`:协议方法、逐会话 agent 创建、生命周期订阅、清理 |
+6
View File
@@ -13,6 +13,7 @@ import { Context } from '@deepseek-ai/cordis'
import type { Readable, Writable } from 'node:stream'
import Schema from '@deepseek-ai/schemastery'
import { JsonRpcLineTransport } from '@deepseek-ai/dsh-sdk-protocol'
import { observeRuntime, type RuntimeProcessEvents } from './process-events.ts'
import { HarnessSdkJsonRpcServer } from './server.ts'
export * from './server.ts'
@@ -30,6 +31,8 @@ export interface JsonRpcConfig {
output?: Writable
/** Process-exit override; production uses `process.exit`. */
exit?: (code: number) => void
/** Process-event override; production uses `process`. */
processEvents?: RuntimeProcessEvents
}
export const Config: Schema<JsonRpcConfig> = Schema.object({
@@ -54,10 +57,13 @@ export function apply(ctx: Context, config: JsonRpcConfig): void {
const output = config.output ?? process.stdout
/* v8 ignore next -- production exit wiring; tests always inject the runtime hooks */
const exit = config.exit ?? ((code: number): void => { process.exit(code) })
/* v8 ignore next -- production process wiring; tests always inject the runtime hooks */
const processEvents = config.processEvents ?? process
const transport = new JsonRpcLineTransport(input, output)
const server = new HarnessSdkJsonRpcServer(ctx, transport, {
maxTokensAsSuccess: resolvedConfig.maxTokensAsSuccess,
runtime: observeRuntime(ctx, rootFiber, processEvents, input),
})
// Compositions can order Schedule after its activation handler is installed.
// Like the app startup marker, this carries readiness, not another control API.
+82
View File
@@ -0,0 +1,82 @@
/**
* Records the last process event seen before runtime teardown, for the SDK
* server's liveness failures. The launcher owns signal and failure handling;
* this module only observes.
*
* @module @deepseek-ai/dsh-sdk-jsonrpc-server/process-events
*/
import { FiberState, type Context, type Fiber } from '@deepseek-ai/cordis'
import type { Readable } from 'node:stream'
import type { RuntimeObservation, RuntimeProcessEvent } from './server.ts'
/** The slice of `process` this module observes; `node:events` emitters satisfy it. */
export interface RuntimeProcessEvents {
listenerCount(event: string): number
prependListener(event: string, listener: (...args: unknown[]) => void): unknown
off(event: string, listener: (...args: unknown[]) => void): unknown
}
/** Events whose first listener replaces a Node default, so observation joins only an existing owner. */
const OWNED_PROCESS_EVENTS = ['SIGTERM', 'SIGINT', 'unhandledRejection'] as const
/** Longest failure text copied into an SDK error message. */
const FAILURE_TEXT_LIMIT = 200
/** Never throws: a listener that threw here would end the dispatch before the listener that owns the event runs. */
function failureText(reason: unknown): string {
try {
const text = reason instanceof Error ? reason.message : String(reason)
return text.replace(/\n[\s\S]*$/, '').slice(0, FAILURE_TEXT_LIMIT)
} catch (_unprintable: unknown) {
// The value has no string form, such as an object without a prototype or an Error whose message is not a string.
return '<unprintable>'
}
}
/**
* Observe runtime disposal, termination signals, fatal failures, and input end until `ctx` is disposed.
* A signal or unhandled rejection is observed only when another listener already
* handles it, because the first listener for those events disables Node's default
* termination. Recording stops once runtime disposal begins, so an event caused by
* the teardown does not replace the one before it.
* @param ctx - context that owns the listeners.
* @param runtimeFiber - fiber whose disposal ends the whole runtime.
* @param processEvents - process event source.
* @param input - protocol input whose end is recorded as `stdin closed`.
* @returns whether runtime disposal is in progress, and the last event recorded before it began.
*/
export function observeRuntime(
ctx: Context,
runtimeFiber: Fiber,
processEvents: RuntimeProcessEvents,
input: Readable,
): RuntimeObservation {
let last: RuntimeProcessEvent | undefined
const unloading = (): boolean =>
runtimeFiber.state === FiberState.UNLOADING || runtimeFiber.state === FiberState.DISPOSED
const observe = (description: string): void => {
if (!unloading()) last = { description, at: new Date() }
}
ctx.effect(() => {
const listeners: [event: string, listener: (...args: unknown[]) => void][] = [
// The monitor event never replaces Node's default handling of an uncaught exception.
['uncaughtExceptionMonitor', (error) => { observe(`uncaught exception: ${failureText(error)}`) }],
]
for (const event of OWNED_PROCESS_EVENTS) {
if (processEvents.listenerCount(event) === 0) continue
listeners.push([event, event === 'unhandledRejection'
? (reason) => { observe(`unhandled rejection: ${failureText(reason)}`) }
: () => { observe(event) }])
}
// Prepended so the record exists before the owner's listener starts teardown.
for (const [event, listener] of listeners) processEvents.prependListener(event, listener)
const onInputEnd = (): void => { observe('stdin closed') }
input.once('end', onInputEnd)
return () => {
for (const [event, listener] of listeners) processEvents.off(event, listener)
input.off('end', onInputEnd)
}
}, 'jsonrpc.processEvents')
return { unloading, lastProcessEvent: () => last }
}
+56 -4
View File
@@ -6,7 +6,7 @@
*/
import type {} from '@deepseek-ai/dsh-fs'
import type { Context } from '@deepseek-ai/cordis'
import { FiberState, type Context, type Fiber } from '@deepseek-ai/cordis'
import { AsyncLocalStorage } from 'node:async_hooks'
import { resolve } from 'node:path'
import { QueryActivity } from './query-activity.ts'
@@ -59,6 +59,23 @@ interface SessionRecord {
handle: AgentHandle
/** Latest live failure not superseded by a subsequently committed terminal. */
failure: { readonly error: unknown; readonly atOffset: SessionLogOffset } | undefined
/** When the registry dropped this Agent while the server still held its handle, and the first plugin unloading at that time. */
disposal: { readonly at: Date; readonly origin: string | undefined } | undefined
}
/** A process event observed by the hosting plugin entry. */
export interface RuntimeProcessEvent {
/** Event name and, for a failure, the first line of its message. */
readonly description: string
readonly at: Date
}
/** What the hosting plugin entry observes about the runtime that surrounds the server. */
export interface RuntimeObservation {
/** Whether disposal of the whole runtime is in progress, which ends every plugin in the process. */
unloading(): boolean
/** The last process event recorded before that disposal began; an observation, not an established cause. */
lastProcessEvent(): RuntimeProcessEvent | undefined
}
function encodedImage(block: SessionPromptParams['contentBlocks'][number]): block is SdkEncodedImageBlock {
@@ -105,6 +122,8 @@ function promptTimeZone(requested: string | undefined): string | undefined {
export interface HarnessSdkJsonRpcServerOptions {
/** Report max-token termination as an accepted result instead of an infrastructure error. */
maxTokensAsSuccess?: boolean
/** Runtime state that a liveness failure reports; without it the failure makes no statement about the runtime. */
runtime?: RuntimeObservation
}
function successStatus(reason: string, options: HarnessSdkJsonRpcServerOptions): 'ok' | 'error' {
@@ -134,6 +153,9 @@ export class HarnessSdkJsonRpcServer {
private readonly disposers: (() => void)[] = []
private shutdownTask: Promise<Record<string, never>> | undefined
private shuttingDown = false
private readonly unloading = new Set<Fiber>()
/** Name of the plugin whose unload began while no other was in progress; overlapping unloads can make it an unrelated plugin. */
private unloadOrigin: string | undefined
private initialized = false
private approvalRequests = false
private readonly lifetime = new AbortController()
@@ -207,6 +229,19 @@ export class HarnessSdkJsonRpcServer {
if (record?.handle.agent !== agent) return
record.failure = { error, atOffset: agent.session.seq }
}))
this.disposers.push(ctx.on('agent/disposed', ({ agent }) => {
const record = this.sessions.get(agent.session.id)
if (record?.handle.agent === agent) record.disposal = { at: new Date(), origin: this.unloadOrigin }
}))
this.disposers.push(ctx.on('internal/status', (fiber, previous) => {
if (fiber.state === FiberState.UNLOADING) {
if (this.unloading.size === 0) this.unloadOrigin = fiber.name
this.unloading.add(fiber)
} else if (previous === FiberState.UNLOADING) {
this.unloading.delete(fiber)
if (this.unloading.size === 0) this.unloadOrigin = undefined
}
}))
this.disposers.push(ctx.on('agent/status', ({ agent, status }) => {
this.transport.notify('session.status', { sessionId: String(agent.session.id), status })
}))
@@ -459,10 +494,27 @@ export class HarnessSdkJsonRpcServer {
return this.sessions.get(root.session.id)?.handle.agent === root
}
/** Reject a retained record whose Agent left the registry, naming what the server observed. */
private assertLiveAgent(rec: SessionRecord, sessionId: string): void {
if (this.ctx.agents.get(rec.handle.agent.id) !== rec.handle.agent) {
throw new Error(`session agent was disposed outside the server: ${sessionId}`)
// Root disposal also unloads the registry; reading it as optional keeps one failure for both stages.
if (this.ctx.get('agents')?.get(rec.handle.agent.id) === rec.handle.agent) return
throw new Error(`session agent was disposed outside the server: ${sessionId}; ${this.disposalContext(rec)}`)
}
private disposalContext(rec: SessionRecord): string {
const runtime = this.options.runtime
if (runtime?.unloading()) {
const event = runtime.lastProcessEvent()
return event === undefined
? 'the runtime is shutting down; no process event was observed before teardown'
: `the runtime is shutting down; last process event before teardown: ${event.description} at ${event.at.toISOString()}`
}
if (this.shuttingDown) return 'the SDK server is shutting down'
// Runtime disposal removes this server's listeners before the Agent leaves, so a record exists only here.
const at = rec.disposal === undefined ? '' : ` at ${rec.disposal.at.toISOString()}`
const running = runtime === undefined ? '' : ' while the runtime keeps running'
const origin = rec.disposal?.origin ? `; first plugin unloading at that time: "${rec.disposal.origin}"` : ''
return `the agent loop was unloaded${at}${running}${origin}`
}
/**
@@ -677,7 +729,7 @@ export class HarnessSdkJsonRpcServer {
meta: { cwd },
agentOptions,
}))
const rec: SessionRecord = { handle, failure: undefined }
const rec: SessionRecord = { handle, failure: undefined, disposal: undefined }
this.sessions.set(sessionId, rec)
return rec
}
@@ -0,0 +1,117 @@
import { mountWorkingDirectoryFixture } from '../../../subagent/subagent/tests/working-directory-fixture.ts'
/** A liveness failure states whether the runtime or only the agent loop went away, and what the server observed. */
import { Context, FiberState } from '@deepseek-ai/cordis'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { brandString } from '@deepseek-ai/dsh-brand'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import SubagentRuntime, { NO_START_CAPABILITIES } from '@deepseek-ai/dsh-subagent'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
import { HarnessSdkJsonRpcServer, type RuntimeProcessEvent } from '../src/server.ts'
const TIME = String.raw`\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z`
/**
* Real agent loop with one idle `main` Session; the system-prompt fiber is a dependency the loop requires.
* The server observes the test's own root context as its runtime.
*/
async function setup(lastProcessEvent: () => RuntimeProcessEvent | undefined = () => undefined) {
const root = await mkdtemp(join(tmpdir(), 'dsh-sdk-disposal-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
const systemPrompt = await ctx.plugin(SystemPrompt, {})
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(JsonlSessionPersistence, { root })
ctx.llm.registerAdapter(['mock'], new MockAdapter(Array.from({ length: 5 }, () => textResponse('answer'))))
const server = new HarnessSdkJsonRpcServer(ctx, {
request: () => Promise.reject(new Error('the server must not request the client')),
notify: () => {},
}, {
runtime: {
unloading: () => ctx.fiber.state === FiberState.UNLOADING || ctx.fiber.state === FiberState.DISPOSED,
lastProcessEvent,
},
})
await server.initialize({ cwd: root, provider: 'mock', model: 'mock' })
await server.prompt({ sessionId: 'main', contentBlocks: [{ type: 'text', text: 'first' }] })
const main = ctx.agents.get(brandString<SessionId>('main'))!
await main.whenIdle()
return { ctx, server, main, systemPrompt }
}
describe('SDK liveness failure context', () => {
it('names the first plugin unloading when the agent loop goes away while the runtime keeps running', async () => {
const { ctx, server, systemPrompt } = await setup()
await systemPrompt.dispose()
await expect(server.prompt({ sessionId: 'main', contentBlocks: [{ type: 'text', text: 'again' }] })).rejects.toThrow(new RegExp(
`^session agent was disposed outside the server: main; the agent loop was unloaded at ${TIME} `
+ 'while the runtime keeps running; first plugin unloading at that time: "SystemPrompt"$',
))
await server.shutdown()
await ctx.fiber.dispose()
})
it.each([
{
label: 'the last process event observed before teardown',
lastProcessEvent: () => ({ description: 'SIGTERM', at: new Date('2026-01-02T03:04:05.006Z') }),
context: 'last process event before teardown: SIGTERM at 2026-01-02T03:04:05.006Z',
},
{ label: 'that no process event was observed', lastProcessEvent: undefined, context: 'no process event was observed before teardown' },
])('reports $label when the runtime shuts down under a pending wait', async ({ lastProcessEvent, context }) => {
const { ctx, server, main } = await setup(lastProcessEvent)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
ctx.on('agent/pre-step', async ({ agent }, next) => {
if (agent.session.header.parentSession !== undefined) {
entered.resolve(undefined)
await release.promise
}
return next()
})
ctx.subagents.registerProvider({
name: 'local-test', capabilities: NO_START_CAPABILITIES, inheritsParentContext: false,
prepareContinuable: () => Promise.resolve({}),
})
await ctx.subagents.startActivation({
provider: 'local-test', label: 'running child', delivery: 'caller', signal: new AbortController().signal,
parent: main, prompt: [{ type: 'text', text: 'work' }],
})
await entered.promise
// The plugin entry shuts the server down from an effect of the same root.
ctx.effect(() => () => server.shutdown(), 'test jsonrpc.serve')
const waiting = server.wait({ sessionId: 'main' })
const outcome = expect(waiting).rejects.toThrow(
`session agent was disposed outside the server: main; the runtime is shutting down; ${context}`,
)
const agents = ctx.agents
const disposing = ctx.fiber.dispose()
// The wait is still joined to the child, so it reads the registry only after the root Agent has left.
await vi.waitFor(() => { expect(agents.get(main.id)).toBeUndefined() })
release.resolve(undefined)
await outcome
await disposing
})
})
@@ -1,5 +1,6 @@
import { MESSAGES_RESPONSE } from './messages-response.ts'
import { mountWorkingDirectoryFixture } from '../../../subagent/subagent/tests/working-directory-fixture.ts'
import { EventEmitter } from 'node:events'
import { createServer } from 'node:http'
import type { IncomingMessage, Server, ServerResponse } from 'node:http'
import { mkdtemp, rm } from 'node:fs/promises'
@@ -11,9 +12,12 @@ import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
import { brandString } from '@deepseek-ai/dsh-brand'
import { LlmAdapter } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
import type { SessionId } from '@deepseek-ai/dsh-session'
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import SubagentRuntime, { NO_START_CAPABILITIES } from '@deepseek-ai/dsh-subagent'
import * as jsonrpc from '../src/index.ts'
/**
@@ -35,6 +39,8 @@ interface ApplyHarness {
fiber: Awaited<ReturnType<Context['plugin']>>
/** Frames, write completions, and exits in observation order. */
events: WireEvent[]
/** Stands in for `process`; SIGTERM has an owner, as under the launcher. */
processEvents: EventEmitter
outputErrors: Error[]
send(frame: Record<string, unknown>): void
sendRaw(text: string): void
@@ -121,10 +127,13 @@ async function mountPlugin(
const exit = (code: number): void => { events.push({ kind: 'exit', code }) }
ctx.effect(() => () => { events.push({ kind: 'root-disposed' }) }, 'jsonrpc test root-disposal witness')
const processEvents = new EventEmitter()
processEvents.on('SIGTERM', () => {})
const fiber = await ctx.plugin(jsonrpc, {
input,
output,
exit,
processEvents,
})
const frames = (): Record<string, unknown>[] =>
@@ -133,6 +142,7 @@ async function mountPlugin(
ctx,
fiber,
events,
processEvents,
outputErrors,
send: (frame) => { input.write(`${JSON.stringify(frame)}\n`) },
sendRaw: (text) => { input.write(text) },
@@ -287,6 +297,68 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it('reports the signal that preceded runtime shutdown to a pending session/wait', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-signal-'))
const llmServer = await mockCompletionServer()
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
vi.stubEnv('DEEPSEEK_BASE_URL', llmServer.url)
const harness = await mountPlugin(storageDir, {
beforeServer: async (ctx) => { await ctx.plugin(SubagentRuntime) },
})
const release = Promise.withResolvers<undefined>()
try {
const { ctx } = harness
harness.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { cwd: storageDir, provider: 'deepseek-official', model: 'dsagent-model' } })
await harness.waitForFrame(frame => frame.id === 1, 'initialize response')
harness.send({ jsonrpc: '2.0', id: 2, method: 'session/prompt', params: { sessionId: 'main', contentBlocks: [{ type: 'text', text: 'first' }] } })
await harness.waitForFrame(
frame => frame.method === 'session.status'
&& (frame.params as { status?: string } | undefined)?.status === 'idle',
'idle session status',
)
const main = ctx.agents.get(brandString<SessionId>('main'))!
const entered = Promise.withResolvers<undefined>()
ctx.on('agent/pre-step', async ({ agent }, next) => {
if (agent.session.header.parentSession !== undefined) {
entered.resolve(undefined)
await release.promise
}
return next()
})
ctx.subagents.registerProvider({
name: 'local-test', capabilities: NO_START_CAPABILITIES, inheritsParentContext: false,
prepareContinuable: () => Promise.resolve({}),
})
await ctx.subagents.startActivation({
provider: 'local-test', label: 'running child', delivery: 'caller', signal: new AbortController().signal,
parent: main, prompt: [{ type: 'text', text: 'work' }],
})
await entered.promise
harness.send({ jsonrpc: '2.0', id: 3, method: 'session/wait', params: { sessionId: 'main' } })
// Stream delivery completes before a timer runs, so the wait is joined to the child here.
await settle()
harness.processEvents.emit('SIGTERM')
const agents = ctx.agents
const disposing = harness.dispose()
await vi.waitFor(() => { expect(agents.get(main.id)).toBeUndefined() })
release.resolve(undefined)
const response = await harness.waitForFrame(frame => frame.id === 3, 'wait response')
const error = response.error as { code: number; message: string }
expect(error.code).toBe(-32603)
expect(error.message).toMatch(new RegExp(
'^session agent was disposed outside the server: main; the runtime is shutting down; '
+ String.raw`last process event before teardown: SIGTERM at \d{4}-`,
))
await disposing
} finally {
release.resolve(undefined)
await harness.dispose()
await rm(storageDir, { recursive: true, force: true })
}
})
it('answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-shutdown-'))
const harness = await mountPlugin(storageDir, { writeDelayMs: 10 })
@@ -0,0 +1,98 @@
/** The process-event record keeps the event before teardown and leaves ownership of each event unchanged. */
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import { describe, expect, it } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { observeRuntime } from '../src/process-events.ts'
function setup() {
const ctx = new Context()
const events = new EventEmitter()
const input = new PassThrough()
// The launcher owns these two; nothing owns SIGINT in this composition.
const seenByOwner: (string | undefined)[] = []
const owner = (): void => { seenByOwner.push(last()?.description) }
events.on('SIGTERM', owner)
events.on('unhandledRejection', owner)
const runtime = observeRuntime(ctx, ctx.fiber, events, input)
const last = () => runtime.lastProcessEvent()
return { ctx, events, input, runtime, last, seenByOwner }
}
describe('SDK process-event record', () => {
it('records a signal before the listener that owns it runs', async () => {
const { ctx, events, last, seenByOwner } = setup()
expect(last()).toBeUndefined()
const before = Date.now()
events.emit('SIGTERM')
expect(seenByOwner).toEqual(['SIGTERM'])
expect(last()?.description).toBe('SIGTERM')
expect(last()?.at.getTime()).toBeGreaterThanOrEqual(before)
await ctx.fiber.dispose()
})
it('leaves an event without an owner to the Node default', async () => {
const { ctx, events, last } = setup()
expect(events.listenerCount('SIGINT')).toBe(0)
events.emit('SIGINT')
expect(last()).toBeUndefined()
await ctx.fiber.dispose()
})
it('records the first line of a failure, bounded to 200 characters', async () => {
const { ctx, events, last } = setup()
events.emit('unhandledRejection', new Error('route failed\n at connect'))
expect(last()?.description).toBe('unhandled rejection: route failed')
events.emit('uncaughtExceptionMonitor', 'x'.repeat(300))
expect(last()?.description).toBe(`uncaught exception: ${'x'.repeat(200)}`)
await ctx.fiber.dispose()
})
it('records a failure without a string form and still reaches the listener that owns the event', async () => {
const { ctx, events, last, seenByOwner } = setup()
events.emit('unhandledRejection', Object.create(null))
expect(last()?.description).toBe('unhandled rejection: <unprintable>')
expect(seenByOwner).toEqual(['unhandled rejection: <unprintable>'])
await ctx.fiber.dispose()
})
it('records the end of protocol input', async () => {
const { ctx, input, last } = setup()
input.resume()
input.end()
await new Promise<void>((resolve) => { input.once('end', resolve) })
expect(last()?.description).toBe('stdin closed')
await ctx.fiber.dispose()
})
it('keeps the event before teardown and removes its listeners on disposal', async () => {
const { ctx, events, input, runtime, last } = setup()
events.emit('SIGTERM')
expect(runtime.unloading()).toBe(false)
let unloadingDuringTeardown: boolean | undefined
// Registered last, so this runs while the record's listeners are still attached.
ctx.effect(() => () => {
unloadingDuringTeardown = runtime.unloading()
events.emit('unhandledRejection', new Error('caused by teardown'))
}, 'test teardown failure')
await ctx.fiber.dispose()
expect(unloadingDuringTeardown).toBe(true)
expect(last()?.description).toBe('SIGTERM')
expect(events.listenerCount('SIGTERM')).toBe(1)
expect(events.listenerCount('unhandledRejection')).toBe(1)
expect(events.listenerCount('uncaughtExceptionMonitor')).toBe(0)
expect(input.listenerCount('end')).toBe(0)
})
})
+80 -1
View File
@@ -65,6 +65,14 @@ function promptAgentFixture(fields: Pick<Agent, 'id' | 'followup'> & Partial<Pic
}
}
/** Complete the handshake on a route that is already registered, so no adapter is mounted. */
async function initializedServer(ctx: Context): Promise<HarnessSdkJsonRpcServer> {
ctx.provide('llm', { listProviders: () => [{ id: 'fake' }], resolveCallConfig: () => Promise.resolve({}) })
const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
await server.initialize({ cwd: process.cwd(), provider: 'fake', model: 'fake' })
return server
}
afterEach(async () => {
await Promise.all(servers.splice(0).map(server => new Promise(resolve => server.close(resolve))))
vi.unstubAllEnvs()
@@ -507,6 +515,77 @@ describe('HarnessSdkJsonRpcServer', () => {
await server.shutdown()
})
it('reports when the registry dropped the agent if no plugin unload accompanied it', async () => {
const agent = promptAgentFixture({ id: brandString<SessionId>('dropped'), followup: vi.fn<Agent['followup']>() })
let live = true
const ctx = testContext()
ctx.provide('agents', {
create: vi.fn(async () => ({ agent, dispose: vi.fn(() => Promise.resolve()) })),
get: () => live ? agent : undefined,
})
const server = await initializedServer(ctx)
const prompt = () => server.prompt({ sessionId: 'dropped', contentBlocks: [{ type: 'text', text: 'hi' }] })
await prompt()
live = false
ctx.emit('agent/disposed', { agent })
await expect(prompt()).rejects.toThrow(new RegExp(
String.raw`^session agent was disposed outside the server: dropped; the agent loop was unloaded at \d{4}-\d{2}-\d{2}T[\d:.]+Z$`,
))
await server.shutdown()
})
it('reports an unloaded agent registry as a disposed agent', async () => {
const agent = promptAgentFixture({ id: brandString<SessionId>('unregistered'), followup: vi.fn<Agent['followup']>() })
const ctx = testContext()
const registry = await ctx.plugin({
name: 'test-agent-registry',
apply(registryCtx: Context) {
registryCtx.provide('agents', {
create: vi.fn(async () => ({ agent, dispose: vi.fn(() => Promise.resolve()) })),
get: () => agent,
})
},
})
const server = await initializedServer(ctx)
const prompt = () => server.prompt({ sessionId: 'unregistered', contentBlocks: [{ type: 'text', text: 'hi' }] })
await prompt()
await registry.dispose()
await expect(prompt()).rejects.toThrow(/^session agent was disposed outside the server: unregistered; the agent loop was unloaded$/)
await server.shutdown()
})
it('reports its own shutdown to a wait that outlives the agent', async () => {
const idle = Promise.withResolvers<undefined>()
const agent = promptAgentFixture({
id: brandString<SessionId>('closing'),
followup: vi.fn<Agent['followup']>(),
whenIdle: () => idle.promise,
})
let live = true
const ctx = testContext()
ctx.provide('agents', {
create: vi.fn(async () => ({ agent, dispose: vi.fn(() => Promise.resolve()) })),
get: () => live ? agent : undefined,
})
const server = await initializedServer(ctx)
await server.prompt({ sessionId: 'closing', contentBlocks: [{ type: 'text', text: 'hi' }] })
const waiting = server.wait({ sessionId: 'closing' })
const outcome = expect(waiting).rejects.toThrow(
'session agent was disposed outside the server: closing; the SDK server is shutting down',
)
const shutdown = server.shutdown()
live = false
idle.resolve(undefined)
await outcome
await shutdown
})
it('forwards whole-agent status without attributing a turn outcome', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
@@ -1432,6 +1511,6 @@ describe('HarnessSdkJsonRpcServer', () => {
const server = new HarnessSdkJsonRpcServer(ctx, new FakeTransport())
await expect(server.shutdown()).rejects.toBe(listenerFailure)
expect(disposed.toSorted()).toEqual(Array.from({ length: subscription }, (_, index) => index + 1))
expect(disposed.toSorted((a, b) => a - b)).toEqual(Array.from({ length: subscription }, (_, index) => index + 1))
})
})
+2 -2
View File
@@ -9,8 +9,8 @@
en: ddf4dabea526cef1
zh: 6e31cab10d2f3ed8
/deepseek-harness-python-sdk/start-a-runtime:
en: 05298d7872586fcf
zh: 9262ee9b2a8dee7d
en: 130fcf823217a00b
zh: 59013ce608934404
/deepseek-harness-python-sdk/run-text-and-commands:
en: 6dec2d510bce71bd
zh: 742ca999aaacd137
+2
View File
@@ -50,6 +50,8 @@ print(result.final_response)
`DeepSeekHarness` starts lazily and reuses its runtime until `close()` or context-manager exit. The initial profile handshake has an independent 30-second default bound through `initialize_timeout_seconds`; ordinary activity remains unbounded after its protocol response, whose wait can be limited with `request_timeout_seconds`. A timeout names the selected profile and includes retained runtime diagnostics. `cwd` is the agent workspace; `runtime_cwd` independently selects the subprocess working directory. Both become absolute before launch. `provider`, `model`, optional `reasoning_effort`, and optional positive `max_tokens` are sent during JSON-RPC initialization. `base_url` and `api_key` explicitly override `DEEPSEEK_BASE_URL` and `DEEPSEEK_API_KEY` in the child environment.
The SDK logs every line the runtime writes to stderr, as it arrives, to the Python logger `deepseek_harness.runtime` at `INFO`, prefixed with `dsh runtime[<pid>] stderr:`. That stream carries the runtime's fatal reports, including the stack of an uncaught exception or unhandled rejection that ends the process. A host that configures logging at `INFO`, for example with `logging.basicConfig(level=logging.INFO)`, receives these lines in its own log; without logging configuration Python shows nothing below `WARNING`. Set that logger's level to silence it.
`harness.resume_session(saved_session_id)` restores persisted history and returns a `Session` ready for `run()`. Save the original session id and reuse its `dsh_home` and workspace. Restoration preserves the stored directory, repairs an interrupted final turn, and sends no new input. Missing, unreadable, incompatible, or occupied sessions raise without creating a replacement. `start_session(id)` only opens a lazy handle; it does not request persisted restoration. This API does not restore shell, browser, or other external processes.
Call `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` to replace the saved permission preset before resumed execution. Omitting options or passing an empty dict preserves saved permissions. Unknown keys and options other than a dict or `None` raise `TypeError` before the resume request is sent. The selected preset updates both sandbox and approval policy and persists for later resumes; it must exist in the profile’s permission service. The standard `sdk` profile offers `read-only`, `workspace-write`, and `danger-full-access`. Profiles without that service, such as `sdk-minimal`, reject explicit overrides. A session already restored by a reminder also rejects overrides; use `/permission` for that live session.
+2
View File
@@ -50,6 +50,8 @@ print(result.final_response)
`DeepSeekHarness` 延迟启动运行时,并在调用 `close()` 或退出上下文管理器前复用该进程。首次 profile 握手通过 `initialize_timeout_seconds` 使用独立的 30 秒默认上限;普通活动在协议响应后仍不设时限;`request_timeout_seconds` 可以限制协议响应的等待。超时诊断会指明所选 profile,并包含保留的运行时诊断。`cwd` 是 agent workspace;`runtime_cwd` 独立选择子进程工作目录。两者都会在启动前转成绝对路径。`provider`、`model`、可选的 `reasoning_effort` 和可选的正整数 `max_tokens` 通过 JSON-RPC 初始化发送。`base_url` 与 `api_key` 会显式覆盖子进程环境中的 `DEEPSEEK_BASE_URL` 与 `DEEPSEEK_API_KEY`。
SDK 把运行时写到 stderr 的每一行实时记录到 Python logger `deepseek_harness.runtime`,级别为 `INFO`,前缀为 `dsh runtime[<pid>] stderr:`。该输出包含运行时的致命错误报告,包括导致进程结束的未捕获异常或未处理拒绝的堆栈。宿主把日志配置为 `INFO`(例如 `logging.basicConfig(level=logging.INFO)`)后,这些行会进入宿主自己的日志;未配置日志时,Python 不显示低于 `WARNING` 的记录。调整该 logger 的级别即可关闭。
`harness.resume_session(saved_session_id)` 恢复持久化历史,并返回可调用 `run()` 的 `Session`。请保存原会话 id,并沿用其 `dsh_home` 和工作区。恢复会保留存储的目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时会抛出异常,不创建替代会话。`start_session(id)` 只打开惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。
调用 `harness.resume_session(saved_session_id, {"permission_mode": "danger-full-access"})` 可在恢复后的执行开始前覆盖已保存的权限预设;省略选项或传入空字典时保留历史权限。若选项含未知键,或传入的选项既非字典也非 `None`,SDK 会在发送恢复请求前抛出 `TypeError`。所选预设同时更新 sandbox 和审批策略,并持久化供后续恢复使用;该预设必须存在于 profile 的权限服务中。标准 `sdk` profile 提供 `read-only`、`workspace-write` 和 `danger-full-access`。缺少该服务的 profile(如 `sdk-minimal`)会拒绝显式覆盖。已被提醒任务恢复的会话也会拒绝覆盖;请对该运行中会话使用 `/permission`。
+6 -1
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import logging
import os
import queue
import subprocess
@@ -18,6 +19,8 @@ from .errors import JsonRpcError, SdkProtocolError, TransportClosedError
from .models import CommandExecution, IncomingRequest, InitializeResponse, JsonObject, JsonValue, Notification, ResumeSessionOptions, UserQuestionAnswer, UserQuestionRequest
ModelT = TypeVar("ModelT", bound=BaseModel)
# Every line the runtime writes to stderr, as it arrives. The host's logging configuration decides whether it is shown.
_runtime_logger = logging.getLogger("deepseek_harness.runtime")
NotificationFilter: TypeAlias = Callable[[Notification], bool]
UserQuestionHandler: TypeAlias = Callable[[UserQuestionRequest, threading.Event], UserQuestionAnswer | JsonObject]
@@ -459,7 +462,9 @@ class HarnessClient:
if proc is None or proc.stderr is None:
return
for line in proc.stderr:
self._stderr_lines.append(line.rstrip())
text = line.rstrip()
self._stderr_lines.append(text)
_runtime_logger.info("dsh runtime[%d] stderr: %s", proc.pid, text)
def _handle_message(self, message: object) -> None:
if not isinstance(message, dict):
+49
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
import logging
import inspect
import sys
import threading
@@ -20,6 +21,7 @@ def test_high_level_sdk_runs_turn_and_preserves_auto_review_errors(tmp_path: Pat
script.write_text(
"""
import json
import logging
import os
import sys
@@ -226,6 +228,7 @@ def test_session_run_invokes_notification_callback_before_returning(tmp_path: Pa
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -265,6 +268,7 @@ def test_high_level_sdk_rejects_turn_end_without_reason_kind(tmp_path: Path) ->
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -303,6 +307,7 @@ def test_relative_cwd_is_absolute_in_process_environment_and_wire(
script.write_text(
"""
import json
import logging
import os
import sys
@@ -339,6 +344,7 @@ def test_session_run_includes_subagent_finished_for_parent_session(tmp_path: Pat
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -381,6 +387,7 @@ def test_session_run_collects_nested_subagent_tree_without_polluting_root_events
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -441,6 +448,7 @@ def test_session_run_ignores_notifications_for_other_sessions(tmp_path: Path) ->
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -478,6 +486,7 @@ def test_high_level_session_run_does_not_accumulate_global_notifications(tmp_pat
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -508,6 +517,7 @@ def test_session_run_waits_for_late_idle_without_replaying_stale_notifications(t
script.write_text(
"""
import json
import logging
import sys
import time
@@ -552,6 +562,7 @@ def test_client_starts_subprocess_sends_requests_and_routes_notifications(tmp_pa
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -721,6 +732,7 @@ def test_client_contains_notification_filter_failure_to_its_subscription(tmp_pat
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -763,6 +775,7 @@ def test_client_rejects_unaccepted_session_prompt_response(tmp_path: Path) -> No
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -789,6 +802,7 @@ def test_client_routes_bridge_requests_and_sends_responses(tmp_path: Path) -> No
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -824,6 +838,7 @@ def test_client_ignores_non_json_stdout_lines(tmp_path: Path) -> None:
script.write_text(
"""
import json
import logging
import sys
print("node warning: experimental loader", flush=True)
@@ -877,6 +892,7 @@ def test_client_close_times_out_when_shutdown_does_not_respond(tmp_path: Path) -
script.write_text(
"""
import json
import logging
import signal
import sys
import time
@@ -915,6 +931,7 @@ def test_client_close_allows_eof_quiescence_after_shutdown_response(tmp_path: Pa
script.write_text(
"""
import json
import logging
import os
from pathlib import Path
import sys
@@ -951,6 +968,7 @@ def test_initialize_failure_reaps_started_runtime(tmp_path: Path) -> None:
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -1017,6 +1035,7 @@ def test_client_close_is_idempotent_before_and_after_start(tmp_path: Path) -> No
script.write_text(
"""
import json
import logging
import sys
for line in sys.stdin:
@@ -1063,6 +1082,7 @@ def test_client_serializes_concurrent_writes(tmp_path: Path) -> None:
script.write_text(
"""
import json
import logging
import os
import sys
@@ -1107,6 +1127,7 @@ def _install_fake_bundled_dsh(
runtime.write_text(
"""
import json
import logging
import os
import sys
@@ -1201,3 +1222,31 @@ def test_client_reports_missing_bundled_runtime_dependency(monkeypatch: pytest.M
with pytest.raises(FileNotFoundError, match="Install deepseek-harness-runtime-bin"):
HarnessClient(HarnessConfig(dsh_home="/explicit/home")).start()
def test_runtime_stderr_lines_reach_the_runtime_logger(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
script = tmp_path / "failing_runtime.py"
script.write_text(
"""
import sys
print("dsh: fatal load failure: TypeError: boom", file=sys.stderr, flush=True)
print(" at node:internal/deps/undici/undici:6933:28", file=sys.stderr, flush=True)
sys.exit(1)
""".strip()
)
with caplog.at_level(logging.INFO, logger="deepseek_harness.runtime"):
with HarnessClient(HarnessConfig(request_timeout_seconds=2), _launch_args=(sys.executable, str(script))) as client:
pid = client._proc.pid
with pytest.raises(Exception, match="fatal load failure"):
client.initialize(provider="deepseek-official", cwd="/workspace", model="dsagent")
# The reader thread ends at the runtime's stderr EOF, after it has logged every line.
client._stderr_thread.join(timeout=5)
assert not client._stderr_thread.is_alive()
records = [record for record in caplog.records if record.name == "deepseek_harness.runtime"]
assert [(record.levelno, record.getMessage()) for record in records] == [
(logging.INFO, f"dsh runtime[{pid}] stderr: dsh: fatal load failure: TypeError: boom"),
(logging.INFO, f"dsh runtime[{pid}] stderr: at node:internal/deps/undici/undici:6933:28"),
]