@botlearn-course/daemon 0.0.29-beta.5 → 0.0.29-beta.6

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/README.md CHANGED
@@ -99,8 +99,12 @@ pnpm exec vitest run src/runtimes/__tests__/runtime-binaries.test.ts
99
99
  目录并存时明确失败,不覆盖数据。该一次性迁移由 daemon 维护,在存量目录迁移完且旧版本
100
100
  退出后可移除。第三方运行时仍可能生成 `.codewhale/state` 等项目状态,不能将其作为学习材料。
101
101
  runtime workspace 独立可写。activation-scoped Skill Provider binding 只留在 daemon control
102
- process 内存;DeepSeek 只通过 clean-env `course_skills` Unix Socket relay 按需读取当前授权
103
- `SKILL.md`/reference,endpoint/token 不进入 runtime env、MCP config、state、workspace 或日志。
102
+ process 内存;DeepSeek 通过每轮注册的 `courseskills_*` 原生外部工具按需读取当前授权
103
+ `SKILL.md`/reference。0.8.39 保留同步 MCP 目录的 clean-env Unix Socket relay;其他版本
104
+ 必须声明 `external_tools` 能力,缺失时明确失败。两条路径复用同一 Course 授权与读取逻辑,
105
+ endpoint/token 不进入 runtime env、MCP config、state、workspace 或日志。
106
+ 原生引用工具按 `nextOffset` 分页读取,避免大文件被运行时截断;字段与边界见
107
+ `docs/specs/agent-service-sandbox-daemon-websocket.md` §9.2.2。
104
108
  系统提示词只使用服务端下发的 `runtime_prompt`。长期模型 provider key 留在 Agent Service,runtime
105
109
  只拿 generation-scoped proxy grant。
106
110
 
@@ -3,6 +3,8 @@ import type { WorkspaceScanMeasurement } from "./file-candidates.js";
3
3
  import { type RuntimeSkillProviderFactory } from "./runtime-skills.js";
4
4
  import { type PersistentSessionExecution, type PreparedPersistentTurn, type RunReportingClient } from "./run-dispatcher.js";
5
5
  import type { CourseRuntime, RunEvent, RunEventReceipt, RunFileCandidate, RunFileRecord, RunStartPayload } from "./types.js";
6
+ /** Task-scoped CourseRuns route each run to its own native thread (course-agent-session-scope.md). */
7
+ export declare const NATIVE_SESSION_KEY_CAPABILITY = "native_session_key_v1";
6
8
  export declare function workspaceDurabilityCapabilities(): string[];
