@qilin-agent/sdk-client 3.1.6 → 3.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -9,29 +9,35 @@
9
9
  en: 2518c7e7142a83a6
10
10
  zh: 545d4928b779b606
11
11
  /qilin-agent-sdk-client/summary:
12
- en: 296fd5fa9e2d56ca
13
- zh: 89f81af039e90708
12
+ en: 70401f813a4ec462
13
+ zh: adc796652c0001be
14
14
  /qilin-agent-sdk-client/table-of-contents:
15
15
  en: d152484eb41ac6b4
16
16
  zh: 09388d293f9be9cb
17
17
  /qilin-agent-sdk-client/use-this-package:
18
- en: 316b142489dd050f
19
- zh: 2b37ae57b2a52b5e
18
+ en: d1fb034253df8f93
19
+ zh: 15d4268fc08bab24
20
20
  /qilin-agent-sdk-client/use-this-package/running-agent-turns-with-deepseekharness:
21
- en: 01c58dddd7e62de2
22
- zh: 6dbd46e244f3f135
21
+ en: 1a36c54463e17340
22
+ zh: ad67f9cbccc56def
23
+ /qilin-agent-sdk-client/use-this-package/run-text-and-native-commands:
24
+ en: bde754f330ab5705
25
+ zh: 458e4ba89e64f7ad
23
26
  /qilin-agent-sdk-client/use-this-package/lower-level-control-with-harnessclient:
24
- en: eb8d1958801816b6
25
- zh: 1a6087e2dd1a9347
27
+ en: 28d1a81527e0854d
28
+ zh: 921c660a4d55fc9d
29
+ /qilin-agent-sdk-client/use-this-package/native-user-questions:
30
+ en: f5b9d6a7363bd9e5
31
+ zh: f53b3786d22a729d
26
32
  /qilin-agent-sdk-client/understand-the-implementation:
27
33
  en: 8773f50c51da85f0
28
34
  zh: 4649ebc69357deb0
29
35
  /qilin-agent-sdk-client/understand-the-implementation/design-concept:
30
- en: 109a9c832204693c
31
- zh: 6af985fe4abe57e2
36
+ en: 83c5e9664dd07ec9
37
+ zh: 09af294568e2f9e0
32
38
  /qilin-agent-sdk-client/understand-the-implementation/source-map:
33
- en: a3c7978a80f5aba3
34
- zh: fdc4dfdafd2eccfa
39
+ en: ee896439a5c07ca3
40
+ zh: 1b18751fe2db250e
35
41
  /qilin-agent-sdk-client/understand-the-implementation/owned-activity-flow:
36
42
  en: 94a42babac5f1c7d
37
43
  zh: df9e42ed02f7d002
@@ -48,8 +54,8 @@
48
54
  en: 7abe0be104a791e7
49
55
  zh: 445311f78b1069ca
50
56
  /qilin-agent-sdk-client/known-limitations-and-deferred-work:
51
- en: 7b24f3cd40fd7971
52
- zh: bdb0f7c37f1658da
57
+ en: 271f07e1f61c4eb7
58
+ zh: 984fa1e6ee4b389f
53
59
  /qilin-agent-sdk-client/known-limitations-and-deferred-work/dev-note:
54
60
  en: 6177a56f053936a4
55
61
  zh: 0f4b20228c2d15da
package/README.md CHANGED
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
9
9
 
10
10
  ## Summary
11
11
 
12
- `qilin-sdk-client` lets TypeScript programs start and drive a complete QiLin runtime over stdio JSON-RPC. Use `DeepSeekHarness` to open sessions, send text or image prompts, collect event and notification streams, and obtain the last committed assistant response when the runtime becomes idle; use `HarnessClient` for direct protocol requests and subscriptions. Callers may provide `qilinBin`; otherwise the client resolves the same-version `@qilin-agent/cli` executable. The client owns the subprocess across runs, exposes typed transport and protocol failures, and reaps it on `close()` or `await using`. It is suitable when the caller can choose the runtime profile and launch settings.
12
+ `qilin-sdk-client` lets TypeScript programs drive a complete QiLin runtime over stdio JSON-RPC. Use `run()` for ordinary text, supported slash commands, and image content blocks, and `onNotification` to observe its notifications. `HarnessClient` provides direct protocol access. Callers may provide `qilinBin`; otherwise the client resolves the same-version `@qilin-agent/cli` executable. The client owns the subprocess, reports typed failures, and reaps it on `close()` or `await using`.
13
13
 
14
14
  ## Table of Contents
15
15
 
@@ -25,10 +25,38 @@ English | [中文](README.zh.md)
25
25
  <a id="use-this-package"></a>
26
26
  ## Use this package
27
27
 
28
- `HarnessSession.getWorkingDirectory()` reads the effective directory; `setWorkingDirectory(path)` changes it and returns the validated absolute path. Either method creates an unknown Session without starting a model turn. Relative paths use the Session's current directory. Origin metadata, permissions, and existing processes remain unchanged. `HarnessClient` exposes the same methods with a leading `sessionId` argument.
29
-
30
28
  Use this client when TypeScript code must drive a complete Harness runtime from another process and you can name the runtime executable explicitly. The common path is minimal: construct a `DeepSeekHarness` with a launch spec, run prompts, and close it so the child process is always reaped.
31
29
 
30
+ For client-owned approvals, call `harness.client.start()`, install `harness.client.onRequest(handler)`, then call `harness.start()` with `approvalRequests: true` in the Harness options. The handler receives `approval/request` parameters and returns `{ outcome: "allowed-once" | "rejected" | "cancelled" }`; a rejected handler returns a JSON-RPC error and the runtime fails that approval closed. A replacement client needs its own handler; a closed client cannot restart. Native user questions keep their `onUserQuestion` callback. Enabling approvals without the additional-request handler returns an unknown-request error and fails approvals closed as `unavailable`. Without the opt-in, existing approval answerers remain in control. See the [wire protocol](../protocol/README.md) for request fields and cancellation.
31
+
32
+ For example, this terminal embedding asks for each one-operation grant. It does not change the Session's permission mode. Node deployments need an available pnpm for package operations; the [Python runtime](../../../python/sdk-runtime/README.md) can supply its explicitly downloaded Node/pnpm instead.
33
+
34
+ ```ts
35
+ import { createInterface } from 'node:readline/promises'
36
+ import { stdin, stdout } from 'node:process'
37
+ import { DeepSeekHarness } from '@qilin-agent/sdk-client'
38
+
39
+ const terminal = createInterface({ input: stdin, output: stdout })
40
+ try {
41
+ await using harness = new DeepSeekHarness({
42
+ qilinHome: '/absolute/path/to/isolated-qilin-home', approvalRequests: true,
43
+ })
44
+ harness.client.start()
45
+ harness.client.onRequest(async (method, params) => {
46
+ if (method !== 'approval/request') throw new Error(`Unsupported request: ${method}`)
47
+ const answer = await terminal.question(`${JSON.stringify(params)}\nAllow once? [y/N] `)
48
+ return { outcome: answer.trim().toLowerCase() === 'y' ? 'allowed-once' : 'rejected' }
49
+ })
50
+ console.log((await harness.run('List the installed plugins.')).finalResponse)
51
+ } finally {
52
+ terminal.close()
53
+ }
54
+ ```
55
+
56
+ `await harness.resumeSession(savedId)` restores a persisted session from the configured `qilinHome` and returns a `HarnessSession` ready for `run()`. Save the original session id and reuse its home and workspace. Restoration preserves conversation history and its directory, repairs an interrupted final turn, and sends no new input. Missing, unreadable, incompatible, or occupied sessions reject without creating a replacement. `session(id)` remains a lazy handle for an in-process session; it does not request persisted restoration. Shell, browser, and other external processes are not restored by this API.
57
+
58
+ `HarnessSession.getWorkingDirectory()` reads the effective directory; `setWorkingDirectory(path)` changes it and returns the validated absolute path. Either method creates an unknown Session without starting a model turn. Relative paths use the Session's current directory. Origin metadata, permissions, and existing processes remain unchanged. `HarnessClient` exposes the same methods with a leading `sessionId` argument.
59
+
32
60
  ### Running agent turns with DeepSeekHarness
33
61
 
34
62
  ```ts
@@ -37,9 +65,10 @@ import { ReasoningEffortId } from '@qilin-agent/llm'
37
65
 
38
66
  await using harness = new DeepSeekHarness({
39
67
  profile: 'sdk',
68
+ qilinHome: '/absolute/path/to/qilin-home',
40
69
  patches: ['./automation.cordis.yml'],
41
70
  provider: 'deepseek-official',
42
- model: 'deepseek-v4-flash',
71
+ model: 'deepseek-flash',
43
72
  reasoningEffort: ReasoningEffortId('max'),
44
73
  maxTokens: 49_152,
45
74
  })
@@ -47,14 +76,46 @@ const result = await harness.run('say hi')
47
76
  console.log(result.finalResponse)
48
77
  ```
49
78
 
