@qoder-ai/qoder-agent-sdk 1.0.57 → 1.0.59

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.md CHANGED
@@ -6,6 +6,8 @@ The SDK starts `qodercli` for you, streams agent messages back to Node.js, and
6
6
  lets your application configure tools, permissions, working directories, MCP
7
7
  servers, hooks, and interactive sessions.
8
8
 
9
+ For compression billing messages, see [压缩费用消息接口](doc/compact-usage.md).
10
+
9
11
  ## Installation
10
12
 
11
13
  ```bash
@@ -23,49 +25,55 @@ installed if your application uses SDK tools or MCP integration.
23
25
 
24
26
  ## Runtime Behavior
25
27
 
26
- The npm package uses `WorkerTransport.default` for `query()` by default. During
27
- `npm install`, its postinstall script downloads the Worker runtime selected by
28
- the package's pinned CLI version into `dist/_worker`. It does not download the
29
- process CLI unless `QODER_INSTALL_BUNDLED_CLI=1` is set.
30
-
31
- You can still select a transport explicitly on the same `query()` entry:
28
+ `query()` always runs through a process-wide qodercli daemon. The first query
29
+ starts that daemon and reuses it for later queries in the same process; pass
30
+ `options.daemon` to bind a query to a daemon you started yourself with
31
+ `startDaemon()`. The daemon owns the CLI process boundary, so the SDK does not
32
+ spawn a separate CLI per query. Call `shutdownDaemon()` before your host
33
+ process exits to stop the shared daemon.
34
+
35
+ During `npm install`, the postinstall script downloads the CLI binary selected
36
+ by the package's pinned CLI version into `dist/_bundled`; worker packages also
37
+ deliver the worker runtime into `dist/_worker`.
38
+
39
+ The daemon launches qodercli either as a native process carrier or as a Node
40
+ worker runtime. `startDaemon()` / `initDaemon()` accept
41
+ `launchMode: 'process' | 'worker'`; without it, the first query's
42
+ `options.transport` (`ProcessTransport` or `WorkerTransport`) selects the
43
+ carrier, otherwise the package's `DEFAULT_RUNTIME_TRANSPORT` applies. Worker
44
+ mode launches the bundled `dist/_worker` runtime, or the runtime passed through
45
+ `pathToQoderWorkerRuntime`; when no worker runtime is available the daemon
46
+ falls back to the process carrier. A later query whose launch mode differs from
47
+ the ready daemon is rejected with `DaemonConfigurationConflictError`.
48
+
49
+ The process carrier uses `pathToQoderCLIExecutable` when provided, then
50
+ `QODERCLI_PATH`, then the bundled CLI, then a locally installed `qodercli`.
51
+ JavaScript CLI entries run through `executable` (or the SDK host's Node binary).
52
+
53
+ `Options.transport`, `ProcessTransport`, and `WorkerTransport` remain
54
+ available: selecting either transport no longer spawns a per-query process or
55
+ worker, it selects the shared daemon's carrier. Query options that configure
56
+ the CLI process, such as `pathToQoderCLIExecutable`, `executable`,
57
+ `executableArgs`, `env`, `proxy`, `vpcEndpoint`, and `auth`, configure the
58
+ shared daemon instead. Because the daemon is shared, every query in one process
59
+ must pass compatible daemon-level options.
60
+
61
+ `options.extraHeaders` accepts a `Record<string, string>` for the first Qoder
62
+ main-model request of the first queryable input and its network retries. Later
63
+ tool continuations, subagents, and queries do not inherit these headers. Existing
64
+ built-in headers take precedence. Use a paired CLI build with `extra_headers`
65
+ support. For example, after the host obtains the user's paid-usage confirmation:
32
66
 
33
67
  ```ts