7
9
  export interface AgentServiceSandboxOptions {
8
10
  wsUrl: string;
@@ -49,6 +51,8 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
49
51
  private activeSessionId;
50
52
  /** 全局串行下当前正在执行 turn 的 session(persistNativeSession 路由用)。 */
51
53
  private currentTurnSessionId;
54
+ /** Native session key of the current turn; persistNativeSession writes only this slot. */
55
+ private currentTurnNativeKey;
52
56
  private heartbeatMs;
53
57
  private staleMs;
54
58
  /** Server-advertised bounded pipeline; legacy peers remain stop-and-wait. */
@@ -26,6 +26,9 @@ const ASSET_ACTIVATION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[
26
26
  /** 出站 seq 基址:seq = connection_epoch * SEQ_EPOCH_BASE + n,跨重连单调(合同 §1.1)。 */
27
27
  const SEQ_EPOCH_BASE = 1_000_000_000;
28
28
  const RUNTIME_LOG_WINDOW_MS = 60_000;
29
+ /** Task-scoped CourseRuns route each run to its own native thread (course-agent-session-scope.md). */
30
+ export const NATIVE_SESSION_KEY_CAPABILITY = "native_session_key_v1";
31
+ const COURSE_NATIVE_SESSION_KEY = "course";
29
32
  const WORKSPACE_FILE_TRANSFER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
30
33
  export function workspaceDurabilityCapabilities() {
31
34
  return ["workspace_nas_v1", "workspace_identity_v1"];
@@ -223,7 +226,7 @@ function emptySessionState() {
223
226
  workspaceId: null,
224
227
  workspaceRef: null,
225
228
  runtimeId: null,
226
- nativeSessionId: null,
229
+ nativeSessions: {},
227
230
  contextRevision: 0,
228
231
  activationId: null,
229
232
  completedCommands: [],
@@ -233,6 +236,24 @@ function emptySessionState() {
233
236
  spool: [],
234
237
  };
235
238
  }
239
+ function normalizeNativeSessions(value) {
240
+ const sessions = {};
241
+ if (value.nativeSessions && typeof value.nativeSessions === "object") {
242
+ for (const [key, handle] of Object.entries(value.nativeSessions)) {
243
+ if (typeof handle === "string" && handle)
244
+ sessions[key] = handle;
245
+ }
246
+ }
247
+ else if (typeof value.nativeSessionId === "string" && value.nativeSessionId) {
248
+ // State written before session keys existed held only the CourseRun thread.
249
+ sessions[COURSE_NATIVE_SESSION_KEY] = value.nativeSessionId;
250
+ }
251
+ return sessions;
252
+ }
253
+ function nativeSessionKey(payload) {
254
+ const key = payload.runtime.native_session_key;
255
+ return typeof key === "string" && key ? key : COURSE_NATIVE_SESSION_KEY;
256
+ }
236
257
  function normalizeSessionState(value) {
237
258
  const base = emptySessionState();
238
259
  if (!value || typeof value !== "object")
@@ -242,7 +263,7 @@ function normalizeSessionState(value) {
242
263
  workspaceId: typeof value.workspaceId === "string" ? value.workspaceId : null,
243
264
  workspaceRef: typeof value.workspaceRef === "string" ? value.workspaceRef : null,
244
265
  runtimeId: typeof value.runtimeId === "string" ? value.runtimeId : null,
245
- nativeSessionId: typeof value.nativeSessionId === "string" ? value.nativeSessionId : null,
266
+ nativeSessions: normalizeNativeSessions(value),
246
267
  contextRevision: Number(value.contextRevision ?? 0),
247
268
  activationId: typeof value.activationId === "string" ? value.activationId : null,
248
269
  completedCommands: Array.isArray(value.completedCommands)
@@ -364,6 +385,8 @@ export class AgentServiceSandboxClient {
364
385
  activeSessionId = null;
365
386
  /** 全局串行下当前正在执行 turn 的 session(persistNativeSession 路由用)。 */
366
387
  currentTurnSessionId = null;
388
+ /** Native session key of the current turn; persistNativeSession writes only this slot. */
389
+ currentTurnNativeKey = COURSE_NATIVE_SESSION_KEY;
367
390
  heartbeatMs = 15_000;
368
391
  staleMs = 45_000;
369
392
  /** Server-advertised bounded pipeline; legacy peers remain stop-and-wait. */
@@ -413,6 +436,7 @@ export class AgentServiceSandboxClient {
413
436
  // mode; re-expose only after the activation fence above has been checked.
414
437
  exposeRuntimeSessionWorkspace(scope.sessionId, this.sandboxGeneration, session.workspaceId ?? scope.sessionId);
415
438
  this.currentTurnSessionId = scope.sessionId;
439
+ this.currentTurnNativeKey = nativeSessionKey(payload);
416
440
  const runtimeEnv = runtimeChildEnv(process.env);
417
441
  delete runtimeEnv.DEEPSEEK_API_KEY;
418
442
  delete runtimeEnv.DEEPSEEK_BASE_URL;
@@ -425,7 +449,7 @@ export class AgentServiceSandboxClient {
425
449
  workspaceDir: prepared.workspaceDir,
426
450
  transcriptFile: prepared.transcriptFile,
427
451
  runtimeStateDir: prepared.rootDir,
428
- nativeSessionId: session.nativeSessionId,
452
+ nativeSessionId: session.nativeSessions[this.currentTurnNativeKey] ?? null,
429
453
  contextRevision,
430
454
  runtimeEnv,
431
455
  inputAttachmentGrant: activation.inputAttachmentGrant,
@@ -439,7 +463,11 @@ export class AgentServiceSandboxClient {
439
463
  const session = this.state.sessions[sessionId];
440
464
  if (!session)
441
465
  return;
442
- session.nativeSessionId = nativeSessionId.trim() || null;
466
+ const handle = nativeSessionId.trim();
467
+ if (handle)
468
+ session.nativeSessions[this.currentTurnNativeKey] = handle;
469
+ else
470
+ delete session.nativeSessions[this.currentTurnNativeKey];
443
471
  this.persist();
444
472
  }
445
473
  async finishTurn(payload) {
@@ -877,6 +905,7 @@ export class AgentServiceSandboxClient {
877
905
  WORKSPACE_FILE_READ_BINARY_CAPABILITY,
878
906
  WORKSPACE_FILES_LIST_CAPABILITY,
879
907
  RUNTIME_PROMPT_CAPABILITY,
908
+ NATIVE_SESSION_KEY_CAPABILITY,
880
909
  ...workspaceDurabilityCapabilities(),
881
910
  ],
882
911
  daemon_version: this.options.daemonVersion,
@@ -1159,7 +1188,7 @@ export class AgentServiceSandboxClient {
1159
1188
  await this.sendSessionFrame("session.opened", sessionId, {
1160
1189
  workspace_id: session.workspaceId,
1161
1190
  workspace_ref: session.workspaceRef,
1162
- native_session_id: session.nativeSessionId,
1191
+ native_session_id: session.nativeSessions[COURSE_NATIVE_SESSION_KEY] ?? null,
1163
1192
  workspace_readable: true,
1164
1193
  workspace_writable: true,
1165
1194
  });
@@ -0,0 +1,64 @@
1
+ import { type PreparedRuntimeSkillProvider, type RuntimeSkillEvent } from "../runtime-skills.js";
2
+ type NativeResult = {
3
+ success: boolean;
4
+ content: Array<{
5
+ type: "input_text";
6
+ text: string;
7
+ }>;
8
+ };
9
+ export declare const DEEPSEEK_COURSE_SKILL_TOOLS: {
10
+ namespace: string;
11
+ name: string;
12
+ description: string;
13
+ input_schema: {
14
+ readonly type: "object";
15
+ readonly properties: {};
16
+ readonly additionalProperties: false;
17
+ } | {
18
+ properties: {
19
+ offset: {
20
+ type: string;
21
+ minimum: number;
22
+ description: string;
23
+ };
24
+ maxChars: {
25
+ type: string;
26
+ minimum: number;
27
+ maximum: number;
28
+ description: string;
29
+ };
30
+ ref: {
31
+ readonly type: "string";
32
+ readonly minLength: 5;
33
+ readonly maxLength: 240;
34
+ };
35
+ path: {
36
+ readonly type: "string";
37
+ readonly minLength: 1;
38
+ readonly maxLength: 240;
39
+ };
40
+ };
41
+ type: "object";
42
+ required: readonly ["ref", "path"];
43
+ additionalProperties: false;
44
+ };
45
+ defer_loading: boolean;
46
+ }[];
47
+ export declare class DeepseekCourseSkills {
48
+ private readonly runtime;
49
+ private readonly calls;
50
+ private applied?;
51
+ constructor(options: {
52
+ prepared?: PreparedRuntimeSkillProvider;
53
+ onEvent(event: RuntimeSkillEvent): Promise<void>;
54
+ });
55
+ markApplied(): Promise<void>;
56
+ execute(payload: unknown, scope: {
57
+ threadId: string;
58
+ turnId: string;
59
+ }, signal: AbortSignal): Promise<{
60
+ callId: string;
61
+ result: NativeResult;
62
+ } | null>;
63
+ }
64
+ export {};
@@ -0,0 +1,192 @@
1
+ import { COURSE_SKILL_TOOLS, CourseSkillsMcpRuntime } from "../mcp/course-skills-server.js";
2
+ import { RuntimeSkillProviderError, } from "../runtime-skills.js";
3
+ const TOOL_PREFIX = "courseskills_";
4
+ const MAX_REQUEST_BYTES = 32 * 1024;
5
+ const DEFAULT_PAGE_CHARS = 4000;
6
+ const MAX_PAGE_CHARS = 6000;
7
+ const MAX_RESULT_CHARS = 10000;
8
+ export const DEEPSEEK_COURSE_SKILL_TOOLS = COURSE_SKILL_TOOLS.map((tool) => ({
9
+ namespace: "courseskills",
10
+ // The runtime reserves mcp_ names for its own MCP dispatcher.
11
+ name: `${TOOL_PREFIX}${tool.name}`,
12
+ description: tool.description + (tool.name === "load_reference"
13
+ ? " 分页按 Unicode 码点计数,默认每页 4000、最多 6000;nextOffset 非空时用它作为 offset 继续读取。" : ""),
14
+ input_schema: tool.name === "load_reference" ? {
15
+ ...tool.inputSchema,
16
+ properties: {
17
+ ...tool.inputSchema.properties,
18
+ offset: { type: "integer", minimum: 0, description: "起始 Unicode 码点位置,默认 0。" },
19
+ maxChars: { type: "integer", minimum: 1, maximum: MAX_PAGE_CHARS,
20
+ description: "本页最多 Unicode 码点数,默认 4000;序列化预算可能缩小本页。" },
21
+ },
22
+ } : tool.inputSchema,
23
+ defer_loading: false,
24
+ }));
25
+ export class DeepseekCourseSkills {
26
+ runtime;
27
+ calls = new Map();
28
+ applied;
29
+ constructor(options) {
30
+ this.runtime = new CourseSkillsMcpRuntime(options);
31
+ }
32
+ markApplied() {
33
+ this.applied ??= this.runtime.emitAppliedEvents();
34
+ return this.applied;
35
+ }
36
+ async execute(payload, scope, signal) {
37
+ if (signal.aborted)
38
+ return null;
39
+ const request = objectValue(payload);
40
+ if (!request || !validId(scope.threadId) || !validId(scope.turnId)
41
+ || !validId(request.thread_id) || !validId(request.turn_id)) {
42
+ throw invalid("skill_tool_fence_invalid");
43
+ }
44
+ if (request.thread_id !== scope.threadId || request.turn_id !== scope.turnId)
45
+ return null;
46
+ let requestBytes;
47
+ try {
48
+ requestBytes = Buffer.byteLength(JSON.stringify(request), "utf8");
49
+ }
50
+ catch {
51
+ throw invalid("skill_tool_request_invalid");
52
+ }
53
+ if (requestBytes > MAX_REQUEST_BYTES)
54
+ throw invalid("skill_tool_request_too_large");
55
+ if (!validId(request.call_id) || request.namespace !== "courseskills"
56
+ || typeof request.tool !== "string"
57
+ || !DEEPSEEK_COURSE_SKILL_TOOLS.some((tool) => tool.name === request.tool)
58
+ || !objectValue(request.arguments)) {
59
+ throw invalid("skill_tool_request_invalid");
60
+ }
61
+ const key = JSON.stringify([scope.threadId, scope.turnId, request.call_id]);
62
+ let fingerprint;
63
+ try {
64
+ fingerprint = JSON.stringify([request.namespace, request.tool, canonical(request.arguments)]);
65
+ }
66
+ catch {
67
+ throw invalid("skill_tool_request_invalid");
68
+ }
69
+ const previous = this.calls.get(key);
70
+ if (previous !== undefined) {
71
+ if (previous !== fingerprint)
72
+ throw invalid("skill_tool_replay_conflict");
73
+ return null;
74
+ }
75
+ // Reserve before awaiting so concurrent SSE replay cannot execute twice.
76
+ this.calls.set(key, fingerprint);
77
+ const isReference = request.tool === `${TOOL_PREFIX}load_reference`;
78
+ let args = request.arguments;
79
+ let offset = 0;
80
+ let maxChars = DEFAULT_PAGE_CHARS;
81
+ if (isReference) {
82
+ const { offset: requestedOffset = 0, maxChars: requestedMax = DEFAULT_PAGE_CHARS, ...providerArgs } = args;
83
+ if (typeof requestedOffset !== "number" || !Number.isSafeInteger(requestedOffset)
84
+ || requestedOffset < 0 || typeof requestedMax !== "number"
85
+ || !Number.isSafeInteger(requestedMax) || requestedMax < 1 || requestedMax > MAX_PAGE_CHARS) {
86
+ return { callId: request.call_id, result: toolFailure("skill_request_invalid") };
87
+ }
88
+ offset = requestedOffset;
89
+ maxChars = requestedMax;
90
+ args = providerArgs;
91
+ }
92
+ const response = await this.runtime.handle({
93
+ jsonrpc: "2.0",
94
+ id: request.call_id,
95
+ method: "tools/call",
96
+ params: {
97
+ name: request.tool.slice(TOOL_PREFIX.length),
98
+ arguments: args,
99
+ },
100
+ });
101
+ if (signal.aborted)
102
+ return null;
103
+ const result = objectValue(response?.result);
104
+ if (!result || !Array.isArray(result.content) || typeof result.isError !== "boolean") {
105
+ throw invalid("skill_tool_response_invalid");
106
+ }
107
+ const content = result.content.map((item) => {
108
+ const entry = objectValue(item);
109
+ if (entry?.type !== "text" || typeof entry.text !== "string") {
110
+ throw invalid("skill_tool_response_invalid");
111
+ }
112
+ return { type: "input_text", text: entry.text };
113
+ });
114
+ const native = { success: !result.isError, content };
115
+ return { callId: request.call_id,
116
+ result: isReference && native.success ? referencePage(native, offset, maxChars) : native };
117
+ }
118
+ }
119
+ function toolFailure(code) {
120
+ return { success: false, content: [{ type: "input_text", text: JSON.stringify({
121
+ schemaVersion: "tool-result/0.1", ok: false, code,
122
+ error: { message: "课程技能请求失败" }, evidence: [],
123
+ }) }] };
124
+ }
125
+ function referencePage(result, offset, maxChars) {
126
+ if (result.content.length !== 1)
127
+ throw invalid("skill_tool_response_invalid");
128
+ let envelope;
129
+ try {
130
+ envelope = objectValue(JSON.parse(result.content[0].text));
131
+ }
132
+ catch {
133
+ throw invalid("skill_tool_response_invalid");
134
+ }
135
+ const data = objectValue(envelope?.data);
136
+ if (!envelope || !data || typeof data.content !== "string" || typeof data.bytes !== "number") {
137
+ throw invalid("skill_tool_response_invalid");
138
+ }
139
+ const chars = Array.from(data.content);
140
+ if (offset > chars.length)
141
+ return toolFailure("skill_reference_offset_invalid");
142
+ const serialize = (count) => {
143
+ const content = chars.slice(offset, offset + count).join("");
144
+ const nextOffset = offset + count < chars.length ? offset + count : null;
145
+ return JSON.stringify({ ...envelope, data: { ...data, content,
146
+ bytes: Buffer.byteLength(content, "utf8"), offset, nextOffset,
147
+ totalChars: chars.length, totalBytes: data.bytes,
148
+ truncated: nextOffset !== null || data.truncated === true,
149
+ } });
150
+ };
151
+ let low = 0;
152
+ let high = Math.min(maxChars, chars.length - offset);
153
+ let text = serialize(high);
154
+ if (text.length > MAX_RESULT_CHARS) {
155
+ // Measure the complete envelope including JSON escaping and metadata.
156
+ while (low < high) {
157
+ const middle = Math.ceil((low + high) / 2);
158
+ if (serialize(middle).length <= MAX_RESULT_CHARS)
159
+ low = middle;
160
+ else
161
+ high = middle - 1;
162
+ }
163
+ text = serialize(low);
164
+ if ((low === 0 && offset < chars.length) || text.length > MAX_RESULT_CHARS) {
165
+ return toolFailure("skill_reference_page_too_large");
166
+ }
167
+ }
168
+ return { success: true, content: [{ type: "input_text", text }] };
169
+ }
170
+ function objectValue(value) {
171
+ return value !== null && typeof value === "object" && !Array.isArray(value)
172
+ ? value : null;
173
+ }
174
+ function validId(value) {
175
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,240}$/.test(value);
176
+ }
177
+ function invalid(code) {
178
+ return new RuntimeSkillProviderError(code, "Course Skill dynamic tool request failed");
179
+ }
180
+ /** Stable JSON fingerprint: object key order is irrelevant to a replay. */
181
+ function canonical(value) {
182
+ if (value === null || typeof value === "string" || typeof value === "boolean")
183
+ return value;
184
+ if (typeof value === "number" && Number.isFinite(value))
185
+ return value;
186
+ if (Array.isArray(value))
187
+ return value.map(canonical);
188
+ const object = objectValue(value);
189
+ if (!object)
190
+ throw invalid("skill_tool_request_invalid");
191
+ return Object.fromEntries(Object.keys(object).sort().map((key) => [key, canonical(object[key])]));
192
+ }
@@ -10,6 +10,7 @@ import { sanitizeRuntimeFailureText } from "../redaction.js";
10
10
  import { runtimeChildEnv, runtimeChildLaunch } from "../runtime-env.js";
11
11
  import { ToolSemantics } from "./tool-semantics.js";
12
12
  import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
13
+ import { DeepseekCourseSkills, DEEPSEEK_COURSE_SKILL_TOOLS } from "./deepseek-course-skills.js";
13
14
  import { DEEPSEEK_TUI_ZH_CN_BASE_PROMPT_VERSION, deepseekRuntimeSystemPrompt, usesChineseDeepseekBasePrompt, } from "./deepseek-tui-base-prompt.js";
14
15
  import { adaptDeepseekProgressStarted, cleanupProgressMcpConfig, createDeepseekProgressState, createProgressMcpConfig, deepseekProgressDispositions, isDeepseekProgressCompletion, progressMcpAutoInjectionSupported, progressSystemContext, } from "./progress.js";
15
16
  import { consoleLogger, wrapEngineAdapter, } from "./engine.js";
@@ -47,6 +48,9 @@ const COMPACTION_THRESHOLD_PERCENT = 80;
47
48
  const REQUEST_USER_INPUT_TOOL_NAME = "request_user_input";
48
49
  const USER_INPUT_HANDOFF_MAX_CHARS = 8_000;
49
50
  const DEEPSEEK_COURSE_SKILL_TOOL_ALIASES = new Set([
51
+ "courseskills_list_skills",
52
+ "courseskills_load_skill",
53
+ "courseskills_load_reference",
50
54
  "mcp_courseskills_list_skills",
51
55
  "mcp_courseskills_load_skill",
52
56
  "mcp_courseskills_load_reference",
@@ -221,8 +225,7 @@ export class DeepseekTuiAdapter {
221
225
  : POOL_KEY;
222
226
  releaseTurn = await acquireDeepseekTurn(turnQueueKey, turnAbort.signal);
223
227
  handle = await this.acquireHandle(opts, turnAbort.signal);
224
- const version = this.explicitServerUrl ? undefined
225
- : readCommandVersion(this.resolveBinary(), [], { env: opts.env })?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0];
228
+ const version = handle.runtimeVersion;
226
229
  await opts.onRuntimeMetadata?.({ type: this.id, adapter_version: "1", ...(version ? { version } : {}) });
227
230
  if (turnAbort.signal.aborted)
228
231
  throw abortReason(turnAbort.signal);
@@ -430,18 +433,32 @@ export class DeepseekTuiAdapter {
430
433
  throw abortReason(signal);
431
434
  const token = randomToken();
432
435
  const baseUrl = `http://127.0.0.1:${port}`;
436
+ const binary = this.resolveBinary();
437
+ const runtimeVersion = readCommandVersion(binary, [], { env: opts.env })
438
+ ?.match(/\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?/)?.[0];
439
+ // 0.8.39 predates external tools and waits for its MCP catalog synchronously.
440
+ // Newer runtimes must advertise native external tools; never silently fall
441
+ // back to asynchronous MCP discovery after a capability/protocol failure.
442
+ const legacySkillsMcp = runtimeVersion === "0.8.39";
443
+ const needsCourseSkills = Boolean(opts.skillProvider || managedActivationId);
444
+ const courseSkills = needsCourseSkills && !legacySkillsMcp
445
+ ? new DeepseekCourseSkills({
446
+ prepared: opts.skillProvider,
447
+ onEvent: opts.onSkillEvent ?? (async () => { }),
448
+ })
449
+ : undefined;
433
450
  let courseSkillsMcpServer;
434
451
  let progressMcpConfig;
435
452
  let runtimeConfigPath;
436
453
  try {
437
- courseSkillsMcpServer = (opts.skillProvider || managedActivationId)
454
+ courseSkillsMcpServer = needsCourseSkills && legacySkillsMcp
438
455
  ? await startCourseSkillsMcpServer({
439
456
  prepared: opts.skillProvider,
440
457
  onEvent: opts.onSkillEvent ?? (async () => { }),
441
458
  })
442
459
  : undefined;
443
460
  progressMcpConfig =
444
- this.progressPromptInjectionEnabled || courseSkillsMcpServer
461
+ this.progressPromptInjectionEnabled || needsCourseSkills
445
462
  || (managedActivationId && opts.env?.DEEPSEEK_BASE_URL?.trim())
446
463
  ? createProgressMcpConfig({
447
464
  ...(courseSkillsMcpServer
@@ -449,7 +466,7 @@ export class DeepseekTuiAdapter {
449
466
  : {}),
450
467
  })
451
468
  : undefined;
452
- if (courseSkillsMcpServer && progressMcpConfig) {
469
+ if (needsCourseSkills && progressMcpConfig) {
453
470
  prepareRuntimeSkillsHome(progressMcpConfig.dir, Boolean(this.managedActivationId(opts)));
454
471
  }
455
472
  runtimeConfigPath = createManagedRuntimeConfig(opts, progressMcpConfig);
@@ -458,7 +475,6 @@ export class DeepseekTuiAdapter {
458
475
  cleanupDeepseekResources({ progressMcpConfig, courseSkillsMcpServer });
459
476
  throw error;
460
477
  }
461
- const binary = this.resolveBinary();
462
478
  const args = [
463
479
  "serve",
464
480
  "--http",
@@ -474,7 +490,7 @@ export class DeepseekTuiAdapter {
474
490
  try {
475
491
  child = this.spawnFn(launch.binary, launch.args, {
476
492
  cwd: opts.cwd,
477
- env: this.spawnEnv(opts, progressMcpConfig?.path, runtimeConfigPath, progressMcpConfig && courseSkillsMcpServer
493
+ env: this.spawnEnv(opts, progressMcpConfig?.path, runtimeConfigPath, progressMcpConfig && needsCourseSkills
478
494
  ? path.join(progressMcpConfig.dir, RUNTIME_SKILLS_RELATIVE_PATH)
479
495
  : undefined),
480
496
  ...launch.identity,
@@ -500,6 +516,8 @@ export class DeepseekTuiAdapter {
500
516
  stderrTail: "",
501
517
  progressMcpConfig,
502
518
  courseSkillsMcpServer,
519
+ courseSkills,
520
+ runtimeVersion,
503
521
  };
504
522
  child.stderr?.setEncoding("utf8");
505
523
  child.stderr?.on("data", (chunk) => {
@@ -520,6 +538,14 @@ export class DeepseekTuiAdapter {
520
538
  });
521
539
  try {
522
540
  await waitForHealth(baseUrl, this.fetchFn, handle, STARTUP_TIMEOUT_MS, signal);
541
+ if (courseSkills) {
542
+ const info = await this.requestJson(`${baseUrl}/v1/runtime/info`, { headers: authHeaders(token), signal: AbortSignal.any([
543
+ signal, AbortSignal.timeout(STARTUP_TIMEOUT_MS),
544
+ ]) });
545
+ if (info.capabilities?.external_tools !== true) {
546
+ throw new Error("course_skill_runtime_external_tools_unavailable");
547
+ }
548
+ }
523
549
  await courseSkillsMcpServer?.markApplied();
524
550
  }
525
551
  catch (error) {
@@ -766,7 +792,7 @@ export class DeepseekTuiAdapter {
766
792
  };
767
793
  signal.addEventListener("abort", onAbort, { once: true });
768
794
  let eventsError;
769
- const eventsReaderPromise = this.readEvents(eventsUrl, headers, opts, eventsAbort.signal).catch((err) => {
795
+ const eventsReaderPromise = this.readEvents(eventsUrl, headers, opts, eventsAbort.signal, handle.courseSkills).catch((err) => {
770
796
  eventsError = err;
771
797
  return null;
772
798
  });
@@ -783,6 +809,8 @@ export class DeepseekTuiAdapter {
783
809
  body.model = selection.model;
784
810
  if (selection.reasoningEffort)
785
811
  body.reasoning_effort = selection.reasoningEffort;
812
+ if (handle.courseSkills)
813
+ body.dynamic_tools = DEEPSEEK_COURSE_SKILL_TOOLS;
786
814
  if (signal.aborted)
787
815
  throw abortReason(signal);
788
816
  const started = await this.requestJson(`${baseUrl}/v1/threads/${encodeURIComponent(threadId)}/turns`, {
@@ -794,6 +822,8 @@ export class DeepseekTuiAdapter {
794
822
  signal: AbortSignal.timeout(5_000),
795
823
  });
796
824
  turnId = stringField(started?.turn, "id") ?? stringField(started, "turn_id") ?? "";
825
+ if (turnId && !signal.aborted)
826
+ await handle.courseSkills?.markApplied();
797
827
  if (signal.aborted)
798
828
  await interrupt();
799
829
  const eventsReader = await eventsReaderPromise;
@@ -837,7 +867,7 @@ export class DeepseekTuiAdapter {
837
867
  if (!res.ok)
838
868
  throw new Error(`interrupt failed HTTP ${res.status}`);
839
869
  }
840
- async readEvents(url, headers, opts, signal) {
870
+ async readEvents(url, headers, opts, signal, courseSkills) {
841
871
  const res = await this.fetchFn(url, { method: "GET", headers, signal });
842
872
  if (!res.ok)
843
873
  throw new DeepseekHttpError(res.status, "", "events stream failed");
@@ -878,11 +908,32 @@ export class DeepseekTuiAdapter {
878
908
  text += chunk;
879
909
  };
880
910
  const toolSemantics = new ToolSemantics(true);
881
- const emit = (eventName, payload) => {
911
+ const emit = async (eventName, payload) => {
882
912
  // 其他 turn 的事件(并发轮次、历史重放)一律过滤。
883
913
  const eventTurnId = stringField(payload, "turn_id") ?? stringField(payload?.payload, "turn_id");
884
914
  if (turnId && eventTurnId && eventTurnId !== turnId)
885
915
  return false;
916
+ if (eventName === "tool_call.requested" || embeddedDeepseekEvent(payload) === "tool_call.requested") {
917
+ if (!courseSkills)
918
+ throw new Error("course_skill_unexpected_external_tool_request");
919
+ const threadUrl = new URL(url);
920
+ threadUrl.pathname = threadUrl.pathname.replace(/\/events$/, "");
921
+ threadUrl.search = "";
922
+ const threadId = decodeURIComponent(threadUrl.pathname.split("/").at(-1));
923
+ const executed = await courseSkills.execute(payload?.payload ?? payload, { threadId, turnId }, signal);
924
+ if (executed) {
925
+ const resultUrl = `${threadUrl}/turns/${encodeURIComponent(turnId)}/tool-calls/${encodeURIComponent(executed.callId)}/result`;
926
+ const response = await this.fetchFn(resultUrl, {
927
+ method: "POST",
928
+ headers: { ...headers, "content-type": "application/json" },
929
+ body: JSON.stringify(executed.result),
930
+ signal,
931
+ });
932
+ if (!response.ok)
933
+ throw new Error(`course_skill_result_delivery_failed HTTP ${response.status}`);
934
+ }
935
+ return false;
936
+ }
886
937
  seq += 1;
887
938
  const toolStarted = eventName === "tool.started" || isToolStarted(eventName, payload);
888
939
  const toolCompleted = eventName === "tool.completed" || isToolCompleted(eventName, payload);
@@ -998,7 +1049,7 @@ export class DeepseekTuiAdapter {
998
1049
  buf = buf.slice(idx + 2);
999
1050
  if (!frame)
1000
1051
  continue;
1001
- if (emit(frame.event, frame.data)) {
1052
+ if (await emit(frame.event, frame.data)) {
1002
1053
  await reader.cancel().catch(() => undefined);
1003
1054
  const progressDispositions = deepseekProgressDispositions(progressState);
1004
1055
  return {
@@ -1023,7 +1074,7 @@ export class DeepseekTuiAdapter {
1023
1074
  if (buf.trim()) {
1024
1075
  const frame = parseSseFrame(buf);
1025
1076
  if (frame)
1026
- emit(frame.event, frame.data);
1077
+ await emit(frame.event, frame.data);
1027
1078
  }
1028
1079
  const progressDispositions = deepseekProgressDispositions(progressState);
1029
1080
  return {
@@ -17,6 +17,7 @@ const ACTIONS = {
17
17
  upload_file: 'upload', file_upload: 'upload', 'workspace.upload': 'upload',
18
18
  prepare_attachment: 'prepare_attachment', materialize_attachment: 'prepare_attachment', input_attachment: 'prepare_attachment',
19
19
  tool_search: 'discover_tools', tool_search_tool_regex: 'discover_tools',
20
+ courseskills_list_skills: 'load_skill', courseskills_load_skill: 'load_skill', courseskills_load_reference: 'load_skill',
20
21
  mcp_courseskills_list_skills: 'load_skill', mcp_courseskills_load_skill: 'load_skill', mcp_courseskills_load_reference: 'load_skill',
21
22
  load_skill: 'load_skill',
22
23
  subagent: 'delegate',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botlearn-course/daemon",
3
- "version": "0.0.29-beta.5",
3
+ "version": "0.0.29-beta.6",
4
4
  "description": "BotLearn Course daemon for Agent Service managed sandboxes (internal).",
5
5
  "type": "module",
6
6
  "bin": {