50
- The subprocess starts lazily on first use and stays owned by the instance across `run()` calls; call `close()` (or use `await using`) so the child is always reaped. `start()` memoizes the bounded `initialize` handshake, which carries the workspace cwd, provider/model route, optional adapter-owned `reasoningEffort`, and optional positive `maxTokens` output cap. The server validates that exact route before it accepts prompts; an omitted effort preserves the model's default. `initializeTimeoutMs` defaults to 10 seconds, and its diagnostic names the selected profile with the retained stderr tail. `run(input, { sessionId?, onNotification? })` accepts text or `SdkPromptContentBlock[]`; an inline raster block carries canonical base64 plus `mimeType` and becomes a durable attachment inside the runtime. The call owns one activity interval: it queues the prompt, waits until its message id appears in a durable inbox receipt, then collects through the next whole-agent `idle`. It returns `RunResult { sessionId, finalResponse, events, notifications }`, where `finalResponse` is the last committed root-session assistant text in that interval — not a response causally assigned to the prompt, because steering, injected context, and other queued work may contribute before idle. `session(id?)` opens a named or fresh session handle. When a failed handshake is cleaned up successfully, the instance installs a fresh client so a later call retries with a new process until terminal `close()`; if initialization and cleanup both fail, `start()` returns an ordered `AggregateError` and retains the failed client instead of spawning beside a process whose exit is unproved. `maxTokens` caps each root-agent request output and is inherited by in-process descendants; compaction plugins own their separate summary limits.
79
+ The subprocess starts lazily on first use and stays owned by the instance across `run()` calls; call `close()` (or use `await using`) so the child is always reaped. `start()` memoizes the bounded `initialize` handshake, which carries the workspace cwd, provider/model route, optional adapter-owned `reasoningEffort`, and optional positive `maxTokens` output cap. The server validates that exact route before it accepts prompts; an omitted effort preserves the model's default. `initializeTimeoutMs` defaults to 10 seconds, and its diagnostic names the selected profile with the retained stderr tail. `run(input, { sessionId?, onNotification? })` accepts text or `SdkPromptContentBlock[]`; an inline raster block carries canonical base64 plus `mimeType` and becomes a durable attachment inside the runtime. For ordinary input, the call owns one activity interval: it queues the prompt, waits until its message id appears in a durable inbox receipt, then collects through the next whole-agent `idle`. That path returns `RunResult { sessionId, finalResponse, finishReason, events, notifications }`, where `finalResponse` is the last committed root-session assistant text in that interval — not a response causally assigned to the prompt, because steering, injected context, and other queued work may contribute before idle. `session(id?)` opens a named or fresh session handle. When a failed handshake is cleaned up successfully, the instance installs a fresh client so a later call retries with a new process until terminal `close()`; if initialization and cleanup both fail, `start()` returns an ordered `AggregateError` and retains the failed client instead of spawning beside a process whose exit is unproved. `maxTokens` caps each root-agent request output and is inherited by in-process descendants; compaction plugins own their separate summary limits.
80
+
81
+ ### Run text and native commands
82
+
83
+ `await session.run(input, { onNotification })` accepts a string or `SdkPromptContentBlock[]` and routes both through the runtime's [supported command forms and Desktop aliases](../server/README.md#command-input). Unrecognized input remains an ordinary prompt with its original block order. Ordinary input, including images, uses the existing prompt queue. Commands retain their native admission and timing.
84
+
85
+ Select a model that supports image input. Submit a command and image in the existing content-block array, for example `session.run([{ type: 'text', text: '/plan Analyze this image.' }, { type: 'image', data: imageBase64, mimeType: 'image/png' }])`; `harness.run()` accepts the same input. Plan input and goal creation or editing accept images; `/plan off`, goal controls, compact, and permission commands reject them through the [native attachment rules](../server/README.md#command-input). Native command input supports encoded raster images, not general file uploads or client-supplied attachment references.
86
+
87
+ ```ts
88
+ import { DeepSeekHarness } from '@qilin-agent/sdk-client'
89
+
90
+ await using harness = new DeepSeekHarness({ profile: 'sdk', qilinHome: '/absolute/path/to/qilin-home' })
91
+ const session = harness.session()
92
+ const result = await session.run('/compact')
93
+ console.log(result.finalResponse)
94
+ ```
95
+
96
+ String and content-block input always return `RunResult` with `sessionId`, `finalResponse`, `finishReason`, root events and Session-tree notifications. State-only commands return native result text; commands that submit model work wait for that activity and return its final assistant text, or an empty string when none is emitted. Native refusals use `finishReason === "error"`; routing, protocol, transport and observer failures reject. Command ids and native outcomes remain in `command/run` and `command/done` events. A completion without its matching command lifecycle events raises `SdkProtocolError` instead of returning a partial result. For literal queued input, use the low-level `client.prompt(sessionId, blocks)` and manage subsequent activity; runtime skill recognition still applies.
97
+
98
+ Every call subscribes before sending and releases its subscription before settlement. `onNotification` observes the input's Session-tree activity in wire order; the interval can include overlapping work. The SDK consumes internal completion receipts. Concurrent calls retain independent results, including a native busy result during model activity. Timeout or observer failure does not roll back runtime work or authorize automatic retry.
99
+
100
+ Launch options supply initial values. A permission command changes only its target Session; later inputs and restoration retain that state, other Sessions keep theirs, and new Sessions use configured defaults. It does not update the options object or saved user defaults. An approval-policy change during a running turn can inject a notice and cause another step. See [permission presets](../../interaction/permission-presets/README.md) for native transition and restoration behavior.
101
+
102
+ `run('/plan')` enters plan mode; `/plan off` leaves; `/plan <message>` enters and steers the body. `run()` waits for submitted model activity, native review and approved continuation without an extra caller-owned subscription or wait. Answer plan review through the user-question handler; the `exit_plan_mode` plan is in the question's `detail`. Plan mode does not change permissions. Goal creation and resume through `run()` wait across automatic rounds until the goal stops and the last reply ends; pause or clear returns `aborted`, while blocking or lost activation reports failure.
51
103
 
52
104
  ### Lower-level control with HarnessClient
53
105
 
54
106
  `HarnessClient` is the protocol client under the run API: explicit `start()`, `initialize()`, `prompt()`, `request()`, and `close()`, plus notification subscriptions. `prompt()` returns the queued message id as soon as the runtime accepts it and never waits for agent activity. `subscribe(filter?)` returns a `NotificationSubscription` (awaitable `next()`, non-blocking `tryNext()`, async iteration); `subscribeSessionTree(id)` scopes to one session and the descendants discovered from `subagent.started` lineage edges — the runtime notifies for every session in its context, and scoping is client-side, exactly like the Python SDK.
55
107
 
108
+ Task-owning consumers can subscribe before `prompt()`, then call `request('session/wait', { sessionId })` and drain queued notifications with `tryNext()`. This waits for managed descendants and their root summary turns; `HarnessSession.run()` retains its next-idle interval for ordinary prompts. `validatedSessionEvent()` validates the event envelope and the assistant/turn fields consumed by SDK readers before they enter an output fold.
109
+
56
110
  The client exports typed errors for every failure mode: `JsonRpcResponseError` (a wire error response, code and data preserved), `RequestTimeoutError` (a configured bound elapsed), `SdkProtocolError` (a response outside the documented protocol), and `TransportClosedError` (the runtime is gone — the message carries the exit code and a bounded stderr tail). `close()` requests protocol `shutdown` (bounded by `shutdownTimeoutMs`, default 1000 ms), then walks a stdin-EOF → SIGTERM → SIGKILL ladder until the process has exited; it is idempotent, and a closed client refuses reuse. `HarnessClientOptions.env` replaces the child environment entirely when given (`undefined` inherits the parent's); callers own credential policy — `scrubbedParentEnv` from `qilin-subprocess` is the shared scrub base for isolation-minded launches.
57
111
 
112
+ <a id="native-user-questions"></a>
113
+ ### Native user questions
114
+
115
+ Pass `onUserQuestion` to `DeepSeekHarness` or `HarnessClient` to answer the built-in `ask_user_question` tool through the native SDK protocol. The callback receives `{ requestId, sessionId, questions }` and `{ signal }`; return `{ answers: [{ id, selected, custom? }] }`, using one item per question id. Alternatively return `{ cancelled: true }` for user dismissal. Plan-review dismissal ends the native turn and keeps plan mode active. Your application owns the UI or simulated-user policy. The SDK automatically advertises the callback at initialization and can receive answers while other requests are pending. `HarnessClient.initialize()` starts the process when needed; an explicit `start()` is optional.
116
+
117
+ Observe the signal to release host work when the runtime cancels the question, disconnects, or the client closes. The SDK stops awaiting cancelled callbacks and ignores their later answers. A throwing callback reports a provider error; missing or malformed answers never count as approval. Without a callback, native in-process answerers remain available, and a missing answerer reports `NO_PROVIDER`.
118
+
58
119
  -----
59
120
 
60
121
  <a id="understand-the-implementation"></a>
@@ -67,16 +128,16 @@ This section explains the design behind the client; the observable behavior is f
67
128
 
68
129
  ### Design concept
69
130
 
70
- The client is two layers over one wire: `DeepSeekHarness` (owned runs) over `HarnessClient` (the protocol client), mirroring the Python SDK's layering. It runs outside any harness context, so it spawns the runtime directly rather than through the `qilin-subprocess` service — the seam's documented exception for SDK-managed transports — and its teardown ladder lives in this package. The runtime notifies for every session in its context; session-tree scoping is a client-side filter over `subagent.started` lineage edges.
131
+ The client is two layers over one wire: `DeepSeekHarness` (owned runs) over `HarnessClient` (the protocol client), mirroring the Python SDK's layering. Both SDKs expose `run()` for prompt-or-command input; request construction and response validation stay in internal helpers. It runs outside any harness context, so it spawns the runtime directly rather than through the `qilin-subprocess` service — the seam's documented exception for SDK-managed transports — and its teardown ladder lives in this package. The runtime notifies for every session in its context; session-tree scoping is a client-side filter over `subagent.started` lineage edges.
71
132
 
72
133
  ### Source map
73
134
 
74
135
  | File | Role |
75
136
  |---|---|
76
- | [`src/api.ts`](src/api.ts) | `DeepSeekHarness` + `HarnessSession`: owned runs, receipt-to-idle collection, `finalResponse` |
137
+ | [`src/api.ts`](src/api.ts) | `DeepSeekHarness` + `HarnessSession`: unified input routing, owned activity intervals and command results |
77
138
  | [`src/client.ts`](src/client.ts) | `HarnessClient`: spawn, handshake, requests, subscription fan-out, typed errors |
78
139
  | [`src/dispose.ts`](src/dispose.ts) | Private teardown ladder: stdin EOF → SIGTERM → SIGKILL to actual exit |
79
- | [`src/types.ts`](src/types.ts) | Launch and timeout options, notification shapes, `RunResult` |
140
+ | [`src/types.ts`](src/types.ts) | Launch and timeout options, notifications, `RunResult` |
80
141
  | [`src/index.ts`](src/index.ts) | Consumer interface: the two client layers and caller-facing types |
81
142
 
82
143
  ### Owned activity flow
@@ -121,9 +182,9 @@ None in the client process. Profile, patch, provider, model, and history choices
121
182
  These limits define when the client is a poor fit or needs special care. They are current package constraints, not a comparison with other SDK clients or a task backlog.
122
183
 
123
184
  - **No bundled-runtime resolution** — the client resolves the same-version `@qilin-agent/cli` package (or a caller-provided `qilinBin`); packaged-executable discovery stays Python-side until a TypeScript distribution consumer exists.
124
- - **No mid-turn cancel** — the wire has no prompt-cancel method; abandoning a turn means closing the runtime (see the [protocol limitations](../protocol/README.md#known-limitations-and-deferred-work)).
125
- - **No per-prompt result** — low-level `prompt()` returns only an enqueue receipt; high-level `run()` owns receipt-to-idle collection, and abandoning it means closing the runtime.
126
- - **Client→server notifications and server→client requests are unimplemented** on both wire ends; the transport carries them for future approval flows.
185
+ - **No runtime cancellation request** — an RPC timeout or observer failure ends local waiting without stopping runtime work. Stopping runtime work requires closing the harness (see the [protocol limitations](../protocol/README.md#known-limitations-and-deferred-work)).
186
+ - **No exclusive model response** — prompt results cover receipt-to-idle activity and can include steering or other queued work. Concurrent calls observe the Session's actual event stream; a command result does not own a later turn.
187
+ - **Callbacks must release their own resources** — the SDK delivers cancellation through `AbortSignal`; application work that ignores it may continue after the SDK stops awaiting its answer.
127
188
 
128
189
  <a id="dev-note"></a>
129
190
  ### Dev Note
package/README.zh.md CHANGED
@@ -9,7 +9,7 @@ kind: "package-library"
9
9
 
10
10
  ## 概述
11
11
 
12
- `qilin-sdk-client` 让 TypeScript 程序通过 stdio JSON-RPC 启动并驱动完整的 QiLin 运行时。使用 `DeepSeekHarness` 可打开会话、发送文本或图像提示词、收集事件与通知流,并在运行时进入 idle 后取得最后提交的助手响应;使用 `HarnessClient` 可直接发送协议请求和订阅通知。调用方可以提供 `qilinBin`;否则客户端解析同版本的 `@qilin-agent/cli` 可执行文件。客户端跨多次运行持有子进程,公开类型化的传输与协议错误,并在 `close()` 或 `await using` 时回收进程。它适用于调用方能够选择运行时 profile 和启动设置的场景。
12
+ `qilin-sdk-client` 让 TypeScript 程序通过 stdio JSON-RPC 驱动完整的 QiLin 运行时。使用 `run()` 运行普通文本、支持的 slash 命令和图片内容块,通过 `onNotification` 观察其通知。`HarnessClient` 提供直接协议访问。调用方可以提供 `qilinBin`;否则客户端解析同版本的 `@qilin-agent/cli` 可执行文件。客户端持有子进程,报告类型化错误,并在 `close()` 或 `await using` 时回收进程。
13
13
 
14
14
  ## 目录
15
15
 
@@ -25,10 +25,38 @@ kind: "package-library"
25
25
  <a id="use-this-package"></a>
26
26
  ## 使用本包
27
27
 
28
- `HarnessSession.getWorkingDirectory()` 读取有效目录;`setWorkingDirectory(path)` 修改目录并返回校验后的绝对路径。两个方法都可创建未知 Session,而不启动模型轮次。相对路径以 Session 当前目录解析。起始目录元数据、权限与已有进程保持不变。`HarnessClient` 提供同名方法,并以 `sessionId` 作为首个参数。
29
-
30
28
  当 TypeScript 代码需要从另一进程驱动完整 Harness 运行时、且你能显式指名运行时可执行文件时,使用本客户端。常用路径极简:用启动规格构造 `DeepSeekHarness`,运行提示词,然后关闭它,使子进程总能被回收。
31
29
 
30
+ 若由客户端处理审批,先调用 `harness.client.start()`,安装 `harness.client.onRequest(handler)`,再调用 `harness.start()`,并在 Harness 选项中设置 `approvalRequests: true`。处理器接收 `approval/request` 参数,返回 `{ outcome: "allowed-once" | "rejected" | "cancelled" }`;处理器拒绝时返回 JSON-RPC 错误,运行时拒绝放行该审批。替换客户端时需要为新实例安装处理器;已关闭的客户端不能重启。原生问答仍由 `onUserQuestion` 回调处理。启用审批但未安装附加请求处理器时,服务端请求收到未知请求错误,审批以 `unavailable` 拒绝放行。未启用时保留现有审批应答链。请求字段与取消规则见[协议](../protocol/README.zh.md)。
31
+
32
+ 下面的终端接入示例会逐项询问一次性授权,不改变会话的权限模式。Node 部署的包操作需要可用的 pnpm;[Python 运行时](../../../python/sdk-runtime/README.zh.md) 可以提供显式下载的 Node/pnpm。
33
+
34
+ ```ts
35
+ import { createInterface } from 'node:readline/promises'
36
+ import { stdin, stdout } from 'node:process'
37
+ import { DeepSeekHarness } from '@qilin-agent/sdk-client'
38
+
39
+ const terminal = createInterface({ input: stdin, output: stdout })
40
+ try {
41
+ await using harness = new DeepSeekHarness({
42
+ qilinHome: '/absolute/path/to/isolated-qilin-home', approvalRequests: true,
43
+ })
44
+ harness.client.start()
45
+ harness.client.onRequest(async (method, params) => {
46
+ if (method !== 'approval/request') throw new Error(`Unsupported request: ${method}`)
47
+ const answer = await terminal.question(`${JSON.stringify(params)}\nAllow once? [y/N] `)
48
+ return { outcome: answer.trim().toLowerCase() === 'y' ? 'allowed-once' : 'rejected' }
49
+ })
50
+ console.log((await harness.run('List the installed plugins.')).finalResponse)
51
+ } finally {
52
+ terminal.close()
53
+ }
54
+ ```
55
+
56
+ `await harness.resumeSession(savedId)` 从配置的 `qilinHome` 恢复持久化会话,并返回可调用 `run()` 的 `HarnessSession`。请保存原会话 id,并沿用其 home 和工作区。恢复会保留对话历史及其目录、修复最后一个被中断的轮次,且不发送新输入。会话缺失、不可读、不兼容或被占用时,请求失败且不创建替代会话。`session(id)` 仍是当前进程内会话的惰性句柄,不会请求持久化恢复。此 API 不恢复 shell、浏览器或其他外部进程。
57
+
58
+ `HarnessSession.getWorkingDirectory()` 读取有效目录;`setWorkingDirectory(path)` 修改目录并返回校验后的绝对路径。两个方法都可创建未知 Session,而不启动模型轮次。相对路径以 Session 当前目录解析。起始目录元数据、权限与已有进程保持不变。`HarnessClient` 提供同名方法,并以 `sessionId` 作为首个参数。
59
+
32
60
  ### 用 DeepSeekHarness 运行 agent 轮次
33
61
 
34
62
  ```ts
@@ -37,9 +65,10 @@ import { ReasoningEffortId } from '@qilin-agent/llm'
37
65
 
38
66
  await using harness = new DeepSeekHarness({
39
67
  profile: 'sdk',
68
+ qilinHome: '/absolute/path/to/qilin-home',
40
69
  patches: ['./automation.cordis.yml'],
41
70
  provider: 'deepseek-official',
42
- model: 'deepseek-v4-flash',
71
+ model: 'deepseek-flash',
43
72
  reasoningEffort: ReasoningEffortId('max'),
44
73
  maxTokens: 49_152,
45
74
  })
@@ -47,14 +76,46 @@ const result = await harness.run('say hi')
47
76
  console.log(result.finalResponse)
48
77
  ```
49
78
 
50
- 子进程在首次使用时惰性启动,并在多次 `run()` 调用之间持续归实例所有;请调用 `close()`(或使用 `await using`),子进程才总能被回收。`start()` 会记忆化有界的 `initialize` 握手,其中包含工作区 cwd、提供方/模型路由、可选且由适配器持有的 `reasoningEffort`,以及可选的正整数 `maxTokens` 输出上限。服务器会在接受提示词前校验该确切路由;省略推理强度时保留模型自身的默认值。`initializeTimeoutMs` 默认 10 秒,诊断会写明所选 profile 并附带保留的 stderr 尾部。`run(input, { sessionId?, onNotification? })` 接受文本或 `SdkPromptContentBlock[]`;内联栅格图像块携带规范 base64 与 `mimeType`,并在运行时内变成持久附件。该调用拥有一个活动区间:它将提示词排入队列,等待其消息 id 出现在持久入队回执中,然后持续收集到整个 agent 下一次进入 `idle`。它返回 `RunResult { sessionId, finalResponse, events, notifications }`,其中 `finalResponse` 是该区间内根会话最后提交的助手文本——并非因果上归属于该提示词的响应,因为 steering(中途引导)、注入的上下文和其他排队工作都可能在 idle 前参与其中。`session(id?)` 打开具名或全新的会话句柄。握手失败且清理成功时,实例会换入全新客户端,使后续调用用新进程重试,直到终结性的 `close()`;如果初始化和清理均失败,`start()` 会返回保留两个原因的有序 `AggregateError`,并继续保留失败的客户端,避免在原进程退出尚未得到证明时启动另一个进程。`maxTokens` 限制每个根 agent 请求的输出量,并由进程内后代继承;压缩(compaction)插件单独持有摘要上限。
79
+ 子进程在首次使用时惰性启动,并在多次 `run()` 调用之间持续归实例所有;请调用 `close()`(或使用 `await using`),子进程才总能被回收。`start()` 会记忆化有界的 `initialize` 握手,其中包含工作区 cwd、提供方/模型路由、可选且由适配器持有的 `reasoningEffort`,以及可选的正整数 `maxTokens` 输出上限。服务器会在接受提示词前校验该确切路由;省略推理强度时保留模型自身的默认值。`initializeTimeoutMs` 默认 10 秒,诊断会写明所选 profile 并附带保留的 stderr 尾部。`run(input, { sessionId?, onNotification? })` 接受文本或 `SdkPromptContentBlock[]`;内联栅格图像块携带规范 base64 与 `mimeType`,并在运行时内变成持久附件。对于普通输入,该调用拥有一个活动区间:它将提示词排入队列,等待其消息 id 出现在持久入队回执中,然后持续收集到整个 agent 下一次进入 `idle`。该路径返回 `RunResult { sessionId, finalResponse, finishReason, events, notifications }`,其中 `finalResponse` 是该区间内根会话最后提交的助手文本——并非因果上归属于该提示词的响应,因为 steering(中途引导)、注入的上下文和其他排队工作都可能在 idle 前参与其中。`session(id?)` 打开具名或全新的会话句柄。握手失败且清理成功时,实例会换入全新客户端,使后续调用用新进程重试,直到终结性的 `close()`;如果初始化和清理均失败,`start()` 会返回保留两个原因的有序 `AggregateError`,并继续保留失败的客户端,避免在原进程退出尚未得到证明时启动另一个进程。`maxTokens` 限制每个根 agent 请求的输出量,并由进程内后代继承;压缩(compaction)插件单独持有摘要上限。
80
+
81
+ ### 运行文本与原生命令
82
+
83
+ `await session.run(input, { onNotification })` 接受字符串或 `SdkPromptContentBlock[]`,两者都交给运行时的[命令形式与 Desktop 别名](../server/README.zh.md#command-input)识别规则。未识别的输入保持普通提示词及原始内容块顺序。普通输入(包括图片)使用既有的提示词队列。命令保留原生接纳规则与执行时序。
84
+
85
+ 先选择支持图片输入的模型。通过现有内容块数组同时提交命令和图片,例如 `session.run([{ type: 'text', text: '/plan Analyze this image.' }, { type: 'image', data: imageBase64, mimeType: 'image/png' }])`;`harness.run()` 接受相同输入。计划输入和目标创建、编辑接受图片;`/plan off`、目标控制、压缩和权限命令按[原生附件规则](../server/README.zh.md#command-input)拒绝图片。原生命令输入支持编码栅格图片,不支持一般文件上传或客户端提供的附件引用。
86
+
87
+ ```ts
88
+ import { DeepSeekHarness } from '@qilin-agent/sdk-client'
89
+
90
+ await using harness = new DeepSeekHarness({ profile: 'sdk', qilinHome: '/absolute/path/to/qilin-home' })
91
+ const session = harness.session()
92
+ const result = await session.run('/compact')
93
+ console.log(result.finalResponse)
94
+ ```
95
+
96
+ 字符串和内容块输入始终返回 `RunResult`,包含 `sessionId`、`finalResponse`、`finishReason`、根会话事件和会话树通知。仅改变状态的命令返回原生结果文本;提交模型工作的命令等待对应活动并返回最终助手文本,未输出助手文本时返回空字符串。原生拒绝通过 `finishReason === "error"` 表达,路由、协议、传输和观察回调失败会拒绝 Promise。命令 id 和原生结果保留在 `command/run`、`command/done` 事件中。完成通知缺少匹配的命令生命周期事件时抛出 `SdkProtocolError`,不会返回不完整的结果。需要按原文排队时,使用底层 `client.prompt(sessionId, blocks)` 并管理后续活动;运行时技能识别仍然适用。
97
+
98
+ 每次调用在发送前建立订阅,并在结束前释放。`onNotification` 按传输顺序接收本次输入的会话树活动;区间可以包含其他重叠工作。内部完成回执由 SDK 消费。并发调用保留各自结果,因此模型运行期间仍能取得另一条命令的忙碌错误。超时或观察回调失败不回滚运行时工作,也不授权自动重试。
99
+
100
+ 启动选项提供初始值。权限命令只修改目标 Session;后续输入与恢复保留该状态,其他 Session 保留自己的状态,新 Session 使用配置默认值。命令不修改选项对象或已保存的用户默认值。运行中的审批策略变化可以注入通知并触发下一步骤。原生转换与恢复行为见[权限 preset](../../interaction/permission-presets/README.zh.md)。
101
+
102
+ `run('/plan')` 进入计划模式;`/plan off` 退出;`/plan <message>` 进入并通过 steer 提交正文。`run()` 等待提交的模型活动、原生审阅及获批后的执行,无需调用者另行订阅或等待。通过用户问题处理器回答计划审阅;`exit_plan_mode` 的计划正文位于问题的 `detail`。计划模式不改变权限。通过 `run()` 创建或恢复目标时,会跨越自动轮次等待,直到目标停止及最后回复结束;暂停或清除返回 `aborted`,目标阻塞或失去激活状态报告失败。
51
103
 
52
104
  ### 用 HarnessClient 做低层控制
53
105
 
54
106
  `HarnessClient` 是运行 API 之下的协议客户端:显式 `start()`、`initialize()`、`prompt()`、`request()` 与 `close()`,外加通知订阅。`prompt()` 在运行时接受排队消息后立即返回该消息的 id,绝不等待 agent 活动。`subscribe(filter?)` 返回 `NotificationSubscription`(可等待的 `next()`、非阻塞 `tryNext()`、异步迭代);`subscribeSessionTree(id)` 把范围限定到一个会话及从 `subagent.started` 血缘边发现的后代——运行时对上下文内每个会话都发通知,范围限定在客户端完成,与 Python SDK 完全一致。
55
107
 
108
+ 拥有完整任务的消费者可以先订阅,再调用 `prompt()`,随后调用 `request('session/wait', { sessionId })`,并通过 `tryNext()` 取完已排队的通知。这会等待受管理后代及其触发的根 Agent 摘要轮次;`HarnessSession.run()` 对普通提示词仍以首次空闲作为活动区间终点。`validatedSessionEvent()` 在事件进入输出折叠前,校验事件封装及 SDK 读取方使用的 assistant/turn 字段。
109
+
56
110
  本客户端为每种失败模式导出类型化错误:`JsonRpcResponseError`(协议错误响应,保留 code 与 data)、`RequestTimeoutError`(配置的时限已到)、`SdkProtocolError`(响应超出文档化协议)、`TransportClosedError`(运行时已消失——消息携带退出码与有界 stderr 尾部)。`close()` 先请求协议 `shutdown`(受 `shutdownTimeoutMs` 约束,默认 1000 毫秒),然后走 stdin-EOF → SIGTERM → SIGKILL 阶梯直到进程退出;幂等,已关闭的客户端拒绝复用。`HarnessClientOptions.env` 给定时整体替换子进程环境(`undefined` 原样继承父进程环境);凭据策略归调用方——`qilin-subprocess` 的 `scrubbedParentEnv` 是面向隔离启动的共享擦除基底。
57
111
 
112
+ <a id="native-user-questions"></a>
113
+ ### 原生用户问答
114
+
115
+ 向 `DeepSeekHarness` 或 `HarnessClient` 传入 `onUserQuestion`,即可通过原生 SDK 协议回答内建的 `ask_user_question` 工具。回调接收 `{ requestId, sessionId, questions }` 与 `{ signal }`;返回 `{ answers: [{ id, selected, custom? }] }`,每个问题 id 对应一项。也可返回 `{ cancelled: true }` 表示用户关闭问题。关闭计划审查会结束原生轮次,并保持计划模式。应用自行提供 UI 或模拟用户策略。SDK 在初始化时自动声明此回调,也能在其他请求待决时接收答案。`HarnessClient.initialize()` 会在需要时启动进程,无需显式调用 `start()`。
116
+
117
+ 运行时取消问题、断开连接或客户端关闭时,应响应 signal 释放宿主工作。SDK 停止等待已取消的回调,并忽略晚到答案。回调抛错会报告提供方错误;缺失或格式错误的答案均不构成批准。未提供回调时,原生进程内回答方仍可用,缺少回答方则报告 `NO_PROVIDER`。
118
+
58
119
  -----
59
120
 
60
121
  <a id="understand-the-implementation"></a>
@@ -67,16 +128,16 @@ console.log(result.finalResponse)
67
128
 
68
129
  ### 设计理念
69
130
 
70
- 客户端是同一协议上的两层:`DeepSeekHarness`(自有运行)叠加在 `HarnessClient`(协议客户端)之上,与 Python SDK 的分层一致。它运行在任何 harness 上下文之外,因此直接 spawn 运行时而非经由 `qilin-subprocess` 服务——即该 seam 记录的 SDK 托管传输例外——其关闭阶梯也位于本包。运行时对上下文内每个会话都发通知;会话树范围限定是客户端对 `subagent.started` 血缘边的过滤。
131
+ 客户端是同一协议上的两层:`DeepSeekHarness`(自有运行)叠加在 `HarnessClient`(协议客户端)之上,与 Python SDK 的分层一致。两种 SDK 都通过公开 `run()` 接收提示词或命令,请求构造与响应校验保留在内部辅助函数中。它运行在任何 harness 上下文之外,因此直接 spawn 运行时而非经由 `qilin-subprocess` 服务——即该 seam 记录的 SDK 托管传输例外——其关闭阶梯也位于本包。运行时对上下文内每个会话都发通知;会话树范围限定是客户端对 `subagent.started` 血缘边的过滤。
71
132
 
72
133
  ### 源码地图
73
134
 
74
135
  | 文件 | 职责 |
75
136
  |---|---|
76
- | [`src/api.ts`](src/api.ts) | `DeepSeekHarness` + `HarnessSession`:自有运行、从回执到 idle 的收集、`finalResponse` |
137
+ | [`src/api.ts`](src/api.ts) | `DeepSeekHarness` + `HarnessSession`:统一输入路由、自有活动区间与命令结果 |
77
138
  | [`src/client.ts`](src/client.ts) | `HarnessClient`:spawn、握手、请求、订阅扇出、类型化错误 |
78
139
  | [`src/dispose.ts`](src/dispose.ts) | 私有关闭阶梯:stdin EOF → SIGTERM → SIGKILL 直到真正退出 |
79
- | [`src/types.ts`](src/types.ts) | 启动与超时选项、通知结构、`RunResult` |
140
+ | [`src/types.ts`](src/types.ts) | 启动与超时选项、通知、`RunResult` |
80
141
  | [`src/index.ts`](src/index.ts) | 消费方接口:两层客户端与面向调用方的类型 |
81
142
 
82
143
  ### 自有活动流程
@@ -121,9 +182,9 @@ console.log(result.finalResponse)
121
182
  这些限制说明本客户端何时不合适或需要特别注意。它们是当前包约束,不是与其他 SDK 客户端的对比或任务积压。
122
183
 
123
184
  - **无捆绑运行时解析**——客户端解析同版本 `@qilin-agent/cli` 包(或调用方提供的 `qilinBin`);打包可执行文件的发现留在 Python 侧,直到出现 TypeScript 发行版消费方。
124
- - **无轮次中取消**——协议层没有提示词取消方法;放弃轮次意味着关闭运行时(见[协议限制](../protocol/README.zh.md#known-limitations-and-deferred-work))。
125
- - **没有逐提示词结果**——低层 `prompt()` 只返回入队回执;高层 `run()` 负责从回执到 idle 的收集,放弃该过程意味着关闭运行时。
126
- - **客户端→服务端通知与服务端→客户端请求**在协议两端都未实现;传输层为未来审批流程保留了承载能力。
185
+ - **无运行时取消请求**——RPC 超时或观察回调失败会结束本地等待,不会停止运行时工作。停止运行时工作需要关闭 harness(见[协议限制](../protocol/README.zh.md#known-limitations-and-deferred-work))。
186
+ - **无独占模型响应**——提示词结果涵盖从回执到 idle 的活动,可能包含 steering 或其他排队工作。并发调用观察 Session 的实际事件流;命令结果不独占后续 turn。
187
+ - **回调必须释放自己的资源**——SDK 通过 `AbortSignal` 发出取消;忽略它的应用工作可能在 SDK 停止等待答案后继续运行。
127
188
 
128
189
  <a id="dev-note"></a>
129
190
  ### 开发备注
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { spawn } from "node:child_process";
4
4
  import { JsonRpcLineTransport, JsonRpcResponseError, JsonRpcResponseError as JsonRpcResponseError$1 } from "@qilin-agent/sdk-protocol";
5
+ import { SessionId, SessionSeq } from "@qilin-agent/session";
5
6
  import { existsSync, readFileSync } from "node:fs";
6
7
  import { fileURLToPath } from "node:url";
7
8
  //#region lib/types/dispose.js
@@ -339,6 +340,9 @@ var HarnessClient = class {
339
340
  spawnError;
340
341
  streamsSettled = Promise.resolve();
341
342
  closeTask;
343
+ userQuestions = /* @__PURE__ */ new Map();
344
+ userQuestionHandler;
345
+ requestHandler;
342
346
  constructor(options = {}, runtime) {
343
347
  this.options = options;
344
348
  this.runtime = runtime ?? resolveQilinLaunch(options);
@@ -350,6 +354,7 @@ var HarnessClient = class {
350
354
  start() {
351
355
  if (this.closeTask !== void 0) throw new TransportClosedError("QiLin runtime client is closed");
352
356
  if (this.child !== void 0) return;
357
+ this.userQuestionHandler = this.options.onUserQuestion;
353
358
  const child = spawn(this.runtime.command, this.runtime.args, {
354
359
  cwd: this.runtime.cwd,
355
360
  env: this.runtime.environment(),
@@ -403,7 +408,35 @@ var HarnessClient = class {
403
408
  this.transport?.close();
404
409
  });
405
410
  const transport = new JsonRpcLineTransport(child.stdout, child.stdin);
411
+ transport.onRequest(async (method, params) => {
412
+ if (method !== "user-question/ask") {
413
+ if (this.requestHandler !== void 0) return this.requestHandler(method, params);
414
+ throw new SdkProtocolError(`unknown runtime request: ${method}`);
415
+ }
416
+ const handler = this.userQuestionHandler;
417
+ if (handler === void 0) throw new SdkProtocolError("user-question/ask requires an onUserQuestion callback");
418
+ if (!isUserQuestionRequest(params)) throw new SdkProtocolError("user-question/ask requires requestId, sessionId, and questions");
419
+ const requestId = params.requestId;
420
+ if (this.userQuestions.has(requestId)) throw new SdkProtocolError("duplicate user-question requestId");
421
+ const controller = new AbortController();
422
+ this.userQuestions.set(requestId, controller);
423
+ const cancelled = Promise.withResolvers();
424
+ const onAbort = () => {
425
+ cancelled.reject(controller.signal.reason);
426
+ };
427
+ controller.signal.addEventListener("abort", onAbort, { once: true });
428
+ try {
429
+ return await Promise.race([Promise.resolve().then(() => {
430
+ controller.signal.throwIfAborted();
431
+ return handler(params, { signal: controller.signal });
432
+ }), cancelled.promise]);
433
+ } finally {
434
+ controller.signal.removeEventListener("abort", onAbort);
435
+ this.userQuestions.delete(requestId);
436
+ }
437
+ });
406
438
  transport.onNotification((method, params) => {
439
+ if (method === "user-question.cancelled" && typeof params.requestId === "string") this.userQuestions.get(params.requestId)?.abort(/* @__PURE__ */ new Error("SDK runtime cancelled the user question"));
407
440
  this.dispatchNotification({
408
441
  method,
409
442
  params
@@ -413,12 +446,29 @@ var HarnessClient = class {
413
446
  this.transport = transport;
414
447
  }
415
448
  /**
416
- * Perform the process-wide handshake.
449
+ * Install the additional-request handler; native questions retain their onUserQuestion callback.
450
+ * @param handler - receives wire parameters and returns the JSON-RPC result; rejection sends an error.
451
+ * @throws when the client has not started or has already closed.
452
+ */
453
+ onRequest(handler) {
454
+ if (this.closeTask !== void 0) throw new TransportClosedError("QiLin runtime client is closed; create a new client to install a request handler");
455
+ if (this.transport === void 0) throw new TransportClosedError("start the SDK client before installing a request handler");
456
+ this.requestHandler = handler;
457
+ }
458
+ /**
459
+ * Start the runtime if needed, then perform the process-wide handshake.
417
460
  * @param params - workspace cwd plus the provider/model route.
418
461
  * @returns the runtime's wire identity.
419
462
  */
420
463
  async initialize(params) {
421
- const result = await this.request("initialize", { ...params }, this.runtime.initializeTimeoutMs);
464
+ this.start();
465
+ const result = await this.request("initialize", {
466
+ ...params,
467
+ ...this.userQuestionHandler === void 0 ? {} : { capabilities: {
468
+ ...params.capabilities,
469
+ userQuestions: true
470
+ } }
471
+ }, this.runtime.initializeTimeoutMs);
422
472
  if (!isRecord(result) || !isRecord(result.serverInfo) || typeof result.serverInfo.name !== "string" || typeof result.serverInfo.version !== "string") throw new SdkProtocolError(`initialize returned no server identity: ${JSON.stringify(result)}`);
423
473
  return { serverInfo: {
424
474
  name: result.serverInfo.name,
@@ -426,7 +476,7 @@ var HarnessClient = class {
426
476
  } };
427
477
  }
428
478
  /**
429
- * Queue one prompt and return its durable inbox identity.
479
+ * Queue one prompt without native command routing and return its durable inbox identity.
430
480
  * @param sessionId - target session; an unknown id creates it.
431
481
  * @param contentBlocks - the user message, sent verbatim.
432
482
  * @returns the queued message id.
@@ -443,12 +493,10 @@ var HarnessClient = class {
443
493
  /**
444
494
  * Restore persisted history without sending a prompt; failures propagate without creating a session.
445
495
  * @param sessionId - persisted identity in this runtime's configured persistence store.
446
- * @returns the restored session identity.
496
+ * @returns after the session is ready for prompts.
447
497
  */
448
498
  async resumeSession(sessionId) {
449
- const result = await this.request("session/resume", { sessionId });
450
- if (!isRecord(result) || result.sessionId !== sessionId) throw new SdkProtocolError(`session/resume returned an unexpected session id: ${JSON.stringify(result)}`);
451
- return sessionId;
499
+ await this.request("session/resume", { sessionId });
452
500
  }
453
501
  /**
454
502
  * Read a Session's effective working directory, recovering it if missing.
@@ -566,6 +614,7 @@ var HarnessClient = class {
566
614
  return this.closeTask;
567
615
  }
568
616
  async performClose() {
617
+ this.abortUserQuestions(new TransportClosedError("SDK client is closing"));
569
618
  const child = this.child;
570
619
  if (child === void 0) return;
571
620
  try {
@@ -604,8 +653,12 @@ var HarnessClient = class {
604
653
  return false;
605
654
  }
606
655
  failSubscriptions(error) {
656
+ this.abortUserQuestions(error);
607
657
  for (const subscription of this.subscriptions.values()) subscription.fail(error);
608
658
  }
659
+ abortUserQuestions(error) {
660
+ for (const controller of this.userQuestions.values()) controller.abort(error);
661
+ }
609
662
  appendStderr(lines) {
610
663
  const kept = lines.filter((line) => line.length > 0);
611
664
  this.stderrTail.push(...kept);
@@ -625,6 +678,42 @@ var HarnessClient = class {
625
678
  }
626
679
  };
627
680
  /**
681
+ * Send routed input for the package's high-level run API; absent from the package exports.
682
+ * @param client - client owning the initialized runtime connection.
683
+ * @param sessionId - target Session; an unknown id creates it.
684
+ * @param input - text or content blocks, without client-side command interpretation.
685
+ * @returns the validated prompt receipt or native command execution.
686
+ */
687
+ async function queryInput(client, sessionId, input) {
688
+ const params = {
689
+ sessionId: SessionId(sessionId),
690
+ contentBlocks: normalizeInput(input)
691
+ };
692
+ const value = await client.request("session/query", params);
693
+ if (isRecord(value)) {
694
+ if (value.kind === "prompt" && typeof value.messageId === "string" && value.messageId.length > 0) return {
695
+ kind: "prompt",
696
+ messageId: value.messageId
697
+ };
698
+ if (value.kind === "command") return {
699
+ kind: "command",
700
+ execution: commandExecution(value.execution)
701
+ };
702
+ }
703
+ throw new SdkProtocolError(`session/query returned an invalid routing result: ${JSON.stringify(value)}`);
704
+ }
705
+ /**
706
+ * Normalize routed input: a string becomes one text block; blocks pass verbatim.
707
+ * @param input - prompt or command text, or content blocks.
708
+ * @returns the content blocks to send.
709
+ */
710
+ function normalizeInput(input) {
711
+ return typeof input === "string" ? [{
712
+ type: "text",
713
+ text: input
714
+ }] : input;
715
+ }
716
+ /**
628
717
  * Whether `value` is a plain JSON object (the wire-boundary shape probe).
629
718
  * @param value - the wire value to probe.
630
719
  * @returns `true` iff `value` is a non-null, non-array object.
@@ -632,17 +721,43 @@ var HarnessClient = class {
632
721
  function isRecord(value) {
633
722
  return typeof value === "object" && value !== null && !Array.isArray(value);
634
723
  }
724
+ /** Decode the native handler result returned by session/query. */
725
+ function commandExecution(value) {
726
+ if (isRecord(value) && typeof value.commandId === "string" && value.commandId.length > 0 && isRecord(value.result)) {
727
+ const commandId = value.commandId;
728
+ const { kind, text, sourceEventSeq } = value.result;
729
+ if (kind === "success" && (text === void 0 || typeof text === "string") && (sourceEventSeq === void 0 || typeof sourceEventSeq === "number" && Number.isSafeInteger(sourceEventSeq) && sourceEventSeq >= 0)) return {
730
+ commandId,
731
+ result: {
732
+ kind,
733
+ ...text === void 0 ? {} : { text },
734
+ ...sourceEventSeq === void 0 ? {} : { sourceEventSeq: SessionSeq(sourceEventSeq) }
735
+ }
736
+ };
737
+ if (kind === "error" && typeof text === "string" && text.trim().length > 0) return {
738
+ commandId,
739
+ result: {
740
+ kind,
741
+ text
742
+ }
743
+ };
744
+ }
745
+ throw new SdkProtocolError(`session/query returned an invalid command result: ${JSON.stringify(value)}`);
746
+ }
635
747
  /** The message of a thrown value (the transport only throws `Error`s; `String` covers the rest). */
636
748
  function errorMessage(error) {
637
749
  /* v8 ignore next -- the transport and dispose ladder reject only with Errors */
638
750
  return error instanceof Error ? error.message : String(error);
639
751
  }
752
+ /** Check the question envelope before handing runtime input to application code. */
753
+ function isUserQuestionRequest(value) {
754
+ return isRecord(value) && typeof value.requestId === "string" && value.requestId.length > 0 && typeof value.sessionId === "string" && Array.isArray(value.questions) && value.questions.length > 0 && value.questions.every((question) => isRecord(question) && typeof question.id === "string" && typeof question.question === "string");
755
+ }
640
756
  //#endregion
641
757
  //#region lib/types/api.js
642
758
  /**
643
- * High-level run API over {@link HarnessClient}: `DeepSeekHarness` owns one
644
- * runtime subprocess across many sessions; `HarnessSession.run` sends a
645
- * prompt and settles when the whole agent next becomes idle.
759
+ * High-level run API over {@link HarnessClient}: route text to prompts or native
760
+ * commands and collect prompt activity for text and image input.
646
761
  *
647
762
  * @module @qilin-agent/sdk-client/api
648
763
  */
@@ -660,6 +775,7 @@ var DeepSeekHarness = class {
660
775
  model;
661
776
  reasoningEffort;
662
777
  maxTokens;
778
+ approvalRequests;
663
779
  initialized;
664
780
  closed = false;
665
781
  constructor(options = {}, clientFactory) {
@@ -667,9 +783,10 @@ var DeepSeekHarness = class {
667
783
  this.clientInstance = this.createClient();
668
784
  this.cwd = resolve(options.cwd ?? options.processCwd ?? process.cwd());
669
785
  this.provider = options.provider ?? "deepseek-official";
670
- this.model = options.model ?? "deepseek-v4-flash";
786
+ this.model = options.model ?? "deepseek-flash";
671
787
  this.reasoningEffort = options.reasoningEffort;
672
788
  this.maxTokens = options.maxTokens;
789
+ this.approvalRequests = options.approvalRequests;
673
790
  }
674
791
  /**
675
792
  * The underlying JSON-RPC client (exposed for low-level access). A failed
@@ -700,7 +817,8 @@ var DeepSeekHarness = class {
700
817
  provider: this.provider,
701
818
  model: this.model,
702
819
  ...this.reasoningEffort === void 0 ? {} : { reasoningEffort: this.reasoningEffort },
703
- ...this.maxTokens === void 0 ? {} : { maxTokens: this.maxTokens }
820
+ ...this.maxTokens === void 0 ? {} : { maxTokens: this.maxTokens },
821
+ ...this.approvalRequests === void 0 ? {} : { approvalRequests: this.approvalRequests }
704
822
  });
705
823
  } catch (error) {
706
824
  this.initialized = void 0;
@@ -732,14 +850,14 @@ var DeepSeekHarness = class {
732
850
  */
733
851
  async resumeSession(sessionId) {
734
852
  await this.start();
735
- const restoredId = await this.client.resumeSession(sessionId);
736
- return new HarnessSession(this, restoredId);
853
+ await this.client.resumeSession(sessionId);
854
+ return new HarnessSession(this, sessionId);
737
855
  }
738
856
  /**
739
- * Run one prompt on a fresh (or named) session.
740
- * @param input - prompt text, or content blocks sent verbatim.
741
- * @param options - optional session id and per-notification observer.
742
- * @returns the owned activity interval.
857
+ * Run text or content blocks on a fresh or named Session through native input routing.
858
+ * @param input - prompt or command text, optionally accompanied by image content blocks.
859
+ * @param options - optional Session identity and notification observer.
860
+ * @returns the completed input's RunResult, including its Session id.
743
861
  */
744
862
  run(input, options) {
745
863
  return this.session(options?.sessionId).run(input, options);
@@ -761,6 +879,47 @@ var DeepSeekHarness = class {
761
879
  return this.close();
762
880
  }
763
881
  };
882
+ /** Collect one input's root events and Session-tree notifications from its admission. */
883
+ var RunActivity = class {
884
+ sessionId;
885
+ receipt;
886
+ commandDone = false;
887
+ received = false;
888
+ events = [];
889
+ notifications = [];
890
+ constructor(sessionId, receipt) {
891
+ this.sessionId = sessionId;
892
+ this.receipt = receipt;
893
+ }
894
+ /** Ignore pre-receipt traffic; validate root events before invoking the observer. */
895
+ record(notification, onNotification) {
896
+ if (notification.method === "session.query.completed") return false;
897
+ if (!this.received) {
898
+ if (notification.method !== "session.event" || notification.params.sessionId !== this.sessionId || !this.matchesReceipt(notification.params.event)) return false;
899
+ this.received = true;
900
+ }
901
+ const event = notification.method === "session.event" && notification.params.sessionId === this.sessionId ? validatedSessionEvent(notification.params.event) : void 0;
902
+ if (event?.type === "command/done" && "commandId" in this.receipt && isRecord(event.data) && event.data.commandId === this.receipt.commandId) this.commandDone = true;
903
+ this.notifications.push(notification);
904
+ onNotification?.(notification);
905
+ if (event !== void 0) this.events.push(event);
906
+ return true;
907
+ }
908
+ matchesReceipt(event) {
909
+ return "messageId" in this.receipt ? isInboxReceipt(event, this.receipt.messageId) : isRecord(event) && event.type === "command/run" && isRecord(event.data) && event.data.commandId === this.receipt.commandId;
910
+ }
911
+ result(completed) {
912
+ if (completed !== void 0 && !this.commandDone) throw new SdkProtocolError("Command completion is missing matching lifecycle events");
913
+ const terminal = this.events.findLast((event) => event.type === "turn/end");
914
+ return {
915
+ sessionId: this.sessionId,
916
+ finalResponse: completed?.finalResponse ?? finalResponse(this.events),
917
+ finishReason: completed?.finishReason ?? terminal?.data.reason.kind ?? null,
918
+ events: this.events,
919
+ notifications: this.notifications
920
+ };
921
+ }
922
+ };
764
923
  /**
765
924
  * One SDK session: a stable id plus owned activity intervals.
766
925
  */
@@ -793,64 +952,63 @@ var HarnessSession = class {
793
952
  return this.harness.client.setWorkingDirectory(this.id, path);
794
953
  }
795
954
  /**
796
- * Queue one prompt, then observe the whole session through its next idle.
797
- * @param input - prompt text, or content blocks sent verbatim.
798
- * @param options - optional per-notification observer.
799
- * @returns the owned activity interval; rejects on transport loss, timeout,
800
- * or a protocol error.
955
+ * Run text or content blocks through native prompt-or-command routing.
956
+ * @param input - prompt or command text, optionally accompanied by image content blocks; image-only input is an ordinary prompt.
957
+ * @param options - a per-notification observer.
958
+ * @returns RunResult after prompt activity, a state-only command, or command-started model work ends.
959
+ * Goal creation and resume include automatic rounds through goal termination and the closing reply.
960
+ * Native handler refusals return finishReason="error".
961
+ * @throws on routing, protocol, transport or observer failure; runtime work is not rolled back.
801
962
  */
802
963
  async run(input, options) {
803
964
  await this.harness.start();
804
965
  const client = this.harness.client;
805
- const contentBlocks = normalizeInput(input);
806
- const events = [];
807
- const notifications = [];
808
966
  const subscription = client.subscribeSessionTree(this.id);
809
- const collect = (notification) => {
810
- if (notification.method === "session.event" && notification.params.sessionId === this.id) {
811
- const event = validatedSessionEvent(notification.params.event);
812
- notifications.push(notification);
813
- options?.onNotification?.(notification);
814
- events.push(event);
815
- return;
816
- }
817
- notifications.push(notification);
818
- options?.onNotification?.(notification);
819
- };
820
967
  try {
821
- const messageId = await client.prompt(this.id, contentBlocks);
822
- let received = false;
968
+ const response = await queryInput(client, this.id, input);
969
+ if (response.kind === "command") {
970
+ const activity = new RunActivity(this.id, { commandId: response.execution.commandId });
971
+ while (true) {
972
+ const notification = await subscription.next();
973
+ const params = notification.params;
974
+ if (notification.method === "session.query.completed" && params.sessionId === this.id) {
975
+ if (typeof params.commandId !== "string" || params.commandId.length === 0) throw new SdkProtocolError("Invalid session.query.completed command identity");
976
+ if (params.commandId !== response.execution.commandId) continue;
977
+ if (typeof params.finalResponse !== "string" || typeof params.finishReason !== "string" || params.finishReason.length === 0) throw new SdkProtocolError("Invalid session.query.completed result");
978
+ while (!activity.commandDone) {
979
+ const queued = subscription.tryNext();
980
+ if (queued === void 0) break;
981
+ activity.record(queued, options?.onNotification);
982
+ }
983
+ return activity.result({
984
+ finalResponse: params.finalResponse,
985
+ finishReason: params.finishReason
986
+ });
987
+ }
988
+ activity.record(notification, options?.onNotification);
989
+ }
990
+ }
991
+ const activity = new RunActivity(this.id, { messageId: response.messageId });
992
+ let delegated = false;
823
993
  while (true) {
824
994
  const notification = await subscription.next();
825
- if (!received) {
826
- if (notification.method !== "session.event" || notification.params.sessionId !== this.id || !isInboxReceipt(notification.params.event, messageId)) continue;
827
- received = true;
995
+ if (notification.method === "subagent.started") delegated = true;
996
+ if (!activity.record(notification, options?.onNotification)) continue;
997
+ if (notification.method !== "session.status") continue;
998
+ if (notification.params.sessionId !== this.id) continue;
999
+ if (notification.params.status !== "idle") continue;
1000
+ if (delegated) {
1001
+ await client.request("session/wait", { sessionId: this.id });
1002
+ for (let queued = subscription.tryNext(); queued !== void 0; queued = subscription.tryNext()) activity.record(queued, options?.onNotification);
828
1003
  }
829
- collect(notification);
830
- if (notification.method === "session.status" && notification.params.sessionId === this.id && notification.params.status === "idle") break;
1004
+ break;
831
1005
  }
1006
+ return activity.result();
832
1007
  } finally {
833
1008
  subscription.close();
834
1009
  }
835
- return {
836
- sessionId: this.id,
837
- finalResponse: finalResponse(events),
838
- events,
839
- notifications
840
- };
841
1010
  }
842
1011
  };
843
- /**
844
- * Normalize run input: a string becomes one text block; blocks pass verbatim.
845
- * @param input - prompt text or content blocks.
846
- * @returns the content blocks to send.
847
- */
848
- function normalizeInput(input) {
849
- return typeof input === "string" ? [{
850
- type: "text",
851
- text: input
852
- }] : input;
853
- }
854
1012
  /** Validate the provider-read fields of one wire turn-end reason. */
855
1013
  function validatedTurnEndReason(value) {
856
1014
  if (!isRecord(value) || typeof value.kind !== "string") throw new SdkProtocolError(`turn/end carried no reason envelope: ${JSON.stringify(value)}`);
@@ -869,7 +1027,11 @@ function validatedTurnEndReason(value) {
869
1027
  }
870
1028
  return value;
871
1029
  }
872
- /** Validate the fields in a wire `session.event` envelope before returning the typed result. */
1030
+ /**
1031
+ * Validate the event envelope and assistant/turn fields consumed by SDK readers.
1032
+ * @param value - the raw `session.event` event payload.
1033
+ * @returns the event, or throws a protocol error for malformed consumed fields.
1034
+ */
873
1035
  function validatedSessionEvent(value) {
874
1036
  if (!isRecord(value) || typeof value.type !== "string") throw new SdkProtocolError(`session.event carried no event envelope: ${JSON.stringify(value)}`);
875
1037
  if (value.type === "assistant/message") {
@@ -904,4 +1066,4 @@ function finalResponse(events) {
904
1066
  return "";
905
1067
  }
906
1068
  //#endregion
907
- export { DeepSeekHarness, HarnessClient, HarnessSession, JsonRpcResponseError, RequestTimeoutError, SdkProtocolError, TransportClosedError };
1069
+ export { DeepSeekHarness, HarnessClient, HarnessSession, JsonRpcResponseError, RequestTimeoutError, SdkProtocolError, TransportClosedError, validatedSessionEvent };
@@ -1,7 +1,6 @@
1
1
  /**
2
- * High-level run API over {@link HarnessClient}: `DeepSeekHarness` owns one
3
- * runtime subprocess across many sessions; `HarnessSession.run` sends a
4
- * prompt and settles when the whole agent next becomes idle.
2
+ * High-level run API over {@link HarnessClient}: route text to prompts or native
3
+ * commands and collect prompt activity for text and image input.
5
4
  *
6
5
  * @module @qilin-agent/sdk-client/api
7
6
  */
@@ -23,6 +22,7 @@ export declare class DeepSeekHarness implements AsyncDisposable {
23
22
  private readonly model;
24
23
  private readonly reasoningEffort;
25
24
  private readonly maxTokens;
25
+ private readonly approvalRequests;
26
26
  private initialized;
27
27
  private closed;
28
28
  /** @param options - qilin launch configuration plus the session route, effort, and output cap. */
@@ -61,10 +61,10 @@ export declare class DeepSeekHarness implements AsyncDisposable {
61
61
  */
62
62
  resumeSession(sessionId: string): Promise<HarnessSession>;
63
63
  /**
64
- * Run one prompt on a fresh (or named) session.
65
- * @param input - prompt text, or content blocks sent verbatim.
66
- * @param options - optional session id and per-notification observer.
67
- * @returns the owned activity interval.
64
+ * Run text or content blocks on a fresh or named Session through native input routing.
65
+ * @param input - prompt or command text, optionally accompanied by image content blocks.
66
+ * @param options - optional Session identity and notification observer.
67
+ * @returns the completed input's RunResult, including its Session id.
68
68
  */
69
69
  run(input: string | SdkPromptContentBlock[], options?: RunOptions): Promise<RunResult>;
70
70
  /**
@@ -81,11 +81,14 @@ export declare class DeepSeekHarness implements AsyncDisposable {
81
81
  }
82
82
  /** Construct the high-level API against a generic process for package-local fake-runtime tests. */
83
83
  export declare function createProcessDeepSeekHarness(runtime: RuntimeProcessOptions, options?: DeepSeekHarnessOptions): DeepSeekHarness;
84
- /** Per-run options: target session and streaming observer. */
84
+ /** Per-run Session identity and notification observer. */
85
85
  export interface RunOptions {
86
86
  /** Session id to run on; omitted mints a fresh session per call. */
87
87
  sessionId?: string;
88
- /** Observer invoked with every notification for this session tree, in wire order. */
88
+ /**
89
+ * Observe the input's Session-tree activity in wire order until completion.
90
+ * The interval can include overlapping work from other inputs.
91
+ */
89
92
  onNotification?: (notification: HarnessNotification) => void;
90
93
  }
91
94
  /**
@@ -111,20 +114,22 @@ export declare class HarnessSession {
111
114
  */
112
115
  setWorkingDirectory(path: string): Promise<string>;
113
116
  /**
114
- * Queue one prompt, then observe the whole session through its next idle.
115
- * @param input - prompt text, or content blocks sent verbatim.
116
- * @param options - optional per-notification observer.
117
- * @returns the owned activity interval; rejects on transport loss, timeout,
118
- * or a protocol error.
117
+ * Run text or content blocks through native prompt-or-command routing.
118
+ * @param input - prompt or command text, optionally accompanied by image content blocks; image-only input is an ordinary prompt.
119
+ * @param options - a per-notification observer.
120
+ * @returns RunResult after prompt activity, a state-only command, or command-started model work ends.
121
+ * Goal creation and resume include automatic rounds through goal termination and the closing reply.
122
+ * Native handler refusals return finishReason="error".
123
+ * @throws on routing, protocol, transport or observer failure; runtime work is not rolled back.
119
124
  */
120
125
  run(input: string | SdkPromptContentBlock[], options?: Pick<RunOptions, 'onNotification'>): Promise<RunResult>;
121
126
  }
122
127
  /**
123
- * Normalize run input: a string becomes one text block; blocks pass verbatim.
124
- * @param input - prompt text or content blocks.
125
- * @returns the content blocks to send.
128
+ * Validate the event envelope and assistant/turn fields consumed by SDK readers.
129
+ * @param value - the raw `session.event` event payload.
130
+ * @returns the event, or throws a protocol error for malformed consumed fields.
126
131
  */
127
- export declare function normalizeInput(input: string | SdkPromptContentBlock[]): SdkPromptContentBlock[];
132
+ export declare function validatedSessionEvent(value: unknown): SessionEvent;
128
133
  /**
129
134
  * Extract the concatenated text of the last assistant message.
130
135
  * @param events - the activity interval's `session.event` payloads in wire order.
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * @module @qilin-agent/sdk-client/client
13
13
  */
14
- import { type InitializeParams, type InitializeResult, type SdkPromptContentBlock } from '@qilin-agent/sdk-protocol';
14
+ import { type InitializeParams, type InitializeResult, type SessionQueryResult, type SdkPromptContentBlock } from '@qilin-agent/sdk-protocol';
15
15
  import { type RuntimeProcessOptions } from './launch.ts';
16
16
  import type { HarnessClientOptions, HarnessNotification, NotificationFilter } from './types.ts';
17
17
  /**
@@ -76,6 +76,9 @@ export declare class HarnessClient {
76
76
  private spawnError;
77
77
  private streamsSettled;
78
78
  private closeTask;
79
+ private readonly userQuestions;
80
+ private userQuestionHandler;
81
+ private requestHandler;
79
82
  /** @param options - qilin profile, patch, home, process, environment, and timeout options. */
80
83
  constructor(options?: HarnessClientOptions);
81
84
  /**
@@ -84,13 +87,19 @@ export declare class HarnessClient {
84
87
  */
85
88
  start(): void;
86
89
  /**
87
- * Perform the process-wide handshake.
90
+ * Install the additional-request handler; native questions retain their onUserQuestion callback.
91
+ * @param handler - receives wire parameters and returns the JSON-RPC result; rejection sends an error.
92
+ * @throws when the client has not started or has already closed.
93
+ */
94
+ onRequest(handler: (method: string, params: Record<string, unknown>) => Promise<unknown>): void;
95
+ /**
96
+ * Start the runtime if needed, then perform the process-wide handshake.
88
97
  * @param params - workspace cwd plus the provider/model route.
89
98
  * @returns the runtime's wire identity.
90
99
  */
91
100
  initialize(params: InitializeParams): Promise<InitializeResult>;
92
101
  /**
93
- * Queue one prompt and return its durable inbox identity.
102
+ * Queue one prompt without native command routing and return its durable inbox identity.
94
103
  * @param sessionId - target session; an unknown id creates it.
95
104
  * @param contentBlocks - the user message, sent verbatim.
96
105
  * @returns the queued message id.
@@ -99,9 +108,9 @@ export declare class HarnessClient {
99
108
  /**
100
109
  * Restore persisted history without sending a prompt; failures propagate without creating a session.
101
110
  * @param sessionId - persisted identity in this runtime's configured persistence store.
102
- * @returns the restored session identity.
111
+ * @returns after the session is ready for prompts.
103
112
  */
104
- resumeSession(sessionId: string): Promise<string>;
113
+ resumeSession(sessionId: string): Promise<void>;
105
114
  /**
106
115
  * Read a Session's effective working directory, recovering it if missing.
107
116
  * @param sessionId - target Session; an unknown id creates it.
@@ -154,12 +163,27 @@ export declare class HarnessClient {
154
163
  private recordSessionRelationship;
155
164
  private isDescendantOf;
156
165
  private failSubscriptions;
166
+ private abortUserQuestions;
157
167
  private appendStderr;
158
168
  private settleStreams;
159
169
  private closedError;
160
170
  }
161
171
  /** Construct the transport against a generic process for package-local fake-runtime tests. */
162
172
  export declare function createProcessHarnessClient(options: RuntimeProcessOptions): HarnessClient;
173
+ /**
174
+ * Send routed input for the package's high-level run API; absent from the package exports.
175
+ * @param client - client owning the initialized runtime connection.
176
+ * @param sessionId - target Session; an unknown id creates it.
177
+ * @param input - text or content blocks, without client-side command interpretation.
178
+ * @returns the validated prompt receipt or native command execution.
179
+ */
180
+ export declare function queryInput(client: HarnessClient, sessionId: string, input: string | SdkPromptContentBlock[]): Promise<SessionQueryResult>;
181
+ /**
182
+ * Normalize routed input: a string becomes one text block; blocks pass verbatim.
183
+ * @param input - prompt or command text, or content blocks.
184
+ * @returns the content blocks to send.
185
+ */
186
+ export declare function normalizeInput(input: string | SdkPromptContentBlock[]): SdkPromptContentBlock[];
163
187
  /**
164
188
  * Whether `value` is a plain JSON object (the wire-boundary shape probe).
165
189
  * @param value - the wire value to probe.
@@ -8,10 +8,10 @@
8
8
  *
9
9
  * @module @qilin-agent/sdk-client
10
10
  */
11
- export { DeepSeekHarness, HarnessSession } from './api.ts';
11
+ export { DeepSeekHarness, HarnessSession, validatedSessionEvent } from './api.ts';
12
12
  export type { RunOptions } from './api.ts';
13
13
  export { HarnessClient, RequestTimeoutError, SdkProtocolError, TransportClosedError, } from './client.ts';
14
14
  export type { NotificationSubscription } from './client.ts';
15
15
  export { JsonRpcResponseError } from '@qilin-agent/sdk-protocol';
16
- export type { ContentBlock, SdkPromptContentBlock, DeepSeekHarnessOptions, HarnessClientOptions, HarnessNotification, NotificationFilter, RunResult, } from './types.ts';
16
+ export type { ContentBlock, SdkEncodedImageBlock, SdkPromptContentBlock, SdkUserQuestionAnswer, SdkUserQuestionResult, SdkUserQuestionRequest, DeepSeekHarnessOptions, HarnessClientOptions, HarnessNotification, NotificationFilter, RunResult, } from './types.ts';
17
17
  //# sourceMappingURL=index.d.ts.map
@@ -5,7 +5,7 @@
5
5
  * @module @qilin-agent/sdk-client/types
6
6
  */
7
7
  import type { ContentBlock, ReasoningEffortId } from '@qilin-agent/llm';
8
- import type { SdkPromptContentBlock } from '@qilin-agent/sdk-protocol';
8
+ import type { SdkPromptContentBlock, SdkUserQuestionResult, SdkUserQuestionRequest } from '@qilin-agent/sdk-protocol';
9
9
  import type { SessionEvent } from '@qilin-agent/session';
10
10
  /** One server-to-client notification as received off the wire. */
11
11
  export interface HarnessNotification {
@@ -18,6 +18,10 @@ export interface HarnessNotification {
18
18
  export type NotificationFilter = (notification: HarnessNotification) => boolean;
19
19
  /** Launch and timeout options for {@link HarnessClient}. */
20
20
  export interface HarnessClientOptions {
21
+ /** Answer or dismiss runtime questions; observe the signal to release host work on runtime cancellation. */
22
+ onUserQuestion?: (request: SdkUserQuestionRequest, context: {
23
+ signal: AbortSignal;
24
+ }) => Promise<SdkUserQuestionResult>;
21
25
  /** Absolute or caller-relative qilin CLI module; omitted resolves this package's same-version dependency. */
22
26
  qilinBin?: string;
23
27
  /** Named profile serving the SDK protocol (default `sdk`). */
@@ -53,19 +57,23 @@ export interface DeepSeekHarnessOptions extends HarnessClientOptions {
53
57
  cwd?: string;
54
58
  /** Provider route for SDK-created agents (default `deepseek-official`). */
55
59
  provider?: string;
56
- /** Model for SDK-created agents (default `deepseek-v4-flash`). */
60
+ /** Model for SDK-created agents (default `deepseek-flash`). */
57
61
  model?: string;
58
62
  /** Adapter-owned reasoning effort for the selected provider/model route. */
59
63
  reasoningEffort?: ReasoningEffortId;
60
64
  /** Maximum output tokens for each conversation-model request. */
61
65
  maxTokens?: number;
66
+ /** Enable server approval requests; install client.onRequest() after client.start() and before harness.start(). */
67
+ approvalRequests?: boolean;
62
68
  }
63
- /** One owned session activity interval, from enqueue receipt through idle. */
69
+ /** Result of one SDK input, including the model activity or native operation it owns. */
64
70
  export interface RunResult {
65
71
  /** The session the activity ran on. */
66
72
  sessionId: string;
67
- /** Concatenated text of the interval's last assistant message (empty when none). */
73
+ /** Final assistant text (empty when absent), native state-only result text, or a failure diagnostic. */
68
74
  finalResponse: string;
75
+ /** Model turn ending or native operation outcome; null when no terminal reason was recorded. */
76
+ finishReason: string | null;
69
77
  /** Every `session.event` payload for the root session, in wire order. */
70
78
  events: SessionEvent[];
71
79
  /** Every notification for the root session and discovered descendants, in wire order. */
@@ -74,4 +82,6 @@ export interface RunResult {
74
82
  /** Re-exported content-block alias so SDK callers need no extra import. */
75
83
  export type { ContentBlock };
76
84
  export type { SdkPromptContentBlock };
85
+ export type { SdkEncodedImageBlock } from '@qilin-agent/sdk-protocol';
86
+ export type { SdkUserQuestionAnswer, SdkUserQuestionResult, SdkUserQuestionRequest } from '@qilin-agent/sdk-protocol';
77
87
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@qilin-agent/sdk-client",
3
3
  "description": "TypeScript client SDK for driving a QiLin runtime subprocess over stdio JSON-RPC: the DeepSeekHarness high-level turns API and the lower-level HarnessClient",
4
- "version": "3.1.6",
4
+ "version": "3.1.8",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -29,18 +29,19 @@
29
29
  ],
30
30
  "license": "MIT",
31
31
  "dependencies": {
32
- "@qilin-agent/cli": "3.1.6"
32
+ "@qilin-agent/cli": "3.1.8"
33
33
  },
34
34
  "peerDependencies": {
35
- "@qilin-agent/llm": "3.1.6",
36
- "@qilin-agent/sdk-protocol": "3.1.6",
37
- "@qilin-agent/kylin": "~4.0.5",
38
- "@qilin-agent/session": "3.1.6"
35
+ "@qilin-agent/llm": "3.1.8",
36
+ "@qilin-agent/sdk-protocol": "3.1.8",
37
+ "@qilin-agent/session": "3.1.8",
38
+ "@qilin-agent/kylin": "~4.0.6-alpha.2"
39
39
  },
40
40
  "devDependencies": {
41
- "@qilin-agent/llm": "3.1.6",
42
- "@qilin-agent/session": "3.1.6",
43
- "@qilin-agent/kylin": "~4.0.5",
44
- "@qilin-agent/sdk-protocol": "3.1.6"
41
+ "@qilin-agent/experimental-translator": "3.1.8",
42
+ "@qilin-agent/llm": "3.1.8",
43
+ "@qilin-agent/sdk-protocol": "3.1.8",
44
+ "@qilin-agent/session": "3.1.8",
45
+ "@qilin-agent/kylin": "~4.0.6-alpha.2"
45
46
  }
46
47
  }