dsh-rest-api 0.0.0-stage → 0.1.0

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/runtime.js ADDED
@@ -0,0 +1,1384 @@
1
+ /**
2
+ * dsh-rest-api 核心运行时:
3
+ * - 统一 Run 状态机驱动同步 `/messages`、异步长轮询 `/runs`、SSE `/events` 与 Webhook 回调
4
+ * - 按 session_id 严格 FIFO 串行、跨 session 并发
5
+ * - 支持真正停止(agent.cancel)、Web UI 双向取消感知、动态 Preset 与侧边栏 Workspace 分组归属
6
+ */
7
+
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import { mkdir, realpath, stat } from "node:fs/promises";
10
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
11
+ import { installModelSelection } from "@deepseek-ai/dsh-agent";
12
+ import { brandString } from "@deepseek-ai/dsh-brand";
13
+ import { dshHomePath, expandHomePath } from "@deepseek-ai/dsh-home-paths";
14
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
15
+ import { setSandboxMode } from "@deepseek-ai/dsh-sandbox-policy";
16
+ import { SessionSeq } from "@deepseek-ai/dsh-session";
17
+ import { SessionPersistenceNotFoundError } from "@deepseek-ai/dsh-session-persistence";
18
+ import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
19
+
20
+ import {
21
+ authorizeRequest,
22
+ collectSecretsForRedaction,
23
+ enforceTextBudget,
24
+ normalizePrefix,
25
+ openSseStream,
26
+ parsePathSegment,
27
+ parseWaitSeconds,
28
+ readJsonBody,
29
+ redactSecrets,
30
+ validatePromptPayload,
31
+ validateWebhookUrl,
32
+ waitWithTimeoutAndAbort,
33
+ writeJson,
34
+ writeSseComment,
35
+ writeSseEvent,
36
+ } from "./http.js";
37
+
38
+ const TERMINAL_STATUSES = new Set(["completed", "cancelled", "failed"]);
39
+ const MAX_WAIT_SECONDS = 60;
40
+ const DEFAULT_CANCEL_WAIT_SECONDS = 5;
41
+ const SSE_HEARTBEAT_MS = 15_000;
42
+ const SAFE_DIR_SLUG = /^[a-zA-Z0-9._-]{1,64}$/;
43
+
44
+ const DEFAULT_DEPS = {
45
+ installModelSelection,
46
+ brandString,
47
+ createUserMessage,
48
+ setSandboxMode,
49
+ setApprovalPolicy,
50
+ SessionSeq,
51
+ SessionPersistenceNotFoundError,
52
+ dshHomePath,
53
+ expandHomePath,
54
+ fetchImpl: globalThis.fetch,
55
+ };
56
+
57
+ /** 解析默认或自定义工作区路径(自动展开 `~` 并遵循 `DSH_HOME`)。 */
58
+ export function resolveWorkspacePath(rawDir, deps = DEFAULT_DEPS) {
59
+ if (typeof rawDir === "string" && rawDir.trim().length > 0) {
60
+ return resolve(deps.expandHomePath(rawDir.trim()));
61
+ }
62
+ return resolve(deps.dshHomePath("rest-api-workspace"));
63
+ }
64
+
65
+ /** 从配置或指定环境变量解析 Bearer API Key。 */
66
+ export function resolveConfiguredApiKey(config) {
67
+ if (typeof config.apiKey === "string" && config.apiKey.trim().length > 0) {
68
+ return config.apiKey.trim();
69
+ }
70
+ if (typeof config.apiKeyEnv === "string" && config.apiKeyEnv.trim().length > 0) {
71
+ const envVal = process.env[config.apiKeyEnv.trim()];
72
+ if (typeof envVal === "string" && envVal.trim().length > 0) {
73
+ return envVal.trim();
74
+ }
75
+ }
76
+ return "";
77
+ }
78
+
79
+ /** 等待 Agent 及其派生子代理完全进入空闲态。 */
80
+ async function waitUntilQuiescent(ctx, agent) {
81
+ const subagents = ctx.get?.("subagents");
82
+ while (true) {
83
+ if (ctx.agents.get(agent.id) !== agent) {
84
+ throw new Error("session agent was disposed before turn completed");
85
+ }
86
+ await agent.whenIdle();
87
+ const idleSeq = agent.session.seq;
88
+ const waitedChildren = await subagents?.waitForChildren?.(agent);
89
+ if (ctx.agents.get(agent.id) !== agent) {
90
+ throw new Error("session agent was disposed before turn completed");
91
+ }
92
+ if (!waitedChildren && agent.status === "idle" && agent.session.seq === idleSeq) {
93
+ return;
94
+ }
95
+ }
96
+ }
97
+
98
+ /** 将工作区内的文件路径规范化为相对路径字符串,禁止越界与泄漏宿主机绝对路径。 */
99
+ async function normalizeArtifactRef(candidatePath, workspaceRoot) {
100
+ if (typeof candidatePath !== "string" || candidatePath.trim().length === 0) return null;
101
+ const resolvedWorkspace = resolve(workspaceRoot);
102
+ const absoluteCandidate = isAbsolute(candidatePath)
103
+ ? resolve(candidatePath)
104
+ : resolve(resolvedWorkspace, candidatePath);
105
+ const rel = relative(resolvedWorkspace, absoluteCandidate);
106
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
107
+ return null;
108
+ }
109
+ try {
110
+ const info = await stat(absoluteCandidate);
111
+ if (!info.isFile()) return null;
112
+ } catch {
113
+ return null;
114
+ }
115
+ return rel.split(sep).join("/");
116
+ }
117
+
118
+ /** 从本轮事件片段 [startSeq, session.seq) 中提取最终回复文本、制品列表与结束原因。 */
119
+ async function extractTurnOutput(session, startSeq, workspaceRoot, SessionSeqFn) {
120
+ let started = false;
121
+ let finalText = "";
122
+ let turnReason;
123
+ const presentedCandidates = [];
124
+ const toolWriteCandidates = [];
125
+ const successfulCallIds = new Set();
126
+ const pendingWriteCalls = new Map();
127
+
128
+ const length = session.seq;
129
+ for (let seq = startSeq; seq < length; seq++) {
130
+ const event = session.eventAt(SessionSeqFn(seq));
131
+ if (!event) continue;
132
+
133
+ if (event.type === "turn/start") {
134
+ started = true;
135
+ turnReason = void 0;
136
+ continue;
137
+ }
138
+ if (!started) continue;
139
+
140
+ if (event.type === "assistant/message") {
141
+ const blocks = event.data?.message?.content ?? [];
142
+ const text = blocks
143
+ .filter((block) => block && block.type === "text" && typeof block.text === "string")
144
+ .map((block) => block.text)
145
+ .join("");
146
+ if (text.trim().length > 0) {
147
+ finalText = text.trim();
148
+ }
149
+ } else if (event.type === "deliverables/presented") {
150
+ const files = event.data?.files;
151
+ if (Array.isArray(files)) {
152
+ for (const item of files) {
153
+ if (item && typeof item.path === "string") {
154
+ presentedCandidates.push(item.path);
155
+ }
156
+ }
157
+ }
158
+ } else if (event.type === "tool/call") {
159
+ const toolName = event.data?.name;
160
+ const callId = event.data?.callId;
161
+ const args = event.data?.arguments;
162
+ if (typeof callId === "string" && (toolName === "write" || toolName === "edit")) {
163
+ let parsedArgs = args;
164
+ if (typeof args === "string") {
165
+ try {
166
+ parsedArgs = JSON.parse(args);
167
+ } catch {
168
+ parsedArgs = null;
169
+ }
170
+ }
171
+ const targetPath = parsedArgs?.file_path ?? parsedArgs?.path;
172
+ if (typeof targetPath === "string") {
173
+ pendingWriteCalls.set(callId, targetPath);
174
+ }
175
+ }
176
+ } else if (event.type === "tool/result") {
177
+ const callId = event.data?.message?.toolCallId;
178
+ const isError = Boolean(event.data?.message?.isError ?? event.data?.error);
179
+ if (typeof callId === "string" && !isError) {
180
+ successfulCallIds.add(callId);
181
+ if (pendingWriteCalls.has(callId) && typeof event.data?.meta?.path === "string") {
182
+ pendingWriteCalls.set(callId, event.data.meta.path);
183
+ }
184
+ }
185
+ } else if (event.type === "turn/end") {
186
+ turnReason = event.data?.reason;
187
+ }
188
+ }
189
+
190
+ for (const [callId, filePath] of pendingWriteCalls.entries()) {
191
+ if (successfulCallIds.has(callId)) {
192
+ toolWriteCandidates.push(filePath);
193
+ }
194
+ }
195
+
196
+ const seen = new Set();
197
+ const artifacts = [];
198
+ for (const candidate of [...presentedCandidates, ...toolWriteCandidates]) {
199
+ const ref = await normalizeArtifactRef(candidate, workspaceRoot);
200
+ if (ref && !seen.has(ref)) {
201
+ seen.add(ref);
202
+ artifacts.push(ref);
203
+ }
204
+ }
205
+
206
+ return {
207
+ text: finalText,
208
+ artifacts,
209
+ turnReason,
210
+ };
211
+ }
212
+
213
+ /** 读取单个普通或 Schemastery volatile 配置字段。 */
214
+ function readVolatile(value) {
215
+ return value !== null && typeof value === "object" && typeof value.get === "function"
216
+ ? value.get()
217
+ : value;
218
+ }
219
+
220
+ /** 将包含 volatile 引用的配置对象解包为当前时刻的普通快照,支持在 Web 设置页保存后热生效。 */
221
+ export function resolveRuntimeConfig(raw) {
222
+ if (!raw || typeof raw !== "object") return {};
223
+ const snapshot = {};
224
+ for (const [key, value] of Object.entries(raw)) {
225
+ snapshot[key] = readVolatile(value);
226
+ }
227
+ return snapshot;
228
+ }
229
+
230
+ export class RestApiRuntime {
231
+ constructor(ctx, config, deps = {}) {
232
+ this.ctx = ctx;
233
+ this._rawConfig = config;
234
+ this.deps = { ...DEFAULT_DEPS, ...deps };
235
+ this.prefix = normalizePrefix(this.config.routePrefix);
236
+
237
+ /** sessionId -> Promise chain,保证同会话严格 FIFO、跨会话并发。 */
238
+ this.sessionChains = new Map();
239
+ /** sessionId -> Promise,串行化同一会话的 create/resume。 */
240
+ this.sessionInitLocks = new Map();
241
+ /** sessionId -> 当前正在执行的 RunRecord(用于将 session/event 桥接到 SSE)。 */
242
+ this.runningRunBySession = new Map();
243
+ /** sessionId -> 本轮 agent/error 记录。 */
244
+ this.turnErrors = new Map();
245
+
246
+ /** runId -> RunRecord */
247
+ this.runs = new Map();
248
+ /** `${sessionId}\0${requestId}` -> runId */
249
+ this.idempotencyIndex = new Map();
250
+ /** requestId -> Set<runId> */
251
+ this.requestIdIndex = new Map();
252
+ /** sessionId -> Set<runId> */
253
+ this.sessionActiveRuns = new Map();
254
+ /** runId -> Set<(eventName, payload) => void> */
255
+ this.sseSubscribers = new Map();
256
+
257
+ this.disposeErrorListener = ctx.on?.("agent/error", ({ agent, error }) => {
258
+ if (!agent) return;
259
+ const key = String(agent.session.id);
260
+ this.turnErrors.set(key, error instanceof Error ? error.message : String(error));
261
+ });
262
+
263
+ this.disposeSessionEventListener = ctx.on?.("session/event", (session, event) => {
264
+ this.forwardSessionEventToSse(session, event);
265
+ });
266
+
267
+ this.gcTimer = setInterval(() => this.pruneExpiredRuns(), 60_000);
268
+ this.gcTimer.unref?.();
269
+ }
270
+
271
+ /** 每次读取均解包最新 volatile 配置,使 Web 设置页修改后即时热生效。 */
272
+ get config() {
273
+ return resolveRuntimeConfig(this._rawConfig);
274
+ }
275
+
276
+ get apiKey() {
277
+ return resolveConfiguredApiKey(this.config);
278
+ }
279
+
280
+ get secrets() {
281
+ return collectSecretsForRedaction(this.apiKey);
282
+ }
283
+
284
+ get defaultWorkspaceDir() {
285
+ return resolveWorkspacePath(this.config.workspaceDir, this.deps);
286
+ }
287
+
288
+ get defaultWebhookUrl() {
289
+ return validateWebhookUrl(this.config.defaultWebhookUrl) ?? void 0;
290
+ }
291
+
292
+ dispose() {
293
+ this.disposeErrorListener?.();
294
+ this.disposeSessionEventListener?.();
295
+ clearInterval(this.gcTimer);
296
+ for (const listeners of this.sseSubscribers.values()) {
297
+ listeners.clear();
298
+ }
299
+ this.sseSubscribers.clear();
300
+ }
301
+
302
+ observeUrl() {
303
+ const raw = this.ctx.get?.("webStartup")?.publicUrl;
304
+ if (typeof raw === "string" && raw.trim().length > 0) {
305
+ return raw.endsWith("/") ? raw : `${raw}/`;
306
+ }
307
+ try {
308
+ return `${this.ctx.webServer.getOrigin()}/`;
309
+ } catch {
310
+ return void 0;
311
+ }
312
+ }
313
+
314
+ /** 将会话实时事件精简并转发给对应 Run 的 SSE 订阅者。 */
315
+ forwardSessionEventToSse(session, event) {
316
+ if (!session || !event) return;
317
+ const sessionId = String(session.id);
318
+ const run = this.runningRunBySession.get(sessionId);
319
+ if (!run) return;
320
+ const listeners = this.sseSubscribers.get(run.runId);
321
+ if (!listeners || listeners.size === 0) return;
322
+
323
+ if (event.type === "assistant/message") {
324
+ const blocks = event.data?.message?.content ?? [];
325
+ const text = blocks
326
+ .filter((block) => block && block.type === "text" && typeof block.text === "string")
327
+ .map((block) => block.text)
328
+ .join("");
329
+ if (text.trim().length > 0) {
330
+ this.emitRunSse(run, "assistant.message", {
331
+ run_id: run.runId,
332
+ session_id: run.sessionId,
333
+ seq: event.seq,
334
+ text: redactSecrets(text, this.secrets),
335
+ });
336
+ }
337
+ } else if (event.type === "tool/call") {
338
+ this.emitRunSse(run, "tool.call", {
339
+ run_id: run.runId,
340
+ session_id: run.sessionId,
341
+ seq: event.seq,
342
+ call_id: event.data?.callId,
343
+ name: event.data?.name,
344
+ });
345
+ } else if (event.type === "tool/result") {
346
+ this.emitRunSse(run, "tool.result", {
347
+ run_id: run.runId,
348
+ session_id: run.sessionId,
349
+ seq: event.seq,
350
+ call_id: event.data?.message?.toolCallId,
351
+ is_error: Boolean(event.data?.message?.isError ?? event.data?.error),
352
+ });
353
+ } else if (event.type === "deliverables/presented") {
354
+ const files = Array.isArray(event.data?.files)
355
+ ? event.data.files.map((f) => f?.path).filter((p) => typeof p === "string")
356
+ : [];
357
+ if (files.length > 0) {
358
+ this.emitRunSse(run, "deliverables.presented", {
359
+ run_id: run.runId,
360
+ session_id: run.sessionId,
361
+ seq: event.seq,
362
+ files,
363
+ });
364
+ }
365
+ }
366
+ }
367
+
368
+ emitRunSse(run, eventName, payload) {
369
+ const listeners = this.sseSubscribers.get(run.runId);
370
+ if (!listeners || listeners.size === 0) return;
371
+ for (const listener of [...listeners]) {
372
+ try {
373
+ listener(eventName, payload);
374
+ } catch {
375
+ listeners.delete(listener);
376
+ }
377
+ }
378
+ }
379
+
380
+ pruneExpiredRuns() {
381
+ const cutoff = Date.now() - this.config.runRetentionMs;
382
+ for (const [runId, run] of this.runs.entries()) {
383
+ if (!TERMINAL_STATUSES.has(run.status)) continue;
384
+ const finishedMs = run.finishedAt ? Date.parse(run.finishedAt) : 0;
385
+ if (finishedMs > 0 && finishedMs < cutoff) {
386
+ this.runs.delete(runId);
387
+ const idemKey = `${run.sessionId}\0${run.requestId}`;
388
+ if (this.idempotencyIndex.get(idemKey) === runId) {
389
+ this.idempotencyIndex.delete(idemKey);
390
+ }
391
+ const reqSet = this.requestIdIndex.get(run.requestId);
392
+ if (reqSet) {
393
+ reqSet.delete(runId);
394
+ if (reqSet.size === 0) this.requestIdIndex.delete(run.requestId);
395
+ }
396
+ }
397
+ }
398
+ }
399
+
400
+ enqueueSession(sessionId, task) {
401
+ const prev = this.sessionChains.get(sessionId) ?? Promise.resolve();
402
+ const run = prev.then(task, task);
403
+ const tail = run.then(
404
+ () => {
405
+ if (this.sessionChains.get(sessionId) === tail) this.sessionChains.delete(sessionId);
406
+ },
407
+ () => {
408
+ if (this.sessionChains.get(sessionId) === tail) this.sessionChains.delete(sessionId);
409
+ },
410
+ );
411
+ this.sessionChains.set(sessionId, tail);
412
+ return run;
413
+ }
414
+
415
+ /** 构造模型选择:优先请求覆盖 -> 插件配置 -> dsh 全局默认模型。 */
416
+ resolveAgentOptions(overrides = {}) {
417
+ const defaults = this.ctx.get?.("agentDefaultModel")?.currentSelection?.();
418
+ const provider = overrides.provider || this.config.provider || defaults?.provider;
419
+ const model = overrides.model || this.config.model || defaults?.model;
420
+ const options = {};
421
+ if (provider) options.provider = provider;
422
+ if (model) options.model = model;
423
+ return options;
424
+ }
425
+
426
+ /**
427
+ * 解析并确保目标 Workspace 分组存在:
428
+ * 1. 若指定了 `workspace_dir`:直接使用该目录并配以对应标题;
429
+ * 2. 若仅指定了 `workspace_title`:优先复用侧边栏已有的同名分组,否则在默认目录旁为其创建子目录;
430
+ * 3. 默认使用插件配置的 `workspaceDir` + `workspaceTitle`。
431
+ */
432
+ async ensureWorkspace(overrides = {}) {
433
+ const title = overrides.workspace_title || this.config.workspaceTitle || "API Tasks";
434
+
435
+ if (!overrides.workspace_dir && overrides.workspace_title && this.ctx.workspaceRegistry?.list) {
436
+ const existing = this.ctx.workspaceRegistry
437
+ .list()
438
+ .find((ws) => ws.title === overrides.workspace_title);
439
+ if (existing) {
440
+ return { workspace: existing, canonicalCwd: existing.path };
441
+ }
442
+ }
443
+
444
+ let rawDir;
445
+ if (overrides.workspace_dir) {
446
+ rawDir = resolveWorkspacePath(overrides.workspace_dir, this.deps);
447
+ } else if (overrides.workspace_title && overrides.workspace_title !== (this.config.workspaceTitle || "API Tasks")) {
448
+ const slug = SAFE_DIR_SLUG.test(overrides.workspace_title)
449
+ ? overrides.workspace_title
450
+ : `group-${createHash("sha256").update(overrides.workspace_title, "utf8").digest("hex").slice(0, 12)}`;
451
+ rawDir = join(this.defaultWorkspaceDir, ".groups", slug);
452
+ } else {
453
+ rawDir = this.defaultWorkspaceDir;
454
+ }
455
+
456
+ await mkdir(rawDir, { recursive: true });
457
+ const canonicalCwd = await realpath(rawDir);
458
+ const workspace = await this.ctx.workspaceRegistry.create(canonicalCwd, title);
459
+ return { workspace, canonicalCwd };
460
+ }
461
+
462
+ async getOrCreateAgent(sessionId, overrides = {}) {
463
+ const brandedId = this.deps.brandString(sessionId);
464
+ const existing = this.ctx.agents.get(brandedId);
465
+ if (existing !== void 0) {
466
+ await this.ensureWorkspaceAttachment(existing);
467
+ return existing;
468
+ }
469
+
470
+ const pending = this.sessionInitLocks.get(sessionId);
471
+ if (pending !== void 0) {
472
+ return await pending;
473
+ }
474
+
475
+ const initPromise = this.initAgent(sessionId, overrides).finally(() => {
476
+ if (this.sessionInitLocks.get(sessionId) === initPromise) {
477
+ this.sessionInitLocks.delete(sessionId);
478
+ }
479
+ });
480
+ this.sessionInitLocks.set(sessionId, initPromise);
481
+ return await initPromise;
482
+ }
483
+
484
+ async initAgent(sessionId, overrides = {}) {
485
+ const brandedId = this.deps.brandString(sessionId);
486
+ const live = this.ctx.agents.get(brandedId);
487
+ if (live !== void 0) {
488
+ await this.ensureWorkspaceAttachment(live);
489
+ return live;
490
+ }
491
+
492
+ const { workspace, canonicalCwd } = await this.ensureWorkspace(overrides);
493
+ const requestedPreset = overrides.preset || this.config.presetId || void 0;
494
+ const presets = this.ctx.get?.("agentPresets") ?? this.ctx.agentPresets;
495
+ let resolvedPreset;
496
+ if (presets && requestedPreset) {
497
+ resolvedPreset = (await presets.resolve(requestedPreset)).id;
498
+ }
499
+
500
+ const setup = async (agentCtx) => {
501
+ this.deps.installModelSelection(agentCtx);
502
+ if (presets && resolvedPreset) {
503
+ await presets.mount(agentCtx, resolvedPreset);
504
+ }
505
+ };
506
+
507
+ const agentOptions = this.resolveAgentOptions(overrides);
508
+ let handle;
509
+ let isNew = false;
510
+ try {
511
+ handle = await this.ctx.agents.resume({
512
+ resumeSessionId: brandedId,
513
+ agentOptions,
514
+ setup,
515
+ });
516
+ this.ctx.logger?.info?.("[dsh-rest-api] resumed session %s", sessionId.slice(0, 16));
517
+ } catch (error) {
518
+ if (
519
+ !(error instanceof this.deps.SessionPersistenceNotFoundError) &&
520
+ error?.name !== "SessionPersistenceNotFoundError"
521
+ ) {
522
+ throw error;
523
+ }
524
+ handle = await this.ctx.agents.create({
525
+ sessionId: brandedId,
526
+ meta: {
527
+ cwd: canonicalCwd,
528
+ ...(resolvedPreset ? { agentPreset: resolvedPreset } : {}),
529
+ },
530
+ agentOptions,
531
+ setup,
532
+ });
533
+ isNew = true;
534
+ this.ctx.logger?.info?.(
535
+ "[dsh-rest-api] created session %s (preset=%s, group=%s)",
536
+ sessionId.slice(0, 16),
537
+ resolvedPreset ?? "default",
538
+ workspace.title,
539
+ );
540
+ }
541
+
542
+ const agent = handle.agent;
543
+ if (isNew) {
544
+ this.deps.setSandboxMode(agent.session, this.config.sandboxMode);
545
+ this.deps.setApprovalPolicy(agent.session, this.config.approvalPolicy);
546
+ }
547
+ await this.ensureWorkspaceAttachment(agent, workspace);
548
+ return agent;
549
+ }
550
+
551
+ async ensureWorkspaceAttachment(agent, knownWorkspace = void 0) {
552
+ const cwd = agent.session.header.cwd;
553
+ if (!cwd || !this.ctx.workspaceRegistry) return;
554
+ try {
555
+ const canonical = await realpath(cwd);
556
+ const workspace =
557
+ knownWorkspace && knownWorkspace.path === canonical
558
+ ? knownWorkspace
559
+ : await this.ctx.workspaceRegistry.create(canonical, this.config.workspaceTitle || "API Tasks");
560
+ if (!workspace.sessionIds.includes(agent.id)) {
561
+ await workspace.attachSession(agent.id);
562
+ }
563
+ } catch (error) {
564
+ this.ctx.logger?.warn?.(
565
+ "[dsh-rest-api] failed to attach session %s to workspace: %s",
566
+ String(agent.id).slice(0, 16),
567
+ error instanceof Error ? error.message : String(error),
568
+ );
569
+ }
570
+ }
571
+
572
+ createRunRecord(
573
+ sessionId,
574
+ requestId,
575
+ prompt,
576
+ { trackIdempotency = false, overrides = {}, webhookUrl = void 0, webhookHeaders = void 0 } = {},
577
+ ) {
578
+ if (trackIdempotency) {
579
+ const idemKey = `${sessionId}\0${requestId}`;
580
+ const existingId = this.idempotencyIndex.get(idemKey);
581
+ if (existingId !== void 0) {
582
+ const existingRun = this.runs.get(existingId);
583
+ if (existingRun !== void 0) {
584
+ return { run: existingRun, duplicated: true };
585
+ }
586
+ }
587
+ const conflictSet = this.requestIdIndex.get(requestId);
588
+ if (conflictSet && conflictSet.size > 0) {
589
+ for (const otherId of conflictSet) {
590
+ const otherRun = this.runs.get(otherId);
591
+ if (otherRun && otherRun.sessionId !== sessionId) {
592
+ throw Object.assign(
593
+ new Error("request_id already belongs to another session"),
594
+ { statusCode: 409 },
595
+ );
596
+ }
597
+ }
598
+ }
599
+ }
600
+
601
+ const deferred = Promise.withResolvers();
602
+ const runId = `run_${randomUUID().replaceAll("-", "")}`;
603
+ const record = {
604
+ runId,
605
+ requestId,
606
+ sessionId,
607
+ prompt,
608
+ overrides,
609
+ webhookUrl: webhookUrl ?? this.defaultWebhookUrl,
610
+ webhookHeaders,
611
+ status: "queued",
612
+ createdAt: new Date().toISOString(),
613
+ startedAt: void 0,
614
+ finishedAt: void 0,
615
+ text: void 0,
616
+ artifacts: void 0,
617
+ error: void 0,
618
+ cancelRequested: false,
619
+ donePromise: deferred.promise,
620
+ resolveDone: deferred.resolve,
621
+ };
622
+
623
+ this.runs.set(runId, record);
624
+ if (trackIdempotency) {
625
+ this.idempotencyIndex.set(`${sessionId}\0${requestId}`, runId);
626
+ }
627
+ let reqSet = this.requestIdIndex.get(requestId);
628
+ if (reqSet === void 0) {
629
+ reqSet = new Set();
630
+ this.requestIdIndex.set(requestId, reqSet);
631
+ }
632
+ reqSet.add(runId);
633
+
634
+ let activeSet = this.sessionActiveRuns.get(sessionId);
635
+ if (activeSet === void 0) {
636
+ activeSet = new Set();
637
+ this.sessionActiveRuns.set(sessionId, activeSet);
638
+ }
639
+ activeSet.add(runId);
640
+
641
+ void this.enqueueSession(sessionId, () => this.executeRun(record));
642
+ return { run: record, duplicated: false };
643
+ }
644
+
645
+ finishRun(run, patch) {
646
+ if (TERMINAL_STATUSES.has(run.status)) return;
647
+ run.status = patch.status;
648
+ run.finishedAt = new Date().toISOString();
649
+ if (patch.text !== void 0) run.text = patch.text;
650
+ if (patch.artifacts !== void 0) run.artifacts = patch.artifacts;
651
+ if (patch.error !== void 0) run.error = patch.error;
652
+
653
+ if (this.runningRunBySession.get(run.sessionId) === run) {
654
+ this.runningRunBySession.delete(run.sessionId);
655
+ }
656
+ const activeSet = this.sessionActiveRuns.get(run.sessionId);
657
+ if (activeSet) {
658
+ activeSet.delete(run.runId);
659
+ if (activeSet.size === 0) this.sessionActiveRuns.delete(run.sessionId);
660
+ }
661
+
662
+ const serialized = this.serializeRun(run);
663
+ this.emitRunSse(run, `run.${run.status}`, serialized);
664
+ this.sseSubscribers.delete(run.runId);
665
+
666
+ run.resolveDone(run);
667
+
668
+ if (run.webhookUrl) {
669
+ void this.deliverWebhook(run, serialized);
670
+ }
671
+ }
672
+
673
+ /** 异步向调用方 Webhook 投递终态结果(指数退避重试 3 次,不阻塞主链路)。 */
674
+ async deliverWebhook(run, serialized) {
675
+ const fetchImpl = this.deps.fetchImpl;
676
+ if (typeof fetchImpl !== "function") return;
677
+ const payload = JSON.stringify({
678
+ event: `run.${run.status}`,
679
+ ...serialized,
680
+ });
681
+ const headers = {
682
+ "Content-Type": "application/json; charset=utf-8",
683
+ "User-Agent": "dsh-rest-api/0.1",
684
+ ...(run.webhookHeaders ?? {}),
685
+ };
686
+ const timeoutMs = this.config.webhookTimeoutMs ?? 10_000;
687
+ const delays = [0, 1000, 3000];
688
+
689
+ for (let attempt = 0; attempt < delays.length; attempt++) {
690
+ if (delays[attempt] > 0) {
691
+ await new Promise((r) => setTimeout(r, delays[attempt]));
692
+ }
693
+ const ac = new AbortController();
694
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
695
+ timer.unref?.();
696
+ try {
697
+ const resp = await fetchImpl(run.webhookUrl, {
698
+ method: "POST",
699
+ headers,
700
+ body: payload,
701
+ signal: ac.signal,
702
+ redirect: "manual",
703
+ });
704
+ clearTimeout(timer);
705
+ if (resp.ok) return;
706
+ this.ctx.logger?.warn?.(
707
+ "[dsh-rest-api] webhook attempt %d for %s returned HTTP %d",
708
+ attempt + 1,
709
+ run.runId,
710
+ resp.status,
711
+ );
712
+ } catch (error) {
713
+ clearTimeout(timer);
714
+ this.ctx.logger?.warn?.(
715
+ "[dsh-rest-api] webhook attempt %d for %s failed: %s",
716
+ attempt + 1,
717
+ run.runId,
718
+ error instanceof Error ? error.message : String(error),
719
+ );
720
+ }
721
+ }
722
+ }
723
+
724
+ async executeRun(run) {
725
+ if (run.cancelRequested || TERMINAL_STATUSES.has(run.status)) {
726
+ this.finishRun(run, { status: "cancelled", error: "cancelled" });
727
+ return;
728
+ }
729
+
730
+ run.status = "running";
731
+ run.startedAt = new Date().toISOString();
732
+ this.runningRunBySession.set(run.sessionId, run);
733
+ this.emitRunSse(run, "run.status", this.serializeRun(run));
734
+
735
+ try {
736
+ const agent = await this.getOrCreateAgent(run.sessionId, run.overrides);
737
+ await agent.whenIdle();
738
+
739
+ if (run.cancelRequested) {
740
+ this.finishRun(run, { status: "cancelled", error: "cancelled" });
741
+ return;
742
+ }
743
+
744
+ const startSeq = agent.session.seq;
745
+ this.turnErrors.delete(run.sessionId);
746
+
747
+ const userMessage = this.deps.createUserMessage({
748
+ content: [{ type: "text", text: run.prompt }],
749
+ source: { kind: "user" },
750
+ });
751
+ agent.followup(userMessage);
752
+
753
+ await waitUntilQuiescent(this.ctx, agent);
754
+
755
+ try {
756
+ await this.ctx.sessions.flush(agent.session);
757
+ } catch (flushErr) {
758
+ this.ctx.logger?.warn?.(
759
+ "[dsh-rest-api] session flush failed (%s): %s",
760
+ run.sessionId.slice(0, 16),
761
+ flushErr instanceof Error ? flushErr.message : String(flushErr),
762
+ );
763
+ }
764
+
765
+ const workspaceRoot = agent.session.header.cwd ?? this.defaultWorkspaceDir;
766
+ const output = await extractTurnOutput(
767
+ agent.session,
768
+ startSeq,
769
+ workspaceRoot,
770
+ this.deps.SessionSeq,
771
+ );
772
+ const recordedError = this.turnErrors.get(run.sessionId);
773
+ this.turnErrors.delete(run.sessionId);
774
+
775
+ const sanitizedText = redactSecrets(output.text, this.secrets).trim();
776
+ const artifacts = output.artifacts.length > 0 ? output.artifacts : void 0;
777
+
778
+ if (run.cancelRequested || output.turnReason?.kind === "cancelled") {
779
+ this.finishRun(run, {
780
+ status: "cancelled",
781
+ text: sanitizedText.length > 0 ? sanitizedText : void 0,
782
+ artifacts,
783
+ error: "cancelled",
784
+ });
785
+ return;
786
+ }
787
+
788
+ if (output.turnReason?.kind === "error" || (recordedError && sanitizedText.length === 0)) {
789
+ this.finishRun(run, {
790
+ status: "failed",
791
+ error: redactSecrets(recordedError ?? "agent turn failed", this.secrets),
792
+ });
793
+ return;
794
+ }
795
+
796
+ if (sanitizedText.length === 0) {
797
+ this.finishRun(run, {
798
+ status: "failed",
799
+ error: "agent returned empty response",
800
+ });
801
+ return;
802
+ }
803
+
804
+ const safeText = enforceTextBudget(
805
+ (candidate) => ({
806
+ run_id: run.runId,
807
+ request_id: run.requestId,
808
+ session_id: run.sessionId,
809
+ status: "completed",
810
+ text: candidate,
811
+ ...(artifacts ? { artifacts } : {}),
812
+ }),
813
+ sanitizedText,
814
+ this.config.maxResponseBytes,
815
+ );
816
+
817
+ this.finishRun(run, {
818
+ status: "completed",
819
+ text: safeText,
820
+ artifacts,
821
+ });
822
+ } catch (error) {
823
+ if (run.cancelRequested) {
824
+ this.finishRun(run, { status: "cancelled", error: "cancelled" });
825
+ return;
826
+ }
827
+ const message = redactSecrets(error instanceof Error ? error.message : String(error), this.secrets);
828
+ this.ctx.logger?.error?.(
829
+ "[dsh-rest-api] run %s (session=%s) failed: %s",
830
+ run.runId,
831
+ run.sessionId.slice(0, 16),
832
+ message,
833
+ );
834
+ this.finishRun(run, {
835
+ status: "failed",
836
+ error: message,
837
+ });
838
+ }
839
+ }
840
+
841
+ findRun(identifier, expectedSessionId = void 0) {
842
+ const direct = this.runs.get(identifier);
843
+ if (direct !== void 0) {
844
+ if (expectedSessionId !== void 0 && direct.sessionId !== expectedSessionId) return void 0;
845
+ return direct;
846
+ }
847
+ const reqSet = this.requestIdIndex.get(identifier);
848
+ if (!reqSet || reqSet.size === 0) return void 0;
849
+ let latest;
850
+ for (const runId of reqSet) {
851
+ const candidate = this.runs.get(runId);
852
+ if (!candidate) continue;
853
+ if (expectedSessionId !== void 0 && candidate.sessionId !== expectedSessionId) continue;
854
+ latest = candidate;
855
+ }
856
+ return latest;
857
+ }
858
+
859
+ async cancelRun(run, waitMs = DEFAULT_CANCEL_WAIT_SECONDS * 1000) {
860
+ if (TERMINAL_STATUSES.has(run.status)) {
861
+ return { run, stopped: false };
862
+ }
863
+
864
+ run.cancelRequested = true;
865
+ if (run.status === "queued") {
866
+ this.finishRun(run, { status: "cancelled", error: "cancelled" });
867
+ return { run, stopped: true };
868
+ }
869
+
870
+ const agent = this.ctx.agents.get(this.deps.brandString(run.sessionId));
871
+ if (agent !== void 0 && agent.status === "running") {
872
+ this.ctx.logger?.info?.(
873
+ "[dsh-rest-api] cancelling active agent turn (run=%s, session=%s)",
874
+ run.runId,
875
+ run.sessionId.slice(0, 16),
876
+ );
877
+ agent.cancel({ kind: "user" });
878
+ }
879
+
880
+ if (waitMs > 0) {
881
+ await waitWithTimeoutAndAbort(run.donePromise, waitMs, void 0);
882
+ }
883
+ return { run, stopped: true };
884
+ }
885
+
886
+ async cancelSession(sessionId, { clearQueue = true, waitMs = DEFAULT_CANCEL_WAIT_SECONDS * 1000 } = {}) {
887
+ const cancelledRunIds = [];
888
+ const activeSet = this.sessionActiveRuns.get(sessionId);
889
+ let runningRun;
890
+
891
+ if (activeSet) {
892
+ for (const runId of [...activeSet]) {
893
+ const run = this.runs.get(runId);
894
+ if (!run || TERMINAL_STATUSES.has(run.status)) continue;
895
+ if (run.status === "queued" && clearQueue) {
896
+ run.cancelRequested = true;
897
+ this.finishRun(run, { status: "cancelled", error: "cancelled" });
898
+ cancelledRunIds.push(run.runId);
899
+ } else if (run.status === "running") {
900
+ runningRun = run;
901
+ }
902
+ }
903
+ }
904
+
905
+ let agentWasRunning = false;
906
+ const agent = this.ctx.agents.get(this.deps.brandString(sessionId));
907
+ if (agent !== void 0 && agent.status === "running") {
908
+ agentWasRunning = true;
909
+ if (runningRun) {
910
+ runningRun.cancelRequested = true;
911
+ cancelledRunIds.push(runningRun.runId);
912
+ }
913
+ this.ctx.logger?.info?.("[dsh-rest-api] cancelling session %s", sessionId.slice(0, 16));
914
+ agent.cancel({ kind: "user" });
915
+ if (waitMs > 0) {
916
+ const settlePromise = runningRun ? runningRun.donePromise : agent.whenIdle();
917
+ await waitWithTimeoutAndAbort(settlePromise, waitMs, void 0);
918
+ }
919
+ } else if (runningRun) {
920
+ runningRun.cancelRequested = true;
921
+ cancelledRunIds.push(runningRun.runId);
922
+ if (waitMs > 0) {
923
+ await waitWithTimeoutAndAbort(runningRun.donePromise, waitMs, void 0);
924
+ }
925
+ }
926
+
927
+ const stillRunning = agent !== void 0 && agent.status === "running";
928
+ return {
929
+ session_id: sessionId,
930
+ stopped: cancelledRunIds.length > 0 || agentWasRunning,
931
+ agent_was_running: agentWasRunning,
932
+ status: stillRunning ? "cancelling" : (cancelledRunIds.length > 0 || agentWasRunning ? "cancelled" : "idle"),
933
+ cancelled_run_ids: cancelledRunIds,
934
+ ...(this.observeUrl() ? { observe_url: this.observeUrl() } : {}),
935
+ };
936
+ }
937
+
938
+ serializeRun(run) {
939
+ const out = {
940
+ run_id: run.runId,
941
+ request_id: run.requestId,
942
+ session_id: run.sessionId,
943
+ status: run.status,
944
+ created_at: run.createdAt,
945
+ };
946
+ if (run.startedAt !== void 0) out.started_at = run.startedAt;
947
+ if (run.finishedAt !== void 0) out.finished_at = run.finishedAt;
948
+ if (run.text !== void 0) out.text = run.text;
949
+ if (run.artifacts !== void 0 && run.artifacts.length > 0) out.artifacts = run.artifacts;
950
+ if (run.error !== void 0) out.error = run.error;
951
+ const url = this.observeUrl();
952
+ if (url !== void 0) out.observe_url = url;
953
+ return out;
954
+ }
955
+
956
+ activeStats() {
957
+ let running = 0;
958
+ let queued = 0;
959
+ for (const run of this.runs.values()) {
960
+ if (run.status === "running") running++;
961
+ else if (run.status === "queued") queued++;
962
+ }
963
+ return { running, queued, total_retained: this.runs.size };
964
+ }
965
+
966
+ async handleHttp(req, res) {
967
+ const timeoutMs = this.config.requestTimeoutMs;
968
+ if (this.ctx.webServer?.server && Number.isFinite(timeoutMs) && timeoutMs > 0) {
969
+ this.ctx.webServer.server.requestTimeout = timeoutMs;
970
+ }
971
+ req.setTimeout?.(timeoutMs);
972
+
973
+ const auth = authorizeRequest(req, {
974
+ authMode: this.config.authMode,
975
+ apiKey: this.apiKey,
976
+ });
977
+ if (!auth.ok) {
978
+ writeJson(res, auth.statusCode, { error: auth.error }, auth.headers ?? {});
979
+ return;
980
+ }
981
+
982
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
983
+ const pathname = url.pathname;
984
+ const relPath = pathname === this.prefix ? "/" : pathname.slice(this.prefix.length);
985
+
986
+ // GET /v1/health
987
+ if (relPath === "/health") {
988
+ if (req.method !== "GET") {
989
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "GET" });
990
+ return;
991
+ }
992
+ const modelChoice = this.resolveAgentOptions();
993
+ writeJson(res, 200, {
994
+ status: "ok",
995
+ plugin: "dsh-rest-api",
996
+ preset: this.config.presetId || null,
997
+ provider: modelChoice.provider ?? null,
998
+ model: modelChoice.model ?? null,
999
+ workspace_title: this.config.workspaceTitle,
1000
+ workspace_dir: this.defaultWorkspaceDir,
1001
+ auth_mode: this.config.authMode,
1002
+ request_timeout_ms: this.ctx.webServer?.server?.requestTimeout ?? this.config.requestTimeoutMs,
1003
+ observe_url: this.observeUrl() ?? null,
1004
+ ...this.activeStats(),
1005
+ });
1006
+ return;
1007
+ }
1008
+
1009
+ // GET /v1/runs(列出近期与活跃 runs)
1010
+ if (relPath === "/runs") {
1011
+ if (req.method !== "GET") {
1012
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "GET" });
1013
+ return;
1014
+ }
1015
+ this.handleListRuns(res, url.searchParams);
1016
+ return;
1017
+ }
1018
+
1019
+ // POST /v1/sessions/{session_id}/messages(同步模式)
1020
+ const msgMatch = /^\/sessions\/([^/]+)\/messages$/.exec(relPath);
1021
+ if (msgMatch) {
1022
+ if (req.method !== "POST") {
1023
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "POST" });
1024
+ return;
1025
+ }
1026
+ await this.handleSyncMessage(req, res, msgMatch[1]);
1027
+ return;
1028
+ }
1029
+
1030
+ // POST /v1/sessions/{session_id}/runs(异步提交)
1031
+ const runsCreateMatch = /^\/sessions\/([^/]+)\/runs$/.exec(relPath);
1032
+ if (runsCreateMatch) {
1033
+ if (req.method !== "POST") {
1034
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "POST" });
1035
+ return;
1036
+ }
1037
+ await this.handleCreateRun(req, res, runsCreateMatch[1]);
1038
+ return;
1039
+ }
1040
+
1041
+ // POST /v1/sessions/{session_id}/cancel(会话级停止)
1042
+ const sessionCancelMatch = /^\/sessions\/([^/]+)\/cancel$/.exec(relPath);
1043
+ if (sessionCancelMatch) {
1044
+ if (req.method !== "POST") {
1045
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "POST" });
1046
+ return;
1047
+ }
1048
+ await this.handleCancelSession(req, res, sessionCancelMatch[1], url.searchParams);
1049
+ return;
1050
+ }
1051
+
1052
+ // GET /v1/runs/{id}/events 或 /v1/sessions/{sid}/runs/{id}/events(SSE 进度流)
1053
+ const runEventsMatch =
1054
+ /^\/runs\/([^/]+)\/events$/.exec(relPath) ??
1055
+ /^\/sessions\/([^/]+)\/runs\/([^/]+)\/events$/.exec(relPath);
1056
+ if (runEventsMatch) {
1057
+ if (req.method !== "GET") {
1058
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "GET" });
1059
+ return;
1060
+ }
1061
+ const hasSession = runEventsMatch.length === 3;
1062
+ const rawSession = hasSession ? runEventsMatch[1] : void 0;
1063
+ const rawRun = hasSession ? runEventsMatch[2] : runEventsMatch[1];
1064
+ await this.handleRunEventsSse(req, res, rawRun, rawSession);
1065
+ return;
1066
+ }
1067
+
1068
+ // POST /v1/runs/{id}/cancel 或 /v1/sessions/{sid}/runs/{id}/cancel
1069
+ const runCancelMatch =
1070
+ /^\/runs\/([^/]+)\/cancel$/.exec(relPath) ??
1071
+ /^\/sessions\/([^/]+)\/runs\/([^/]+)\/cancel$/.exec(relPath);
1072
+ if (runCancelMatch) {
1073
+ if (req.method !== "POST") {
1074
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "POST" });
1075
+ return;
1076
+ }
1077
+ const hasSession = runCancelMatch.length === 3;
1078
+ const rawSession = hasSession ? runCancelMatch[1] : void 0;
1079
+ const rawRun = hasSession ? runCancelMatch[2] : runCancelMatch[1];
1080
+ await this.handleCancelRun(req, res, rawRun, rawSession, url.searchParams);
1081
+ return;
1082
+ }
1083
+
1084
+ // GET /v1/runs/{id} 或 /v1/sessions/{sid}/runs/{id}(查询 / 长轮询)
1085
+ const runGetMatch =
1086
+ /^\/runs\/([^/]+)$/.exec(relPath) ??
1087
+ /^\/sessions\/([^/]+)\/runs\/([^/]+)$/.exec(relPath);
1088
+ if (runGetMatch) {
1089
+ if (req.method !== "GET") {
1090
+ writeJson(res, 405, { error: "method not allowed" }, { Allow: "GET" });
1091
+ return;
1092
+ }
1093
+ const hasSession = runGetMatch.length === 3;
1094
+ const rawSession = hasSession ? runGetMatch[1] : void 0;
1095
+ const rawRun = hasSession ? runGetMatch[2] : runGetMatch[1];
1096
+ await this.handleGetRun(req, res, rawRun, rawSession, url.searchParams);
1097
+ return;
1098
+ }
1099
+
1100
+ writeJson(res, 404, { error: "not found" });
1101
+ }
1102
+
1103
+ handleListRuns(res, searchParams) {
1104
+ const sessionFilter = searchParams.get("session_id");
1105
+ const statusFilter = searchParams.get("status");
1106
+ const rawLimit = Number(searchParams.get("limit") ?? "50");
1107
+ const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 200) : 50;
1108
+
1109
+ const items = [];
1110
+ for (const run of [...this.runs.values()].reverse()) {
1111
+ if (sessionFilter && run.sessionId !== sessionFilter) continue;
1112
+ if (statusFilter && run.status !== statusFilter) continue;
1113
+ items.push(this.serializeRun(run));
1114
+ if (items.length >= limit) break;
1115
+ }
1116
+ writeJson(res, 200, { items });
1117
+ }
1118
+
1119
+ async parsePromptRequest(req, res, rawSessionId) {
1120
+ const sessionId = parsePathSegment(rawSessionId);
1121
+ if (sessionId === null) {
1122
+ writeJson(res, 400, { error: "invalid session_id" });
1123
+ return null;
1124
+ }
1125
+ const contentType = req.headers?.["content-type"]?.split(";", 1)[0]?.trim().toLowerCase();
1126
+ if (contentType !== "application/json") {
1127
+ writeJson(res, 415, { error: "Content-Type must be application/json" });
1128
+ return null;
1129
+ }
1130
+ let body;
1131
+ try {
1132
+ body = await readJsonBody(req, this.config.maxRequestBytes);
1133
+ } catch (error) {
1134
+ writeJson(res, error?.statusCode ?? 400, { error: error instanceof Error ? error.message : "bad request" });
1135
+ return null;
1136
+ }
1137
+ const validated = validatePromptPayload(body, {
1138
+ allowRequestOverrides: this.config.allowRequestOverrides,
1139
+ allowCustomWorkspaceDir: this.config.allowCustomWorkspaceDir,
1140
+ });
1141
+ if (!validated.ok) {
1142
+ writeJson(res, 400, { error: validated.error });
1143
+ return null;
1144
+ }
1145
+ return {
1146
+ sessionId,
1147
+ requestId: validated.requestId,
1148
+ prompt: validated.prompt,
1149
+ overrides: validated.overrides,
1150
+ webhookUrl: validated.webhookUrl,
1151
+ webhookHeaders: validated.webhookHeaders,
1152
+ };
1153
+ }
1154
+
1155
+ async handleSyncMessage(req, res, rawSessionId) {
1156
+ const parsed = await this.parsePromptRequest(req, res, rawSessionId);
1157
+ if (!parsed) return;
1158
+
1159
+ const { run } = this.createRunRecord(parsed.sessionId, parsed.requestId, parsed.prompt, {
1160
+ trackIdempotency: false,
1161
+ overrides: parsed.overrides,
1162
+ webhookUrl: parsed.webhookUrl,
1163
+ webhookHeaders: parsed.webhookHeaders,
1164
+ });
1165
+
1166
+ await run.donePromise;
1167
+
1168
+ if (run.status === "cancelled") {
1169
+ writeJson(res, 409, {
1170
+ error: "cancelled",
1171
+ run_id: run.runId,
1172
+ request_id: run.requestId,
1173
+ session_id: run.sessionId,
1174
+ });
1175
+ return;
1176
+ }
1177
+ if (run.status !== "completed" || typeof run.text !== "string" || run.text.trim().length === 0) {
1178
+ writeJson(res, 502, {
1179
+ error: run.error ?? "agent execution failed",
1180
+ run_id: run.runId,
1181
+ request_id: run.requestId,
1182
+ });
1183
+ return;
1184
+ }
1185
+
1186
+ const response = {
1187
+ request_id: run.requestId,
1188
+ text: run.text,
1189
+ };
1190
+ if (run.artifacts && run.artifacts.length > 0) {
1191
+ response.artifacts = run.artifacts;
1192
+ }
1193
+ writeJson(res, 200, response);
1194
+ }
1195
+
1196
+ async handleCreateRun(req, res, rawSessionId) {
1197
+ const parsed = await this.parsePromptRequest(req, res, rawSessionId);
1198
+ if (!parsed) return;
1199
+
1200
+ try {
1201
+ const { run, duplicated } = this.createRunRecord(parsed.sessionId, parsed.requestId, parsed.prompt, {
1202
+ trackIdempotency: true,
1203
+ overrides: parsed.overrides,
1204
+ webhookUrl: parsed.webhookUrl,
1205
+ webhookHeaders: parsed.webhookHeaders,
1206
+ });
1207
+ writeJson(res, duplicated ? 200 : 202, this.serializeRun(run));
1208
+ } catch (error) {
1209
+ writeJson(res, error?.statusCode ?? 500, {
1210
+ error: redactSecrets(error instanceof Error ? error.message : String(error), this.secrets),
1211
+ });
1212
+ }
1213
+ }
1214
+
1215
+ async handleGetRun(req, res, rawRunId, rawSessionId, searchParams) {
1216
+ const runId = parsePathSegment(rawRunId);
1217
+ if (runId === null) {
1218
+ writeJson(res, 400, { error: "invalid run_id" });
1219
+ return;
1220
+ }
1221
+ let sessionId;
1222
+ if (rawSessionId !== void 0) {
1223
+ sessionId = parsePathSegment(rawSessionId);
1224
+ if (sessionId === null) {
1225
+ writeJson(res, 400, { error: "invalid session_id" });
1226
+ return;
1227
+ }
1228
+ }
1229
+
1230
+ const run = this.findRun(runId, sessionId);
1231
+ if (!run) {
1232
+ writeJson(res, 404, { error: "run not found" });
1233
+ return;
1234
+ }
1235
+
1236
+ const waitSeconds = parseWaitSeconds(searchParams.get("wait"), 0, MAX_WAIT_SECONDS);
1237
+ if (!TERMINAL_STATUSES.has(run.status) && waitSeconds > 0) {
1238
+ const ac = new AbortController();
1239
+ const onClose = () => ac.abort();
1240
+ req.once("close", onClose);
1241
+ try {
1242
+ await waitWithTimeoutAndAbort(run.donePromise, waitSeconds * 1000, ac.signal);
1243
+ } finally {
1244
+ req.off("close", onClose);
1245
+ }
1246
+ }
1247
+
1248
+ if (res.writableEnded || res.destroyed) return;
1249
+ writeJson(res, 200, this.serializeRun(run));
1250
+ }
1251
+
1252
+ async handleRunEventsSse(req, res, rawRunId, rawSessionId) {
1253
+ const runId = parsePathSegment(rawRunId);
1254
+ if (runId === null) {
1255
+ writeJson(res, 400, { error: "invalid run_id" });
1256
+ return;
1257
+ }
1258
+ let sessionId;
1259
+ if (rawSessionId !== void 0) {
1260
+ sessionId = parsePathSegment(rawSessionId);
1261
+ if (sessionId === null) {
1262
+ writeJson(res, 400, { error: "invalid session_id" });
1263
+ return;
1264
+ }
1265
+ }
1266
+
1267
+ const run = this.findRun(runId, sessionId);
1268
+ if (!run) {
1269
+ writeJson(res, 404, { error: "run not found" });
1270
+ return;
1271
+ }
1272
+
1273
+ openSseStream(res);
1274
+ let eventCounter = 1;
1275
+ writeSseEvent(res, "run.snapshot", this.serializeRun(run), eventCounter++);
1276
+
1277
+ if (TERMINAL_STATUSES.has(run.status)) {
1278
+ writeSseEvent(res, `run.${run.status}`, this.serializeRun(run), eventCounter++);
1279
+ res.end();
1280
+ return;
1281
+ }
1282
+
1283
+ await new Promise((resolveStream) => {
1284
+ let closed = false;
1285
+ const cleanup = () => {
1286
+ if (closed) return;
1287
+ closed = true;
1288
+ clearInterval(heartbeat);
1289
+ req.off("close", cleanup);
1290
+ const set = this.sseSubscribers.get(run.runId);
1291
+ if (set) {
1292
+ set.delete(onEvent);
1293
+ if (set.size === 0) this.sseSubscribers.delete(run.runId);
1294
+ }
1295
+ if (!res.writableEnded && !res.destroyed) {
1296
+ res.end();
1297
+ }
1298
+ resolveStream();
1299
+ };
1300
+
1301
+ const onEvent = (eventName, payload) => {
1302
+ if (closed) return;
1303
+ writeSseEvent(res, eventName, payload, eventCounter++);
1304
+ if (eventName === "run.completed" || eventName === "run.cancelled" || eventName === "run.failed") {
1305
+ cleanup();
1306
+ }
1307
+ };
1308
+
1309
+ let set = this.sseSubscribers.get(run.runId);
1310
+ if (set === void 0) {
1311
+ set = new Set();
1312
+ this.sseSubscribers.set(run.runId, set);
1313
+ }
1314
+ set.add(onEvent);
1315
+
1316
+ const heartbeat = setInterval(() => {
1317
+ if (closed) return;
1318
+ writeSseComment(res, "ping");
1319
+ }, SSE_HEARTBEAT_MS);
1320
+ heartbeat.unref?.();
1321
+
1322
+ req.once("close", cleanup);
1323
+ });
1324
+ }
1325
+
1326
+ async handleCancelRun(req, res, rawRunId, rawSessionId, searchParams) {
1327
+ const runId = parsePathSegment(rawRunId);
1328
+ if (runId === null) {
1329
+ writeJson(res, 400, { error: "invalid run_id" });
1330
+ return;
1331
+ }
1332
+ let sessionId;
1333
+ if (rawSessionId !== void 0) {
1334
+ sessionId = parsePathSegment(rawSessionId);
1335
+ if (sessionId === null) {
1336
+ writeJson(res, 400, { error: "invalid session_id" });
1337
+ return;
1338
+ }
1339
+ }
1340
+
1341
+ const run = this.findRun(runId, sessionId);
1342
+ if (!run) {
1343
+ writeJson(res, 404, { error: "run not found" });
1344
+ return;
1345
+ }
1346
+
1347
+ const waitSeconds = parseWaitSeconds(
1348
+ searchParams.get("wait"),
1349
+ DEFAULT_CANCEL_WAIT_SECONDS,
1350
+ MAX_WAIT_SECONDS,
1351
+ );
1352
+ const { stopped } = await this.cancelRun(run, waitSeconds * 1000);
1353
+ writeJson(res, 200, {
1354
+ ...this.serializeRun(run),
1355
+ stopped,
1356
+ });
1357
+ }
1358
+
1359
+ async handleCancelSession(req, res, rawSessionId, searchParams) {
1360
+ const sessionId = parsePathSegment(rawSessionId);
1361
+ if (sessionId === null) {
1362
+ writeJson(res, 400, { error: "invalid session_id" });
1363
+ return;
1364
+ }
1365
+ let body = {};
1366
+ try {
1367
+ body = await readJsonBody(req, 64 * 1024, { allowEmpty: true });
1368
+ } catch (error) {
1369
+ writeJson(res, error?.statusCode ?? 400, { error: error instanceof Error ? error.message : "bad request" });
1370
+ return;
1371
+ }
1372
+ const clearQueue = body?.clear_queue !== false;
1373
+ const waitSeconds = parseWaitSeconds(
1374
+ searchParams.get("wait"),
1375
+ DEFAULT_CANCEL_WAIT_SECONDS,
1376
+ MAX_WAIT_SECONDS,
1377
+ );
1378
+ const result = await this.cancelSession(sessionId, {
1379
+ clearQueue,
1380
+ waitMs: waitSeconds * 1000,
1381
+ });
1382
+ writeJson(res, 200, result);
1383
+ }
1384
+ }