@botlearn-course/daemon 0.0.32-beta.1 → 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,14 +1,16 @@
1
1
  import { MD_REVIEW_TOOL, MdReviewPreparation, prepareMdReviewDirectory } from "./md-review.js";
2
2
  import { createHash } from "node:crypto";
3
3
  import { spawn } from "node:child_process";
4
- 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";
5
5
  import path from "node:path";
6
6
  import net from "node:net";
7
7
  import { MAX_PROGRESS_EVENTS_PER_ATTEMPT } from "../mcp/report-progress.js";
8
8
  import { prepareRuntimeSkillsHome, RUNTIME_SKILLS_RELATIVE_PATH, } from "../runtime-skill-materialization.js";
9
9
  import { startCourseSkillsMcpServer, } from "../mcp/course-skills-server.js";
10
10
  import { sanitizeRuntimeFailureText } from "../redaction.js";
11
+ import { ensureDaemonHome } from "../auth-store.js";
11
12
  import { runtimeChildEnv, runtimeChildLaunch } from "../runtime-env.js";
13
+ import { quiesceRuntimeWriters } from "../runtime-quiescence.js";
12
14
  import { ToolSemantics } from "./tool-semantics.js";
13
15
  import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
14
16
  import { DeepseekCourseSkills, DEEPSEEK_COURSE_SKILL_TOOLS } from "./deepseek-course-skills.js";