34
- import {
35
- qodercliAuth,
36
- query,
37
- WorkerTransport,
38
- } from "@qoder-ai/qoder-agent-sdk";
39
-
40
- const q = query({
41
- prompt: "Summarize this repository.",
68
+ query({
69
+ prompt,
42
70
  options: {
43
- auth: qodercliAuth(),
44
- transport: WorkerTransport.default,
71
+ ...options,
72
+ extraHeaders: { "Cosy-Paid-Confirmed": "true" },
45
73
  },
46
74
  });
47
75
  ```
48
76
 
49
- The worker transport uses the runtime installed at
50
- `dist/_worker/qoder-worker-runtime.obf.mjs`. To use another Worker runtime,
51
- pass its path explicitly with
52
- `new WorkerTransport({ pathToQoderWorkerRuntime })`. Environment variables do
53
- not override the Worker runtime entry.
54
-
55
- The package includes a `dist/runtime-manifest.json` that records the default
56
- runtime and the URL template for qodercli Worker runtime artifacts. At
57
- installation time, the SDK resolves exactly one artifact for its own brand,
58
- the current operating system, and the current architecture. It does not fall
59
- back to the universal artifact. The SDK package itself does not need to host a
60
- copy of the archive. The presence of `dist/_worker` is used as an integrity
61
- check after installation, not as the mode selector.
62
-
63
- The installed Worker runtime is self-contained. Platform packages include the
64
- matching native keychain, PTY, image-processing, and ripgrep assets. Linux
65
- packages retain both glibc and musl image-processing bindings. OpenHarmony does
66
- not have an install-delivered platform artifact and must use an explicitly
67
- supplied runtime source.
68
-
69
77
  If your environment blocks install scripts or network downloads, skip postinstall
70
78
  runtime downloads:
71
79
 
@@ -73,27 +81,13 @@ runtime downloads:
73
81
  QODER_SKIP_DOWNLOAD=1 npm install @qoder-ai/qoder-agent-sdk zod
74
82
  ```
75
83
 
76
- `QODER_SKIP_DOWNLOAD` only affects install-time downloads. It does not change the
77
- package's default runtime. Then point the process transport at an existing
78
- `qodercli`:
84
+ `QODER_SKIP_DOWNLOAD` only affects install-time downloads. Point the daemon at
85
+ an existing `qodercli` with:
79
86
 
80
87
  ```bash
81
88
  export QODERCLI_PATH=/absolute/path/to/qodercli
82
89
  ```
83
90
 
84
- To use an existing Worker runtime, pass its absolute path through
85
- `new WorkerTransport({ pathToQoderWorkerRuntime })`.
86
-
87
- `query()` is the only query entry point and defaults to Worker. Pass
88
- `transport: ProcessTransport.default`,
89
- `transport: WorkerTransport.default`, or a custom transport provider when a
90
- single call needs to override the package default.
91
-
92
- `pathToQoderCLIExecutable` accepts either local runtime form. Native binaries
93
- and ordinary CLI `.js`/`.mjs` entries use the process transport; recognized
94
- `qoder-worker-runtime*.mjs` entries use the Worker transport. An explicit
95
- `transport` provider always takes precedence over automatic path selection.
96
-
97
91
  ## Authentication
98
92
 
99
93
  Every SDK query needs an explicit authentication option.
@@ -213,6 +207,11 @@ for await (const message of q) {
213
207
  }
214
208
  ```
215
209
 
210
+ ## Business Attribution
211
+
212
+ For Qoder integrations, set product on the daemon and type on each query.
213
+ See the [short integration guide](doc/business-context.md).
214
+
216
215
  ## Code Security
217
216
 
218
217
  Built-in code security is disabled by default in SDK sessions. Enable only the
@@ -452,8 +451,8 @@ non-fatal `system/mirror_error` messages. Each append batch is submitted once:
452
451
  the SDK does not retry a mutation whose commit outcome may be unknown.
453
452
  `loadTimeoutMs` defaults to 60,000 ms.
454
453
  Session storage cannot be combined with `persistSession: false`, file
455
- checkpointing, custom transports, or the Cloud Agent runtime. Session storage
456
- supports the built-in Process and Worker transports. Use
454
+ checkpointing, or the Cloud Agent runtime. It works on daemon-backed queries.
455
+ Use
457
456
  `importSessionToStore(sessionId, store, options)` to copy an existing local main
458
457
  transcript, child-agent transcripts, and metadata into a store.
459
458
 
@@ -2,7 +2,9 @@ export type DefaultRuntimeTransport = 'process' | 'worker';
2
2
  /**
3
3
  * The default transport baked into the packaged SDK bundle.
4
4
  *
5
- * Development / plain `tsc` builds default to `process`. Release bundles replace
6
- * `__QODER_DEFAULT_RUNTIME_TRANSPORT__` through esbuild `define`.
5
+ * Development / plain `tsc` builds default to `process`. Legacy bundles may
6
+ * replace `__QODER_DEFAULT_RUNTIME_TRANSPORT__` through esbuild `define`; the
7
+ * value is retained for integrations that read it, while every Query now
8
+ * executes through the process-wide daemon.
7
9
  */
8
10
  export declare const DEFAULT_RUNTIME_TRANSPORT: DefaultRuntimeTransport;
@@ -2,6 +2,18 @@
2
2
  * Custom error types for the Qoder Agent SDK.
3
3
  */
4
4
  import type { SDKResultMessage } from '../protocol/messages.js';
5
+ export declare class QoderCliProcessError extends Error {
6
+ readonly code: "QODER_CLI_PROCESS_ERROR";
7
+ readonly exitCode?: number | null;
8
+ readonly signal?: NodeJS.Signals | null;
9
+ readonly stderr?: string;
10
+ constructor(message: string, options?: {
11
+ exitCode?: number | null;
12
+ signal?: NodeJS.Signals | null;
13
+ stderr?: string;
14
+ cause?: unknown;
15
+ });
16
+ }
5
17
  /** JSONL 帧超过传输预算;输入与输出使用不同错误码,避免把执行端输出问题归因于用户输入。 */
6
18
  export declare class FrameTooLargeError extends Error {
7
19
  readonly direction: 'input' | 'output';
@@ -1,41 +1,26 @@
1
1
  /**
2
- * ProcessTransport — Spawns qodercli as a child process and
3
- * manages stdin/stdout communication using JSONL (JSON Lines) format.
2
+ * ProcessTransport compatibility surface.
4
3
  *
5
- * This is the primary transport for Node.js environments. It:
6
- * 1. Builds CLI arguments from the provided options
7
- * 2. Spawns the CLI process (or delegates to a custom spawner)
8
- * 3. Reads stdout line-by-line, parsing each as JSON
9
- * 4. Writes to stdin as JSON + newline
10
- * 5. Handles graceful shutdown: close stdin → wait → SIGTERM → wait → SIGKILL
4
+ * The child-process implementation is gone: selecting this transport now runs
5
+ * the Query through the process-wide daemon. The exported types and members
6
+ * stay so existing integrations keep compiling and keep the same behavior.
11
7
  */
12
8
  import type { QueryTransportProvider, Transport } from './transport.js';
13
- import type { StdoutMessage } from '../types/control.js';
14
9
  import type { SdkPluginConfig, ToolConfig } from '../types/common.js';
15
10
  import type { PermissionMode } from '../types/permissions.js';
16
11
  import type { McpServerConfigForProcessTransport, McpServerToolPolicy } from '../types/mcp.js';
17
12
  import type { InternalAuthOptions } from '../types/auth.js';
18
13
  import type { SecurityScanOptions, SpawnedProcess, SpawnOptions, SettingSource } from '../types/options.js';
19
14
  import type { DiagnosticsSink } from './sdk-diagnostics.js';
20
- export declare class QoderCliProcessError extends Error {
21
- readonly code: "QODER_CLI_PROCESS_ERROR";
22
- readonly exitCode?: number | null;
23
- readonly signal?: NodeJS.Signals | null;
24
- readonly stderr?: string;
25
- constructor(message: string, options?: {
26
- exitCode?: number | null;
27
- signal?: NodeJS.Signals | null;
28
- stderr?: string;
29
- cause?: unknown;
30
- });
31
- }
32
- /**
33
- * Options for configuring the ProcessTransport.
34
- *
35
- * These map 1:1 to the CLI flags and environment variables that the
36
- * qodercli understands.
37
- */
15
+ export { QoderCliProcessError } from './errors.js';
16
+ type ToolsOption = string[] | {
17
+ type: 'preset';
18
+ preset: 'qodercli';
19
+ };
38
20
  export interface ProcessTransportOptions {
21
+ business?: {
22
+ type: string;
23
+ };
39
24
  /** Path to the Qoder CLI executable (binary or script) */
40
25
  pathToQoderCLIExecutable?: string;
41
26
  /** Override executable name (node, bun, deno) for script entry points */
@@ -120,95 +105,7 @@ export interface ProcessTransportOptions {
120
105
  */
121
106
  onAuthExpired?: () => void;
122
107
  }
123
- type ToolsOption = string[] | {
124
- type: 'preset';
125
- preset: 'qodercli';
126
- };
127
- export declare class ProcessTransport implements Transport, QueryTransportProvider<ProcessTransportOptions> {
108
+ export declare class ProcessTransport implements QueryTransportProvider<ProcessTransportOptions> {
128
109
  static readonly default: ProcessTransport;
129
- private process;
130
- private customHandle;
131
- private options;
132
- private ready;
133
- private closed;
134
- private shutdownStarted;
135
- private initializePromise;
136
- private authExpiredFired;
137
- private pendingInput;
138
- private diagnostics?;
139
- private processExitError;
140
- private processStopped;
141
- private closeTimer;
142
- private killTimer;
143
- private stderrTail;
144
- private launchOptionsBuilder;
145
- constructor(options?: ProcessTransportOptions);
146
110
  create(options: ProcessTransportOptions): Transport;
147
- /**
148
- * Build CLI arguments, resolve the executable, spawn the process,
149
- * and mark the transport as ready.
150
- */
151
- initialize(): Promise<void>;
152
- private _doInitialize;
153
- /** Write a JSON line to stdin. */
154
- write(data: string): void;
155
- private writeReadyLine;
156
- private flushPendingInput;
157
- /** Whether the transport is ready to send/receive. */
158
- isReady(): boolean;
159
- /** Signal that no more input will be sent (close stdin). */
160
- endInput(): void;
161
- private endReadyInput;
162
- /**
163
- * Async generator that yields parsed JSON messages from stdout.
164
- *
165
- * Uses readline to split stdout into lines. Each non-empty line is
166
- * expected to be a complete JSON object (JSONL format).
167
- *
168
- * The generator completes when:
169
- * - The readline interface closes (process exited or stdout ended)
170
- * - The transport is closed
171
- */
172
- readMessages(): AsyncGenerator<StdoutMessage, void, unknown>;
173
- /**
174
- * Close the transport with graceful shutdown:
175
- *
176
- * 1. Close stdin (signal to CLI that no more input is coming)
177
- * 2. Wait CLOSE_GRACE_MS for the process to exit on its own
178
- * 3. Send SIGTERM
179
- * 4. Wait KILL_GRACE_MS for the process to exit
180
- * 5. Send SIGKILL if still running
181
- */
182
- close(): void;
183
- /** 回收进程资源,不改变调用方主动关闭状态;异常仍由读取循环传播。 */
184
- private shutdownProcess;
185
- private hasProcessStopped;
186
- private finishProcess;
187
- private observeProcess;
188
- /**
189
- * Get the underlying process PID, if available.
190
- */
191
- get pid(): number | undefined;
192
- /**
193
- * Get the stdout stream from the process or custom handle.
194
- */
195
- private getStdout;
196
- private appendStderr;
197
- private createSpawnError;
198
- private createProcessExitError;
199
- private getStderrTail;
200
- private waitForProcessExit;
201
- /**
202
- * Resolve the executable command and arguments.
203
- *
204
- * If the CLI path is a script file (.js/.mjs/.ts/.tsx/.jsx), we need
205
- * an interpreter (node/bun/deno). Otherwise the path is a native binary
206
- * and is used directly as the command.
207
- */
208
- private resolveExecutable;
209
- /** 清理 runtime 已消费或不再可能消费的启动制品。 */
210
- private cleanupLaunchArtifacts;
211
- /** Fire `onAuthExpired` at most once per session. */
212
- private fireAuthExpired;
213
- }
214
- export {};
111
+ }
@@ -1,6 +1,16 @@
1
- import { type ProcessTransportOptions } from './process-transport.js';
1
+ import type { ProcessTransportOptions } from './process-transport.js';
2
+ import type { RuntimeLaunchOptions } from './runtime-launch-options.js';
2
3
  import type { QueryTransportProvider, Transport } from './transport.js';
4
+ /** SDK-internal options for the daemon session transport provider. */
5
+ export interface DaemonQueryTransportOptions extends RuntimeLaunchOptions {
6
+ /** SDK-internal: config root created by SessionStore materialization. */
7
+ materializedSessionConfigDir?: string;
8
+ }
9
+ /**
10
+ * Options a custom transport provider receives. Kept as the historical
11
+ * `ProcessTransportOptions` shape so existing providers keep compiling.
12
+ */
3
13
  export type QueryTransportCreateOptions = ProcessTransportOptions;
4
14
  export type QueryTransportProviderOption = QueryTransportProvider<QueryTransportCreateOptions>;
5
15
  export declare function isQueryTransportProvider(value: unknown): value is QueryTransportProviderOption;
6
- export declare function createQueryTransport(provider: QueryTransportProviderOption, options: QueryTransportCreateOptions): Transport;
16
+ export declare function createQueryTransport<T extends object>(provider: QueryTransportProvider<T>, options: T): Transport;
@@ -18,6 +18,9 @@ type ToolsOption = string[] | {
18
18
  preset: 'qodercli';
19
19
  };
20
20
  export interface RuntimeLaunchOptions {
21
+ business?: {
22
+ type: string;
23
+ };
21
24
  cwd?: string;
22
25
  env?: Record<string, string | undefined>;
23
26
  proxy?: string;
@@ -1,16 +1,14 @@
1
1
  /**
2
- * WorkerTransport — runs qoder-worker-runtime inside a Node worker thread.
2
+ * WorkerTransport compatibility surface.
3
3
  *
4
- * This transport keeps the existing SDK stream-json protocol but replaces the
5
- * child-process boundary with worker stdin/stdout/stderr streams. It is meant
6
- * for hosts that already own a Node runtime, including Node SEA hosts, and want
7
- * to avoid spawning a second qoder SEA process.
4
+ * The worker-thread implementation is gone: selecting this transport now runs
5
+ * the Query through the process-wide daemon. The exported classes, helpers and
6
+ * option types stay so existing integrations keep compiling and running.
8
7
  */
9
8
  import type { QueryTransportProvider, Transport } from './transport.js';
10
9
  import type { ProcessTransportOptions } from './process-transport.js';
11
- import type { StdoutMessage } from '../types/control.js';
12
10
  import type { DiagnosticsSink } from './sdk-diagnostics.js';
13
- import { type RuntimeLaunchOptions } from './runtime-launch-options.js';
11
+ import type { RuntimeLaunchOptions } from './runtime-launch-options.js';
14
12
  import { hasResolvableQoderWorkerRuntime, resolveQoderWorkerRuntimePath } from './worker-runtime-path.js';
15
13
  export { hasResolvableQoderWorkerRuntime, resolveQoderWorkerRuntimePath };
16
14
  export declare class QoderWorkerRuntimeError extends Error {
@@ -49,52 +47,10 @@ export interface WorkerRuntimeTransportOptions extends RuntimeLaunchOptions, Wor
49
47
  onAuthExpired?: () => void;
50
48
  }
51
49
  export declare class WorkerTransport implements QueryTransportProvider<ProcessTransportOptions> {
52
- static readonly default: WorkerTransport;
53
50
  private readonly options;
51
+ static readonly default: WorkerTransport;
54
52
  constructor(options?: WorkerTransportOptions);
53
+ /** query() 用它把 worker 选择映射成 daemon 的宿主形态。 */
54
+ getPathToQoderWorkerRuntime(): string | undefined;
55
55
  create(options: ProcessTransportOptions): Transport;
56
- }
57
- export declare class WorkerRuntimeTransport implements Transport {
58
- private worker;
59
- private options;
60
- private ready;
61
- private closed;
62
- private initializePromise;
63
- private authExpiredFired;
64
- private pendingInput;
65
- private diagnostics?;
66
- private workerExitError;
67
- private stderrTail;
68
- private observedExitCode;
69
- private launchOptionsBuilder;
70
- private closeTimer;
71
- private closePromise;
72
- private abortSignal?;
73
- private abortListener?;
74
- constructor(options?: WorkerRuntimeTransportOptions);
75
- initialize(): Promise<void>;
76
- private _doInitialize;
77
- write(data: string): void;
78
- isReady(): boolean;
79
- endInput(): void;
80
- readMessages(): AsyncGenerator<StdoutMessage, void, unknown>;
81
- close(): Promise<void>;
82
- private performClose;
83
- get threadId(): number | undefined;
84
- private writeReadyLine;
85
- private flushPendingInput;
86
- private endReadyInput;
87
- private destroyWorkerStreams;
88
- private appendStderr;
89
- private createWorkerError;
90
- private createWorkerExitError;
91
- private getStderrTail;
92
- private recordWorkerExit;
93
- private recordSuppressedWorkerExit;
94
- private formatStderrTailForDiagnostics;
95
- private waitForWorkerExit;
96
- private clearCloseTimer;
97
- private cleanupAbortListener;
98
- private cleanupLaunchArtifacts;
99
- private fireAuthExpired;
100
56
  }
@@ -17,12 +17,6 @@ export declare const SESSION_STORE_FORK_BARRIER_CAPABILITY = "session_store_fork
17
17
  */
18
18
  export declare const DAEMON_HEARTBEAT_TIMEOUT_MS = 120000;
19
19
  export declare const DAEMON_KEEP_ALIVE_CAPABILITY = "daemon_keep_alive_v1";
20
- /**
21
- * daemon 会话 close 改成「关信道即回包、后台排干 teardown」的能力位(CLI 仓镜像)。
22
- * 会话 initialize 回包声明它时,QueryRunner.close 不再隐式等 memory / evolution
23
- * flush;旧 CLI 不声明则保持原有等待语义(版本错配保护)。
24
- */
25
- export declare const DAEMON_ASYNC_SESSION_TEARDOWN_CAPABILITY = "daemon_async_session_teardown_v1";
26
20
  export interface DaemonConnectionOptions {
27
21
  input: Writable;
28
22
  output: Readable;
@@ -52,6 +46,9 @@ export interface DaemonConnectionOptions {
52
46
  heartbeatTimeoutMs?: number;
53
47
  }
54
48
  export interface DaemonInitializeOptions {
49
+ business?: {
50
+ product: string;
51
+ };
55
52
  /** Advertised in addition to the capability this SDK cannot work without. */
56
53
  capabilities?: readonly string[];
57
54
  timeoutMs?: number;
@@ -280,6 +277,7 @@ export declare class DaemonConnection {
280
277
  private readOutput;
281
278
  private acceptFrame;
282
279
  private rememberTimedOutRequestId;
280
+ private abandonSessionFromLateResponse;
283
281
  private routeSessionMessage;
284
282
  private acceptControlResponse;
285
283
  private hasPendingSessionRequest;
@@ -4,6 +4,9 @@ import type { DaemonWireSessionMessage } from './protocol.js';
4
4
  import type { DaemonConnection, DaemonSessionIdClaim } from './daemon-connection.js';
5
5
  import type { DiagnosticsSink } from '../core/sdk-diagnostics.js';
6
6
  export type DaemonSessionTransportOptions = {
7
+ business?: {
8
+ type: string;
9
+ };
7
10
  workerArgs: string[];
8
11
  cwd?: string;
9
12
  configDir?: string;
@@ -1,6 +1,12 @@
1
1
  import type { InternalAuthOptions } from '../types/auth.js';
2
+ import type { QueryTransportProvider } from '../core/transport.js';
3
+ import type { DaemonQueryTransportOptions } from '../core/query-transport.js';
2
4
  import { type Daemon } from './start-daemon.js';
3
5
  export interface InitDaemonOptions {
6
+ /** daemon 全局产品身份;初始化后不能由 Query 覆盖。 */
7
+ business?: {
8
+ product: string;
9
+ };
4
10
  auth: InternalAuthOptions;
5
11
  pathToQoderCLIExecutable?: string;
6
12
  /** 语义同 `StartDaemonOptions.executable`。 */
@@ -13,6 +19,10 @@ export interface InitDaemonOptions {
13
19
  /** 语义同 `StartDaemonOptions.vpcEndpoint`。 */
14
20
  vpcEndpoint?: string;
15
21
  env?: Record<string, string | undefined>;
22
+ /** 宿主形态:process=spawn CLI 二进制;worker=Node 跑 worker runtime。缺省 process。 */
23
+ launchMode?: 'process' | 'worker';
24
+ /** worker 形态下覆盖 worker runtime 产物路径。 */
25
+ pathToQoderWorkerRuntime?: string;
16
26
  /** 语义同 `StartDaemonOptions.stderr`:daemon 子进程 stderr 的实时回调。 */
17
27
  stderr?: (data: string) => void;
18
28
  /** 语义同 `StartDaemonOptions.debug`。 */
@@ -20,16 +30,24 @@ export interface InitDaemonOptions {
20
30
  /** 语义同 `StartDaemonOptions.debugFile`。 */
21
31
  debugFile?: string;
22
32
  }
23
- export type DaemonFallbackReason = 'protocol_version_mismatch' | 'daemon_unavailable';
24
- export type DaemonInitResult = {
25
- mode: 'daemon';
33
+ export interface GlobalDaemonHandle {
34
+ /**
35
+ * A daemon-shaped handle that resolves every call against the initialization
36
+ * started by `acquireGlobalDaemon`. It is usable before the handshake
37
+ * completes; asynchronous members wait for readiness instead of failing.
38
+ */
26
39
  daemon: Daemon;
27
- } | {
28
- mode: 'direct';
29
- reason: DaemonFallbackReason;
30
- };
40
+ transportProvider: QueryTransportProvider<DaemonQueryTransportOptions>;
41
+ }
31
42
  export declare class DaemonConfigurationConflictError extends Error {
32
43
  constructor();
33
44
  }
34
- export declare function initDaemon(options: InitDaemonOptions): Promise<DaemonInitResult>;
45
+ export declare function initDaemon(options: InitDaemonOptions): Promise<Daemon>;
46
+ /**
47
+ * Start a query handle backed by the process-wide daemon. The daemon starts
48
+ * immediately, and each Query's session transport waits for that same
49
+ * initialization; a failure rejects the Query instead of falling back to a
50
+ * direct CLI transport.
51
+ */
52
+ export declare function acquireGlobalDaemon(options: InitDaemonOptions): GlobalDaemonHandle;
35
53
  export declare function shutdownDaemon(): Promise<void>;
@@ -0,0 +1,13 @@
1
+ import type { ProcessTransportOptions } from '../core/process-transport.js';
2
+ import type { Transport } from '../core/transport.js';
3
+ /**
4
+ * Built-in Process/Worker transport selections keep their public surface but
5
+ * execute through the process-wide daemon. This adapter is used when a caller
6
+ * invokes the legacy provider's `create()` directly; `query()` routes the same
7
+ * selections without reaching the provider.
8
+ */
9
+ export interface LegacyDaemonLaunch {
10
+ readonly launchMode: 'process' | 'worker';
11
+ readonly pathToQoderWorkerRuntime?: string;
12
+ }
13
+ export declare function createLegacyDaemonTransport(options: ProcessTransportOptions, launch: LegacyDaemonLaunch): Transport;
@@ -106,6 +106,9 @@ export type DaemonWireSessionMessage = JsonObject & {
106
106
  };
107
107
  export type DaemonProtocolFrame = DaemonControlRequestFrame | DaemonControlResponseFrame | DaemonSessionUpdatedStatusEventFrame | KeepAliveFrame | DaemonProtocolErrorFrame | DaemonWireSessionMessage;
108
108
  export type InitializeDaemonParams = {
109
+ business?: {
110
+ product: string;
111
+ };
109
112
  daemon_protocol_version: typeof DAEMON_PROTOCOL_VERSION;
110
113
  sdk_version: string;
111
114
  capabilities: string[];
@@ -136,6 +139,9 @@ export type InitializeDaemonResult = {
136
139
  capabilities: string[];
137
140
  };
138
141
  export type OpenSessionParams = {
142
+ business?: {
143
+ type: string;
144
+ };
139
145
  worker_args: string[];
140
146
  cwd?: string;
141
147
  config_dir?: string;
@@ -1,6 +1,6 @@
1
1
  import type { InternalAuthOptions } from '../types/auth.js';
2
- import type { ProcessTransportOptions } from '../core/process-transport.js';
3
2
  import type { QueryTransportProvider } from '../core/transport.js';
3
+ import type { DaemonQueryTransportOptions } from '../core/query-transport.js';
4
4
  import type { DaemonGetModelsParams, DaemonValidateByokModelParams } from './protocol.js';
5
5
  import type { BYOKProviderInfo, ByokConfigCheckResult, ByokConfigInfo, ByokConfigReference, CheckByokConfigInput, CreateByokConfigInput, DeleteByokConfigInput, UpdateByokConfigInput } from '../protocol/control.js';
6
6
  import type { AccountInfo, ModelInfo, UsageInfo } from '../protocol/common.js';
@@ -16,6 +16,10 @@ export interface DaemonSessionInfo {
16
16
  updatedAt: string;
17
17
  }
18
18
  export interface StartDaemonOptions {
19
+ /** daemon 全局产品身份;不同产品使用不同 daemon。 */
20
+ business?: {
21
+ product: string;
22
+ };
19
23
  /**
20
24
  * Credentials for the daemon's own account plane and its in-process Sessions.
21
25
  *
@@ -46,6 +50,13 @@ export interface StartDaemonOptions {
46
50
  */
47
51
  heartbeatTimeoutMs?: number;
48
52
  pathToQoderCLIExecutable?: string;
53
+ /**
54
+ * 宿主形态:`process` spawn CLI 二进制;`worker` 用 Node 跑 worker runtime
55
+ * (老 Windows 无法运行 Bun 二进制时使用)。缺省 `process`。
56
+ */
57
+ launchMode?: 'process' | 'worker';
58
+ /** worker 形态下覆盖 worker runtime 产物路径;缺省用随包/已安装产物。 */
59
+ pathToQoderWorkerRuntime?: string;
49
60
  /**
50
61
  * 运行 CLI 脚本入口的解释器(node/bun/deno 等),语义与 `query()` 的
51
62
  * `Options.executable` 一致:只在解析出的 CLI 入口是脚本文件(.js/.mjs/.ts/...)
@@ -234,7 +245,7 @@ interface InternalDaemonRuntime {
234
245
  * when unset, or when the CLI does not support bypass updates).
235
246
  */
236
247
  noProxy: string | null;
237
- readonly transportProvider: QueryTransportProvider<ProcessTransportOptions>;
248
+ readonly transportProvider: QueryTransportProvider<DaemonQueryTransportOptions>;
238
249
  }
239
250
  export declare function getDaemonRuntime(daemon: Daemon): InternalDaemonRuntime | undefined;
240
251
  export declare function startDaemon(options: StartDaemonOptions): Promise<Daemon>;