@botlearn-course/daemon 0.0.31 → 0.0.32-beta.2

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.
@@ -1,13 +1,16 @@
1
+ import { MD_REVIEW_TOOL, MdReviewPreparation, prepareMdReviewDirectory } from "./md-review.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { spawn } from "node:child_process";
3
- import { chmodSync, existsSync, lstatSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
4
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
4
5
  import path from "node:path";
5
6
  import net from "node:net";
6
7
  import { MAX_PROGRESS_EVENTS_PER_ATTEMPT } from "../mcp/report-progress.js";
7
8
  import { prepareRuntimeSkillsHome, RUNTIME_SKILLS_RELATIVE_PATH, } from "../runtime-skill-materialization.js";
8
9
  import { startCourseSkillsMcpServer, } from "../mcp/course-skills-server.js";
9
10
  import { sanitizeRuntimeFailureText } from "../redaction.js";
11
+ import { ensureDaemonHome } from "../auth-store.js";
10
12
  import { runtimeChildEnv, runtimeChildLaunch } from "../runtime-env.js";
13
+ import { quiesceRuntimeWriters } from "../runtime-quiescence.js";
11
14
  import { ToolSemantics } from "./tool-semantics.js";
12
15
  import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
13
16
  import { DeepseekCourseSkills, DEEPSEEK_COURSE_SKILL_TOOLS } from "./deepseek-course-skills.js";
@@ -35,7 +38,48 @@ function isMissingThreadHttpError(error) {
35
38
  const log = consoleLogger;
36
39
  const DEEPSEEK_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
37
40
  const STARTUP_TIMEOUT_MS = 30_000;
41
+ /**
42
+ * Upper bound for loading an existing native thread into a server process that has not
43
+ * touched it yet (`POST /v1/threads/{id}/resume`). The run signal already ends this wait
44
+ * at the dispatcher's run deadline (`limits.timeout_seconds`, 30–7200 s) or on cancel;
45
+ * this cap stops one stuck load from consuming a long run budget. Codewhale 0.9.12 took
46
+ * about 13 s for a long history on shared storage, so 120 s leaves room for slower volumes.
47
+ */
48
+ const THREAD_RESUME_PREWARM_TIMEOUT_MS = 120_000;
49
+ /**
50
+ * Short window for compact/turn submission to return its turn id. The runtime may have
51
+ * accepted a timed-out submission, so callers report it and never resubmit blindly.
52
+ */
53
+ const SUBMIT_TIMEOUT_MS = 5_000;
54
+ /**
55
+ * Codewhale 0.10 waits up to 180 s for model response headers and then resends once.
56
+ * Managed runs keep the 0.9.12 bound (45 s, one retry); 0.8.39 ignores this variable.
57
+ */
58
+ const MANAGED_STREAM_OPEN_TIMEOUT_SECS = "45";
59
+ /** Runtime versions whose external tool protocol has passed the MD review integration. */
60
+ const MD_REVIEW_RUNTIME_VERSIONS = new Set(["0.9.12", "0.10.4"]);
61
+ /**
62
+ * Versions verified to apply a PATCHed system prompt to an already loaded thread. Other
63
+ * versions keep the first prompt, so a prompt change replaces their server process.
64
+ */
65
+ const PROMPT_REFRESHING_RUNTIME_VERSIONS = new Set(["0.10.4"]);
66
+ /** Versions verified to read `CODEWHALE_RUNTIME_TOKEN` for `serve --http`. */
67
+ const RUNTIME_TOKEN_ENV_VERSIONS = new Set(["0.9.12", "0.10.4"]);
38
68
  const STARTUP_POLL_MS = 250;
69
+ /**
70
+ * Upper bound for a stopped server process to exit before its replacement may start.
71
+ * Codewhale holds the runtime directory's exclusive owner lock until the process exits,
72
+ * so a replacement started earlier fails with a lock collision. SIGTERM normally ends the
73
+ * server within milliseconds; the force step starts at half the budget and the launcher's
74
+ * cgroup quiesce waits up to 5 s for `populated 0`.
75
+ */
76
+ const PROCESS_EXIT_CONFIRM_BUDGET_MS = 15_000;
77
+ const PROCESS_EXIT_POLL_MS = 50;
78
+ /**
79
+ * Daemon-home record of the live managed server. A daemon that crashed leaves its server
80
+ * holding the runtime lock; the next daemon stops exactly that process group at startup.
81
+ */
82
+ const RUNTIME_PROCESS_RECORD = "deepseek-runtime-process.json";
39
83
  /** 单轮流式 assistant 文本字节上限。 */
40
84
  const SSE_TEXT_CAP = 1 * 1024 * 1024;
41
85
  const VISION_MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/;
@@ -64,7 +108,11 @@ const DEEPSEEK_COURSE_SKILL_TOOL_ALIASES = new Set([
64
108
  "courseskills:load_skill",
65
109
  "courseskills:load_reference",
66
110
  ]);
67
- function createManagedRuntimeConfig(opts, progressMcpConfig) {
111
+ /**
112
+ * Managed `config.toml` content without the per-process MCP path. Managed runs pass only
113
+ * the daemon relay address and local token here; the text is part of the process key.
114
+ */
115
+ function managedRuntimeConfigBody(opts) {
68
116
  const model = opts.env?.BOTLEARN_DEEPSEEK_VISION_MODEL?.trim();
69
117
  const managedProxy = Boolean(opts.env?.BOTLEARN_AGENT_SERVICE_ACTIVATION_ID?.trim()
70
118
  && opts.env?.DEEPSEEK_BASE_URL?.trim());
@@ -73,9 +121,6 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
73
121
  if (model && !VISION_MODEL_PATTERN.test(model)) {
74
122
  throw new Error("invalid managed DeepSeek vision model");
75
123
  }
76
- if (!progressMcpConfig) {
77
- throw new Error("managed DeepSeek runtime config requires an ephemeral config directory");
78
- }
79
124
  const apiKey = opts.env?.DEEPSEEK_API_KEY?.trim();
80
125
  const rawBaseUrl = opts.env?.DEEPSEEK_BASE_URL?.trim();
81
126
  if (!apiKey || !rawBaseUrl) {
@@ -104,11 +149,7 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
104
149
  ]
105
150
  : [];
106
151
  baseUrl.pathname = `${baseUrl.pathname.replace(/\/+$/, "")}/v1`;
107
- const configPath = path.join(progressMcpConfig.dir, "config.toml");
108
- const managedRuntime = Boolean(process.env.BOTLEARN_RUNTIME_USER?.trim()
109
- || process.env.BOTLEARN_RUNTIME_LAUNCH_MODE?.trim());
110
- writeFileSync(configPath, [
111
- `mcp_config_path = ${JSON.stringify(progressMcpConfig.path)}`,
152
+ return [
112
153
  ...providerConfig,
113
154
  ...(managedProxy && !(opts.skillProvider?.catalog.length) ? [
114
155
  "[tools.overrides]",
@@ -125,7 +166,18 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
125
166
  `base_url = ${JSON.stringify(baseUrl.toString())}`,
126
167
  "",
127
168
  ] : []),
128
- ].join("\n"), { mode: managedRuntime ? 0o640 : 0o600 });
169
+ ].join("\n");
170
+ }
171
+ function writeManagedRuntimeConfig(body, progressMcpConfig) {
172
+ if (body === undefined)
173
+ return undefined;
174
+ if (!progressMcpConfig) {
175
+ throw new Error("managed DeepSeek runtime config requires an ephemeral config directory");
176
+ }
177
+ const configPath = path.join(progressMcpConfig.dir, "config.toml");
178
+ const managedRuntime = Boolean(process.env.BOTLEARN_RUNTIME_USER?.trim()
179
+ || process.env.BOTLEARN_RUNTIME_LAUNCH_MODE?.trim());
180
+ writeFileSync(configPath, [`mcp_config_path = ${JSON.stringify(progressMcpConfig.path)}`, body].join("\n"), { mode: managedRuntime ? 0o640 : 0o600 });
129
181
  if (managedRuntime)
130
182
  chmodSync(configPath, 0o640);
131
183
  return configPath;
@@ -133,6 +185,18 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
133
185
  const PROCESS_POOL = new Map();
134
186
  /** 单 daemon、单套 env 配置:池里最多一个 server。 */
135
187
  const POOL_KEY = "default";
188
+ /**
189
+ * Server processes that were told to stop but whose exit is not confirmed yet. Every
190
+ * spawn first confirms these are gone; an unconfirmed handle stays here for the next check.
191
+ */
192
+ const RELEASING = new Set();
193
+ export class DeepseekProcessNotReleasedError extends Error {
194
+ errorCode = "runtime_previous_process_not_released";
195
+ constructor() {
196
+ super("runtime_previous_process_not_released: previous DeepSeek server did not exit");
197
+ this.name = "DeepseekProcessNotReleasedError";
198
+ }
199
+ }
136
200
  let exitCleanupHookInstalled = false;
137
201
  const DEEPSEEK_TURN_QUEUES = new Map();
138
202
  /**
@@ -185,15 +249,22 @@ export class DeepseekTuiAdapter {
185
249
  explicitAuthToken;
186
250
  fetchFn;
187
251
  spawnFn;
252
+ threadPrewarmTimeoutMs;
253
+ processExitBudgetMs;
254
+ submitTimeoutMs;
188
255
  progressEventMappingEnabled;
189
256
  progressPromptInjectionEnabled;
190
257
  resolvedBinary = null;
258
+ runtimeVersions = new Map();
191
259
  constructor(deps = {}) {
192
260
  this.explicitBinary = deps.binary ?? process.env.BOTLEARN_DEEPSEEK_TUI_BIN;
193
261
  this.explicitServerUrl = deps.serverUrl ?? process.env.BOTLEARN_DEEPSEEK_TUI_URL;
194
262
  this.explicitAuthToken = deps.authToken ?? process.env.BOTLEARN_DEEPSEEK_TUI_TOKEN;
195
263
  this.fetchFn = deps.fetchFn ?? fetch;
196
264
  this.spawnFn = deps.spawnFn ?? spawn;
265
+ this.threadPrewarmTimeoutMs = deps.threadPrewarmTimeoutMs ?? THREAD_RESUME_PREWARM_TIMEOUT_MS;
266
+ this.processExitBudgetMs = deps.processExitBudgetMs ?? PROCESS_EXIT_CONFIRM_BUDGET_MS;
267
+ this.submitTimeoutMs = deps.submitTimeoutMs ?? SUBMIT_TIMEOUT_MS;
197
268
  this.progressPromptInjectionEnabled =
198
269
  !this.explicitServerUrl && progressMcpAutoInjectionSupported();
199
270
  this.progressEventMappingEnabled = this.explicitServerUrl
@@ -235,9 +306,12 @@ export class DeepseekTuiAdapter {
235
306
  if (turnAbort.signal.aborted)
236
307
  throw abortReason(turnAbort.signal);
237
308
  handle.inFlight += 1;
309
+ handle.runsServed += 1;
238
310
  countedInFlight = true;
239
311
  if (handle.idleTimer)
240
312
  clearTimeout(handle.idleTimer);
313
+ // Failure diagnostics describe this run only, also on a reused process.
314
+ handle.stderrTail = "";
241
315
  const headers = authHeaders(handle.token);
242
316
  if (threadId && !isValidThreadId(threadId)) {
243
317
  return {
@@ -252,15 +326,31 @@ export class DeepseekTuiAdapter {
252
326
  let maintenanceUsage;
253
327
  while (true) {
254
328
  try {
329
+ const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
330
+ const settings = sha256Hex(JSON.stringify([
331
+ this.runtimeSystemContext(opts) ?? null, selection.model ?? null,
332
+ ]));
255
333
  if (!threadId) {
256
334
  threadId = await this.createThread(handle.baseUrl, headers, opts, turnAbort.signal);
335
+ handle.loadedThreads.add(threadId);
336
+ handle.threadSettings.set(threadId, settings);
257
337
  }
258
338
  else {
259
- const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
260
339
  if (opts.systemPrompt !== undefined || opts.systemContext !== undefined
261
340
  || opts.skillProvider || selection.model) {
262
341
  await this.patchThreadSettings(handle.baseUrl, headers, threadId, opts, selection.model, turnAbort.signal);
342
+ // Codewhale 0.10 rebuilds a loaded engine when its settings change; load the
343
+ // thread again under the run deadline instead of the short submit window.
344
+ if (handle.threadSettings.get(threadId) !== settings) {
345
+ handle.loadedThreads.delete(threadId);
346
+ }
347
+ handle.threadSettings.set(threadId, settings);
263
348
  }
349
+ // Load the existing thread after the settings update and before compact/turn,
350
+ // so cold history rebuilding runs under the run deadline instead of the short
351
+ // submit windows. Codewhale 0.9.12 keeps the prompt of an already loaded
352
+ // engine, so loading before PATCH would serve the previous system prompt.
353
+ await this.prewarmThread(handle, headers, threadId, turnAbort.signal);
264
354
  if (managedActivationId && this.compactionRequired(opts)) {
265
355
  const compacted = await this.compactThread({
266
356
  baseUrl: handle.baseUrl,
@@ -368,6 +458,9 @@ export class DeepseekTuiAdapter {
368
458
  ...(err instanceof DeepseekUserInputHandoffError
369
459
  ? { runtimeFailure: { error_code: "runtime_interactive_tool_handoff_failed" } }
370
460
  : {}),
461
+ ...(err instanceof DeepseekProcessNotReleasedError
462
+ ? { runtimeFailure: { error_code: err.errorCode } }
463
+ : {}),
371
464
  };
372
465
  }
373
466
  finally {
@@ -375,14 +468,10 @@ export class DeepseekTuiAdapter {
375
468
  opts.signal.removeEventListener("abort", onAbort);
376
469
  if (handle && countedInFlight) {
377
470
  handle.inFlight = Math.max(0, handle.inFlight - 1);
378
- if (managedActivationId && !this.explicitServerUrl && handle.inFlight === 0) {
379
- if (PROCESS_POOL.get(POOL_KEY) === handle)
380
- PROCESS_POOL.delete(POOL_KEY);
381
- shutdownHandle(handle, "managed-activation-finished");
382
- }
383
- else if (!this.explicitServerUrl) {
471
+ // A managed process belongs to its RuntimeSession: the end of an AgentRun
472
+ // never stops it (releaseDeepseekRuntime does). Local processes idle out.
473
+ if (!this.explicitServerUrl && !handle.managed)
384
474
  resetIdle(handle, POOL_KEY);
385
- }
386
475
  }
387
476
  }
388
477
  finally {
@@ -405,12 +494,19 @@ export class DeepseekTuiAdapter {
405
494
  }
406
495
  return {
407
496
  child: nullChild(),
497
+ cgroupScope: null,
498
+ exitObserved: false,
408
499
  baseUrl: trimTrailingSlash(this.explicitServerUrl),
409
500
  token: this.explicitAuthToken ?? "",
410
- managedActivationId: null,
501
+ managed: false,
502
+ sessionKey: null,
503
+ compatDigest: "",
411
504
  closed: false,
412
505
  inFlight: 0,
413
506
  stderrTail: "",
507
+ runsServed: 0,
508
+ loadedThreads: new Set(),
509
+ threadSettings: new Map(),
414
510
  };
415
511
  }
416
512
  const managedActivationId = this.managedActivationId(opts);
@@ -420,27 +516,8 @@ export class DeepseekTuiAdapter {
420
516
  if (opts.skillProvider && !opts.onSkillEvent) {
421
517
  throw new Error("courseskills requires its technical event sink");
422
518
  }
423
- const systemPromptDigest = createHash("sha256")
424
- .update(this.runtimeSystemContext(opts) ?? "").digest("hex");
425
- const existing = PROCESS_POOL.get(POOL_KEY);
426
- if (existing
427
- && !existing.closed
428
- && existing.managedActivationId === managedActivationId
429
- && existing.systemPromptDigest === systemPromptDigest) {
430
- return existing;
431
- }
432
- if (existing) {
433
- PROCESS_POOL.delete(POOL_KEY);
434
- shutdownHandle(existing, "activation-scope-changed");
435
- }
436
- const port = await findFreePort();
437
- if (signal.aborted)
438
- throw abortReason(signal);
439
- const token = randomToken();
440
- const baseUrl = `http://127.0.0.1:${port}`;
441
519
  const binary = this.resolveBinary();
442
- const runtimeVersion = readCommandVersion(binary, [], { env: opts.env })
443
- ?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0];
520
+ const runtimeVersion = this.runtimeVersion(binary, opts.env);
444
521
  // 0.8.39 predates external tools and waits for its MCP catalog synchronously.
445
522
  // Newer runtimes must advertise native external tools; never silently fall
446
523
  // back to asynchronous MCP discovery after a capability/protocol failure.
@@ -449,58 +526,121 @@ export class DeepseekTuiAdapter {
449
526
  // are exposed only when this activation authorizes at least one course Skill.
450
527
  const isolatesSkillProfile = Boolean(opts.skillProvider || managedActivationId);
451
528
  const exposesCourseSkills = (opts.skillProvider?.catalog.length ?? 0) > 0;
452
- const courseSkills = exposesCourseSkills && !legacySkillsMcp
453
- ? new DeepseekCourseSkills({
454
- prepared: opts.skillProvider,
455
- onEvent: opts.onSkillEvent ?? (async () => { }),
456
- })
457
- : undefined;
529
+ const usesProgressConfig = Boolean(this.progressPromptInjectionEnabled || isolatesSkillProfile
530
+ || (managedActivationId && opts.env?.DEEPSEEK_BASE_URL?.trim()));
531
+ const configBody = managedRuntimeConfigBody(opts);
532
+ const sessionKey = managedActivationId ? opts.runtimeSessionKey?.trim() || null : null;
533
+ if (managedActivationId && !sessionKey) {
534
+ throw new Error("managed DeepSeek run requires a RuntimeSession key");
535
+ }
536
+ const compatDigest = createHash("sha256").update(JSON.stringify({
537
+ binary,
538
+ runtimeVersion: runtimeVersion ?? null,
539
+ configBody: configBody ?? null,
540
+ runtimeDir: managedActivationId ? this.managedRuntimeDirPath(opts) : null,
541
+ credentialRef: sha256Hex(opts.env?.DEEPSEEK_API_KEY ?? ""),
542
+ isolatesSkillProfile,
543
+ usesProgressConfig,
544
+ // Older engines keep the first system prompt of a loaded thread (PATCH is ignored).
545
+ prompt: PROMPT_REFRESHING_RUNTIME_VERSIONS.has(runtimeVersion ?? "")
546
+ ? null
547
+ : sha256Hex(this.runtimeSystemContext(opts) ?? ""),
548
+ // 0.8.39 binds its Skill MCP server, and its event sink, to one process.
549
+ legacySkills: legacySkillsMcp && exposesCourseSkills ? managedActivationId : null,
550
+ })).digest("hex");
551
+ let handle = PROCESS_POOL.get(POOL_KEY);
552
+ if (!handle
553
+ || handle.closed
554
+ || handle.sessionKey !== sessionKey
555
+ || handle.compatDigest !== compatDigest) {
556
+ if (handle) {
557
+ PROCESS_POOL.delete(POOL_KEY);
558
+ shutdownHandle(handle, "runtime-process-replaced");
559
+ }
560
+ handle = await this.spawnHandle({
561
+ opts,
562
+ signal,
563
+ binary,
564
+ runtimeVersion,
565
+ managed: Boolean(managedActivationId),
566
+ sessionKey,
567
+ compatDigest,
568
+ configBody,
569
+ usesProgressConfig,
570
+ isolatesSkillProfile,
571
+ legacySkillsMcp: legacySkillsMcp && exposesCourseSkills,
572
+ });
573
+ }
574
+ const needsReviewTools = managedActivationId && MD_REVIEW_RUNTIME_VERSIONS.has(runtimeVersion ?? "")
575
+ && opts.runtimeStateDir && opts.mdReviewEvidence && parseDeepseekRuntimeSelection(opts.extraArgs).model;
576
+ if ((exposesCourseSkills && !legacySkillsMcp) || needsReviewTools) {
577
+ handle.externalTools ??= await this.readExternalToolsCapability(handle, signal);
578
+ if (!handle.externalTools) {
579
+ throw new Error("course_skill_runtime_external_tools_unavailable");
580
+ }
581
+ }
582
+ return handle;
583
+ }
584
+ async spawnHandle(args) {
585
+ const { opts, signal, binary, runtimeVersion } = args;
586
+ // Never start a writer while an older server may still hold the runtime directory lock.
587
+ if (!(await confirmReleasedProcesses(this.processExitBudgetMs))) {
588
+ throw new DeepseekProcessNotReleasedError();
589
+ }
590
+ const port = await findFreePort();
591
+ if (signal.aborted)
592
+ throw abortReason(signal);
593
+ const token = randomToken();
594
+ const baseUrl = `http://127.0.0.1:${port}`;
458
595
  let courseSkillsMcpServer;
459
596
  let progressMcpConfig;
460
597
  let runtimeConfigPath;
461
598
  try {
462
- courseSkillsMcpServer = exposesCourseSkills && legacySkillsMcp
599
+ courseSkillsMcpServer = args.legacySkillsMcp
463
600
  ? await startCourseSkillsMcpServer({
464
601
  prepared: opts.skillProvider,
465
602
  onEvent: opts.onSkillEvent ?? (async () => { }),
466
603
  })
467
604
  : undefined;
468
- progressMcpConfig =
469
- this.progressPromptInjectionEnabled || isolatesSkillProfile
470
- || (managedActivationId && opts.env?.DEEPSEEK_BASE_URL?.trim())
471
- ? createProgressMcpConfig({
472
- ...(courseSkillsMcpServer
473
- ? { courseSkillsSocketPath: courseSkillsMcpServer.socketPath }
474
- : {}),
475
- })
476
- : undefined;
477
- if (isolatesSkillProfile && progressMcpConfig) {
478
- prepareRuntimeSkillsHome(progressMcpConfig.dir, Boolean(this.managedActivationId(opts)));
605
+ progressMcpConfig = args.usesProgressConfig
606
+ ? createProgressMcpConfig({
607
+ ...(courseSkillsMcpServer
608
+ ? { courseSkillsSocketPath: courseSkillsMcpServer.socketPath }
609
+ : {}),
610
+ })
611
+ : undefined;
612
+ if (args.isolatesSkillProfile && progressMcpConfig) {
613
+ prepareRuntimeSkillsHome(progressMcpConfig.dir, args.managed);
479
614
  }
480
- runtimeConfigPath = createManagedRuntimeConfig(opts, progressMcpConfig);
615
+ runtimeConfigPath = writeManagedRuntimeConfig(args.configBody, progressMcpConfig);
481
616
  }
482
617
  catch (error) {
483
618
  cleanupDeepseekResources({ progressMcpConfig, courseSkillsMcpServer });
484
619
  throw error;
485
620
  }
486
- const args = [
621
+ // 0.9.12+ read the runtime API token from the environment; argv is visible to every user.
622
+ const tokenInEnv = RUNTIME_TOKEN_ENV_VERSIONS.has(runtimeVersion ?? "");
623
+ const serveArgs = [
487
624
  "serve",
488
625
  "--http",
489
626
  "--host",
490
627
  "127.0.0.1",
491
628
  "--port",
492
629
  String(port),
493
- "--auth-token",
494
- token,
630
+ ...(tokenInEnv ? [] : ["--auth-token", token]),
495
631
  ];
496
- const launch = runtimeChildLaunch(binary, args);
632
+ const launch = runtimeChildLaunch(binary, serveArgs);
497
633
  let child;
634
+ let childEnv;
498
635
  try {
636
+ childEnv = this.spawnEnv(opts, progressMcpConfig?.path, runtimeConfigPath, progressMcpConfig && args.isolatesSkillProfile
637
+ ? path.join(progressMcpConfig.dir, RUNTIME_SKILLS_RELATIVE_PATH)
638
+ : undefined);
639
+ if (tokenInEnv)
640
+ childEnv.CODEWHALE_RUNTIME_TOKEN = token;
499
641
  child = this.spawnFn(launch.binary, launch.args, {
500
642
  cwd: opts.cwd,
501
- env: this.spawnEnv(opts, progressMcpConfig?.path, runtimeConfigPath, progressMcpConfig && isolatesSkillProfile
502
- ? path.join(progressMcpConfig.dir, RUNTIME_SKILLS_RELATIVE_PATH)
503
- : undefined),
643
+ env: childEnv,
504
644
  ...launch.identity,
505
645
  stdio: ["ignore", "pipe", "pipe"],
506
646
  // 自成进程组:解析到的二进制可能是会再 spawn 真实 deepseek-tui
@@ -515,23 +655,36 @@ export class DeepseekTuiAdapter {
515
655
  installExitCleanupHook();
516
656
  const handle = {
517
657
  child,
658
+ ...(typeof child.pid === "number" && child.pid > 0 ? { pgid: child.pid } : {}),
659
+ // The managed launcher places the server in the cgroup named by its activation scope.
660
+ cgroupScope: launch.binary !== binary
661
+ ? childEnv.BOTLEARN_RUNTIME_ACTIVATION_SCOPE ?? null
662
+ : null,
663
+ exitObserved: false,
518
664
  baseUrl,
519
665
  token,
520
- managedActivationId,
521
- systemPromptDigest,
666
+ managed: args.managed,
667
+ sessionKey: args.sessionKey,
668
+ compatDigest: args.compatDigest,
522
669
  closed: false,
523
670
  inFlight: 0,
524
671
  stderrTail: "",
525
672
  progressMcpConfig,
526
673
  courseSkillsMcpServer,
527
- courseSkills,
528
674
  runtimeVersion,
675
+ runsServed: 0,
676
+ loadedThreads: new Set(),
677
+ threadSettings: new Map(),
529
678
  };
530
679
  child.stderr?.setEncoding("utf8");
531
680
  child.stderr?.on("data", (chunk) => {
532
681
  handle.stderrTail = sanitizeRuntimeFailureText(handle.stderrTail + chunk, 4096);
533
682
  });
683
+ child.on("exit", () => {
684
+ handle.exitObserved = true;
685
+ });
534
686
  child.on("close", () => {
687
+ handle.exitObserved = true;
535
688
  handle.closed = true;
536
689
  if (PROCESS_POOL.get(POOL_KEY) === handle)
537
690
  PROCESS_POOL.delete(POOL_KEY);
@@ -546,14 +699,6 @@ export class DeepseekTuiAdapter {
546
699
  });
547
700
  try {
548
701
  await waitForHealth(baseUrl, this.fetchFn, handle, STARTUP_TIMEOUT_MS, signal);
549
- if (courseSkills) {
550
- const info = await this.requestJson(`${baseUrl}/v1/runtime/info`, { headers: authHeaders(token), signal: AbortSignal.any([
551
- signal, AbortSignal.timeout(STARTUP_TIMEOUT_MS),
552
- ]) });
553
- if (info.capabilities?.external_tools !== true) {
554
- throw new Error("course_skill_runtime_external_tools_unavailable");
555
- }
556
- }
557
702
  await courseSkillsMcpServer?.markApplied();
558
703
  }
559
704
  catch (error) {
@@ -561,13 +706,31 @@ export class DeepseekTuiAdapter {
561
706
  throw error;
562
707
  }
563
708
  PROCESS_POOL.set(POOL_KEY, handle);
564
- resetIdle(handle, POOL_KEY);
709
+ if (handle.managed && handle.pgid)
710
+ writeRuntimeProcessRecord(handle);
711
+ // Managed processes live until their RuntimeSession releases them; idle sandboxes are
712
+ // paused by Agent Service. Local processes keep the daemon idle timer.
713
+ if (!handle.managed)
714
+ resetIdle(handle, POOL_KEY);
565
715
  return handle;
566
716
  }
717
+ async readExternalToolsCapability(handle, signal) {
718
+ const info = await this.requestJson(`${handle.baseUrl}/v1/runtime/info`, { headers: authHeaders(handle.token), signal: AbortSignal.any([
719
+ signal, AbortSignal.timeout(STARTUP_TIMEOUT_MS),
720
+ ]) });
721
+ return info.capabilities?.external_tools === true;
722
+ }
723
+ runtimeVersion(binary, env) {
724
+ if (!this.runtimeVersions.has(binary)) {
725
+ this.runtimeVersions.set(binary, readCommandVersion(binary, [], { env })
726
+ ?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0]);
727
+ }
728
+ return this.runtimeVersions.get(binary);
729
+ }
567
730
  /**
568
731
  * BYOA continues to use the user's default DeepSeek state directory. Managed mode
569
- * pins the durable RuntimeThreadStore to the RuntimeSession workspace even though
570
- * the credential-bearing server process is still reclaimed after every activation.
732
+ * pins the durable RuntimeThreadStore to the RuntimeSession workspace; the process
733
+ * holds only the daemon relay's local token, never a model grant.
571
734
  */
572
735
  spawnEnv(opts, progressMcpConfigPath, runtimeConfigPath, skillsDir) {
573
736
  const env = {
@@ -587,6 +750,7 @@ export class DeepseekTuiAdapter {
587
750
  if (this.managedActivationId(opts)) {
588
751
  env.DEEPSEEK_RUNTIME_DIR = this.prepareManagedRuntimeDir(opts);
589
752
  env.CODEWHALE_TELEMETRY = "false";
753
+ env.CODEWHALE_STREAM_OPEN_TIMEOUT_SECS = MANAGED_STREAM_OPEN_TIMEOUT_SECS;
590
754
  if (runtimeConfigPath) {
591
755
  // Codewhale treats an environment URL as a new route, even when it
592
756
  // equals the file URL, and refuses that route's bound credentials.
@@ -596,11 +760,14 @@ export class DeepseekTuiAdapter {
596
760
  }
597
761
  return env;
598
762
  }
599
- prepareManagedRuntimeDir(opts) {
763
+ managedRuntimeDirPath(opts) {
600
764
  // Keep native transcripts outside the learner's cwd. The managed workspace parent
601
765
  // is control-owned/traverse-only, and its existing activation fence covers both
602
766
  // siblings. This remains on the same NAS volume for atomic migration and resume.
603
- const runtimeDir = path.join(path.dirname(opts.cwd), path.basename(opts.cwd) + MANAGED_RUNTIME_DIR_NAME);
767
+ return path.join(path.dirname(opts.cwd), path.basename(opts.cwd) + MANAGED_RUNTIME_DIR_NAME);
768
+ }
769
+ prepareManagedRuntimeDir(opts) {
770
+ const runtimeDir = this.managedRuntimeDirPath(opts);
604
771
  const legacyDir = path.join(opts.cwd, MANAGED_RUNTIME_DIR_NAME);
605
772
  if (existsSync(legacyDir)) {
606
773
  const legacy = lstatSync(legacyDir);
@@ -671,6 +838,56 @@ export class DeepseekTuiAdapter {
671
838
  this.logAppliedServerPrompt(opts.systemPrompt);
672
839
  return id;
673
840
  }
841
+ /**
842
+ * Loads an existing thread into a server process that has not touched it yet. Cold
843
+ * history rebuilding can take longer than the short compact/turn submit timeouts, so it
844
+ * runs here under the run signal plus a fixed cap. A missing
845
+ * thread keeps its HTTP status so the caller's missing-thread fallback still applies.
846
+ */
847
+ async prewarmThread(handle, headers, threadId, signal) {
848
+ // An external server is not owned by this daemon, so its load state is unknown.
849
+ if (this.explicitServerUrl || handle.loadedThreads.has(threadId))
850
+ return;
851
+ const startedAt = Date.now();
852
+ const timeout = AbortSignal.timeout(this.threadPrewarmTimeoutMs);
853
+ const fields = (outcome) => ({
854
+ threadId,
855
+ outcome,
856
+ durationMs: Date.now() - startedAt,
857
+ freshProcess: handle.runsServed === 1,
858
+ });
859
+ try {
860
+ if (signal.aborted)
861
+ throw abortReason(signal);
862
+ await this.requestJson(`${handle.baseUrl}/v1/threads/${encodeURIComponent(threadId)}/resume`, {
863
+ method: "POST",
864
+ headers,
865
+ signal: AbortSignal.any([signal, timeout]),
866
+ });
867
+ }
868
+ catch (error) {
869
+ if (signal.aborted) {
870
+ log.info("deepseek-tui.thread-prewarm", fields("aborted"));
871
+ throw abortReason(signal);
872
+ }
873
+ if (timeout.aborted) {
874
+ log.warn("deepseek-tui.thread-prewarm", fields("timeout"));
875
+ throw new Error(`thread resume prewarm timed out after ${this.threadPrewarmTimeoutMs}ms`);
876
+ }
877
+ const missing = isMissingThreadHttpError(error);
878
+ log[missing ? "info" : "warn"]("deepseek-tui.thread-prewarm", {
879
+ ...fields(missing ? "missing" : "failed"),
880
+ ...(error instanceof DeepseekHttpError ? { status: error.status } : {}),
881
+ });
882
+ throw error;
883
+ }
884
+ log.info("deepseek-tui.thread-prewarm", fields("loaded"));
885
+ if (signal.aborted)
886
+ throw abortReason(signal);
887
+ if (handle.closed)
888
+ throw new Error("deepseek serve exited during thread resume prewarm");
889
+ handle.loadedThreads.add(threadId);
890
+ }
674
891
  logAppliedServerPrompt(prompt) {
675
892
  if (prompt === undefined)
676
893
  return;
@@ -729,13 +946,12 @@ export class DeepseekTuiAdapter {
729
946
  try {
730
947
  if (signal.aborted)
731
948
  throw abortReason(signal);
732
- const started = await this.requestJson(`${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/compact`, {
949
+ const started = await this.submitWithTimeout(handle, "compaction", `${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/compact`, {
733
950
  method: "POST",
734
951
  headers,
735
952
  body: JSON.stringify({
736
953
  reason: "BotLearn automatic long-context compaction",
737
954
  }),
738
- signal: AbortSignal.timeout(5_000),
739
955
  });
740
956
  turnId = stringField(started?.turn, "id") ?? stringField(started, "turn_id") ?? "";
741
957
  if (signal.aborted)
@@ -777,6 +993,23 @@ export class DeepseekTuiAdapter {
777
993
  }
778
994
  async startTurnAndReadEvents(args) {
779
995
  const { baseUrl, headers, threadId, opts, signal, handle } = args;
996
+ const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
997
+ // Only versions in MD_REVIEW_RUNTIME_VERSIONS register the tool; native sandbox
998
+ // acceptance is separate from bridge tests. Other runtimes follow the SP absent-tool fallback.
999
+ const mdReview = handle.managed && MD_REVIEW_RUNTIME_VERSIONS.has(handle.runtimeVersion ?? "")
1000
+ && opts.runtimeStateDir && opts.mdReviewEvidence && selection.model
1001
+ ? new MdReviewPreparation({ workspace: opts.cwd, stateDir: prepareMdReviewDirectory(opts.cwd),
1002
+ evidence: structuredClone(opts.mdReviewEvidence), model: selection.model,
1003
+ reasoningEffort: selection.reasoningEffort }) : undefined;
1004
+ // Skill tools and their event sink belong to this run, even on a reused process.
1005
+ // 0.8.39 uses its process-bound Skill MCP server instead.
1006
+ const courseSkills = (opts.skillProvider?.catalog.length ?? 0) > 0
1007
+ && handle.runtimeVersion !== "0.8.39"
1008
+ ? new DeepseekCourseSkills({
1009
+ prepared: opts.skillProvider,
1010
+ onEvent: opts.onSkillEvent ?? (async () => { }),
1011
+ })
1012
+ : undefined;
780
1013
  // 事件流必须先于 turn 打开,否则 turn 早期事件会丢。
781
1014
  const eventsUrl = `${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=0`;
782
1015
  const eventsAbort = new AbortController();
@@ -800,12 +1033,11 @@ export class DeepseekTuiAdapter {
800
1033
  };
801
1034
  signal.addEventListener("abort", onAbort, { once: true });
802
1035
  let eventsError;
803
- const eventsReaderPromise = this.readEvents(eventsUrl, headers, opts, eventsAbort.signal, handle.courseSkills).catch((err) => {
1036
+ const eventsReaderPromise = this.readEvents(eventsUrl, headers, opts, eventsAbort.signal, courseSkills, mdReview).catch((err) => {
804
1037
  eventsError = err;
805
1038
  return null;
806
1039
  });
807
1040
  try {
808
- const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
809
1041
  const body = {
810
1042
  prompt: opts.text,
811
1043
  mode: "agent",
@@ -817,21 +1049,24 @@ export class DeepseekTuiAdapter {
817
1049
  body.model = selection.model;
818
1050
  if (selection.reasoningEffort)
819
1051
  body.reasoning_effort = selection.reasoningEffort;
820
- if (handle.courseSkills)
821
- body.dynamic_tools = DEEPSEEK_COURSE_SKILL_TOOLS;
1052
+ const dynamicTools = [
1053
+ ...(courseSkills ? DEEPSEEK_COURSE_SKILL_TOOLS : []),
1054
+ ...(mdReview ? [MD_REVIEW_TOOL] : []),
1055
+ ];
1056
+ if (dynamicTools.length)
1057
+ body.dynamic_tools = dynamicTools;
822
1058
  if (signal.aborted)
823
1059
  throw abortReason(signal);
824
- const started = await this.requestJson(`${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/turns`, {
1060
+ // Once the request is sent, keep a short independent timeout so we can obtain
1061
+ // turnId and explicitly interrupt it even if the outer run is cancelled.
1062
+ const started = await this.submitWithTimeout(handle, "turn", `${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/turns`, {
825
1063
  method: "POST",
826
1064
  headers,
827
1065
  body: JSON.stringify(body),
828
- // Once the request is sent, keep a short independent timeout so we can obtain
829
- // turnId and explicitly interrupt it even if the outer run is cancelled.
830
- signal: AbortSignal.timeout(5_000),
831
1066
  });
832
1067
  turnId = stringField(started?.turn, "id") ?? stringField(started, "turn_id") ?? "";
833
1068
  if (turnId && !signal.aborted)
834
- await handle.courseSkills?.markApplied();
1069
+ await courseSkills?.markApplied();
835
1070
  if (signal.aborted)
836
1071
  await interrupt();
837
1072
  const eventsReader = await eventsReaderPromise;
@@ -875,7 +1110,7 @@ export class DeepseekTuiAdapter {
875
1110
  if (!res.ok)
876
1111
  throw new Error(`interrupt failed HTTP ${res.status}`);
877
1112
  }
878
- async readEvents(url, headers, opts, signal, courseSkills) {
1113
+ async readEvents(url, headers, opts, signal, courseSkills, mdReview) {
879
1114
  const res = await this.fetchFn(url, { method: "GET", headers, signal });
880
1115
  if (!res.ok)
881
1116
  throw new DeepseekHttpError(res.status, "", "events stream failed");
@@ -931,13 +1166,15 @@ export class DeepseekTuiAdapter {
931
1166
  if (turnId && eventTurnId && eventTurnId !== turnId)
932
1167
  return false;
933
1168
  if (eventName === "tool_call.requested" || embeddedDeepseekEvent(payload) === "tool_call.requested") {
934
- if (!courseSkills)
935
- throw new Error("course_skill_unexpected_external_tool_request");
936
1169
  const threadUrl = new URL(url);
937
1170
  threadUrl.pathname = threadUrl.pathname.replace(/\/events$/, "");
938
1171
  threadUrl.search = "";
939
1172
  const threadId = decodeURIComponent(threadUrl.pathname.split("/").at(-1));
940
- const executed = await courseSkills.execute(payload?.payload ?? payload, { threadId, turnId }, signal);
1173
+ const request = payload?.payload ?? payload;
1174
+ const handler = request?.namespace === "mdreview" ? mdReview : courseSkills;
1175
+ if (!handler)
1176
+ throw new Error("runtime_unexpected_external_tool_request");
1177
+ const executed = await handler.execute(request, { threadId, turnId }, signal);
941
1178
  if (executed) {
942
1179
  const resultUrl = `${threadUrl}/turns/${encodeURIComponent(turnId)}/tool-calls/${encodeURIComponent(executed.callId)}/result`;
943
1180
  const response = await this.fetchFn(resultUrl, {
@@ -1112,6 +1349,22 @@ export class DeepseekTuiAdapter {
1112
1349
  };
1113
1350
  };
1114
1351
  }
1352
+ async submitWithTimeout(handle, operation, url, init) {
1353
+ const timeout = AbortSignal.timeout(this.submitTimeoutMs);
1354
+ try {
1355
+ return await this.requestJson(url, { ...init, signal: timeout });
1356
+ }
1357
+ catch (error) {
1358
+ if (!timeout.aborted)
1359
+ throw error;
1360
+ // The runtime may still run a turn we cannot identify or interrupt. Never hand this
1361
+ // process to a later run of the same thread: stop it, and the next run confirms its
1362
+ // exit before starting a replacement. Learner commands run in their own process groups.
1363
+ if (!this.explicitServerUrl)
1364
+ shutdownHandle(handle, `${operation}-submit-timeout`);
1365
+ throw new Error(`${operation} submit timed out after ${this.submitTimeoutMs}ms; the runtime may have accepted it`);
1366
+ }
1367
+ }
1115
1368
  async requestJson(url, init) {
1116
1369
  const headers = new Headers(init.headers);
1117
1370
  if (!headers.has("content-type") && init.body)
@@ -1130,12 +1383,118 @@ export class DeepseekTuiAdapter {
1130
1383
  return (await res.json());
1131
1384
  }
1132
1385
  }
1386
+ /**
1387
+ * Releases the server process owned by `sessionKey` (any process when null) and confirms
1388
+ * that every stopped process has exited. Called by the RuntimeSession owner on session
1389
+ * change or close, drain, shutdown and generation change. False means a process may still
1390
+ * hold the runtime lock; it stays tracked and blocks the next spawn.
1391
+ */
1392
+ export async function releaseDeepseekRuntime(sessionKey, budgetMs = PROCESS_EXIT_CONFIRM_BUDGET_MS) {
1393
+ const handle = PROCESS_POOL.get(POOL_KEY);
1394
+ if (handle && (sessionKey === null || handle.sessionKey === sessionKey)) {
1395
+ PROCESS_POOL.delete(POOL_KEY);
1396
+ shutdownHandle(handle, "runtime-session-released");
1397
+ }
1398
+ return confirmReleasedProcesses(budgetMs);
1399
+ }
1400
+ function runtimeProcessRecordPath() {
1401
+ return path.join(ensureDaemonHome(), RUNTIME_PROCESS_RECORD);
1402
+ }
1403
+ /** Linux process start time (`/proc/<pid>/stat` field 22); null when unavailable. */
1404
+ function linuxProcessStartTime(pid) {
1405
+ try {
1406
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
1407
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null;
1408
+ }
1409
+ catch {
1410
+ return null;
1411
+ }
1412
+ }
1413
+ let processStartTime = linuxProcessStartTime;
1414
+ function writeRuntimeProcessRecord(handle) {
1415
+ const startTime = processStartTime(handle.pgid);
1416
+ if (!startTime)
1417
+ return;
1418
+ const record = {
1419
+ pgid: handle.pgid, startTime, cgroupScope: handle.cgroupScope,
1420
+ };
1421
+ writeFileSync(runtimeProcessRecordPath(), JSON.stringify(record), { mode: 0o600 });
1422
+ }
1423
+ function clearRuntimeProcessRecord(pgid) {
1424
+ try {
1425
+ const record = JSON.parse(readFileSync(runtimeProcessRecordPath(), "utf8"));
1426
+ if (record.pgid === pgid)
1427
+ rmSync(runtimeProcessRecordPath(), { force: true });
1428
+ }
1429
+ catch {
1430
+ // No record, or an unreadable one that the next startup check discards.
1431
+ }
1432
+ }
1433
+ /**
1434
+ * Stops the managed server left by a previous daemon process (crash or SIGKILL), before
1435
+ * this daemon starts any server. Only the recorded server process group is signalled, and
1436
+ * only while its leader still has the recorded start time; learner commands run in their own
1437
+ * process groups. Returns false when that group does not confirm exit; it then stays tracked
1438
+ * and blocks every spawn, like any unconfirmed replacement.
1439
+ */
1440
+ export async function reapPreviousDeepseekRuntime(budgetMs = PROCESS_EXIT_CONFIRM_BUDGET_MS) {
1441
+ const recordPath = runtimeProcessRecordPath();
1442
+ let record;
1443
+ try {
1444
+ record = JSON.parse(readFileSync(recordPath, "utf8"));
1445
+ }
1446
+ catch {
1447
+ rmSync(recordPath, { force: true });
1448
+ return true;
1449
+ }
1450
+ if (!Number.isInteger(record.pgid) || record.pgid < 2
1451
+ || processStartTime(record.pgid) !== record.startTime) {
1452
+ rmSync(recordPath, { force: true });
1453
+ return true;
1454
+ }
1455
+ log.warn("deepseek-tui.previous-daemon-runtime-found", { managed: record.cgroupScope !== null });
1456
+ const orphan = {
1457
+ // Not our child: no exit event, so the empty process group is the only evidence.
1458
+ child: {
1459
+ pid: record.pgid,
1460
+ kill: (signal) => {
1461
+ try {
1462
+ process.kill(-record.pgid, signal);
1463
+ }
1464
+ catch { /* gone or not permitted */ }
1465
+ return true;
1466
+ },
1467
+ unref: () => undefined,
1468
+ },
1469
+ pgid: record.pgid,
1470
+ cgroupScope: record.cgroupScope,
1471
+ exitObserved: true,
1472
+ baseUrl: "",
1473
+ token: "",
1474
+ managed: true,
1475
+ sessionKey: null,
1476
+ compatDigest: "",
1477
+ closed: false,
1478
+ inFlight: 0,
1479
+ stderrTail: "",
1480
+ runsServed: 0,
1481
+ loadedThreads: new Set(),
1482
+ threadSettings: new Map(),
1483
+ };
1484
+ shutdownHandle(orphan, "previous-daemon-runtime");
1485
+ return confirmReleasedProcesses(budgetMs);
1486
+ }
1487
+ /** 仅测试用:替换进程启动时间读取(非 Linux 测试机没有 /proc)。 */
1488
+ export function __setProcessStartTimeForTests(fn) {
1489
+ processStartTime = fn ?? linuxProcessStartTime;
1490
+ }
1133
1491
  /** 仅测试用:清空进程池。 */
1134
1492
  export function __resetDeepseekTuiPoolForTests() {
1135
1493
  for (const [key, handle] of PROCESS_POOL.entries()) {
1136
1494
  shutdownHandle(handle, "test-reset");
1137
1495
  PROCESS_POOL.delete(key);
1138
1496
  }
1497
+ RELEASING.clear();
1139
1498
  DEEPSEEK_TURN_QUEUES.clear();
1140
1499
  }
1141
1500
  function normalizeDeepseekEvent(eventName, payload, seq) {
@@ -1661,6 +2020,8 @@ function shutdownHandle(handle, reason) {
1661
2020
  handle.closed = true;
1662
2021
  if (handle.idleTimer)
1663
2022
  clearTimeout(handle.idleTimer);
2023
+ // The next spawn must confirm this process is gone (stopAndConfirmExit).
2024
+ RELEASING.add(handle);
1664
2025
  // The close listener owns cleanup. The process (or its dispatcher child) may
1665
2026
  // still be writing HOME/.deepseek/snapshots after SIGTERM is sent.
1666
2027
  try {
@@ -1692,6 +2053,98 @@ function shutdownHandle(handle, reason) {
1692
2053
  }
1693
2054
  log.debug("deepseek-tui.shutdown", { reason });
1694
2055
  }
2056
+ /** Confirms every stopped server process has exited; false keeps the rest for a later check. */
2057
+ async function confirmReleasedProcesses(budgetMs) {
2058
+ for (const handle of [...RELEASING]) {
2059
+ if (!(await stopAndConfirmExit(handle, budgetMs)))
2060
+ return false;
2061
+ }
2062
+ return true;
2063
+ }
2064
+ /**
2065
+ * Stops one server process and waits until it can no longer hold the runtime lock.
2066
+ *
2067
+ * The lock is released only when the server exits (Codewhale opens it close-on-exec, so
2068
+ * descendants never inherit it). Evidence is the direct child's exit plus an empty process
2069
+ * group (`kill(-pgid, 0)` → ESRCH; EPERM still means a member exists). Learner commands run
2070
+ * in their own process groups and are not waited for. If the server is still present at half
2071
+ * the budget, a managed child is force-stopped through the launcher's cgroup quiesce (the
2072
+ * control user cannot signal the runtime UID); a local child receives SIGKILL. An exhausted
2073
+ * budget is reported as false and is never treated as released.
2074
+ */
2075
+ async function stopAndConfirmExit(handle, budgetMs) {
2076
+ shutdownHandle(handle, "replacement");
2077
+ const startedAt = Date.now();
2078
+ const deadline = startedAt + budgetMs;
2079
+ let forced = false;
2080
+ while (true) {
2081
+ if (handle.exitObserved && !processGroupAlive(handle.pgid)) {
2082
+ RELEASING.delete(handle);
2083
+ if (handle.pgid)
2084
+ clearRuntimeProcessRecord(handle.pgid);
2085
+ return true;
2086
+ }
2087
+ const now = Date.now();
2088
+ if (now >= deadline) {
2089
+ log.warn("deepseek-tui.process-not-released", {
2090
+ durationMs: now - startedAt,
2091
+ exitObserved: handle.exitObserved,
2092
+ forced,
2093
+ });
2094
+ return false;
2095
+ }
2096
+ if (!forced && now - startedAt >= budgetMs / 2) {
2097
+ forced = true;
2098
+ await forceStop(handle, deadline - now);
2099
+ continue;
2100
+ }
2101
+ await sleep(Math.min(PROCESS_EXIT_POLL_MS, Math.max(1, deadline - now)));
2102
+ }
2103
+ }
2104
+ async function forceStop(handle, remainingMs) {
2105
+ log.warn("deepseek-tui.process-force-stop", { managed: handle.cgroupScope !== null });
2106
+ if (handle.cgroupScope !== null) {
2107
+ let timer;
2108
+ try {
2109
+ await Promise.race([
2110
+ quiesceRuntimeWriters(handle.cgroupScope),
2111
+ new Promise((_resolve, reject) => {
2112
+ timer = setTimeout(() => reject(new Error("quiesce timed out")), remainingMs);
2113
+ }),
2114
+ ]);
2115
+ }
2116
+ catch (error) {
2117
+ log.warn("deepseek-tui.process-force-stop-failed", {
2118
+ error: sanitizeRuntimeFailureText(error instanceof Error ? error.message : String(error), 512),
2119
+ });
2120
+ }
2121
+ finally {
2122
+ if (timer)
2123
+ clearTimeout(timer);
2124
+ }
2125
+ return;
2126
+ }
2127
+ try {
2128
+ if (handle.pgid)
2129
+ process.kill(-handle.pgid, "SIGKILL");
2130
+ else
2131
+ handle.child.kill("SIGKILL");
2132
+ }
2133
+ catch {
2134
+ // The group may already be gone; the next probe decides.
2135
+ }
2136
+ }
2137
+ function processGroupAlive(pgid) {
2138
+ if (!pgid)
2139
+ return false;
2140
+ try {
2141
+ process.kill(-pgid, 0);
2142
+ return true;
2143
+ }
2144
+ catch (error) {
2145
+ return error.code !== "ESRCH";
2146
+ }
2147
+ }
1695
2148
  async function waitForHealth(baseUrl, fetchFn, handle, timeoutMs, signal) {
1696
2149
  const deadline = Date.now() + timeoutMs;
1697
2150
  let lastError = "";
@@ -1735,6 +2188,9 @@ async function findFreePort() {
1735
2188
  });
1736
2189
  });
1737
2190
  }
2191
+ function sha256Hex(value) {
2192
+ return createHash("sha256").update(value).digest("hex");
2193
+ }
1738
2194
  function randomToken() {
1739
2195
  return `blc_ds_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
1740
2196
  }