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

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,14 @@ 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
+ 原生工具分页契约 `course-skills-native/0.2`:正文与引用按 Unicode 码点、目录按完整条目
107
+ 读取。`nextOffset` 非空时继续读取完整内容,每页完整 JSON 不超过 10000 个 JavaScript 字符。
108
+ 小正文与小目录未指定分页参数时保留原结果形状;字段与边界见
109
+ `docs/specs/agent-service-sandbox-daemon-websocket.md` §9.2.2。
104
110
  系统提示词只使用服务端下发的 `runtime_prompt`。长期模型 provider key 留在 Agent Service,runtime
105
111
  只拿 generation-scoped proxy grant。
106
112
 
@@ -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. */
@@ -4,7 +4,7 @@ import { randomUUID } from "node:crypto";
4
4
  import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
5
5
  import path from "node:path";
6
6
  import { ensureDaemonHome } from "./auth-store.js";
7
- import { AGENT_SERVICE_WS_SCHEMA, AGENT_SERVICE_WS_SUBPROTOCOL, createSandboxFrame, createWorkspaceFileChunk, parseSandboxFrame, UnsupportedSandboxProtocolError, WORKSPACE_FILE_READ_BINARY_CAPABILITY, WORKSPACE_FILES_LIST_CAPABILITY, } from "./agent-service-ws-protocol.js";
7
+ import { AGENT_SERVICE_WS_SCHEMA, AGENT_SERVICE_WS_SUBPROTOCOL, createSandboxFrame, createWorkspaceFileChunk, parseSandboxFrame, serializeSandboxFrame, UnsupportedSandboxProtocolError, WORKSPACE_FILE_READ_BINARY_CAPABILITY, WORKSPACE_FILES_LIST_CAPABILITY, } from "./agent-service-ws-protocol.js";
8
8
  import { log as defaultLog, setOperationalLogSink, } from "./log.js";
9
9
  import { availableRunCapabilities, runtimeSupportsCourseSkills, } from "./runtime-capabilities.js";
10
10
  import { activationRuntimeEnv, runtimeChildEnv } from "./runtime-env.js";
@@ -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
  });
@@ -1950,7 +1979,7 @@ export class AgentServiceSandboxClient {
1950
1979
  if (!socket || socket.readyState !== WebSocketClient.OPEN)
1951
1980
  return;
1952
1981
  await new Promise((resolve, reject) => {
1953
- socket.send(JSON.stringify(frame), (error) => (error ? reject(error) : resolve()));
1982
+ socket.send(serializeSandboxFrame(frame), (error) => (error ? reject(error) : resolve()));
1954
1983
  });
1955
1984
  }