@@ -36,7 +38,48 @@ function isMissingThreadHttpError(error) {
36
38
  const log = consoleLogger;
37
39
  const DEEPSEEK_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
38
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"]);
39
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";
40
83
  /** 单轮流式 assistant 文本字节上限。 */
41
84
  const SSE_TEXT_CAP = 1 * 1024 * 1024;
42
85
  const VISION_MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/;
@@ -65,7 +108,11 @@ const DEEPSEEK_COURSE_SKILL_TOOL_ALIASES = new Set([
65
108
  "courseskills:load_skill",
66
109
  "courseskills:load_reference",
67
110
  ]);
68
- 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) {
69
116
  const model = opts.env?.BOTLEARN_DEEPSEEK_VISION_MODEL?.trim();
70
117
  const managedProxy = Boolean(opts.env?.BOTLEARN_AGENT_SERVICE_ACTIVATION_ID?.trim()
71
118
  && opts.env?.DEEPSEEK_BASE_URL?.trim());
@@ -74,9 +121,6 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
74
121
  if (model && !VISION_MODEL_PATTERN.test(model)) {
75
122
  throw new Error("invalid managed DeepSeek vision model");
76
123
  }
77
- if (!progressMcpConfig) {
78
- throw new Error("managed DeepSeek runtime config requires an ephemeral config directory");
79
- }
80
124
  const apiKey = opts.env?.DEEPSEEK_API_KEY?.trim();
81
125
  const rawBaseUrl = opts.env?.DEEPSEEK_BASE_URL?.trim();
82
126
  if (!apiKey || !rawBaseUrl) {
@@ -105,11 +149,7 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
105
149
  ]
106
150
  : [];
107
151
  baseUrl.pathname = `${baseUrl.pathname.replace(/\/+$/, "")}/v1`;
108
- const configPath = path.join(progressMcpConfig.dir, "config.toml");
109
- const managedRuntime = Boolean(process.env.BOTLEARN_RUNTIME_USER?.trim()
110
- || process.env.BOTLEARN_RUNTIME_LAUNCH_MODE?.trim());
111
- writeFileSync(configPath, [
112
- `mcp_config_path = ${JSON.stringify(progressMcpConfig.path)}`,
152
+ return [
113
153
  ...providerConfig,
114
154
  ...(managedProxy && !(opts.skillProvider?.catalog.length) ? [
115
155
  "[tools.overrides]",
@@ -126,7 +166,18 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
126
166
  `base_url = ${JSON.stringify(baseUrl.toString())}`,
127
167
  "",
128
168
  ] : []),
129
- ].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 });
130
181
  if (managedRuntime)
131
182
  chmodSync(configPath, 0o640);
132
183
  return configPath;
@@ -134,6 +185,18 @@ function createManagedRuntimeConfig(opts, progressMcpConfig) {
134
185
  const PROCESS_POOL = new Map();
135
186
  /** 单 daemon、单套 env 配置:池里最多一个 server。 */
136
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
+ }
137
200
  let exitCleanupHookInstalled = false;
138
201
  const DEEPSEEK_TURN_QUEUES = new Map();
139
202
  /**
@@ -186,15 +249,22 @@ export class DeepseekTuiAdapter {
186
249
  explicitAuthToken;
187
250
  fetchFn;
188
251
  spawnFn;
252
+ threadPrewarmTimeoutMs;
253
+ processExitBudgetMs;
254
+ submitTimeoutMs;
189
255
  progressEventMappingEnabled;
190
256
  progressPromptInjectionEnabled;
191
257
  resolvedBinary = null;
258
+ runtimeVersions = new Map();
192
259
  constructor(deps = {}) {
193
260
  this.explicitBinary = deps.binary ?? process.env.BOTLEARN_DEEPSEEK_TUI_BIN;
194
261
  this.explicitServerUrl = deps.serverUrl ?? process.env.BOTLEARN_DEEPSEEK_TUI_URL;
195
262
  this.explicitAuthToken = deps.authToken ?? process.env.BOTLEARN_DEEPSEEK_TUI_TOKEN;
196
263
  this.fetchFn = deps.fetchFn ?? fetch;
197
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;
198
268
  this.progressPromptInjectionEnabled =
199
269
  !this.explicitServerUrl && progressMcpAutoInjectionSupported();
200
270
  this.progressEventMappingEnabled = this.explicitServerUrl
@@ -236,9 +306,12 @@ export class DeepseekTuiAdapter {
236
306
  if (turnAbort.signal.aborted)
237
307
  throw abortReason(turnAbort.signal);
238
308
  handle.inFlight += 1;
309
+ handle.runsServed += 1;
239
310
  countedInFlight = true;
240
311
  if (handle.idleTimer)
241
312
  clearTimeout(handle.idleTimer);
313
+ // Failure diagnostics describe this run only, also on a reused process.
314
+ handle.stderrTail = "";
242
315
  const headers = authHeaders(handle.token);
243
316
  if (threadId && !isValidThreadId(threadId)) {
244
317
  return {
@@ -253,15 +326,31 @@ export class DeepseekTuiAdapter {
253
326
  let maintenanceUsage;
254
327
  while (true) {
255
328
  try {
329
+ const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
330
+ const settings = sha256Hex(JSON.stringify([
331
+ this.runtimeSystemContext(opts) ?? null, selection.model ?? null,
332
+ ]));
256
333
  if (!threadId) {
257
334
  threadId = await this.createThread(handle.baseUrl, headers, opts, turnAbort.signal);
335
+ handle.loadedThreads.add(threadId);
336
+ handle.threadSettings.set(threadId, settings);
258
337
  }
259
338
  else {
260
- const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
261
339
  if (opts.systemPrompt !== undefined || opts.systemContext !== undefined
262
340
  || opts.skillProvider || selection.model) {
263
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);
264
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);
265
354
  if (managedActivationId && this.compactionRequired(opts)) {
266
355
  const compacted = await this.compactThread({
267
356
  baseUrl: handle.baseUrl,
@@ -369,6 +458,9 @@ export class DeepseekTuiAdapter {
369
458
  ...(err instanceof DeepseekUserInputHandoffError
370
459
  ? { runtimeFailure: { error_code: "runtime_interactive_tool_handoff_failed" } }
371
460
  : {}),
461
+ ...(err instanceof DeepseekProcessNotReleasedError
462
+ ? { runtimeFailure: { error_code: err.errorCode } }
463
+ : {}),
372
464
  };
373
465
  }
374
466
  finally {
@@ -376,14 +468,10 @@ export class DeepseekTuiAdapter {
376
468
  opts.signal.removeEventListener("abort", onAbort);
377
469
  if (handle && countedInFlight) {
378
470
  handle.inFlight = Math.max(0, handle.inFlight - 1);
379
- if (managedActivationId && !this.explicitServerUrl && handle.inFlight === 0) {
380
- if (PROCESS_POOL.get(POOL_KEY) === handle)
381
- PROCESS_POOL.delete(POOL_KEY);
382
- shutdownHandle(handle, "managed-activation-finished");
383
- }
384
- 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)
385
474
  resetIdle(handle, POOL_KEY);
386
- }
387
475
  }
388
476
  }
389
477
  finally {
@@ -406,12 +494,19 @@ export class DeepseekTuiAdapter {
406
494
  }
407
495
  return {
408
496
  child: nullChild(),
497
+ cgroupScope: null,
498
+ exitObserved: false,
409
499
  baseUrl: trimTrailingSlash(this.explicitServerUrl),
410
500
  token: this.explicitAuthToken ?? "",
411
- managedActivationId: null,
501
+ managed: false,
502
+ sessionKey: null,
503
+ compatDigest: "",
412
504
  closed: false,
413
505
  inFlight: 0,
414
506
  stderrTail: "",
507
+ runsServed: 0,
508
+ loadedThreads: new Set(),
509
+ threadSettings: new Map(),
415
510
  };
416
511
  }
417
512
  const managedActivationId = this.managedActivationId(opts);
@@ -421,27 +516,8 @@ export class DeepseekTuiAdapter {
421
516
  if (opts.skillProvider && !opts.onSkillEvent) {
422
517
  throw new Error("courseskills requires its technical event sink");
423
518
  }
424
- const systemPromptDigest = createHash("sha256")
425
- .update(this.runtimeSystemContext(opts) ?? "").digest("hex");
426
- const existing = PROCESS_POOL.get(POOL_KEY);
427
- if (existing
428
- && !existing.closed
429
- && existing.managedActivationId === managedActivationId
430
- && existing.systemPromptDigest === systemPromptDigest) {
431
- return existing;
432
- }
433
- if (existing) {
434
- PROCESS_POOL.delete(POOL_KEY);
435
- shutdownHandle(existing, "activation-scope-changed");
436
- }
437
- const port = await findFreePort();
438
- if (signal.aborted)
439
- throw abortReason(signal);
440
- const token = randomToken();
441
- const baseUrl = `http://127.0.0.1:${port}`;
442
519
  const binary = this.resolveBinary();
443
- const runtimeVersion = readCommandVersion(binary, [], { env: opts.env })
444
- ?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0];
520
+ const runtimeVersion = this.runtimeVersion(binary, opts.env);
445
521
  // 0.8.39 predates external tools and waits for its MCP catalog synchronously.
446
522
  // Newer runtimes must advertise native external tools; never silently fall
447
523
  // back to asynchronous MCP discovery after a capability/protocol failure.
@@ -450,58 +526,121 @@ export class DeepseekTuiAdapter {
450
526
  // are exposed only when this activation authorizes at least one course Skill.
451
527
  const isolatesSkillProfile = Boolean(opts.skillProvider || managedActivationId);
452
528
  const exposesCourseSkills = (opts.skillProvider?.catalog.length ?? 0) > 0;
453
- const courseSkills = exposesCourseSkills && !legacySkillsMcp
454
- ? new DeepseekCourseSkills({
455
- prepared: opts.skillProvider,
456
- onEvent: opts.onSkillEvent ?? (async () => { }),
457
- })
458
- : 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}`;
459
595
  let courseSkillsMcpServer;
460
596
  let progressMcpConfig;
461
597
  let runtimeConfigPath;
462
598
  try {
463
- courseSkillsMcpServer = exposesCourseSkills && legacySkillsMcp
599
+ courseSkillsMcpServer = args.legacySkillsMcp
464
600
  ? await startCourseSkillsMcpServer({
465
601
  prepared: opts.skillProvider,
466
602
  onEvent: opts.onSkillEvent ?? (async () => { }),
467
603
  })
468
604
  : undefined;
469
- progressMcpConfig =
470
- this.progressPromptInjectionEnabled || isolatesSkillProfile
471
- || (managedActivationId && opts.env?.DEEPSEEK_BASE_URL?.trim())
472
- ? createProgressMcpConfig({
473
- ...(courseSkillsMcpServer
474
- ? { courseSkillsSocketPath: courseSkillsMcpServer.socketPath }
475
- : {}),
476
- })
477
- : undefined;
478
- if (isolatesSkillProfile && progressMcpConfig) {
479
- 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);
480
614
  }
481
- runtimeConfigPath = createManagedRuntimeConfig(opts, progressMcpConfig);
615
+ runtimeConfigPath = writeManagedRuntimeConfig(args.configBody, progressMcpConfig);
482
616
  }
483
617
  catch (error) {
484
618
  cleanupDeepseekResources({ progressMcpConfig, courseSkillsMcpServer });
485
619
  throw error;
486
620
  }
487
- 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 = [
488
624
  "serve",
489
625
  "--http",
490
626
  "--host",
491
627
  "127.0.0.1",
492
628
  "--port",
493
629
  String(port),
494
- "--auth-token",
495
- token,
630
+ ...(tokenInEnv ? [] : ["--auth-token", token]),
496
631
  ];
497
- const launch = runtimeChildLaunch(binary, args);
632
+ const launch = runtimeChildLaunch(binary, serveArgs);
498
633
  let child;
634
+ let childEnv;
499
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;
500
641
  child = this.spawnFn(launch.binary, launch.args, {
501
642
  cwd: opts.cwd,
502
- env: this.spawnEnv(opts, progressMcpConfig?.path, runtimeConfigPath, progressMcpConfig && isolatesSkillProfile
503
- ? path.join(progressMcpConfig.dir, RUNTIME_SKILLS_RELATIVE_PATH)
504
- : undefined),
643
+ env: childEnv,
505
644
  ...launch.identity,
506
645
  stdio: ["ignore", "pipe", "pipe"],
507
646
  // 自成进程组:解析到的二进制可能是会再 spawn 真实 deepseek-tui
@@ -516,23 +655,36 @@ export class DeepseekTuiAdapter {
516
655
  installExitCleanupHook();
517
656
  const handle = {
518
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,
519
664
  baseUrl,
520
665
  token,
521
- managedActivationId,
522
- systemPromptDigest,
666
+ managed: args.managed,
667
+ sessionKey: args.sessionKey,
668
+ compatDigest: args.compatDigest,
523
669
  closed: false,
524
670
  inFlight: 0,
525
671
  stderrTail: "",
526
672
  progressMcpConfig,
527
673
  courseSkillsMcpServer,
528
- courseSkills,
529
674
  runtimeVersion,
675
+ runsServed: 0,
676
+ loadedThreads: new Set(),
677
+ threadSettings: new Map(),
530
678
  };
531
679
  child.stderr?.setEncoding("utf8");
532
680
  child.stderr?.on("data", (chunk) => {
533
681
  handle.stderrTail = sanitizeRuntimeFailureText(handle.stderrTail + chunk, 4096);
534
682
  });
683
+ child.on("exit", () => {
684
+ handle.exitObserved = true;
685
+ });
535
686
  child.on("close", () => {
687
+ handle.exitObserved = true;
536
688
  handle.closed = true;
537
689
  if (PROCESS_POOL.get(POOL_KEY) === handle)
538
690
  PROCESS_POOL.delete(POOL_KEY);
@@ -547,16 +699,6 @@ export class DeepseekTuiAdapter {
547
699
  });
548
700
  try {
549
701
  await waitForHealth(baseUrl, this.fetchFn, handle, STARTUP_TIMEOUT_MS, signal);
550
- const needsReviewTools = managedActivationId && runtimeVersion === "0.9.12"
551
- && opts.runtimeStateDir && opts.mdReviewEvidence && parseDeepseekRuntimeSelection(opts.extraArgs).model;
552
- if (courseSkills || needsReviewTools) {
553
- const info = await this.requestJson(`${baseUrl}/v1/runtime/info`, { headers: authHeaders(token), signal: AbortSignal.any([
554
- signal, AbortSignal.timeout(STARTUP_TIMEOUT_MS),
555
- ]) });
556
- if (info.capabilities?.external_tools !== true) {
557
- throw new Error("course_skill_runtime_external_tools_unavailable");
558
- }
559
- }
560
702
  await courseSkillsMcpServer?.markApplied();
561
703
  }
562
704
  catch (error) {
@@ -564,13 +706,31 @@ export class DeepseekTuiAdapter {
564
706
  throw error;
565
707
  }
566
708
  PROCESS_POOL.set(POOL_KEY, handle);
567
- 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);
568
715
  return handle;
569
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
+ }
570
730
  /**
571
731
  * BYOA continues to use the user's default DeepSeek state directory. Managed mode
572
- * pins the durable RuntimeThreadStore to the RuntimeSession workspace even though
573
- * 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.
574
734
  */
575
735
  spawnEnv(opts, progressMcpConfigPath, runtimeConfigPath, skillsDir) {
576
736
  const env = {
@@ -590,6 +750,7 @@ export class DeepseekTuiAdapter {
590
750
  if (this.managedActivationId(opts)) {
591
751
  env.DEEPSEEK_RUNTIME_DIR = this.prepareManagedRuntimeDir(opts);
592
752
  env.CODEWHALE_TELEMETRY = "false";
753
+ env.CODEWHALE_STREAM_OPEN_TIMEOUT_SECS = MANAGED_STREAM_OPEN_TIMEOUT_SECS;
593
754
  if (runtimeConfigPath) {
594
755
  // Codewhale treats an environment URL as a new route, even when it
595
756
  // equals the file URL, and refuses that route's bound credentials.
@@ -599,11 +760,14 @@ export class DeepseekTuiAdapter {
599
760
  }
600
761
  return env;
601
762
  }
602
- prepareManagedRuntimeDir(opts) {
763
+ managedRuntimeDirPath(opts) {
603
764
  // Keep native transcripts outside the learner's cwd. The managed workspace parent
604
765
  // is control-owned/traverse-only, and its existing activation fence covers both
605
766
  // siblings. This remains on the same NAS volume for atomic migration and resume.
606
- 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);
607
771
  const legacyDir = path.join(opts.cwd, MANAGED_RUNTIME_DIR_NAME);
608
772
  if (existsSync(legacyDir)) {
609
773
  const legacy = lstatSync(legacyDir);
@@ -674,6 +838,56 @@ export class DeepseekTuiAdapter {
674
838
  this.logAppliedServerPrompt(opts.systemPrompt);
675
839
  return id;
676
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
+ }
677
891
  logAppliedServerPrompt(prompt) {
678
892
  if (prompt === undefined)
679
893
  return;
@@ -732,13 +946,12 @@ export class DeepseekTuiAdapter {
732
946
  try {
733
947
  if (signal.aborted)
734
948
  throw abortReason(signal);
735
- 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`, {
736
950
  method: "POST",
737
951
  headers,
738
952
  body: JSON.stringify({
739
953
  reason: "BotLearn automatic long-context compaction",
740
954
  }),
741
- signal: AbortSignal.timeout(5_000),
742
955
  });
743
956
  turnId = stringField(started?.turn, "id") ?? stringField(started, "turn_id") ?? "";
744
957
  if (signal.aborted)
@@ -781,13 +994,22 @@ export class DeepseekTuiAdapter {
781
994
  async startTurnAndReadEvents(args) {
782
995
  const { baseUrl, headers, threadId, opts, signal, handle } = args;
783
996
  const selection = parseDeepseekRuntimeSelection(opts.extraArgs);
784
- // Initial integration targets 0.9.12; native sandbox acceptance is separate
785
- // from bridge tests. Other runtimes follow the SP absent-tool fallback.
786
- const mdReview = handle.managedActivationId && handle.runtimeVersion === "0.9.12"
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 ?? "")
787
1000
  && opts.runtimeStateDir && opts.mdReviewEvidence && selection.model
788
1001
  ? new MdReviewPreparation({ workspace: opts.cwd, stateDir: prepareMdReviewDirectory(opts.cwd),
789
1002
  evidence: structuredClone(opts.mdReviewEvidence), model: selection.model,
790
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;
791
1013
  // 事件流必须先于 turn 打开,否则 turn 早期事件会丢。
792
1014
  const eventsUrl = `${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=0`;
793
1015
  const eventsAbort = new AbortController();
@@ -811,7 +1033,7 @@ export class DeepseekTuiAdapter {
811
1033
  };
812
1034
  signal.addEventListener("abort", onAbort, { once: true });
813
1035
  let eventsError;
814
- const eventsReaderPromise = this.readEvents(eventsUrl, headers, opts, eventsAbort.signal, handle.courseSkills, mdReview).catch((err) => {
1036
+ const eventsReaderPromise = this.readEvents(eventsUrl, headers, opts, eventsAbort.signal, courseSkills, mdReview).catch((err) => {
815
1037
  eventsError = err;
816
1038
  return null;
817
1039
  });
@@ -828,24 +1050,23 @@ export class DeepseekTuiAdapter {
828
1050
  if (selection.reasoningEffort)
829
1051
  body.reasoning_effort = selection.reasoningEffort;
830
1052
  const dynamicTools = [
831
- ...(handle.courseSkills ? DEEPSEEK_COURSE_SKILL_TOOLS : []),
1053
+ ...(courseSkills ? DEEPSEEK_COURSE_SKILL_TOOLS : []),
832
1054
  ...(mdReview ? [MD_REVIEW_TOOL] : []),
833
1055
  ];
834
1056
  if (dynamicTools.length)
835
1057
  body.dynamic_tools = dynamicTools;
836
1058
  if (signal.aborted)
837
1059
  throw abortReason(signal);
838
- 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`, {
839
1063
  method: "POST",
840
1064
  headers,
841
1065
  body: JSON.stringify(body),
842
- // Once the request is sent, keep a short independent timeout so we can obtain
843
- // turnId and explicitly interrupt it even if the outer run is cancelled.
844
- signal: AbortSignal.timeout(5_000),
845
1066
  });
846
1067
  turnId = stringField(started?.turn, "id") ?? stringField(started, "turn_id") ?? "";
847
1068
  if (turnId && !signal.aborted)
848
- await handle.courseSkills?.markApplied();
1069
+ await courseSkills?.markApplied();
849
1070
  if (signal.aborted)
850
1071
  await interrupt();
851
1072
  const eventsReader = await eventsReaderPromise;
@@ -1128,6 +1349,22 @@ export class DeepseekTuiAdapter {
1128
1349
  };
1129
1350
  };
1130
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
+ }
1131
1368
  async requestJson(url, init) {
1132
1369
  const headers = new Headers(init.headers);
1133
1370
  if (!headers.has("content-type") && init.body)
@@ -1146,12 +1383,118 @@ export class DeepseekTuiAdapter {
1146
1383
  return (await res.json());
1147
1384
  }
1148
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
+ }
1149
1491
  /** 仅测试用:清空进程池。 */
1150
1492
  export function __resetDeepseekTuiPoolForTests() {
1151
1493
  for (const [key, handle] of PROCESS_POOL.entries()) {
1152
1494
  shutdownHandle(handle, "test-reset");
1153
1495
  PROCESS_POOL.delete(key);
1154
1496
  }
1497
+ RELEASING.clear();
1155
1498
  DEEPSEEK_TURN_QUEUES.clear();
1156
1499
  }
1157
1500
  function normalizeDeepseekEvent(eventName, payload, seq) {
@@ -1677,6 +2020,8 @@ function shutdownHandle(handle, reason) {
1677
2020
  handle.closed = true;
1678
2021
  if (handle.idleTimer)
1679
2022
  clearTimeout(handle.idleTimer);
2023
+ // The next spawn must confirm this process is gone (stopAndConfirmExit).
2024
+ RELEASING.add(handle);
1680
2025
  // The close listener owns cleanup. The process (or its dispatcher child) may
1681
2026
  // still be writing HOME/.deepseek/snapshots after SIGTERM is sent.
1682
2027
  try {
@@ -1708,6 +2053,98 @@ function shutdownHandle(handle, reason) {
1708
2053
  }
1709
2054
  log.debug("deepseek-tui.shutdown", { reason });
1710
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
+ }
1711
2148
  async function waitForHealth(baseUrl, fetchFn, handle, timeoutMs, signal) {
1712
2149
  const deadline = Date.now() + timeoutMs;
1713
2150
  let lastError = "";
@@ -1751,6 +2188,9 @@ async function findFreePort() {
1751
2188
  });
1752
2189
  });
1753
2190
  }
2191
+ function sha256Hex(value) {
2192
+ return createHash("sha256").update(value).digest("hex");
2193
+ }
1754
2194
  function randomToken() {
1755
2195
  return `blc_ds_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
1756
2196
  }