@qilin-agent/sdk-client 0.0.0-stage → 3.1.4
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/LICENSE +21 -0
- package/README.i18n.yaml +55 -0
- package/README.md +135 -2
- package/README.zh.md +136 -0
- package/lib/index.js +886 -0
- package/lib/types/api.d.ts +127 -0
- package/lib/types/client.d.ts +163 -0
- package/lib/types/dispose.d.ts +27 -0
- package/lib/types/index.d.ts +17 -0
- package/lib/types/launch.d.ts +58 -0
- package/lib/types/types.d.ts +77 -0
- package/package.json +43 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
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
|
+
* Read a Session's effective working directory, recovering it if missing.
|
|
445
|
+
* @param sessionId - target Session; an unknown id creates it.
|
|
446
|
+
* @returns the absolute effective directory.
|
|
447
|
+
*/
|
|
448
|
+
getWorkingDirectory(sessionId) {
|
|
449
|
+
return this.workingDirectoryRequest("session/working-directory/get", { sessionId });
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Change a Session's effective directory without changing origin or permissions.
|
|
453
|
+
* @param sessionId - target Session; an unknown id creates it.
|
|
454
|
+
* @param path - absolute or Session-current-directory-relative path.
|
|
455
|
+
* @returns the validated absolute directory.
|
|
456
|
+
*/
|
|
457
|
+
setWorkingDirectory(sessionId, path) {
|
|
458
|
+
return this.workingDirectoryRequest("session/working-directory/set", {
|
|
459
|
+
sessionId,
|
|
460
|
+
path
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
async workingDirectoryRequest(method, params) {
|
|
464
|
+
const result = await this.request(method, params);
|
|
465
|
+
if (!isRecord(result) || typeof result.cwd !== "string") throw new SdkProtocolError(`${method} returned no working directory: ${JSON.stringify(result)}`);
|
|
466
|
+
return result.cwd;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Send one JSON-RPC request and await its result.
|
|
470
|
+
* @param method - the wire method name.
|
|
471
|
+
* @param params - the params object; omitted params send `{}`.
|
|
472
|
+
* @param timeoutMs - per-call override of {@link HarnessClientOptions.requestTimeoutMs}.
|
|
473
|
+
* @returns the raw result; rejects with {@link JsonRpcResponseError} on a
|
|
474
|
+
* protocol error response, {@link RequestTimeoutError} on timeout, and
|
|
475
|
+
* {@link TransportClosedError} when the runtime is gone.
|
|
476
|
+
*/
|
|
477
|
+
async request(method, params, timeoutMs) {
|
|
478
|
+
this.start();
|
|
479
|
+
if (this.exitCode !== void 0 || this.spawnError !== void 0) {
|
|
480
|
+
await this.settleStreams();
|
|
481
|
+
throw this.closedError("QiLin runtime is not running");
|
|
482
|
+
}
|
|
483
|
+
const transport = this.transport;
|
|
484
|
+
/* v8 ignore next -- start() either sets the transport or throws */
|
|
485
|
+
if (transport === void 0) throw new TransportClosedError("QiLin runtime is not running");
|
|
486
|
+
const timeout = timeoutMs ?? this.runtime.requestTimeoutMs;
|
|
487
|
+
try {
|
|
488
|
+
if (timeout === void 0) return await transport.request(method, params ?? {});
|
|
489
|
+
const abandon = new AbortController();
|
|
490
|
+
const timer = setTimeout(() => {
|
|
491
|
+
const stderr = this.stderrTail.length === 0 ? "" : `; stderr tail:\n${this.stderrTail.join("\n")}`;
|
|
492
|
+
abandon.abort(new RequestTimeoutError(`${method} timed out after ${timeout}ms waiting for ${this.runtime.description}${stderr}`));
|
|
493
|
+
}, timeout);
|
|
494
|
+
try {
|
|
495
|
+
return await transport.request(method, params ?? {}, abandon.signal);
|
|
496
|
+
} finally {
|
|
497
|
+
clearTimeout(timer);
|
|
498
|
+
}
|
|
499
|
+
} catch (error) {
|
|
500
|
+
if (error instanceof JsonRpcResponseError$1 || error instanceof RequestTimeoutError) throw error;
|
|
501
|
+
await this.settleStreams();
|
|
502
|
+
throw this.closedError(errorMessage(error));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Subscribe to server notifications.
|
|
507
|
+
* @param filter - optional predicate; omitted means every notification.
|
|
508
|
+
* @returns the subscription handle; close it to stop delivery. After
|
|
509
|
+
* {@link close} or runtime death the handle is born failed — there is no
|
|
510
|
+
* producer left, so `next()` rejects instead of waiting forever.
|
|
511
|
+
*/
|
|
512
|
+
subscribe(filter) {
|
|
513
|
+
const id = String(this.subscriptionSerial++);
|
|
514
|
+
const subscription = new NotificationSubscriptionImpl({
|
|
515
|
+
queue: [],
|
|
516
|
+
waiters: [],
|
|
517
|
+
filter,
|
|
518
|
+
failure: void 0
|
|
519
|
+
}, () => {
|
|
520
|
+
this.subscriptions.delete(id);
|
|
521
|
+
});
|
|
522
|
+
if (this.closeTask !== void 0 || this.exitCode !== void 0 || this.spawnError !== void 0) {
|
|
523
|
+
subscription.fail(this.closedError("QiLin runtime closed"));
|
|
524
|
+
return subscription;
|
|
525
|
+
}
|
|
526
|
+
this.subscriptions.set(id, subscription);
|
|
527
|
+
return subscription;
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Subscribe to one session and the descendants discovered from
|
|
531
|
+
* `subagent.started` lineage edges. The runtime notifies for every session
|
|
532
|
+
* in its context, so this client applies the scope.
|
|
533
|
+
* @param sessionId - the root session id.
|
|
534
|
+
* @returns the filtered subscription handle.
|
|
535
|
+
*/
|
|
536
|
+
subscribeSessionTree(sessionId) {
|
|
537
|
+
return this.subscribe((notification) => {
|
|
538
|
+
const params = notification.params;
|
|
539
|
+
if (notification.method === "subagent.started" || notification.method === "subagent.finished") {
|
|
540
|
+
const parentId = params.parentSessionId;
|
|
541
|
+
if (typeof parentId === "string" && this.isDescendantOf(parentId, sessionId)) return true;
|
|
542
|
+
return params.childSessionId === sessionId;
|
|
543
|
+
}
|
|
544
|
+
const relatedId = params.sessionId;
|
|
545
|
+
return typeof relatedId === "string" && this.isDescendantOf(relatedId, sessionId);
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Shut the runtime down and reap it: a best-effort protocol `shutdown`
|
|
550
|
+
* bounded by `shutdownTimeoutMs`, then the shared stdin-EOF → SIGTERM →
|
|
551
|
+
* SIGKILL ladder until the process actually exited. Idempotent.
|
|
552
|
+
* @returns settlement of the complete teardown.
|
|
553
|
+
*/
|
|
554
|
+
close() {
|
|
555
|
+
this.closeTask ??= this.performClose();
|
|
556
|
+
return this.closeTask;
|
|
557
|
+
}
|
|
558
|
+
async performClose() {
|
|
559
|
+
const child = this.child;
|
|
560
|
+
if (child === void 0) return;
|
|
561
|
+
try {
|
|
562
|
+
await this.request("shutdown", void 0, this.runtime.shutdownTimeoutMs ?? 1e3);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
this.appendStderr([`shutdown request failed: ${errorMessage(error)}`]);
|
|
565
|
+
}
|
|
566
|
+
await disposeRuntimeProcess(child, {
|
|
567
|
+
disposeEofGraceMs: this.runtime.disposeEofGraceMs ?? 6e3,
|
|
568
|
+
disposeGraceMs: this.runtime.disposeGraceMs ?? 3e3
|
|
569
|
+
});
|
|
570
|
+
this.transport?.close();
|
|
571
|
+
this.failSubscriptions(this.closedError("QiLin runtime closed"));
|
|
572
|
+
}
|
|
573
|
+
dispatchNotification(notification) {
|
|
574
|
+
this.recordSessionRelationship(notification);
|
|
575
|
+
for (const subscription of this.subscriptions.values()) subscription.push(notification);
|
|
576
|
+
}
|
|
577
|
+
recordSessionRelationship(notification) {
|
|
578
|
+
if (notification.method !== "subagent.started") return;
|
|
579
|
+
const parentId = notification.params.parentSessionId;
|
|
580
|
+
const childId = notification.params.childSessionId;
|
|
581
|
+
if (typeof parentId === "string" && parentId !== "" && typeof childId === "string" && childId !== "" && parentId !== childId) this.sessionParents.set(childId, parentId);
|
|
582
|
+
}
|
|
583
|
+
isDescendantOf(sessionId, rootSessionId) {
|
|
584
|
+
const visited = /* @__PURE__ */ new Set();
|
|
585
|
+
let current = sessionId;
|
|
586
|
+
while (!visited.has(current)) {
|
|
587
|
+
if (current === rootSessionId) return true;
|
|
588
|
+
visited.add(current);
|
|
589
|
+
const parent = this.sessionParents.get(current);
|
|
590
|
+
if (parent === void 0) return false;
|
|
591
|
+
current = parent;
|
|
592
|
+
}
|
|
593
|
+
/* v8 ignore next */
|
|
594
|
+
return false;
|
|
595
|
+
}
|
|
596
|
+
failSubscriptions(error) {
|
|
597
|
+
for (const subscription of this.subscriptions.values()) subscription.fail(error);
|
|
598
|
+
}
|
|
599
|
+
appendStderr(lines) {
|
|
600
|
+
const kept = lines.filter((line) => line.length > 0);
|
|
601
|
+
this.stderrTail.push(...kept);
|
|
602
|
+
if (this.stderrTail.length > STDERR_TAIL_LIMIT) this.stderrTail.splice(0, this.stderrTail.length - STDERR_TAIL_LIMIT);
|
|
603
|
+
}
|
|
604
|
+
settleStreams() {
|
|
605
|
+
return Promise.race([this.streamsSettled, new Promise((resolve) => {
|
|
606
|
+
setTimeout(resolve, STREAM_SETTLE_MS);
|
|
607
|
+
})]);
|
|
608
|
+
}
|
|
609
|
+
closedError(reason) {
|
|
610
|
+
const parts = [`${this.runtime.description}: ${reason}`];
|
|
611
|
+
if (this.spawnError !== void 0) parts.push(`spawn error: ${this.spawnError.message}`);
|
|
612
|
+
if (this.exitCode !== void 0) parts.push(`exit code: ${String(this.exitCode)}`);
|
|
613
|
+
if (this.stderrTail.length > 0) parts.push(`stderr tail:\n${this.stderrTail.join("\n")}`);
|
|
614
|
+
return new TransportClosedError(parts.join("\n"));
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
/**
|
|
618
|
+
* Whether `value` is a plain JSON object (the wire-boundary shape probe).
|
|
619
|
+
* @param value - the wire value to probe.
|
|
620
|
+
* @returns `true` iff `value` is a non-null, non-array object.
|
|
621
|
+
*/
|
|
622
|
+
function isRecord(value) {
|
|
623
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
624
|
+
}
|
|
625
|
+
/** The message of a thrown value (the transport only throws `Error`s; `String` covers the rest). */
|
|
626
|
+
function errorMessage(error) {
|
|
627
|
+
/* v8 ignore next -- the transport and dispose ladder reject only with Errors */
|
|
628
|
+
return error instanceof Error ? error.message : String(error);
|
|
629
|
+
}
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region lib/types/api.js
|
|
632
|
+
/**
|
|
633
|
+
* High-level run API over {@link HarnessClient}: `DeepSeekHarness` owns one
|
|
634
|
+
* runtime subprocess across many sessions; `HarnessSession.run` sends a
|
|
635
|
+
* prompt and settles when the whole agent next becomes idle.
|
|
636
|
+
*
|
|
637
|
+
* @module @qilin-agent/sdk-client/api
|
|
638
|
+
*/
|
|
639
|
+
/**
|
|
640
|
+
* Reusable SDK for running QiLin agent turns in a runtime
|
|
641
|
+
* subprocess. The subprocess starts lazily on first use and stays owned by
|
|
642
|
+
* this instance until {@link close}; always close (or `await using`) so the
|
|
643
|
+
* child is reaped.
|
|
644
|
+
*/
|
|
645
|
+
var DeepSeekHarness = class {
|
|
646
|
+
clientInstance;
|
|
647
|
+
createClient;
|
|
648
|
+
cwd;
|
|
649
|
+
provider;
|
|
650
|
+
model;
|
|
651
|
+
reasoningEffort;
|
|
652
|
+
maxTokens;
|
|
653
|
+
initialized;
|
|
654
|
+
closed = false;
|
|
655
|
+
constructor(options = {}, clientFactory) {
|
|
656
|
+
this.createClient = clientFactory ?? (() => new HarnessClient(options));
|
|
657
|
+
this.clientInstance = this.createClient();
|
|
658
|
+
this.cwd = resolve(options.cwd ?? options.processCwd ?? process.cwd());
|
|
659
|
+
this.provider = options.provider ?? "deepseek-official";
|
|
660
|
+
this.model = options.model ?? "deepseek-v4-flash";
|
|
661
|
+
this.reasoningEffort = options.reasoningEffort;
|
|
662
|
+
this.maxTokens = options.maxTokens;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* The underlying JSON-RPC client (exposed for low-level access). A failed
|
|
666
|
+
* handshake swaps in a fresh instance only after cleanup proves the runtime
|
|
667
|
+
* exited; cleanup failure retains this client, so do not cache it across a
|
|
668
|
+
* failed {@link start}.
|
|
669
|
+
* @returns the client currently owning the runtime subprocess.
|
|
670
|
+
*/
|
|
671
|
+
get client() {
|
|
672
|
+
return this.clientInstance;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Start the subprocess and perform the `initialize` handshake once. On
|
|
676
|
+
* failure, successful SDK-owned cleanup reaps the runtime and installs a
|
|
677
|
+
* fresh client (`HarnessClient.close` is permanent), so a later call retries
|
|
678
|
+
* with a new subprocess unless {@link close} already ended this harness. If
|
|
679
|
+
* cleanup also fails, rejects with an `AggregateError` whose ordered errors
|
|
680
|
+
* preserve both causes and retains the failed client rather than spawning
|
|
681
|
+
* alongside a process whose exit was not proved.
|
|
682
|
+
* @returns settlement of the (memoized) handshake.
|
|
683
|
+
*/
|
|
684
|
+
start() {
|
|
685
|
+
this.initialized ??= (async () => {
|
|
686
|
+
try {
|
|
687
|
+
this.clientInstance.start();
|
|
688
|
+
await this.clientInstance.initialize({
|
|
689
|
+
cwd: this.cwd,
|
|
690
|
+
provider: this.provider,
|
|
691
|
+
model: this.model,
|
|
692
|
+
...this.reasoningEffort === void 0 ? {} : { reasoningEffort: this.reasoningEffort },
|
|
693
|
+
...this.maxTokens === void 0 ? {} : { maxTokens: this.maxTokens }
|
|
694
|
+
});
|
|
695
|
+
} catch (error) {
|
|
696
|
+
this.initialized = void 0;
|
|
697
|
+
try {
|
|
698
|
+
await this.clientInstance.close();
|
|
699
|
+
} catch (cleanupError) {
|
|
700
|
+
throw new AggregateError([error, cleanupError], "QiLin initialization and cleanup failed");
|
|
701
|
+
}
|
|
702
|
+
if (!this.closed) this.clientInstance = this.createClient();
|
|
703
|
+
throw error;
|
|
704
|
+
}
|
|
705
|
+
})();
|
|
706
|
+
return this.initialized;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Open a session handle (no wire traffic; the runtime creates the session
|
|
710
|
+
* on its first prompt or working-directory operation).
|
|
711
|
+
* @param sessionId - explicit id to reuse; omitted mints a fresh one.
|
|
712
|
+
* @returns the session handle.
|
|
713
|
+
*/
|
|
714
|
+
session(sessionId) {
|
|
715
|
+
return new HarnessSession(this, sessionId ?? `session-${randomUUID().replaceAll("-", "")}`);
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Run one prompt on a fresh (or named) session.
|
|
719
|
+
* @param input - prompt text, or content blocks sent verbatim.
|
|
720
|
+
* @param options - optional session id and per-notification observer.
|
|
721
|
+
* @returns the owned activity interval.
|
|
722
|
+
*/
|
|
723
|
+
run(input, options) {
|
|
724
|
+
return this.session(options?.sessionId).run(input, options);
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Shut down and reap the runtime subprocess. Idempotent and terminal —
|
|
728
|
+
* a closed harness no longer retries a failed handshake.
|
|
729
|
+
* @returns settlement of the complete teardown.
|
|
730
|
+
*/
|
|
731
|
+
close() {
|
|
732
|
+
this.closed = true;
|
|
733
|
+
return this.clientInstance.close();
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* `await using` support: {@link close}.
|
|
737
|
+
* @returns settlement of the teardown.
|
|
738
|
+
*/
|
|
739
|
+
[Symbol.asyncDispose]() {
|
|
740
|
+
return this.close();
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
/**
|
|
744
|
+
* One SDK session: a stable id plus owned activity intervals.
|
|
745
|
+
*/
|
|
746
|
+
var HarnessSession = class {
|
|
747
|
+
harness;
|
|
748
|
+
id;
|
|
749
|
+
/**
|
|
750
|
+
* @param harness - the owning harness (supplies the client and handshake).
|
|
751
|
+
* @param id - the wire session id this handle runs on.
|
|
752
|
+
*/
|
|
753
|
+
constructor(harness, id) {
|
|
754
|
+
this.harness = harness;
|
|
755
|
+
this.id = id;
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Read the effective directory and recover a missing directory to the Session origin.
|
|
759
|
+
* @returns the absolute directory used by new independent operations.
|
|
760
|
+
*/
|
|
761
|
+
async getWorkingDirectory() {
|
|
762
|
+
await this.harness.start();
|
|
763
|
+
return this.harness.client.getWorkingDirectory(this.id);
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Change the effective directory without moving existing processes or changing permissions.
|
|
767
|
+
* @param path - absolute or Session-current-directory-relative directory.
|
|
768
|
+
* @returns the validated absolute directory.
|
|
769
|
+
*/
|
|
770
|
+
async setWorkingDirectory(path) {
|
|
771
|
+
await this.harness.start();
|
|
772
|
+
return this.harness.client.setWorkingDirectory(this.id, path);
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Queue one prompt, then observe the whole session through its next idle.
|
|
776
|
+
* @param input - prompt text, or content blocks sent verbatim.
|
|
777
|
+
* @param options - optional per-notification observer.
|
|
778
|
+
* @returns the owned activity interval; rejects on transport loss, timeout,
|
|
779
|
+
* or a protocol error.
|
|
780
|
+
*/
|
|
781
|
+
async run(input, options) {
|
|
782
|
+
await this.harness.start();
|
|
783
|
+
const client = this.harness.client;
|
|
784
|
+
const contentBlocks = normalizeInput(input);
|
|
785
|
+
const events = [];
|
|
786
|
+
const notifications = [];
|
|
787
|
+
const subscription = client.subscribeSessionTree(this.id);
|
|
788
|
+
const collect = (notification) => {
|
|
789
|
+
if (notification.method === "session.event" && notification.params.sessionId === this.id) {
|
|
790
|
+
const event = validatedSessionEvent(notification.params.event);
|
|
791
|
+
notifications.push(notification);
|
|
792
|
+
options?.onNotification?.(notification);
|
|
793
|
+
events.push(event);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
notifications.push(notification);
|
|
797
|
+
options?.onNotification?.(notification);
|
|
798
|
+
};
|
|
799
|
+
try {
|
|
800
|
+
const messageId = await client.prompt(this.id, contentBlocks);
|
|
801
|
+
let received = false;
|
|
802
|
+
while (true) {
|
|
803
|
+
const notification = await subscription.next();
|
|
804
|
+
if (!received) {
|
|
805
|
+
if (notification.method !== "session.event" || notification.params.sessionId !== this.id || !isInboxReceipt(notification.params.event, messageId)) continue;
|
|
806
|
+
received = true;
|
|
807
|
+
}
|
|
808
|
+
collect(notification);
|
|
809
|
+
if (notification.method === "session.status" && notification.params.sessionId === this.id && notification.params.status === "idle") break;
|
|
810
|
+
}
|
|
811
|
+
} finally {
|
|
812
|
+
subscription.close();
|
|
813
|
+
}
|
|
814
|
+
return {
|
|
815
|
+
sessionId: this.id,
|
|
816
|
+
finalResponse: finalResponse(events),
|
|
817
|
+
events,
|
|
818
|
+
notifications
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
/**
|
|
823
|
+
* Normalize run input: a string becomes one text block; blocks pass verbatim.
|
|
824
|
+
* @param input - prompt text or content blocks.
|
|
825
|
+
* @returns the content blocks to send.
|
|
826
|
+
*/
|
|
827
|
+
function normalizeInput(input) {
|
|
828
|
+
return typeof input === "string" ? [{
|
|
829
|
+
type: "text",
|
|
830
|
+
text: input
|
|
831
|
+
}] : input;
|
|
832
|
+
}
|
|
833
|
+
/** Validate the provider-read fields of one wire turn-end reason. */
|
|
834
|
+
function validatedTurnEndReason(value) {
|
|
835
|
+
if (!isRecord(value) || typeof value.kind !== "string") throw new SdkProtocolError(`turn/end carried no reason envelope: ${JSON.stringify(value)}`);
|
|
836
|
+
if (value.kind === "aborted") {
|
|
837
|
+
if (!isRecord(value.reason) || typeof value.reason.kind !== "string") throw new SdkProtocolError(`turn/end carried a malformed aborted reason: ${JSON.stringify(value)}`);
|
|
838
|
+
switch (value.reason.kind) {
|
|
839
|
+
case "user":
|
|
840
|
+
case "parent":
|
|
841
|
+
case "disposed":
|
|
842
|
+
case "legacy": break;
|
|
843
|
+
case "hook":
|
|
844
|
+
if (typeof value.reason.reason !== "string") throw new SdkProtocolError(`turn/end carried a malformed hook abort reason: ${JSON.stringify(value)}`);
|
|
845
|
+
break;
|
|
846
|
+
default: throw new SdkProtocolError(`turn/end carried an unknown abort reason: ${JSON.stringify(value)}`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return value;
|
|
850
|
+
}
|
|
851
|
+
/** Validate the fields in a wire `session.event` envelope before returning the typed result. */
|
|
852
|
+
function validatedSessionEvent(value) {
|
|
853
|
+
if (!isRecord(value) || typeof value.type !== "string") throw new SdkProtocolError(`session.event carried no event envelope: ${JSON.stringify(value)}`);
|
|
854
|
+
if (value.type === "assistant/message") {
|
|
855
|
+
const message = isRecord(value.data) ? value.data.message : void 0;
|
|
856
|
+
const content = isRecord(message) ? message.content : void 0;
|
|
857
|
+
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)}`);
|
|
858
|
+
}
|
|
859
|
+
if (value.type === "turn/end") {
|
|
860
|
+
const data = isRecord(value.data) ? value.data : void 0;
|
|
861
|
+
if (data === void 0) throw new SdkProtocolError(`turn/end event carried malformed data: ${JSON.stringify(value)}`);
|
|
862
|
+
validatedTurnEndReason(data.reason);
|
|
863
|
+
}
|
|
864
|
+
return value;
|
|
865
|
+
}
|
|
866
|
+
/** Whether a raw session event is the durable enqueue receipt for `messageId`. */
|
|
867
|
+
function isInboxReceipt(value, messageId) {
|
|
868
|
+
if (!isRecord(value) || value.type !== "agent/inbox/spliced" || !isRecord(value.data)) return false;
|
|
869
|
+
const inserted = value.data.inserted;
|
|
870
|
+
return Array.isArray(inserted) && inserted.some((message) => isRecord(message) && message.id === messageId);
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Extract the concatenated text of the last assistant message.
|
|
874
|
+
* @param events - the activity interval's `session.event` payloads in wire order.
|
|
875
|
+
* @returns the final response text, or `''` when no assistant message exists.
|
|
876
|
+
*/
|
|
877
|
+
function finalResponse(events) {
|
|
878
|
+
for (let index = events.length - 1; index >= 0; index--) {
|
|
879
|
+
const event = events[index];
|
|
880
|
+
if (event?.type !== "assistant/message") continue;
|
|
881
|
+
return event.data.message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
882
|
+
}
|
|
883
|
+
return "";
|
|
884
|
+
}
|
|
885
|
+
//#endregion
|
|
886
|
+
export { DeepSeekHarness, HarnessClient, HarnessSession, JsonRpcResponseError, RequestTimeoutError, SdkProtocolError, TransportClosedError };
|