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

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
@@ -103,7 +103,9 @@ pnpm exec vitest run src/runtimes/__tests__/runtime-binaries.test.ts
103
103
  `SKILL.md`/reference。0.8.39 保留同步 MCP 目录的 clean-env Unix Socket relay;其他版本
104
104
  必须声明 `external_tools` 能力,缺失时明确失败。两条路径复用同一 Course 授权与读取逻辑,
105
105
  endpoint/token 不进入 runtime env、MCP config、state、workspace 或日志。
106
- 原生引用工具按 `nextOffset` 分页读取,避免大文件被运行时截断;字段与边界见
106
+ 原生工具分页契约 `course-skills-native/0.2`:正文与引用按 Unicode 码点、目录按完整条目
107
+ 读取。`nextOffset` 非空时继续读取完整内容,每页完整 JSON 不超过 10000 个 JavaScript 字符。
108
+ 小正文与小目录未指定分页参数时保留原结果形状;字段与边界见
107
109
  `docs/specs/agent-service-sandbox-daemon-websocket.md` §9.2.2。
108
110
  系统提示词只使用服务端下发的 `runtime_prompt`。长期模型 provider key 留在 Agent Service,runtime
109
111
  只拿 generation-scoped proxy grant。
@@ -3,6 +3,7 @@ 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
+ import type { StartupTimer } from "./startup-timings.js";
6
7
  /** Task-scoped CourseRuns route each run to its own native thread (course-agent-session-scope.md). */
7
8
  export declare const NATIVE_SESSION_KEY_CAPABILITY = "native_session_key_v1";
8
9
  export declare function workspaceDurabilityCapabilities(): string[];
@@ -18,6 +19,8 @@ export interface AgentServiceSandboxOptions {
18
19
  sleep?: (ms: number) => Promise<void>;
19
20
  /** Test/provider injection; production uses the bounded HTTP Runtime Skill Provider. */
20
21
  prepareSkillProvider?: RuntimeSkillProviderFactory;
22
+ /** Cold-start stage timer; its payload is sent once with the first `sandbox.ready`. */
23
+ startupTimer?: StartupTimer;
21
24
  }
