@qilin-agent/sdk-client 0.0.0-stage → 3.1.3

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/lib/index.js ADDED
@@ -0,0 +1,844 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { dirname, resolve } from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { JsonRpcLineTransport, JsonRpcResponseError, JsonRpcResponseError as JsonRpcResponseError$1 } from "@qilin-agent/sdk-protocol";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ //#region lib/types/dispose.js
8
+ /**
9
+ * Private teardown ladder for the runtime subprocess: stdin EOF (cooperative
10
+ * quiesce), then SIGTERM, then SIGKILL, resolving only after the process has
11
+ * actually exited. The SDK client runs OUTSIDE any harness context, so it
12
+ * cannot ride the `qilin-subprocess` service — this module is the seam's
13
+ * documented exception for SDK-managed transports.
14
+ *
15
+ * @module @qilin-agent/sdk-client/dispose
16
+ */
17
+ /**
18
+ * Race the child's exit against a timer. Neither outcome leaves anything
19
+ * behind on the child: the exit listener is removed on timeout and the timer
20
+ * is cleared on exit, so the ladder's tiers never accumulate listeners.
21
+ */
22
+ function exitsWithin(child, ms) {
23
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
24
+ return new Promise((resolve) => {
25
+ const onExit = () => {
26
+ clearTimeout(timer);
27
+ resolve(true);
28
+ };
29
+ const timer = setTimeout(() => {
30
+ child.removeListener("exit", onExit);
31
+ resolve(false);
32
+ }, ms).unref();
33
+ child.once("exit", onExit);
34
+ });
35
+ }
36
+ /** Force-terminate the runtime and reject if no exit edge arrives within the grace. */
37
+ function forceTerminateWithin(child, ms) {
38
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
39
+ return new Promise((resolve, reject) => {
40
+ let accepted = false;
41
+ let settled = false;
42
+ const cleanup = () => {
43
+ clearTimeout(timer);
44
+ child.off("exit", onExit);
45
+ child.off("error", onError);
46
+ };
47
+ const settle = (complete) => {
48
+ if (settled) return;
49
+ settled = true;
50
+ cleanup();
51
+ complete();
52
+ };
53
+ const onExit = () => {
54
+ settle(resolve);
55
+ };
56
+ const onError = (error) => {
57
+ settle(() => {
58
+ reject(error);
59
+ });
60
+ };
61
+ child.once("exit", onExit);
62
+ child.once("error", onError);
63
+ const timer = setTimeout(() => {
64
+ const disposition = accepted ? "accepted" : "refused";
65
+ settle(() => {
66
+ reject(/* @__PURE__ */ new Error(`runtime process did not exit within ${ms}ms after SIGKILL was ${disposition}`));
67
+ });
68
+ }, ms).unref();
69
+ try {
70
+ accepted = child.kill("SIGKILL");
71
+ if (child.exitCode !== null || child.signalCode !== null) settle(resolve);
72
+ } catch (error) {
73
+ settle(() => {
74
+ reject(new Error("SIGKILL failed", { cause: error }));
75
+ });
76
+ }
77
+ });
78
+ }
79
+ /**
80
+ * Tear the runtime down to quiescence, resolving only after exit: close stdin
81
+ * and allow cooperative flush, then use the host's graceful and forced
82
+ * termination semantics. POSIX sends `SIGTERM` before `SIGKILL`; Windows
83
+ * skips directly to forced termination because Node maps both signals to
84
+ * `TerminateProcess`.
85
+ * @param child - the runtime child process to tear down.
86
+ * @param graces - the EOF and termination-confirmation windows (ms).
87
+ * @param platform - the host platform, injectable for unit coverage.
88
+ * @throws When forced termination errors or the child does not report exit
89
+ * within `disposeGraceMs`.
90
+ */
91
+ async function disposeRuntimeProcess(child, graces, platform = process.platform) {
92
+ if (child.exitCode !== null || child.signalCode !== null) return;
93
+ child.stdin?.end();
94
+ if (await exitsWithin(child, graces.disposeEofGraceMs)) return;
95
+ if (platform !== "win32") {
96
+ child.kill("SIGTERM");
97
+ if (await exitsWithin(child, graces.disposeGraceMs)) return;
98
+ }
99
+ await forceTerminateWithin(child, graces.disposeGraceMs);
100
+ }
101
+ /** Read a package manifest from one resolved package.json URL. */
102
+ function manifest(url) {
103
+ return JSON.parse(readFileSync(fileURLToPath(url), "utf8"));
104
+ }
105
+ /**
106
+ * Resolve and version-check a qilin executable from package manifests.
107
+ * @param qilinManifestUrl - resolved URL of the qilin package manifest.
108
+ * @param clientManifestUrl - resolved URL of the SDK client manifest.
109
+ * @returns the absolute qilin executable path.
110
+ */
111
+ function resolveQilinBinFromManifests(qilinManifestUrl, clientManifestUrl) {
112
+ const qilinManifest = manifest(qilinManifestUrl);
113
+ const clientManifest = manifest(clientManifestUrl);
114
+ if (typeof qilinManifest.version !== "string" || qilinManifest.version !== clientManifest.version) throw new Error(`qilin SDK client ${String(clientManifest.version)} requires the same qilin version, got ${String(qilinManifest.version)}`);
115
+ const bin = typeof qilinManifest.bin === "object" && qilinManifest.bin !== null ? qilinManifest.bin.qilin : qilinManifest.bin;
116
+ if (typeof bin !== "string" || bin === "") throw new Error("@qilin-agent/cli declares no qilin executable");
117
+ return resolve(dirname(fileURLToPath(qilinManifestUrl)), bin);
118
+ }
119
+ /**
120
+ * Resolve the Node launch for one same-version qilin package.
121
+ * @param qilinManifestUrl - resolved URL of the qilin package manifest.
122
+ * @param clientManifestUrl - resolved URL of the SDK client manifest.
123
+ * @param sourceLoaderUrl - optional absolute tsx loader URL for deterministic tests.
124
+ * @returns built output, or the source entry plus its compatibility patch and tsx environment.
125
+ */
126
+ function resolveQilinNodeLaunchFromManifests(qilinManifestUrl, clientManifestUrl, sourceLoaderUrl) {
127
+ const bin = resolveQilinBinFromManifests(qilinManifestUrl, clientManifestUrl);
128
+ if (existsSync(bin)) return {
129
+ nodeArgs: [bin],
130
+ patches: [],
131
+ environment: {}
132
+ };
133
+ const packageDir = dirname(fileURLToPath(qilinManifestUrl));
134
+ const sourceBin = resolve(packageDir, "src/bin.ts");
135
+ const sourcePatch = resolve(packageDir, "src/sdk-source.cordis.patch.yml");
136
+ const sourceTsconfig = resolve(packageDir, "tsconfig.json");
137
+ if (!existsSync(sourceBin) || !existsSync(sourcePatch) || !existsSync(sourceTsconfig)) throw new Error(`@qilin-agent/cli is missing its built executable ${bin} and complete source launch files ${sourceBin}, ${sourcePatch}, ${sourceTsconfig}`);
138
+ return {
139
+ nodeArgs: [
140
+ "--import",
141
+ sourceLoaderUrl ?? import.meta.resolve("tsx/esm"),
142
+ sourceBin
143
+ ],
144
+ patches: [sourcePatch],
145
+ environment: { TSX_TSCONFIG_PATH: sourceTsconfig }
146
+ };
147
+ }
148
+ /**
149
+ * Resolve the installed qilin package to a built or source Node launch.
150
+ * @returns the launch descriptor for the current checkout or installed package.
151
+ */
152
+ function installedQilinNodeLaunch() {
153
+ return resolveQilinNodeLaunchFromManifests(import.meta.resolve("@qilin-agent/cli/package.json"), new URL("../package.json", import.meta.url).href);
154
+ }
155
+ /**
156
+ * Resolve caller-relative filesystem inputs and construct canonical qilin argv.
157
+ * @param options - public SDK launch options.
158
+ * @param callerCwd - parent-process directory used for lexical resolution.
159
+ * @returns one generic subprocess spec for the JSON-RPC transport.
160
+ */
161
+ function resolveQilinLaunch(options = {}, callerCwd = process.cwd()) {
162
+ const profile = options.profile ?? "sdk";
163
+ const qilinLaunch = options.qilinBin === void 0 ? installedQilinNodeLaunch() : {
164
+ nodeArgs: [resolve(callerCwd, options.qilinBin)],
165
+ patches: [],
166
+ environment: {}
167
+ };
168
+ const patches = [...qilinLaunch.patches, ...(options.patches ?? []).map((path) => resolve(callerCwd, path))];
169
+ const qilinHome = options.qilinHome === void 0 ? void 0 : resolve(callerCwd, options.qilinHome);
170
+ return {
171
+ command: process.execPath,
172
+ args: [
173
+ ...qilinLaunch.nodeArgs,
174
+ "--profile",
175
+ profile,
176
+ ...patches.flatMap((path) => ["--patch", path])
177
+ ],
178
+ ...options.processCwd === void 0 ? {} : { cwd: resolve(callerCwd, options.processCwd) },
179
+ environment: () => ({
180
+ ...options.env ?? process.env,
181
+ ...qilinLaunch.environment,
182
+ ...qilinHome === void 0 ? {} : { QILIN_HOME: qilinHome }
183
+ }),
184
+ description: `qilin profile ${JSON.stringify(profile)}`,
185
+ initializeTimeoutMs: options.initializeTimeoutMs ?? 1e4,
186
+ ...options.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: options.requestTimeoutMs },
187
+ ...options.shutdownTimeoutMs === void 0 ? {} : { shutdownTimeoutMs: options.shutdownTimeoutMs },
188
+ ...options.disposeEofGraceMs === void 0 ? {} : { disposeEofGraceMs: options.disposeEofGraceMs },
189
+ ...options.disposeGraceMs === void 0 ? {} : { disposeGraceMs: options.disposeGraceMs }
190
+ };
191
+ }
192
+ //#endregion
193
+ //#region lib/types/client.js
194
+ /**
195
+ * Low-level JSON-RPC client for a QiLin SDK runtime subprocess.
196
+ * {@link HarnessClient} owns the child process: it spawns the runtime, speaks
197
+ * the `@qilin-agent/sdk-protocol` wire over the child's stdio, fans
198
+ * server notifications out to subscriptions, and tears the child down to
199
+ * quiescence through a private EOF → SIGTERM → SIGKILL ladder. The design
200
+ * twin is the Python SDK's `HarnessClient` (`python/sdk`); both drive the
201
+ * same runtime protocol. This client runs OUTSIDE any harness context, so it
202
+ * spawns directly rather than through the `qilin-subprocess` service — the
203
+ * seam's documented exception for SDK-managed transports.
204
+ *
205
+ * @module @qilin-agent/sdk-client/client
206
+ */
207
+ /** Retained stderr lines used to diagnose an unexpected runtime death. */
208
+ const STDERR_TAIL_LIMIT = 400;
209
+ /** Grace for the runtime's stdio streams to settle after its exit edge. */
210
+ const STREAM_SETTLE_MS = 100;
211
+ /**
212
+ * The runtime subprocess is gone or unusable: it exited, its stdio closed, or
213
+ * it was never launchable. The message carries the exit code and a stderr
214
+ * tail when available.
215
+ */
216
+ var TransportClosedError = class extends Error {
217
+ /** @param message - the failure description, including any stderr tail. */
218
+ constructor(message) {
219
+ super(message);
220
+ this.name = "TransportClosedError";
221
+ }
222
+ };
223
+ /** A request exceeded {@link HarnessClientOptions.requestTimeoutMs}. */
224
+ var RequestTimeoutError = class extends Error {
225
+ /** @param message - which method timed out. */
226
+ constructor(message) {
227
+ super(message);
228
+ this.name = "RequestTimeoutError";
229
+ }
230
+ };
231
+ /**
232
+ * The runtime answered outside its documented protocol (for example a
233
+ * `session/prompt` response without `accepted: true`).
234
+ */
235
+ var SdkProtocolError = class extends Error {
236
+ /** @param message - the protocol violation description. */
237
+ constructor(message) {
238
+ super(message);
239
+ this.name = "SdkProtocolError";
240
+ }
241
+ };
242
+ /** Internal producer side of a public notification subscription. */
243
+ var NotificationSubscriptionImpl = class {
244
+ state;
245
+ unsubscribe;
246
+ constructor(state, unsubscribe) {
247
+ this.state = state;
248
+ this.unsubscribe = unsubscribe;
249
+ }
250
+ /**
251
+ * Await the next matching notification.
252
+ * @returns the notification; after the runtime died, drains what was
253
+ * already delivered and then rejects; after {@link close}, rejects
254
+ * immediately (the queue is dropped).
255
+ */
256
+ next() {
257
+ const queued = this.state.queue.shift();
258
+ if (queued !== void 0) return Promise.resolve(queued);
259
+ if (this.state.failure !== void 0) return Promise.reject(this.state.failure);
260
+ return new Promise((resolve, reject) => {
261
+ this.state.waiters.push({
262
+ resolve,
263
+ reject
264
+ });
265
+ });
266
+ }
267
+ /**
268
+ * Drain one already-delivered notification without waiting.
269
+ * @returns the next queued notification, or `undefined` when none is queued.
270
+ */
271
+ tryNext() {
272
+ return this.state.queue.shift();
273
+ }
274
+ /** Detach from the client; queued items drop and pending waiters reject. */
275
+ close() {
276
+ this.unsubscribe();
277
+ this.state.queue.length = 0;
278
+ this.fail(new TransportClosedError("notification subscription closed"));
279
+ }
280
+ /**
281
+ * Reject pending and future waits (delivery stops; the first failure wins).
282
+ * Already-queued notifications remain drainable via {@link next}/{@link tryNext}.
283
+ * @param error - the terminal failure delivered to waiters.
284
+ */
285
+ fail(error) {
286
+ this.state.failure ??= error;
287
+ for (const waiter of this.state.waiters.splice(0)) waiter.reject(this.state.failure);
288
+ }
289
+ /**
290
+ * Deliver one notification to a waiter or the queue when the filter
291
+ * matches. A throwing filter fails only THIS subscription (detached, the
292
+ * throw becomes its terminal error) — it never disturbs sibling
293
+ * subscriptions or the transport's read loop.
294
+ * @param notification - the wire notification to deliver.
295
+ */
296
+ push(notification) {
297
+ let matches;
298
+ try {
299
+ matches = this.state.filter === void 0 || this.state.filter(notification);
300
+ } catch (error) {
301
+ this.unsubscribe();
302
+ this.fail(error instanceof Error ? error : new Error(String(error)));
303
+ return;
304
+ }
305
+ if (!matches) return;
306
+ const waiter = this.state.waiters.shift();
307
+ if (waiter !== void 0) waiter.resolve(notification);
308
+ else this.state.queue.push(notification);
309
+ }
310
+ /**
311
+ * Iterate notifications until the subscription or runtime closes (the
312
+ * terminating rejection propagates).
313
+ * @returns an async iterator over {@link next} results.
314
+ */
315
+ async *[Symbol.asyncIterator]() {
316
+ for (;;) yield await this.next();
317
+ }
318
+ };
319
+ /**
320
+ * JSON-RPC client for the QiLin SDK runtime over subprocess stdio.
321
+ *
322
+ * The subprocess starts lazily on {@link start} and is owned by this instance
323
+ * until {@link close}, which requests protocol `shutdown` and then walks the
324
+ * shared EOF → SIGTERM → SIGKILL dispose ladder to quiescence. There is no
325
+ * wire-level cancel: a timed-out request stays running server-side until the
326
+ * runtime is closed.
327
+ */
328
+ var HarnessClient = class {
329
+ /** Original public qilin launch and timeout options for this client. */
330
+ options;
331
+ runtime;
332
+ child;
333
+ transport;
334
+ stderrTail = [];
335
+ subscriptions = /* @__PURE__ */ new Map();
336
+ sessionParents = /* @__PURE__ */ new Map();
337
+ subscriptionSerial = 0;
338
+ exitCode;
339
+ spawnError;
340
+ streamsSettled = Promise.resolve();
341
+ closeTask;
342
+ constructor(options = {}, runtime) {
343
+ this.options = options;
344
+ this.runtime = runtime ?? resolveQilinLaunch(options);
345
+ }
346
+ /**
347
+ * Spawn the runtime subprocess and start reading frames. Idempotent while
348
+ * the process is live; rejects reuse after {@link close}.
349
+ */
350
+ start() {
351
+ if (this.closeTask !== void 0) throw new TransportClosedError("QiLin runtime client is closed");
352
+ if (this.child !== void 0) return;
353
+ const child = spawn(this.runtime.command, this.runtime.args, {
354
+ cwd: this.runtime.cwd,
355
+ env: this.runtime.environment(),
356
+ stdio: [
357
+ "pipe",
358
+ "pipe",
359
+ "pipe"
360
+ ]
361
+ });
362
+ this.child = child;
363
+ child.once("error", (error) => {
364
+ this.spawnError = error;
365
+ this.transport?.close();
366
+ this.failSubscriptions(this.closedError("QiLin runtime failed to start"));
367
+ });
368
+ /* v8 ignore next */
369
+ child.stdin.on("error", () => {});
370
+ let stderrBuffer = "";
371
+ child.stderr.setEncoding("utf8");
372
+ child.stderr.on("data", (chunk) => {
373
+ stderrBuffer += chunk;
374
+ const newline = stderrBuffer.lastIndexOf("\n");
375
+ if (newline >= 0) {
376
+ this.appendStderr(stderrBuffer.slice(0, newline).split("\n"));
377
+ stderrBuffer = stderrBuffer.slice(newline + 1);
378
+ }
379
+ });
380
+ let signalStreamsSettled;
381
+ this.streamsSettled = new Promise((resolve) => {
382
+ signalStreamsSettled = resolve;
383
+ });
384
+ const settled = {
385
+ stderr: false,
386
+ exited: false
387
+ };
388
+ const maybeSettle = () => {
389
+ if (settled.stderr && settled.exited) signalStreamsSettled();
390
+ };
391
+ child.stderr.once("close", () => {
392
+ if (stderrBuffer.length > 0) this.appendStderr([stderrBuffer]);
393
+ settled.stderr = true;
394
+ maybeSettle();
395
+ });
396
+ child.once("exit", (code) => {
397
+ this.exitCode = code;
398
+ settled.exited = true;
399
+ maybeSettle();
400
+ this.failSubscriptions(this.closedError("QiLin runtime exited"));
401
+ });
402
+ child.once("close", () => {
403
+ this.transport?.close();
404
+ });
405
+ const transport = new JsonRpcLineTransport(child.stdout, child.stdin);
406
+ transport.onNotification((method, params) => {
407
+ this.dispatchNotification({
408
+ method,
409
+ params
410
+ });
411
+ });
412
+ transport.start();
413
+ this.transport = transport;
414
+ }
415
+ /**
416
+ * Perform the process-wide handshake.
417
+ * @param params - workspace cwd plus the provider/model route.
418
+ * @returns the runtime's wire identity.
419
+ */
420
+ async initialize(params) {
421
+ const result = await this.request("initialize", { ...params }, this.runtime.initializeTimeoutMs);
422
+ 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
+ return { serverInfo: {
424
+ name: result.serverInfo.name,
425
+ version: result.serverInfo.version
426
+ } };
427
+ }
428
+ /**
429
+ * Queue one prompt and return its durable inbox identity.
430
+ * @param sessionId - target session; an unknown id creates it.
431
+ * @param contentBlocks - the user message, sent verbatim.
432
+ * @returns the queued message id.
433
+ */
434
+ async prompt(sessionId, contentBlocks) {
435
+ const params = {
436
+ sessionId,
437
+ contentBlocks
438
+ };
439
+ const result = await this.request("session/prompt", { ...params });
440
+ if (!isRecord(result) || typeof result.messageId !== "string") throw new SdkProtocolError(`session/prompt returned no message id: ${JSON.stringify(result)}`);
441
+ return result.messageId;
442
+ }
443
+ /**
444
+ * Send one JSON-RPC request and await its result.
445
+ * @param method - the wire method name.
446
+ * @param params - the params object; omitted params send `{}`.
447
+ * @param timeoutMs - per-call override of {@link HarnessClientOptions.requestTimeoutMs}.
448
+ * @returns the raw result; rejects with {@link JsonRpcResponseError} on a
449
+ * protocol error response, {@link RequestTimeoutError} on timeout, and
450
+ * {@link TransportClosedError} when the runtime is gone.
451
+ */
452
+ async request(method, params, timeoutMs) {
453
+ this.start();
454
+ if (this.exitCode !== void 0 || this.spawnError !== void 0) {
455
+ await this.settleStreams();
456
+ throw this.closedError("QiLin runtime is not running");
457
+ }
458
+ const transport = this.transport;
459
+ /* v8 ignore next -- start() either sets the transport or throws */
460
+ if (transport === void 0) throw new TransportClosedError("QiLin runtime is not running");
461
+ const timeout = timeoutMs ?? this.runtime.requestTimeoutMs;
462
+ try {
463
+ if (timeout === void 0) return await transport.request(method, params ?? {});
464
+ const abandon = new AbortController();
465
+ const timer = setTimeout(() => {
466
+ const stderr = this.stderrTail.length === 0 ? "" : `; stderr tail:\n${this.stderrTail.join("\n")}`;
467
+ abandon.abort(new RequestTimeoutError(`${method} timed out after ${timeout}ms waiting for ${this.runtime.description}${stderr}`));
468
+ }, timeout);
469
+ try {
470
+ return await transport.request(method, params ?? {}, abandon.signal);
471
+ } finally {
472
+ clearTimeout(timer);
473
+ }
474
+ } catch (error) {
475
+ if (error instanceof JsonRpcResponseError$1 || error instanceof RequestTimeoutError) throw error;
476
+ await this.settleStreams();
477
+ throw this.closedError(errorMessage(error));
478
+ }
479
+ }
480
+ /**
481
+ * Subscribe to server notifications.
482
+ * @param filter - optional predicate; omitted means every notification.
483
+ * @returns the subscription handle; close it to stop delivery. After
484
+ * {@link close} or runtime death the handle is born failed — there is no
485
+ * producer left, so `next()` rejects instead of waiting forever.
486
+ */
487
+ subscribe(filter) {
488
+ const id = String(this.subscriptionSerial++);
489
+ const subscription = new NotificationSubscriptionImpl({
490
+ queue: [],
491
+ waiters: [],
492
+ filter,
493
+ failure: void 0
494
+ }, () => {
495
+ this.subscriptions.delete(id);
496
+ });
497
+ if (this.closeTask !== void 0 || this.exitCode !== void 0 || this.spawnError !== void 0) {
498
+ subscription.fail(this.closedError("QiLin runtime closed"));
499
+ return subscription;
500
+ }
501
+ this.subscriptions.set(id, subscription);
502
+ return subscription;
503
+ }
504
+ /**
505
+ * Subscribe to one session and the descendants discovered from
506
+ * `subagent.started` lineage edges. The runtime notifies for every session
507
+ * in its context, so this client applies the scope.
508
+ * @param sessionId - the root session id.
509
+ * @returns the filtered subscription handle.
510
+ */
511
+ subscribeSessionTree(sessionId) {
512
+ return this.subscribe((notification) => {
513
+ const params = notification.params;
514
+ if (notification.method === "subagent.started" || notification.method === "subagent.finished") {
515
+ const parentId = params.parentSessionId;
516
+ if (typeof parentId === "string" && this.isDescendantOf(parentId, sessionId)) return true;
517
+ return params.childSessionId === sessionId;
518
+ }
519
+ const relatedId = params.sessionId;
520
+ return typeof relatedId === "string" && this.isDescendantOf(relatedId, sessionId);
521
+ });
522
+ }
523
+ /**
524
+ * Shut the runtime down and reap it: a best-effort protocol `shutdown`
525
+ * bounded by `shutdownTimeoutMs`, then the shared stdin-EOF → SIGTERM →
526
+ * SIGKILL ladder until the process actually exited. Idempotent.
527
+ * @returns settlement of the complete teardown.
528
+ */
529
+ close() {
530
+ this.closeTask ??= this.performClose();
531
+ return this.closeTask;
532
+ }
533
+ async performClose() {
534
+ const child = this.child;
535
+ if (child === void 0) return;
536
+ try {
537
+ await this.request("shutdown", void 0, this.runtime.shutdownTimeoutMs ?? 1e3);
538
+ } catch (error) {
539
+ this.appendStderr([`shutdown request failed: ${errorMessage(error)}`]);
540
+ }
541
+ await disposeRuntimeProcess(child, {
542
+ disposeEofGraceMs: this.runtime.disposeEofGraceMs ?? 6e3,
543
+ disposeGraceMs: this.runtime.disposeGraceMs ?? 3e3
544
+ });
545
+ this.transport?.close();
546
+ this.failSubscriptions(this.closedError("QiLin runtime closed"));
547
+ }
548
+ dispatchNotification(notification) {
549
+ this.recordSessionRelationship(notification);
550
+ for (const subscription of this.subscriptions.values()) subscription.push(notification);
551
+ }
552
+ recordSessionRelationship(notification) {
553
+ if (notification.method !== "subagent.started") return;
554
+ const parentId = notification.params.parentSessionId;
555
+ const childId = notification.params.childSessionId;
556
+ if (typeof parentId === "string" && parentId !== "" && typeof childId === "string" && childId !== "" && parentId !== childId) this.sessionParents.set(childId, parentId);
557
+ }
558
+ isDescendantOf(sessionId, rootSessionId) {
559
+ const visited = /* @__PURE__ */ new Set();
560
+ let current = sessionId;
561
+ while (!visited.has(current)) {
562
+ if (current === rootSessionId) return true;
563
+ visited.add(current);
564
+ const parent = this.sessionParents.get(current);
565
+ if (parent === void 0) return false;
566
+ current = parent;
567
+ }
568
+ /* v8 ignore next */
569
+ return false;
570
+ }
571
+ failSubscriptions(error) {
572
+ for (const subscription of this.subscriptions.values()) subscription.fail(error);
573
+ }
574
+ appendStderr(lines) {
575
+ const kept = lines.filter((line) => line.length > 0);
576
+ this.stderrTail.push(...kept);
577
+ if (this.stderrTail.length > STDERR_TAIL_LIMIT) this.stderrTail.splice(0, this.stderrTail.length - STDERR_TAIL_LIMIT);
578
+ }
579
+ settleStreams() {
580
+ return Promise.race([this.streamsSettled, new Promise((resolve) => {
581
+ setTimeout(resolve, STREAM_SETTLE_MS);
582
+ })]);
583
+ }
584
+ closedError(reason) {
585
+ const parts = [`${this.runtime.description}: ${reason}`];
586
+ if (this.spawnError !== void 0) parts.push(`spawn error: ${this.spawnError.message}`);
587
+ if (this.exitCode !== void 0) parts.push(`exit code: ${String(this.exitCode)}`);
588
+ if (this.stderrTail.length > 0) parts.push(`stderr tail:\n${this.stderrTail.join("\n")}`);
589
+ return new TransportClosedError(parts.join("\n"));
590
+ }
591
+ };
592
+ /**
593
+ * Whether `value` is a plain JSON object (the wire-boundary shape probe).
594
+ * @param value - the wire value to probe.
595
+ * @returns `true` iff `value` is a non-null, non-array object.
596
+ */
597
+ function isRecord(value) {
598
+ return typeof value === "object" && value !== null && !Array.isArray(value);
599
+ }
600
+ /** The message of a thrown value (the transport only throws `Error`s; `String` covers the rest). */
601
+ function errorMessage(error) {
602
+ /* v8 ignore next -- the transport and dispose ladder reject only with Errors */
603
+ return error instanceof Error ? error.message : String(error);
604
+ }
605
+ //#endregion
606
+ //#region lib/types/api.js
607
+ /**
608
+ * High-level run API over {@link HarnessClient}: `DeepSeekHarness` owns one
609
+ * runtime subprocess across many sessions; `HarnessSession.run` sends a
610
+ * prompt and settles when the whole agent next becomes idle.
611
+ *
612
+ * @module @qilin-agent/sdk-client/api
613
+ */
614
+ /**
615
+ * Reusable SDK for running QiLin agent turns in a runtime
616
+ * subprocess. The subprocess starts lazily on first use and stays owned by
617
+ * this instance until {@link close}; always close (or `await using`) so the
618
+ * child is reaped.
619
+ */
620
+ var DeepSeekHarness = class {
621
+ clientInstance;
622
+ createClient;
623
+ cwd;
624
+ provider;
625
+ model;
626
+ reasoningEffort;
627
+ maxTokens;
628
+ initialized;
629
+ closed = false;
630
+ constructor(options = {}, clientFactory) {
631
+ this.createClient = clientFactory ?? (() => new HarnessClient(options));
632
+ this.clientInstance = this.createClient();
633
+ this.cwd = resolve(options.cwd ?? options.processCwd ?? process.cwd());
634
+ this.provider = options.provider ?? "deepseek-official";
635
+ this.model = options.model ?? "deepseek-v4-flash";
636
+ this.reasoningEffort = options.reasoningEffort;
637
+ this.maxTokens = options.maxTokens;
638
+ }
639
+ /**
640
+ * The underlying JSON-RPC client (exposed for low-level access). A failed
641
+ * handshake swaps in a fresh instance only after cleanup proves the runtime
642
+ * exited; cleanup failure retains this client, so do not cache it across a
643
+ * failed {@link start}.
644
+ * @returns the client currently owning the runtime subprocess.
645
+ */
646
+ get client() {
647
+ return this.clientInstance;
648
+ }
649
+ /**
650
+ * Start the subprocess and perform the `initialize` handshake once. On
651
+ * failure, successful SDK-owned cleanup reaps the runtime and installs a
652
+ * fresh client (`HarnessClient.close` is permanent), so a later call retries
653
+ * with a new subprocess unless {@link close} already ended this harness. If
654
+ * cleanup also fails, rejects with an `AggregateError` whose ordered errors
655
+ * preserve both causes and retains the failed client rather than spawning
656
+ * alongside a process whose exit was not proved.
657
+ * @returns settlement of the (memoized) handshake.
658
+ */
659
+ start() {
660
+ this.initialized ??= (async () => {
661
+ try {
662
+ this.clientInstance.start();
663
+ await this.clientInstance.initialize({
664
+ cwd: this.cwd,
665
+ provider: this.provider,
666
+ model: this.model,
667
+ ...this.reasoningEffort === void 0 ? {} : { reasoningEffort: this.reasoningEffort },
668
+ ...this.maxTokens === void 0 ? {} : { maxTokens: this.maxTokens }
669
+ });
670
+ } catch (error) {
671
+ this.initialized = void 0;
672
+ try {
673
+ await this.clientInstance.close();
674
+ } catch (cleanupError) {
675
+ throw new AggregateError([error, cleanupError], "QiLin initialization and cleanup failed");
676
+ }
677
+ if (!this.closed) this.clientInstance = this.createClient();
678
+ throw error;
679
+ }
680
+ })();
681
+ return this.initialized;
682
+ }
683
+ /**
684
+ * Open a session handle (no wire traffic; the runtime creates the session
685
+ * on its first prompt).
686
+ * @param sessionId - explicit id to reuse; omitted mints a fresh one.
687
+ * @returns the session handle.
688
+ */
689
+ session(sessionId) {
690
+ return new HarnessSession(this, sessionId ?? `session-${randomUUID().replaceAll("-", "")}`);
691
+ }
692
+ /**
693
+ * Run one prompt on a fresh (or named) session.
694
+ * @param input - prompt text, or content blocks sent verbatim.
695
+ * @param options - optional session id and per-notification observer.
696
+ * @returns the owned activity interval.
697
+ */
698
+ run(input, options) {
699
+ return this.session(options?.sessionId).run(input, options);
700
+ }
701
+ /**
702
+ * Shut down and reap the runtime subprocess. Idempotent and terminal —
703
+ * a closed harness no longer retries a failed handshake.
704
+ * @returns settlement of the complete teardown.
705
+ */
706
+ close() {
707
+ this.closed = true;
708
+ return this.clientInstance.close();
709
+ }
710
+ /**
711
+ * `await using` support: {@link close}.
712
+ * @returns settlement of the teardown.
713
+ */
714
+ [Symbol.asyncDispose]() {
715
+ return this.close();
716
+ }
717
+ };
718
+ /**
719
+ * One SDK session: a stable id plus owned activity intervals.
720
+ */
721
+ var HarnessSession = class {
722
+ harness;
723
+ id;
724
+ /**
725
+ * @param harness - the owning harness (supplies the client and handshake).
726
+ * @param id - the wire session id this handle runs on.
727
+ */
728
+ constructor(harness, id) {
729
+ this.harness = harness;
730
+ this.id = id;
731
+ }
732
+ /**
733
+ * Queue one prompt, then observe the whole session through its next idle.
734
+ * @param input - prompt text, or content blocks sent verbatim.
735
+ * @param options - optional per-notification observer.
736
+ * @returns the owned activity interval; rejects on transport loss, timeout,
737
+ * or a protocol error.
738
+ */
739
+ async run(input, options) {
740
+ await this.harness.start();
741
+ const client = this.harness.client;
742
+ const contentBlocks = normalizeInput(input);
743
+ const events = [];
744
+ const notifications = [];
745
+ const subscription = client.subscribeSessionTree(this.id);
746
+ const collect = (notification) => {
747
+ if (notification.method === "session.event" && notification.params.sessionId === this.id) {
748
+ const event = validatedSessionEvent(notification.params.event);
749
+ notifications.push(notification);
750
+ options?.onNotification?.(notification);
751
+ events.push(event);
752
+ return;
753
+ }
754
+ notifications.push(notification);
755
+ options?.onNotification?.(notification);
756
+ };
757
+ try {
758
+ const messageId = await client.prompt(this.id, contentBlocks);
759
+ let received = false;
760
+ while (true) {
761
+ const notification = await subscription.next();
762
+ if (!received) {
763
+ if (notification.method !== "session.event" || notification.params.sessionId !== this.id || !isInboxReceipt(notification.params.event, messageId)) continue;
764
+ received = true;
765
+ }
766
+ collect(notification);
767
+ if (notification.method === "session.status" && notification.params.sessionId === this.id && notification.params.status === "idle") break;
768
+ }
769
+ } finally {
770
+ subscription.close();
771
+ }
772
+ return {
773
+ sessionId: this.id,
774
+ finalResponse: finalResponse(events),
775
+ events,
776
+ notifications
777
+ };
778
+ }
779
+ };
780
+ /**
781
+ * Normalize run input: a string becomes one text block; blocks pass verbatim.
782
+ * @param input - prompt text or content blocks.
783
+ * @returns the content blocks to send.
784
+ */
785
+ function normalizeInput(input) {
786
+ return typeof input === "string" ? [{
787
+ type: "text",
788
+ text: input
789
+ }] : input;
790
+ }
791
+ /** Validate the provider-read fields of one wire turn-end reason. */
792
+ function validatedTurnEndReason(value) {
793
+ if (!isRecord(value) || typeof value.kind !== "string") throw new SdkProtocolError(`turn/end carried no reason envelope: ${JSON.stringify(value)}`);
794
+ if (value.kind === "aborted") {
795
+ if (!isRecord(value.reason) || typeof value.reason.kind !== "string") throw new SdkProtocolError(`turn/end carried a malformed aborted reason: ${JSON.stringify(value)}`);
796
+ switch (value.reason.kind) {
797
+ case "user":
798
+ case "parent":
799
+ case "disposed":
800
+ case "legacy": break;
801
+ case "hook":
802
+ if (typeof value.reason.reason !== "string") throw new SdkProtocolError(`turn/end carried a malformed hook abort reason: ${JSON.stringify(value)}`);
803
+ break;
804
+ default: throw new SdkProtocolError(`turn/end carried an unknown abort reason: ${JSON.stringify(value)}`);
805
+ }
806
+ }
807
+ return value;
808
+ }
809
+ /** Validate the fields in a wire `session.event` envelope before returning the typed result. */
810
+ function validatedSessionEvent(value) {
811
+ if (!isRecord(value) || typeof value.type !== "string") throw new SdkProtocolError(`session.event carried no event envelope: ${JSON.stringify(value)}`);
812
+ if (value.type === "assistant/message") {
813
+ const message = isRecord(value.data) ? value.data.message : void 0;
814
+ const content = isRecord(message) ? message.content : void 0;
815
+ if (!Array.isArray(content) || !content.every((block) => isRecord(block) && typeof block.type === "string")) throw new SdkProtocolError(`assistant/message event carried malformed content: ${JSON.stringify(value)}`);
816
+ }
817
+ if (value.type === "turn/end") {
818
+ const data = isRecord(value.data) ? value.data : void 0;
819
+ if (data === void 0) throw new SdkProtocolError(`turn/end event carried malformed data: ${JSON.stringify(value)}`);
820
+ validatedTurnEndReason(data.reason);
821
+ }
822
+ return value;
823
+ }
824
+ /** Whether a raw session event is the durable enqueue receipt for `messageId`. */
825
+ function isInboxReceipt(value, messageId) {
826
+ if (!isRecord(value) || value.type !== "agent/inbox/spliced" || !isRecord(value.data)) return false;
827
+ const inserted = value.data.inserted;
828
+ return Array.isArray(inserted) && inserted.some((message) => isRecord(message) && message.id === messageId);
829
+ }
830
+ /**
831
+ * Extract the concatenated text of the last assistant message.
832
+ * @param events - the activity interval's `session.event` payloads in wire order.
833
+ * @returns the final response text, or `''` when no assistant message exists.
834
+ */
835
+ function finalResponse(events) {
836
+ for (let index = events.length - 1; index >= 0; index--) {
837
+ const event = events[index];
838
+ if (event?.type !== "assistant/message") continue;
839
+ return event.data.message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
840
+ }
841
+ return "";
842
+ }
843
+ //#endregion
844
+ export { DeepSeekHarness, HarnessClient, HarnessSession, JsonRpcResponseError, RequestTimeoutError, SdkProtocolError, TransportClosedError };