1956
1985
  async sendBinaryFrame(content, source) {
@@ -31,6 +31,8 @@ export interface WorkspaceFileChunk {
31
31
  }
32
32
  export declare function createWorkspaceFileChunk(transferId: string, chunkIndex: number, content: Buffer): Buffer;
33
33
  export declare function parseWorkspaceFileChunk(raw: Buffer): WorkspaceFileChunk;
34
+ /** Wire encoding for every outbound frame: well-formed UTF-16, so valid UTF-8 JSON. */
35
+ export declare function serializeSandboxFrame(frame: SandboxFrame): string;
34
36
  export declare function parseSandboxFrame(raw: string, maxBytes?: number): SandboxFrame;
35
37
  export declare function createSandboxFrame(input: {
36
38
  type: SandboxFrameType;
@@ -138,6 +138,17 @@ function nullableString(value, label) {
138
138
  throw new Error(`${label} must be a string or null`);
139
139
  return value;
140
140
  }
141
+ // JSON.stringify escapes a lone UTF-16 surrogate (for example an emoji cut in half by a
142
+ // preview limit) as `\udXXX`; strict JSON parsers such as Agent Service reject it and the
143
+ // replayed frame would fail every reconnect.
144
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
145
+ function wellFormed(_key, value) {
146
+ return typeof value === "string" ? value.replace(LONE_SURROGATE, "\uFFFD") : value;
147
+ }
148
+ /** Wire encoding for every outbound frame: well-formed UTF-16, so valid UTF-8 JSON. */
149
+ export function serializeSandboxFrame(frame) {
150
+ return JSON.stringify(frame, wellFormed);
151
+ }
141
152
  export function parseSandboxFrame(raw, maxBytes = 262_144) {
142
153
  if (Buffer.byteLength(raw, "utf8") > maxBytes)
143
154
  throw new Error("frame exceeds size limit");
@@ -0,0 +1,354 @@
1
+ import { type PreparedRuntimeSkillProvider, type RuntimeSkillEvent } from "../runtime-skills.js";
2
+ export declare const DEEPSEEK_COURSE_SKILL_TOOL_VERSION = "course-skills-native/0.2";
3
+ type NativeResult = {
4
+ success: boolean;
5
+ content: Array<{
6
+ type: "input_text";
7
+ text: string;
8
+ }>;
9
+ };
10
+ export declare const DEEPSEEK_COURSE_SKILL_TOOLS: {
11
+ namespace: string;
12
+ name: string;
13
+ description: string;
14
+ input_schema: {
15
+ properties: {
16
+ maxItems: {
17
+ type: string;
18
+ minimum: number;
19
+ maximum: number;
20
+ description: string;
21
+ };
22
+ offset: {
23
+ type: string;
24
+ minimum: number;
25
+ description: string;
26
+ };
27
+ } | {
28
+ maxChars: {
29
+ type: string;
30
+ minimum: number;
31
+ maximum: number;
32
+ description: string;
33
+ };
34
+ offset: {
35
+ type: string;
36
+ minimum: number;
37
+ description: string;
38
+ };
39
+ } | {
40
+ maxItems: {
41
+ type: string;
42
+ minimum: number;
43
+ maximum: number;
44
+ description: string;
45
+ };
46
+ offset: {
47
+ type: string;
48
+ minimum: number;
49
+ description: string;
50
+ };
51
+ ref: {
52
+ readonly type: "string";
53
+ readonly minLength: 5;
54
+ readonly maxLength: 240;
55
+ };
56
+ } | {
57
+ maxChars: {
58
+ type: string;
59
+ minimum: number;
60
+ maximum: number;
61
+ description: string;
62
+ };
63
+ offset: {
64
+ type: string;
65
+ minimum: number;
66
+ description: string;
67
+ };
68
+ ref: {
69
+ readonly type: "string";
70
+ readonly minLength: 5;
71
+ readonly maxLength: 240;
72
+ };
73
+ } | {
74
+ maxItems: {
75
+ type: string;
76
+ minimum: number;
77
+ maximum: number;
78
+ description: string;
79
+ };
80
+ offset: {
81
+ type: string;
82
+ minimum: number;
83
+ description: string;
84
+ };
85
+ ref: {
86
+ readonly type: "string";
87
+ readonly minLength: 5;
88
+ readonly maxLength: 240;
89
+ };
90
+ path: {
91
+ readonly type: "string";
92
+ readonly minLength: 1;
93
+ readonly maxLength: 240;
94
+ };
95
+ } | {
96
+ maxChars: {
97
+ type: string;
98
+ minimum: number;
99
+ maximum: number;
100
+ description: string;
101
+ };
102
+ offset: {
103
+ type: string;
104
+ minimum: number;
105
+ description: string;
106
+ };
107
+ ref: {
108
+ readonly type: "string";
109
+ readonly minLength: 5;
110
+ readonly maxLength: 240;
111
+ };
112
+ path: {
113
+ readonly type: "string";
114
+ readonly minLength: 1;
115
+ readonly maxLength: 240;
116
+ };
117
+ };
118
+ type: "object";
119
+ additionalProperties: false;
120
+ } | {
121
+ properties: {
122
+ maxItems: {
123
+ type: string;
124
+ minimum: number;
125
+ maximum: number;
126
+ description: string;
127
+ };
128
+ offset: {
129
+ type: string;
130
+ minimum: number;
131
+ description: string;
132
+ };
133
+ } | {
134
+ maxChars: {
135
+ type: string;
136
+ minimum: number;
137
+ maximum: number;
138
+ description: string;
139
+ };
140
+ offset: {
141
+ type: string;
142
+ minimum: number;
143
+ description: string;
144
+ };
145
+ } | {
146
+ maxItems: {
147
+ type: string;
148
+ minimum: number;
149
+ maximum: number;
150
+ description: string;
151
+ };
152
+ offset: {
153
+ type: string;
154
+ minimum: number;
155
+ description: string;
156
+ };
157
+ ref: {
158
+ readonly type: "string";
159
+ readonly minLength: 5;
160
+ readonly maxLength: 240;
161
+ };
162
+ } | {
163
+ maxChars: {
164
+ type: string;
165
+ minimum: number;
166
+ maximum: number;
167
+ description: string;
168
+ };
169
+ offset: {
170
+ type: string;
171
+ minimum: number;
172
+ description: string;
173
+ };
174
+ ref: {
175
+ readonly type: "string";
176
+ readonly minLength: 5;
177
+ readonly maxLength: 240;
178
+ };
179
+ } | {
180
+ maxItems: {
181
+ type: string;
182
+ minimum: number;
183
+ maximum: number;
184
+ description: string;
185
+ };
186
+ offset: {
187
+ type: string;
188
+ minimum: number;
189
+ description: string;
190
+ };
191
+ ref: {
192
+ readonly type: "string";
193
+ readonly minLength: 5;
194
+ readonly maxLength: 240;
195
+ };
196
+ path: {
197
+ readonly type: "string";
198
+ readonly minLength: 1;
199
+ readonly maxLength: 240;
200
+ };
201
+ } | {
202
+ maxChars: {
203
+ type: string;
204
+ minimum: number;
205
+ maximum: number;
206
+ description: string;
207
+ };
208
+ offset: {
209
+ type: string;
210
+ minimum: number;
211
+ description: string;
212
+ };
213
+ ref: {
214
+ readonly type: "string";
215
+ readonly minLength: 5;
216
+ readonly maxLength: 240;
217
+ };
218
+ path: {
219
+ readonly type: "string";
220
+ readonly minLength: 1;
221
+ readonly maxLength: 240;
222
+ };
223
+ };
224
+ type: "object";
225
+ required: readonly ["ref"];
226
+ additionalProperties: false;
227
+ } | {
228
+ properties: {
229
+ maxItems: {
230
+ type: string;
231
+ minimum: number;
232
+ maximum: number;
233
+ description: string;
234
+ };
235
+ offset: {
236
+ type: string;
237
+ minimum: number;
238
+ description: string;
239
+ };
240
+ } | {
241
+ maxChars: {
242
+ type: string;
243
+ minimum: number;
244
+ maximum: number;
245
+ description: string;
246
+ };
247
+ offset: {
248
+ type: string;
249
+ minimum: number;
250
+ description: string;
251
+ };
252
+ } | {
253
+ maxItems: {
254
+ type: string;
255
+ minimum: number;
256
+ maximum: number;
257
+ description: string;
258
+ };
259
+ offset: {
260
+ type: string;
261
+ minimum: number;
262
+ description: string;
263
+ };
264
+ ref: {
265
+ readonly type: "string";
266
+ readonly minLength: 5;
267
+ readonly maxLength: 240;
268
+ };
269
+ } | {
270
+ maxChars: {
271
+ type: string;
272
+ minimum: number;
273
+ maximum: number;
274
+ description: string;
275
+ };
276
+ offset: {
277
+ type: string;
278
+ minimum: number;
279
+ description: string;
280
+ };
281
+ ref: {
282
+ readonly type: "string";
283
+ readonly minLength: 5;
284
+ readonly maxLength: 240;
285
+ };
286
+ } | {
287
+ maxItems: {
288
+ type: string;
289
+ minimum: number;
290
+ maximum: number;
291
+ description: string;
292
+ };
293
+ offset: {
294
+ type: string;
295
+ minimum: number;
296
+ description: string;
297
+ };
298
+ ref: {
299
+ readonly type: "string";
300
+ readonly minLength: 5;
301
+ readonly maxLength: 240;
302
+ };
303
+ path: {
304
+ readonly type: "string";
305
+ readonly minLength: 1;
306
+ readonly maxLength: 240;
307
+ };
308
+ } | {
309
+ maxChars: {
310
+ type: string;
311
+ minimum: number;
312
+ maximum: number;
313
+ description: string;
314
+ };
315
+ offset: {
316
+ type: string;
317
+ minimum: number;
318
+ description: string;
319
+ };
320
+ ref: {
321
+ readonly type: "string";
322
+ readonly minLength: 5;
323
+ readonly maxLength: 240;
324
+ };
325
+ path: {
326
+ readonly type: "string";
327
+ readonly minLength: 1;
328
+ readonly maxLength: 240;
329
+ };
330
+ };
331
+ type: "object";
332
+ required: readonly ["ref", "path"];
333
+ additionalProperties: false;
334
+ };
335
+ defer_loading: boolean;
336
+ }[];
337
+ export declare class DeepseekCourseSkills {
338
+ private readonly runtime;
339
+ private readonly calls;
340
+ private applied?;
341
+ constructor(options: {
342
+ prepared?: PreparedRuntimeSkillProvider;
343
+ onEvent(event: RuntimeSkillEvent): Promise<void>;
344
+ });
345
+ markApplied(): Promise<void>;
346
+ execute(payload: unknown, scope: {
347
+ threadId: string;
348
+ turnId: string;
349
+ }, signal: AbortSignal): Promise<{
350
+ callId: string;
351
+ result: NativeResult;
352
+ } | null>;
353
+ }
354
+ export {};
@@ -0,0 +1,236 @@
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
+ const MAX_PAGE_ITEMS = 32;
9
+ export const DEEPSEEK_COURSE_SKILL_TOOL_VERSION = "course-skills-native/0.2";
10
+ export const DEEPSEEK_COURSE_SKILL_TOOLS = COURSE_SKILL_TOOLS.map((tool) => ({
11
+ namespace: "courseskills",
12
+ // The runtime reserves mcp_ names for its own MCP dispatcher.
13
+ name: `${TOOL_PREFIX}${tool.name}`,
14
+ description: tool.description + (tool.name === "list_skills"
15
+ ? " 目录按完整条目分页;nextOffset 非空时用它作为 offset 继续读取完整目录。"
16
+ : " 分页按 Unicode 码点计数,默认每页 4000、最多 6000;nextOffset 非空时用它作为 offset 继续读取完整内容。"),
17
+ input_schema: {
18
+ ...tool.inputSchema,
19
+ properties: {
20
+ ...tool.inputSchema.properties,
21
+ offset: { type: "integer", minimum: 0, description: tool.name === "list_skills"
22
+ ? "起始条目下标,默认 0。" : "起始 Unicode 码点位置,默认 0。" },
23
+ ...(tool.name === "list_skills" ? {
24
+ maxItems: { type: "integer", minimum: 1, maximum: MAX_PAGE_ITEMS,
25
+ description: "本页最多条目数,默认及上限 32;序列化预算可能缩小本页。" },
26
+ } : {
27
+ maxChars: { type: "integer", minimum: 1, maximum: MAX_PAGE_CHARS,
28
+ description: "本页最多 Unicode 码点数,默认 4000;序列化预算可能缩小本页。" },
29
+ }),
30
+ },
31
+ },
32
+ defer_loading: false,
33
+ }));
34
+ export class DeepseekCourseSkills {
35
+ runtime;
36
+ calls = new Map();
37
+ applied;
38
+ constructor(options) {
39
+ // Pin the catalog used by both grant checks and page offsets for this activation.
40
+ this.runtime = new CourseSkillsMcpRuntime({ ...options, prepared: options.prepared
41
+ ? { ...options.prepared, catalog: structuredClone(options.prepared.catalog) } : undefined });
42
+ }
43
+ markApplied() {
44
+ this.applied ??= this.runtime.emitAppliedEvents();
45
+ return this.applied;
46
+ }
47
+ async execute(payload, scope, signal) {
48
+ if (signal.aborted)
49
+ return null;
50
+ const request = objectValue(payload);
51
+ if (!request || !validId(scope.threadId) || !validId(scope.turnId)
52
+ || !validId(request.thread_id) || !validId(request.turn_id)) {
53
+ throw invalid("skill_tool_fence_invalid");
54
+ }
55
+ if (request.thread_id !== scope.threadId || request.turn_id !== scope.turnId)
56
+ return null;
57
+ let requestBytes;
58
+ try {
59
+ requestBytes = Buffer.byteLength(JSON.stringify(request), "utf8");
60
+ }
61
+ catch {
62
+ throw invalid("skill_tool_request_invalid");
63
+ }
64
+ if (requestBytes > MAX_REQUEST_BYTES)
65
+ throw invalid("skill_tool_request_too_large");
66
+ if (!validId(request.call_id) || request.namespace !== "courseskills"
67
+ || typeof request.tool !== "string"
68
+ || !DEEPSEEK_COURSE_SKILL_TOOLS.some((tool) => tool.name === request.tool)
69
+ || !objectValue(request.arguments)) {
70
+ throw invalid("skill_tool_request_invalid");
71
+ }
72
+ const key = JSON.stringify([scope.threadId, scope.turnId, request.call_id]);
73
+ let fingerprint;
74
+ try {
75
+ fingerprint = JSON.stringify([request.namespace, request.tool, canonical(request.arguments)]);
76
+ }
77
+ catch {
78
+ throw invalid("skill_tool_request_invalid");
79
+ }
80
+ const previous = this.calls.get(key);
81
+ if (previous !== undefined) {
82
+ if (previous !== fingerprint)
83
+ throw invalid("skill_tool_replay_conflict");
84
+ return null;
85
+ }
86
+ // Reserve before awaiting so concurrent SSE replay cannot execute twice.
87
+ this.calls.set(key, fingerprint);
88
+ const isCatalog = request.tool === `${TOOL_PREFIX}list_skills`;
89
+ const isReference = request.tool === `${TOOL_PREFIX}load_reference`;
90
+ const originalArgs = request.arguments;
91
+ const { offset = 0, maxChars = DEFAULT_PAGE_CHARS, maxItems = MAX_PAGE_ITEMS, ...args } = originalArgs;
92
+ const explicitPage = "offset" in originalArgs
93
+ || (isCatalog ? "maxItems" : "maxChars") in originalArgs;
94
+ const allowed = isCatalog ? ["offset", "maxItems"]
95
+ : isReference ? ["ref", "path", "offset", "maxChars"] : ["ref", "offset", "maxChars"];
96
+ if (Object.keys(originalArgs).some((key) => !allowed.includes(key))
97
+ || typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0
98
+ || !validPageLimit(isCatalog ? maxItems : maxChars, isCatalog ? MAX_PAGE_ITEMS : MAX_PAGE_CHARS)) {
99
+ return { callId: request.call_id, result: toolFailure("skill_request_invalid") };
100
+ }
101
+ const response = await this.runtime.handle({
102
+ jsonrpc: "2.0",
103
+ id: request.call_id,
104
+ method: "tools/call",
105
+ params: {
106
+ name: request.tool.slice(TOOL_PREFIX.length),
107
+ arguments: args,
108
+ },
109
+ });
110
+ if (signal.aborted)
111
+ return null;
112
+ const result = objectValue(response?.result);
113
+ if (!result || !Array.isArray(result.content) || typeof result.isError !== "boolean") {
114
+ throw invalid("skill_tool_response_invalid");
115
+ }
116
+ const content = result.content.map((item) => {
117
+ const entry = objectValue(item);
118
+ if (entry?.type !== "text" || typeof entry.text !== "string") {
119
+ throw invalid("skill_tool_response_invalid");
120
+ }
121
+ return { type: "input_text", text: entry.text };
122
+ });
123
+ const native = { success: !result.isError, content };
124
+ return { callId: request.call_id,
125
+ result: !native.success ? native : isCatalog
126
+ ? catalogPage(native, offset, maxItems, explicitPage)
127
+ : contentPage(native, offset, maxChars, isReference, explicitPage) };
128
+ }
129
+ }
130
+ function toolFailure(code) {
131
+ return { success: false, content: [{ type: "input_text", text: JSON.stringify({
132
+ schemaVersion: "tool-result/0.1", ok: false, code,
133
+ error: { message: "课程技能请求失败" }, evidence: [],
134
+ }) }] };
135
+ }
136
+ function contentPage(result, offset, maxChars, isReference, explicitPage) {
137
+ if (result.content.length !== 1)
138
+ throw invalid("skill_tool_response_invalid");
139
+ let envelope;
140
+ try {
141
+ envelope = objectValue(JSON.parse(result.content[0].text));
142
+ }
143
+ catch {
144
+ throw invalid("skill_tool_response_invalid");
145
+ }
146
+ const data = objectValue(envelope?.data);
147
+ if (!envelope || !data || typeof data.content !== "string" || typeof data.bytes !== "number") {
148
+ throw invalid("skill_tool_response_invalid");
149
+ }
150
+ if (!isReference && !explicitPage && result.content[0].text.length <= MAX_RESULT_CHARS)
151
+ return result;
152
+ const chars = Array.from(data.content);
153
+ const kind = isReference ? "reference" : "body";
154
+ if (offset > chars.length)
155
+ return toolFailure(`skill_${kind}_offset_invalid`);
156
+ const serialize = (count) => {
157
+ const content = chars.slice(offset, offset + count).join("");
158
+ const nextOffset = offset + count < chars.length ? offset + count : null;
159
+ return JSON.stringify({ ...envelope, data: { ...data, content,
160
+ bytes: Buffer.byteLength(content, "utf8"), offset, nextOffset,
161
+ totalChars: chars.length, totalBytes: data.bytes,
162
+ truncated: nextOffset !== null || data.truncated === true,
163
+ } });
164
+ };
165
+ return boundedPage(serialize, Math.min(maxChars, chars.length - offset), offset < chars.length, `skill_${kind}_page_too_large`);
166
+ }
167
+ function catalogPage(result, offset, maxItems, explicitPage) {
168
+ if (result.content.length !== 1)
169
+ throw invalid("skill_tool_response_invalid");
170
+ let envelope;
171
+ try {
172
+ envelope = objectValue(JSON.parse(result.content[0].text));
173
+ }
174
+ catch {
175
+ throw invalid("skill_tool_response_invalid");
176
+ }
177
+ const data = objectValue(envelope?.data);
178
+ if (!envelope || !data || !Array.isArray(data.skills))
179
+ throw invalid("skill_tool_response_invalid");
180
+ if (!explicitPage && result.content[0].text.length <= MAX_RESULT_CHARS)
181
+ return result;
182
+ const skills = data.skills;
183
+ if (offset > skills.length)
184
+ return toolFailure("skill_catalog_offset_invalid");
185
+ const serialize = (count) => {
186
+ const nextOffset = offset + count < skills.length ? offset + count : null;
187
+ return JSON.stringify({ ...envelope, data: { ...data, skills: skills.slice(offset, offset + count),
188
+ offset, nextOffset, totalItems: skills.length, truncated: nextOffset !== null } });
189
+ };
190
+ return boundedPage(serialize, Math.min(maxItems, skills.length - offset), offset < skills.length, "skill_catalog_page_too_large");
191
+ }
192
+ /** Bound the complete serialized envelope, preserving full code points or catalog entries. */
193
+ function boundedPage(serialize, count, hasRemaining, errorCode) {
194
+ let low = 0;
195
+ let high = count;
196
+ let text = serialize(high);
197
+ if (text.length > MAX_RESULT_CHARS) {
198
+ while (low < high) {
199
+ const middle = Math.ceil((low + high) / 2);
200
+ if (serialize(middle).length <= MAX_RESULT_CHARS)
201
+ low = middle;
202
+ else
203
+ high = middle - 1;
204
+ }
205
+ text = serialize(low);
206
+ if ((low === 0 && hasRemaining) || text.length > MAX_RESULT_CHARS)
207
+ return toolFailure(errorCode);
208
+ }
209
+ return { success: true, content: [{ type: "input_text", text }] };
210
+ }
211
+ function validPageLimit(value, maximum) {
212
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= maximum;
213
+ }
214
+ function objectValue(value) {
215
+ return value !== null && typeof value === "object" && !Array.isArray(value)
216
+ ? value : null;
217
+ }
218
+ function validId(value) {
219
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,240}$/.test(value);
220
+ }
221
+ function invalid(code) {
222
+ return new RuntimeSkillProviderError(code, "Course Skill dynamic tool request failed");
223
+ }
224
+ /** Stable JSON fingerprint: object key order is irrelevant to a replay. */
225
+ function canonical(value) {
226
+ if (value === null || typeof value === "string" || typeof value === "boolean")
227
+ return value;
228
+ if (typeof value === "number" && Number.isFinite(value))
229
+ return value;
230
+ if (Array.isArray(value))
231
+ return value.map(canonical);
232
+ const object = objectValue(value);
233
+ if (!object)
234
+ throw invalid("skill_tool_request_invalid");
235
+ return Object.fromEntries(Object.keys(object).sort().map((key) => [key, canonical(object[key])]));
236
+ }
@@ -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.7",
4
4
  "description": "BotLearn Course daemon for Agent Service managed sandboxes (internal).",
5
5
  "type": "module",
6
6
  "bin": {