22
25
  /**
23
26
  * Long-running daemon client for one user-scoped managed sandbox (ADR-015).
@@ -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";
@@ -784,7 +784,9 @@ export class AgentServiceSandboxClient {
784
784
  // Attach message/close listeners before awaiting open; the server may send
785
785
  // sandbox.hello immediately after the upgrade completes.
786
786
  const inbox = new SocketInbox(socket);
787
+ this.options.startupTimer?.mark("state_loaded");
787
788
  await waitForOpen(socket);
789
+ this.options.startupTimer?.mark("websocket_open");
788
790
  if (socket.protocol !== AGENT_SERVICE_WS_SUBPROTOCOL) {
789
791
  socket.close(4410, "protocol_incompatible");
790
792
  throw new SandboxClosedError(4410, "protocol_incompatible");
@@ -855,6 +857,7 @@ export class AgentServiceSandboxClient {
855
857
  }
856
858
  }
857
859
  async handleHello(frame) {
860
+ this.options.startupTimer?.mark("hello_received");
858
861
  await this.lifecycleChain;
859
862
  if (frame.sandbox_id !== this.options.sandboxId) {
860
863
  throw new SandboxClosedError(4403, "sandbox_mismatch");
@@ -899,6 +902,8 @@ export class AgentServiceSandboxClient {
899
902
  this.runtimeLogPolicy = runtimeLogPolicy(frame.payload.runtime_log_policy);
900
903
  this.persist();
901
904
  assertWorkspaceFilesystem(process.env.BOTLEARN_AGENT_SERVICE_WORKSPACE_ROOT ?? "");
905
+ this.options.startupTimer?.mark("hello_processed");
906
+ const startupTimings = this.options.startupTimer?.takeReadyPayload();
902
907
  await this.sendControlFrame("sandbox.ready", {
903
908
  protocol_versions: [AGENT_SERVICE_WS_SCHEMA],
904
909
  capabilities: [
@@ -917,6 +922,7 @@ export class AgentServiceSandboxClient {
917
922
  },
918
923
  resumed_sessions: Object.keys(this.state.sessions),
919
924
  spool_frames: this.spoolFrameCount(),
925
+ ...(startupTimings ? { startup_timings: startupTimings } : {}),
920
926
  });
921
927
  this.runtimeLogHandshakeReady = true;
922
928
  }
@@ -1979,7 +1985,7 @@ export class AgentServiceSandboxClient {
1979
1985
  if (!socket || socket.readyState !== WebSocketClient.OPEN)
1980
1986
  return;
1981
1987
  await new Promise((resolve, reject) => {
1982
- socket.send(JSON.stringify(frame), (error) => (error ? reject(error) : resolve()));
1988
+ socket.send(serializeSandboxFrame(frame), (error) => (error ? reject(error) : resolve()));
1983
1989
  });
1984
1990
  }
1985
1991
  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");
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { AgentServiceSandboxClient } from "./agent-service-sandbox.js";
6
6
  import { augmentProcessPath } from "./path-env.js";
7
7
  import { redactSecretString } from "./redaction.js";
8
8
  import { clearAgentServiceControlEnv } from "./runtime-env.js";
9
+ import { StartupTimer, parseBootstrapStartupTimings } from "./startup-timings.js";
9
10
  import { RUNTIME_MODULES, fakeRuntimeEnabled } from "./runtimes/index.js";
10
11
  const pkg = createRequire(import.meta.url)("../package.json");
11
12
  const SESSION_BOOTSTRAP_MAX_BYTES = 64 * 1024;
@@ -119,6 +120,8 @@ export function assertManagedCourseDaemonVersion(actualVersion, selectedVersion)
119
120
  }
120
121
  }
121
122
  async function cmdAgentServiceSession(args) {
123
+ const startupTimer = new StartupTimer(parseBootstrapStartupTimings(process.env.BOTLEARN_BOOTSTRAP_STARTUP_TIMINGS));
124
+ startupTimer.mark("process_start");
122
125
  const bootstrap = args.flags["bootstrap-stdin"] === true
123
126
  ? await readSandboxBootstrapFromStdin()
124
127
  : {
@@ -132,6 +135,7 @@ async function cmdAgentServiceSession(args) {
132
135
  return 1;
133
136
  }
134
137
  assertManagedCourseDaemonVersion(pkg.version, process.env.BOTLEARN_MANAGED_COURSE_DAEMON_VERSION?.trim() || undefined);
138
+ startupTimer.mark("read_bootstrap");
135
139
  augmentProcessPath();
136
140
  const runtimes = new Map();
137
141
  for (const mod of RUNTIME_MODULES) {
@@ -139,11 +143,13 @@ async function cmdAgentServiceSession(args) {
139
143
  continue;
140
144
  runtimes.set(mod.id, mod.create());
141
145
  }
146
+ startupTimer.mark("create_runtimes");
142
147
  const client = new AgentServiceSandboxClient({
143
148
  wsUrl,
144
149
  sandboxId,
145
150
  sandboxToken,
146
151
  runtimes,
152
+ startupTimer,
147
153
  daemonVersion: pkg.version,
148
154
  deepseekTuiVersion: process.env.BOTLEARN_MANAGED_DEEPSEEK_TUI_VERSION?.trim() || undefined,
149
155
  });
@@ -92,8 +92,9 @@ export class CourseSkillsMcpRuntime {
92
92
  try {
93
93
  if (name === "list_skills") {
94
94
  requireExactArguments(args, []);
95
+ const catalog = this.options.prepared?.catalog ?? [];
95
96
  return toolSuccess(id, "skill_catalog_listed", {
96
- skills: (this.options.prepared?.catalog ?? []).map((entry) => ({
97
+ skills: catalog.map((entry) => ({
97
98
  ref: entry.ref,
98
99
  digest: entry.digest,
99
100
  name: entry.name,
@@ -101,6 +102,9 @@ export class CourseSkillsMcpRuntime {
101
102
  version: entry.version,
102
103
  requiredCapabilities: entry.requiredCapabilities,
103
104
  })),
105
+ ...(catalog.length === 0 ? {
106
+ message: "当前课程未为本次任务配备 Skill(技能),无需重复获取技能目录。请依据当前任务说明继续。",
107
+ } : {}),
104
108
  });
105
109
  }
106
110
  if (name === "load_skill") {
@@ -21,6 +21,7 @@ const AGENT_SERVICE_SUPERVISOR_ENV_KEYS = [
21
21
  "BOTLEARN_MANAGED_DEEPSEEK_TUI_VERSION",
22
22
  "BOTLEARN_AGENT_SERVICE_WORKSPACE_ROOT",
23
23
  "BOTLEARN_AGENT_SERVICE_PROFILE_ROOT",
24
+ "BOTLEARN_BOOTSTRAP_STARTUP_TIMINGS",
24
25
  ];
25
26
  const ACTIVATION_RUNTIME_ENV_KEYS = new Set([
26
27
  "DEEPSEEK_API_KEY",
@@ -1,4 +1,5 @@
1
1
  import { type PreparedRuntimeSkillProvider, type RuntimeSkillEvent } from "../runtime-skills.js";
2
+ export declare const DEEPSEEK_COURSE_SKILL_TOOL_VERSION = "course-skills-native/0.2";
2
3
  type NativeResult = {
3
4
  success: boolean;
4
5
  content: Array<{
@@ -11,22 +12,311 @@ export declare const DEEPSEEK_COURSE_SKILL_TOOLS: {
11
12
  name: string;
12
13
  description: string;
13
14
  input_schema: {
14
- readonly type: "object";
15
- readonly properties: {};
16
- readonly additionalProperties: false;
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;
17
120
  } | {
18
121
  properties: {
122
+ maxItems: {
123
+ type: string;
124
+ minimum: number;
125
+ maximum: number;
126
+ description: string;
127
+ };
19
128
  offset: {
20
129
  type: string;
21
130
  minimum: number;
22
131
  description: string;
23
132
  };
133
+ } | {
24
134
  maxChars: {
25
135
  type: string;
26
136
  minimum: number;
27
137
  maximum: number;
28
138
  description: string;
29
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
+ };
30
320
  ref: {
31
321
  readonly type: "string";
32
322
  readonly minLength: 5;
@@ -5,21 +5,30 @@ const MAX_REQUEST_BYTES = 32 * 1024;
5
5
  const DEFAULT_PAGE_CHARS = 4000;
6
6
  const MAX_PAGE_CHARS = 6000;
7
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";
8
10
  export const DEEPSEEK_COURSE_SKILL_TOOLS = COURSE_SKILL_TOOLS.map((tool) => ({
9
11
  namespace: "courseskills",
10
12
  // The runtime reserves mcp_ names for its own MCP dispatcher.
11
13
  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" ? {
14
+ description: tool.description + (tool.name === "list_skills"
15
+ ? " 目录按完整条目分页;nextOffset 非空时用它作为 offset 继续读取完整目录。"
16
+ : " 分页按 Unicode 码点计数,默认每页 4000、最多 6000;nextOffset 非空时用它作为 offset 继续读取完整内容。"),
17
+ input_schema: {
15
18
  ...tool.inputSchema,
16
19
  properties: {
17
20
  ...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
+ 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
+ }),
21
30
  },
22
- } : tool.inputSchema,
31
+ },
23
32
  defer_loading: false,
24
33
  }));
25
34
  export class DeepseekCourseSkills {
@@ -27,7 +36,9 @@ export class DeepseekCourseSkills {
27
36
  calls = new Map();
28
37
  applied;
29
38
  constructor(options) {
30
- this.runtime = new CourseSkillsMcpRuntime(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 });
31
42
  }
32
43
  markApplied() {
33
44
  this.applied ??= this.runtime.emitAppliedEvents();
@@ -74,20 +85,18 @@ export class DeepseekCourseSkills {
74
85
  }
75
86
  // Reserve before awaiting so concurrent SSE replay cannot execute twice.
76
87
  this.calls.set(key, fingerprint);
88
+ const isCatalog = request.tool === `${TOOL_PREFIX}list_skills`;
77
89
  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;
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") };
91
100
  }
92
101
  const response = await this.runtime.handle({
93
102
  jsonrpc: "2.0",
@@ -113,7 +122,9 @@ export class DeepseekCourseSkills {
113
122
  });
114
123
  const native = { success: !result.isError, content };
115
124
  return { callId: request.call_id,
116
- result: isReference && native.success ? referencePage(native, offset, maxChars) : native };
125
+ result: !native.success ? native : isCatalog
126
+ ? catalogPage(native, offset, maxItems, explicitPage)
127
+ : contentPage(native, offset, maxChars, isReference, explicitPage) };
117
128
  }
118
129
  }
119
130
  function toolFailure(code) {
@@ -122,7 +133,7 @@ function toolFailure(code) {
122
133
  error: { message: "课程技能请求失败" }, evidence: [],
123
134
  }) }] };
124
135
  }
125
- function referencePage(result, offset, maxChars) {
136
+ function contentPage(result, offset, maxChars, isReference, explicitPage) {
126
137
  if (result.content.length !== 1)
127
138
  throw invalid("skill_tool_response_invalid");
128
139
  let envelope;
@@ -136,9 +147,12 @@ function referencePage(result, offset, maxChars) {
136
147
  if (!envelope || !data || typeof data.content !== "string" || typeof data.bytes !== "number") {
137
148
  throw invalid("skill_tool_response_invalid");
138
149
  }
150
+ if (!isReference && !explicitPage && result.content[0].text.length <= MAX_RESULT_CHARS)
151
+ return result;
139
152
  const chars = Array.from(data.content);
153
+ const kind = isReference ? "reference" : "body";
140
154
  if (offset > chars.length)
141
- return toolFailure("skill_reference_offset_invalid");
155
+ return toolFailure(`skill_${kind}_offset_invalid`);
142
156
  const serialize = (count) => {
143
157
  const content = chars.slice(offset, offset + count).join("");
144
158
  const nextOffset = offset + count < chars.length ? offset + count : null;
@@ -148,11 +162,39 @@ function referencePage(result, offset, maxChars) {
148
162
  truncated: nextOffset !== null || data.truncated === true,
149
163
  } });
150
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) {
151
194
  let low = 0;
152
- let high = Math.min(maxChars, chars.length - offset);
195
+ let high = count;
153
196
  let text = serialize(high);
154
197
  if (text.length > MAX_RESULT_CHARS) {
155
- // Measure the complete envelope including JSON escaping and metadata.
156
198
  while (low < high) {
157
199
  const middle = Math.ceil((low + high) / 2);
158
200
  if (serialize(middle).length <= MAX_RESULT_CHARS)
@@ -161,12 +203,14 @@ function referencePage(result, offset, maxChars) {
161
203
  high = middle - 1;
162
204
  }
163
205
  text = serialize(low);
164
- if ((low === 0 && offset < chars.length) || text.length > MAX_RESULT_CHARS) {
165
- return toolFailure("skill_reference_page_too_large");
166
- }
206
+ if ((low === 0 && hasRemaining) || text.length > MAX_RESULT_CHARS)
207
+ return toolFailure(errorCode);
167
208
  }
168
209
  return { success: true, content: [{ type: "input_text", text }] };
169
210
  }
211
+ function validPageLimit(value, maximum) {
212
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= maximum;
213
+ }
170
214
  function objectValue(value) {
171
215
  return value !== null && typeof value === "object" && !Array.isArray(value)
172
216
  ? value : null;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Cold-start timing for one daemon process, reported once in `sandbox.ready`.
3
+ *
4
+ * The runtime bootstrap hands its own stage timings over in
5
+ * `BOTLEARN_BOOTSTRAP_STARTUP_TIMINGS`; the daemon appends its stages so Agent
6
+ * Service can log one launcher-to-ready timeline. Values are durations and epoch
7
+ * milliseconds only — never paths, tokens or other payload content.
8
+ */
9
+ export interface BootstrapStartupTimings {
10
+ process_started_at_ms?: number;
11
+ bootstrap_started_at_ms?: number;
12
+ stages_ms: Record<string, number>;
13
+ total_ms?: number;
14
+ }
15
+ export interface StartupTimingsPayload {
16
+ bootstrap?: BootstrapStartupTimings;
17
+ daemon_process_started_at_ms: number;
18
+ daemon_stages_ms: Record<string, number>;
19
+ }
20
+ /** Parse the bootstrap hand-off; anything malformed is dropped, never thrown. */
21
+ export declare function parseBootstrapStartupTimings(raw: string | undefined): BootstrapStartupTimings | undefined;
22
+ /** Sequential stage timer: each mark records milliseconds since the previous mark. */
23
+ export declare class StartupTimer {
24
+ private readonly bootstrap;
25
+ private readonly now;
26
+ private readonly processStartedAt;
27
+ private last;
28
+ private readonly stages;
29
+ private reported;
30
+ constructor(bootstrap: BootstrapStartupTimings | undefined, now?: () => number, processStartedAt?: number);
31
+ mark(stage: string): void;
32
+ /** Return the payload once; later reconnects of the same process report nothing. */
33
+ takeReadyPayload(): StartupTimingsPayload | undefined;
34
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Cold-start timing for one daemon process, reported once in `sandbox.ready`.
3
+ *
4
+ * The runtime bootstrap hands its own stage timings over in
5
+ * `BOTLEARN_BOOTSTRAP_STARTUP_TIMINGS`; the daemon appends its stages so Agent
6
+ * Service can log one launcher-to-ready timeline. Values are durations and epoch
7
+ * milliseconds only — never paths, tokens or other payload content.
8
+ */
9
+ const MAX_STAGES = 32;
10
+ const STAGE_NAME = /^[a-z][a-z0-9_]{0,47}$/u;
11
+ const MAX_MS = 24 * 60 * 60 * 1000;
12
+ function boundedMs(value, max = MAX_MS) {
13
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max
14
+ ? Math.round(value)
15
+ : undefined;
16
+ }
17
+ function boundedEpochMs(value) {
18
+ return boundedMs(value, Number.MAX_SAFE_INTEGER);
19
+ }
20
+ /** Parse the bootstrap hand-off; anything malformed is dropped, never thrown. */
21
+ export function parseBootstrapStartupTimings(raw) {
22
+ if (!raw || raw.length > 4096)
23
+ return undefined;
24
+ let parsed;
25
+ try {
26
+ parsed = JSON.parse(raw);
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ if (!parsed || typeof parsed !== "object")
32
+ return undefined;
33
+ const source = parsed;
34
+ const stages = {};
35
+ const rawStages = source.stagesMs;
36
+ if (rawStages && typeof rawStages === "object") {
37
+ for (const [name, value] of Object.entries(rawStages).slice(0, MAX_STAGES)) {
38
+ const ms = boundedMs(value);
39
+ if (STAGE_NAME.test(name) && ms !== undefined)
40
+ stages[name] = ms;
41
+ }
42
+ }
43
+ const result = { stages_ms: stages };
44
+ const processStartedAt = boundedEpochMs(source.processStartedAtMs);
45
+ const bootstrapStartedAt = boundedEpochMs(source.bootstrapStartedAtMs);
46
+ const total = boundedMs(source.totalMs);
47
+ if (processStartedAt !== undefined)
48
+ result.process_started_at_ms = processStartedAt;
49
+ if (bootstrapStartedAt !== undefined)
50
+ result.bootstrap_started_at_ms = bootstrapStartedAt;
51
+ if (total !== undefined)
52
+ result.total_ms = total;
53
+ return result;
54
+ }
55
+ /** Sequential stage timer: each mark records milliseconds since the previous mark. */
56
+ export class StartupTimer {
57
+ bootstrap;
58
+ now;
59
+ processStartedAt;
60
+ last;
61
+ stages = {};
62
+ reported = false;
63
+ constructor(bootstrap, now = Date.now, processStartedAt = performance.timeOrigin) {
64
+ this.bootstrap = bootstrap;
65
+ this.now = now;
66
+ this.processStartedAt = processStartedAt;
67
+ this.last = Math.round(processStartedAt);
68
+ }
69
+ mark(stage) {
70
+ if (this.reported || !STAGE_NAME.test(stage) || stage in this.stages)
71
+ return;
72
+ if (Object.keys(this.stages).length >= MAX_STAGES)
73
+ return;
74
+ const current = this.now();
75
+ this.stages[stage] = Math.max(0, Math.round(current - this.last));
76
+ this.last = current;
77
+ }
78
+ /** Return the payload once; later reconnects of the same process report nothing. */
79
+ takeReadyPayload() {
80
+ if (this.reported)
81
+ return undefined;
82
+ this.reported = true;
83
+ return {
84
+ ...(this.bootstrap ? { bootstrap: this.bootstrap } : {}),
85
+ daemon_process_started_at_ms: Math.round(this.processStartedAt),
86
+ daemon_stages_ms: { ...this.stages },
87
+ };
88
+ }
89
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botlearn-course/daemon",
3
- "version": "0.0.29-beta.6",
3
+ "version": "0.0.29-beta.8",
4
4
  "description": "BotLearn Course daemon for Agent Service managed sandboxes (internal).",
5
5
  "type": "module",
6
6
  "bin": {