@botlearn-course/daemon 0.0.21-beta.3 → 0.0.21-beta.5

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.
@@ -4,12 +4,6 @@ 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, CourseRuntimeProfile, RunEvent, RunEventReceipt, RunFileCandidate, RunFileRecord, RunStartPayload } from "./types.js";
6
6
  export declare function workspaceDurabilityCapabilities(): string[];
7
- /**
8
- * NAS 是运行时 workspace 的唯一持久事实来源,committed snapshot 只供前端查看。
9
- * 任何 restore payload 都意味着对端仍在下发已删除的 S3 回写指令,必须 fail closed,
10
- * 否则可能用落后的派生快照覆盖 NAS 中较新的内容。
11
- */
12
- export declare function assertWorkspaceRestoreAllowed(requestedRestore: unknown): void;
13
7
  export interface AgentServiceSandboxOptions {
14
8
  wsUrl: string;
15
9
  sandboxId: string;
@@ -53,6 +47,7 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
53
47
  private socket;
54
48
  private sandboxGeneration;
55
49
  private connectionEpoch;
50
+ private currentLifecycleOperationId;
56
51
  private outboundSeq;
57
52
  private inboundSeq;
58
53
  private activeSessionId;
@@ -102,10 +97,9 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
102
97
  private queueRuntimeLog;
103
98
  private assertServerFrame;
104
99
  private handleServerFrame;
105
- /** sandbox.sync 只做对账:重放 spool、关闭待关 session、应用 drain/shutdown。 */
100
+ /** sandbox.sync 只做对账:重放 spool、关闭待关 session、应用 shutdown。 */
106
101
  private applySync;
107
102
  private handleSessionOpen;
108
- private handleWorkspaceCheckpoint;
109
103
  private handleSessionActivate;
110
104
  private handleTurnStart;
111
105
  private handleTurnCancel;
@@ -121,6 +115,7 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
121
115
  private scheduleLifecycle;
122
116
  private currentLifecycleFence;
123
117
  private isCurrentLifecycleFence;
118
+ private isCurrentDrainFence;
124
119
  private runIdsForSession;
125
120
  private deactivateSession;
126
121
  private terminateSessionWriters;
@@ -1,4 +1,5 @@
1
- import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { ensureDaemonHome } from "./auth-store.js";
4
5
  import { AGENT_SERVICE_WS_SCHEMA, AGENT_SERVICE_WS_SUBPROTOCOL, createSandboxFrame, createWorkspaceFileChunk, parseSandboxFrame, UnsupportedSandboxProtocolError, WORKSPACE_FILE_READ_BINARY_CAPABILITY, } from "./agent-service-ws-protocol.js";
@@ -10,11 +11,7 @@ import { parseRuntimeSkillProviderGrantSet, prepareRuntimeSkillProvider, Runtime
10
11
  import { RunDispatcher, } from "./run-dispatcher.js";
11
12
  import { ensureRuntimeSessionDirectories, ensureRuntimeSessionWorkspace, exposeRuntimeSessionWorkspace, removeRuntimeSessionWorkspace, revokeRuntimeSessionWorkspace, runtimeSessionWorkspaceDir, } from "./workspace.js";
12
13
  import { readWorkspaceFile, WorkspaceFileReadError } from "./workspace-file-read.js";
13
- import { checkpointWorkspace, WorkspaceSnapshotControlError, } from "./workspace-snapshot-control.js";
14
- import { assertWorkspaceWriterFreezeSupported, freezeRuntimeWriters, issueWorkspaceWriterFreezeProof, quiesceRuntimeWriters, thawRuntimeWriters, } from "./runtime-quiescence.js";
15
- import { WorkspaceSnapshotStagingError } from "./workspace-snapshot-staging.js";
16
- import { WorkspaceEntrySetError, } from "./workspace-entry-set.js";
17
- import { workspaceSnapshotPolicyCapability, } from "./workspace-snapshot-policy.js";
14
+ import { quiesceRuntimeWriters, } from "./runtime-quiescence.js";
18
15
  import { assertWorkspaceFilesystem, flushWorkspaceFilesystem, } from "./workspace-filesystem.js";
19
16
  import { WebSocketClient, } from "./websocket-client.js";
20
17
  const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000];
@@ -26,33 +23,10 @@ const INPUT_ATTACHMENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-
26
23
  const ASSET_ACTIVATION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
27
24
  /** 出站 seq 基址:seq = connection_epoch * SEQ_EPOCH_BASE + n,跨重连单调(合同 §1.1)。 */
28
25
  const SEQ_EPOCH_BASE = 1_000_000_000;
29
- function agentServiceHttpBase(wsUrl) {
30
- const url = new URL(wsUrl);
31
- url.protocol = url.protocol === "wss:" ? "https:" : "http:";
32
- url.pathname = "/internal/v1";
33
- url.search = "";
34
- url.hash = "";
35
- return url.toString().replace(/\/$/, "");
36
- }
37
26
  const RUNTIME_LOG_WINDOW_MS = 60_000;
38
27
  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;
39
28
  export function workspaceDurabilityCapabilities() {
40
- return [
41
- "workspace_writer_freeze_v1",
42
- "workspace_snapshot_v2",
43
- "workspace_nas_v1",
44
- "workspace_identity_v1",
45
- ];
46
- }
47
- /**
48
- * NAS 是运行时 workspace 的唯一持久事实来源,committed snapshot 只供前端查看。
49
- * 任何 restore payload 都意味着对端仍在下发已删除的 S3 回写指令,必须 fail closed,
50
- * 否则可能用落后的派生快照覆盖 NAS 中较新的内容。
51
- */
52
- export function assertWorkspaceRestoreAllowed(requestedRestore) {
53
- if (requestedRestore !== null && requestedRestore !== undefined) {
54
- throw new Error("workspace_restore_forbidden_for_nas");
55
- }
29
+ return ["workspace_nas_v1", "workspace_identity_v1"];
56
30
  }
57
31
  const DISABLED_RUNTIME_LOG_POLICY = {
58
32
  enabled: false,
@@ -386,6 +360,7 @@ export class AgentServiceSandboxClient {
386
360
  socket = null;
387
361
  sandboxGeneration = 0;
388
362
  connectionEpoch = 0;
363
+ currentLifecycleOperationId = null;
389
364
  outboundSeq = 0;
390
365
  inboundSeq = 0;
391
366
  activeSessionId = null;
@@ -589,7 +564,7 @@ export class AgentServiceSandboxClient {
589
564
  }
590
565
  catch (error) {
591
566
  const close = error instanceof SandboxClosedError ? error : null;
592
- if (close?.code === 4403 || close?.code === 4410) {
567
+ if (close?.code === 4403 || close?.code === 4409 || close?.code === 4410) {
593
568
  this.permanentFailure = true;
594
569
  break;
595
570
  }
@@ -618,7 +593,7 @@ export class AgentServiceSandboxClient {
618
593
  }
619
594
  this.removeOperationalLogSink();
620
595
  if (this.permanentFailure) {
621
- throw new Error("Agent Service sandbox stopped after a permanent protocol failure");
596
+ throw new Error("Agent Service sandbox stopped after a permanent connection failure");
622
597
  }
623
598
  }
624
599
  stop() {
@@ -644,14 +619,16 @@ export class AgentServiceSandboxClient {
644
619
  this.stop();
645
620
  }
646
621
  async drainWorkspace(fence) {
647
- if (!(await this.dispatcher.drain(10_000)) || !this.isCurrentLifecycleFence(fence)) {
622
+ if (!(await this.dispatcher.drain(10_000)) || !this.isCurrentDrainFence(fence)) {
648
623
  return;
649
624
  }
650
625
  await quiesceRuntimeWriters(null);
651
626
  await flushWorkspaceFilesystem();
652
- if (!this.isCurrentLifecycleFence(fence))
627
+ if (!this.isCurrentDrainFence(fence))
653
628
  return;
654
- await this.sendControlFrame("sandbox.drained", {});
629
+ if (fence.operationId === null)
630
+ throw new Error("sandbox drain operation is missing");
631
+ await this.sendControlFrame("sandbox.drained", { operation_id: fence.operationId });
655
632
  this.stop();
656
633
  }
657
634
  async postEvent(agentRunId, event) {
@@ -664,8 +641,7 @@ export class AgentServiceSandboxClient {
664
641
  if (!this.sandboxGeneration || !this.connectionEpoch) {
665
642
  throw new Error("Agent Service sandbox is not authenticated");
666
643
  }
667
- // Terminal truth is never delayed by object storage. Durable workspace checkpointing
668
- // is a separate lifecycle command issued only for pause/cleanup/rotation.
644
+ // Terminal truth remains an ordering barrier after earlier transient blocks.
669
645
  if (event.type === "run.block") {
670
646
  await this.waitForEventCapacity();
671
647
  }
@@ -903,14 +879,12 @@ export class AgentServiceSandboxClient {
903
879
  this.runtimeLogPolicy = runtimeLogPolicy(frame.payload.runtime_log_policy);
904
880
  this.persist();
905
881
  assertWorkspaceFilesystem(process.env.BOTLEARN_AGENT_SERVICE_WORKSPACE_ROOT ?? "");
906
- assertWorkspaceWriterFreezeSupported();
907
882
  await this.sendControlFrame("sandbox.ready", {
908
883
  protocol_versions: [AGENT_SERVICE_WS_SCHEMA],
909
884
  capabilities: [
910
885
  WORKSPACE_FILE_READ_BINARY_CAPABILITY,
911
886
  ...workspaceDurabilityCapabilities(),
912
887
  ],
913
- workspace_snapshot_policy: workspaceSnapshotPolicyCapability(),
914
888
  daemon_version: this.options.daemonVersion,
915
889
  runtime_versions: {
916
890
  course_daemon: this.options.daemonVersion,
@@ -1071,8 +1045,13 @@ export class AgentServiceSandboxClient {
1071
1045
  return;
1072
1046
  case "auth.rotate": {
1073
1047
  const token = frame.payload.reconnect_token;
1048
+ const operationId = frame.payload.operation_id;
1074
1049
  if (typeof token !== "string" || !token)
1075
1050
  throw new Error("invalid reconnect token");
1051
+ if (typeof operationId !== "string" || !operationId) {
1052
+ throw new Error("auth.rotate requires operation_id");
1053
+ }
1054
+ this.currentLifecycleOperationId = operationId;
1076
1055
  this.state.reconnectToken = token;
1077
1056
  this.persist();
1078
1057
  await this.sendCommandAck(frame, "ok");
@@ -1087,17 +1066,14 @@ export class AgentServiceSandboxClient {
1087
1066
  });
1088
1067
  });
1089
1068
  return;
1090
- case "workspace.checkpoint":
1091
- this.scheduleLifecycle("workspace.checkpoint", () => this.handleWorkspaceCheckpoint(frame));
1092
- return;
1093
- case "workspace.thaw":
1094
- await thawRuntimeWriters();
1095
- await this.sendCommandAck(frame, "ok");
1096
- return;
1097
1069
  case "sandbox.shutdown":
1098
1070
  await this.stopGracefully();
1099
1071
  return;
1100
1072
  case "sandbox.drain":
1073
+ if (typeof frame.payload.operation_id !== "string" || !frame.payload.operation_id) {
1074
+ throw new Error("sandbox.drain requires operation_id");
1075
+ }
1076
+ this.currentLifecycleOperationId = frame.payload.operation_id;
1101
1077
  await this.sendCommandAck(frame, "ok");
1102
1078
  this.scheduleLifecycle("sandbox.drain", (fence) => this.drainWorkspace(fence));
1103
1079
  return;
@@ -1107,9 +1083,14 @@ export class AgentServiceSandboxClient {
1107
1083
  throw new Error(`unexpected server frame: ${frame.type}`);
1108
1084
  }
1109
1085
  }
1110
- /** sandbox.sync 只做对账:重放 spool、关闭待关 session、应用 drain/shutdown。 */
1086
+ /** sandbox.sync 只做对账:重放 spool、关闭待关 session、应用 shutdown。 */
1111
1087
  async applySync(frame) {
1112
1088
  await this.replaySpool();
1089
+ const operationId = frame.payload.operation_id;
1090
+ if (operationId !== null && operationId !== undefined && typeof operationId !== "string") {
1091
+ throw new Error("sandbox.sync operation_id is invalid");
1092
+ }
1093
+ this.currentLifecycleOperationId = typeof operationId === "string" ? operationId : null;
1113
1094
  const closeSessions = Array.isArray(frame.payload.close_sessions)
1114
1095
  ? frame.payload.close_sessions.filter((item) => typeof item === "string" && item.length > 0)
1115
1096
  : [];
@@ -1117,32 +1098,21 @@ export class AgentServiceSandboxClient {
1117
1098
  this.scheduleLifecycle("sandbox.sync.close", (fence) => this.closeSession(sessionId, "sync_close", frame, fence));
1118
1099
  }
1119
1100
  const state = frame.payload.state;
1120
- if (frame.payload.thaw_runtime_writers === true) {
1121
- await thawRuntimeWriters();
1122
- }
1123
1101
  if (state === "shutdown") {
1124
1102
  await this.stopGracefully();
1125
1103
  return;
1126
1104
  }
1127
- if (state === "drain") {
1128
- this.scheduleLifecycle("sandbox.sync.drain", (fence) => this.drainWorkspace(fence));
1129
- }
1130
1105
  // idle/run/cancel:实际工作全部由显式命令帧下发(合同 §1.3)。
1131
1106
  }
1132
1107
  async handleSessionOpen(frame) {
1133
1108
  const sessionId = frame.runtime_session_id;
1134
1109
  const session = this.state.sessions[sessionId] ?? emptySessionState();
1135
1110
  const courseRunId = frame.payload.course_run_id;
1136
- // Mixed-version reconciliation may replay a pre-Workspace-identity session.open.
1137
- // Its physical directory was keyed by RuntimeSession id, which is the exact backfill
1138
- // identity used by the database migration.
1139
- const requestedWorkspaceId = typeof frame.payload.workspace_id === "string"
1140
- ? frame.payload.workspace_id
1141
- : session.workspaceId ?? sessionId;
1111
+ const requestedWorkspaceId = frame.payload.workspace_id;
1142
1112
  const requestedWorkspaceRef = frame.payload.workspace_ref;
1143
- assertWorkspaceRestoreAllowed(frame.payload.workspace_restore);
1144
1113
  if (typeof courseRunId !== "string" ||
1145
1114
  courseRunId.length < 1 ||
1115
+ typeof requestedWorkspaceId !== "string" ||
1146
1116
  requestedWorkspaceId.length < 1 ||
1147
1117
  (requestedWorkspaceRef !== null &&
1148
1118
  requestedWorkspaceRef !== undefined &&
@@ -1172,102 +1142,29 @@ export class AgentServiceSandboxClient {
1172
1142
  if (isNewSession || session.activationId === null) {
1173
1143
  ensureRuntimeSessionDirectories(sessionId, this.sandboxGeneration, requestedWorkspaceId);
1174
1144
  }
1145
+ const workspaceDirectory = runtimeSessionWorkspaceDir(requestedWorkspaceId, this.sandboxGeneration);
1146
+ const probePath = path.join(workspaceDirectory, `.botlearn-health-${randomUUID()}`);
1147
+ const probeContent = `sandbox=${this.options.sandboxId}\ngeneration=${this.sandboxGeneration}\n`;
1148
+ try {
1149
+ writeFileSync(probePath, probeContent, { encoding: "utf8", mode: 0o600 });
1150
+ if (readFileSync(probePath, "utf8") !== probeContent) {
1151
+ throw new Error("workspace probe content mismatch");
1152
+ }
1153
+ }
1154
+ finally {
1155
+ rmSync(probePath, { force: true });
1156
+ }
1175
1157
  this.state.sessions[sessionId] = session;
1176
1158
  this.persist();
1177
- // NAS 是唯一的 workspace 权威来源,所以 session.opened 不携带 snapshot 物化标记:
1178
- // 挂载证明只说明当前 generation 已挂上 NAS,不要求运行目录等于某个 committed revision。
1159
+ // NAS 是唯一的 workspace 权威来源。挂载证明只说明当前 generation 已挂上 NAS。
1179
1160
  await this.sendSessionFrame("session.opened", sessionId, {
1180
1161
  workspace_id: session.workspaceId,
1181
1162
  workspace_ref: session.workspaceRef,
1182
1163
  native_session_id: session.nativeSessionId,
1183
- workspace_authority: "nas",
1164
+ workspace_readable: true,
1165
+ workspace_writable: true,
1184
1166
  });
1185
1167
  }
1186
- async handleWorkspaceCheckpoint(frame) {
1187
- const sessionId = frame.runtime_session_id;
1188
- const session = this.state.sessions[sessionId];
1189
- const checkpointId = frame.payload.checkpoint_id;
1190
- const controlToken = frame.payload.control_token;
1191
- const baseRevision = Number(frame.payload.base_revision);
1192
- const sourceKind = frame.payload.source_kind;
1193
- if (!session ||
1194
- this.currentTurnSessionId === sessionId ||
1195
- typeof checkpointId !== "string" ||
1196
- typeof controlToken !== "string" ||
1197
- controlToken.length < 32 ||
1198
- frame.payload.policy_id !== "WorkspaceSnapshotPolicyV1" ||
1199
- ![
1200
- "sandbox_pause",
1201
- "sandbox_cleanup",
1202
- "generation_rotation",
1203
- "maintenance_repair",
1204
- ].includes(String(sourceKind)) ||
1205
- !Number.isSafeInteger(baseRevision) ||
1206
- baseRevision < 0 ||
1207
- frame.payload.agent_run_id != null ||
1208
- frame.payload.worker_attempt != null ||
1209
- frame.payload.activation_id != null) {
1210
- await this.sendCommandAck(frame, "rejected", "invalid_workspace_checkpoint");
1211
- return;
1212
- }
1213
- const lifecycleCheckpoint = [
1214
- "sandbox_pause",
1215
- "sandbox_cleanup",
1216
- "generation_rotation",
1217
- ].includes(String(sourceKind));
1218
- let checkpointCommitted = false;
1219
- try {
1220
- await freezeRuntimeWriters();
1221
- const freezeProof = issueWorkspaceWriterFreezeProof({
1222
- sandboxId: this.options.sandboxId,
1223
- sandboxGeneration: this.sandboxGeneration,
1224
- runtimeSessionId: sessionId,
1225
- checkpointId,
1226
- });
1227
- await checkpointWorkspace({
1228
- wsUrl: this.options.wsUrl,
1229
- reconnectToken: controlToken,
1230
- workspaceDirectory: runtimeSessionWorkspaceDir(session.workspaceId ?? sessionId, this.sandboxGeneration),
1231
- scope: {
1232
- checkpointId,
1233
- baseRevision,
1234
- sandboxId: this.options.sandboxId,
1235
- sandboxGeneration: this.sandboxGeneration,
1236
- connectionEpoch: this.connectionEpoch,
1237
- runtimeSessionId: sessionId,
1238
- },
1239
- freezeProof,
1240
- });
1241
- checkpointCommitted = true;
1242
- // committed revision 只是派生投影,不改变运行目录,所以这里不上报物化标记。
1243
- await this.sendSessionFrame("session.opened", sessionId, {
1244
- workspace_id: session.workspaceId,
1245
- workspace_ref: session.workspaceRef,
1246
- native_session_id: session.nativeSessionId,
1247
- workspace_authority: "nas",
1248
- });
1249
- await this.sendCommandAck(frame, "ok");
1250
- if (!lifecycleCheckpoint)
1251
- await thawRuntimeWriters();
1252
- }
1253
- catch (error) {
1254
- if (!lifecycleCheckpoint || !checkpointCommitted) {
1255
- await thawRuntimeWriters().catch(() => undefined);
1256
- }
1257
- this.log.error("workspace baseline checkpoint failed", {
1258
- sandboxId: this.options.sandboxId,
1259
- runtimeSessionId: sessionId,
1260
- error: error instanceof Error ? redactSecretString(error.message) : "unexpected",
1261
- });
1262
- const deterministic = (error instanceof WorkspaceSnapshotStagingError && !error.retryable) ||
1263
- error instanceof WorkspaceEntrySetError ||
1264
- (error instanceof WorkspaceSnapshotControlError && !error.retryable);
1265
- const errorCode = deterministic && "code" in error
1266
- ? String(error.code)
1267
- : "workspace_checkpoint_retryable";
1268
- await this.sendCommandAck(frame, "rejected", errorCode, !deterministic);
1269
- }
1270
- }
1271
1168
  async handleSessionActivate(frame, fence) {
1272
1169
  const sessionId = frame.runtime_session_id;
1273
1170
  const activationId = frame.activation_id;
@@ -1750,6 +1647,7 @@ export class AgentServiceSandboxClient {
1750
1647
  return {
1751
1648
  sandboxGeneration: this.sandboxGeneration,
1752
1649
  connectionEpoch: this.connectionEpoch,
1650
+ operationId: this.currentLifecycleOperationId,
1753
1651
  socket: this.socket,
1754
1652
  };
1755
1653
  }
@@ -1759,6 +1657,10 @@ export class AgentServiceSandboxClient {
1759
1657
  this.socket === fence.socket &&
1760
1658
  fence.socket?.readyState === WebSocketClient.OPEN;
1761
1659
  }
1660
+ isCurrentDrainFence(fence) {
1661
+ return this.isCurrentLifecycleFence(fence) &&
1662
+ this.currentLifecycleOperationId === fence.operationId;
1663
+ }
1762
1664
  runIdsForSession(sessionId) {
1763
1665
  const runIds = new Set([...this.turnScopes]
1764
1666
  .filter(([, scope]) => scope.sessionId === sessionId)
@@ -3,7 +3,7 @@ export declare const AGENT_SERVICE_WS_SUBPROTOCOL: "botlearn-agent-sandbox.v4";
3
3
  export declare const WORKSPACE_FILE_READ_BINARY_CAPABILITY: "workspace_file_read_binary_v1";
4
4
  export declare const WORKSPACE_FILE_CHUNK_BYTES: number;
5
5
  export declare const WORKSPACE_FILE_CHUNK_HEADER_BYTES = 29;
6
- export type SandboxFrameType = "sandbox.hello" | "sandbox.sync" | "session.open" | "session.activate" | "turn.start" | "turn.cancel" | "session.close" | "sandbox.drain" | "sandbox.shutdown" | "event.ack" | "auth.rotate" | "workspace.file.read" | "workspace.checkpoint" | "workspace.thaw" | "ping" | "sandbox.ready" | "sandbox.heartbeat" | "command.ack" | "session.opened" | "session.open_failed" | "session.closed" | "activation.cleaned" | "turn.event" | "turn.file.report" | "workspace.file.result" | "sandbox.drained" | "sandbox.log" | "pong" | "protocol.error";
6
+ export type SandboxFrameType = "sandbox.hello" | "sandbox.sync" | "session.open" | "session.activate" | "turn.start" | "turn.cancel" | "session.close" | "sandbox.drain" | "sandbox.shutdown" | "event.ack" | "auth.rotate" | "workspace.file.read" | "ping" | "sandbox.ready" | "sandbox.heartbeat" | "command.ack" | "session.opened" | "session.open_failed" | "session.closed" | "activation.cleaned" | "turn.event" | "turn.file.report" | "workspace.file.result" | "sandbox.drained" | "sandbox.log" | "pong" | "protocol.error";
7
7
  export declare class UnsupportedSandboxProtocolError extends Error {
8
8
  readonly schemaVersion: unknown;
9
9
  constructor(schemaVersion: unknown);
@@ -18,8 +18,6 @@ const FRAME_TYPES = new Set([
18
18
  "event.ack",
19
19
  "auth.rotate",
20
20
  "workspace.file.read",
21
- "workspace.checkpoint",
22
- "workspace.thaw",
23
21
  "ping",
24
22
  "sandbox.ready",
25
23
  "sandbox.heartbeat",
@@ -45,7 +43,6 @@ const SESSION_TYPES = new Set([
45
43
  "session.open_failed",
46
44
  "session.closed",
47
45
  "workspace.file.read",
48
- "workspace.checkpoint",
49
46
  "workspace.file.result",
50
47
  ]);
51
48
  /** TURN 帧:必须带 runtime_session_id + agent_run_id + worker_attempt + activation_id 四元组。 */
package/dist/cli.js CHANGED
@@ -4,7 +4,6 @@ import { createRequire } from "node:module";
4
4
  import { hostname } from "node:os";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { authFilePath, clearAuth, machineFingerprint, readAuth, writeAuth } from "./auth-store.js";
7
- import { AgentServiceRunClient } from "./agent-service-client.js";
8
7
  import { AgentServiceSandboxClient } from "./agent-service-sandbox.js";
9
8
  import { CourseClient, isAuthFailure, loginCourseDaemon } from "./course-client.js";
10
9
  import { runCourseDoctor } from "./doctor.js";
@@ -23,7 +22,6 @@ Usage:
23
22
  botlearn-course-daemon course start [--once] [--poll-interval-ms <ms>]
24
23
  botlearn-course-daemon course logout
25
24
  botlearn-course-daemon course doctor
26
- botlearn-course-daemon agent-service run
27
25
  botlearn-course-daemon agent-service session
28
26
  botlearn-course-daemon --help | --version
29
27
 
@@ -43,9 +41,6 @@ Environment:
43
41
 
44
42
  Agent Service sandbox environment:
45
43
  BOTLEARN_COURSE_API_URL
46
- BOTLEARN_AGENT_SERVICE_RUN_ID
47
- BOTLEARN_AGENT_SERVICE_RUN_TOKEN
48
- BOTLEARN_AGENT_SERVICE_WORKER_ID
49
44
  BOTLEARN_AGENT_SERVICE_WS_URL
50
45
  BOTLEARN_AGENT_SERVICE_SANDBOX_ID
51
46
  BOTLEARN_AGENT_SERVICE_SANDBOX_TOKEN`;
@@ -252,48 +247,6 @@ async function cmdDoctor() {
252
247
  // doctor 是诊断不是校验:即使 0 个 runtime 可用也 exit 0。
253
248
  return 0;
254
249
  }
255
- async function cmdAgentServiceRun() {
256
- const courseApiUrl = process.env.BOTLEARN_COURSE_API_URL;
257
- const agentRunId = process.env.BOTLEARN_AGENT_SERVICE_RUN_ID;
258
- const runToken = process.env.BOTLEARN_AGENT_SERVICE_RUN_TOKEN;
259
- const workerId = process.env.BOTLEARN_AGENT_SERVICE_WORKER_ID;
260
- if (!courseApiUrl || !agentRunId || !runToken || !workerId) {
261
- console.error("Agent Service sandbox environment is incomplete");
262
- return 1;
263
- }
264
- augmentProcessPath();
265
- const client = new AgentServiceRunClient(courseApiUrl, agentRunId, runToken, workerId);
266
- const payload = await client.getRun();
267
- if (payload.agent_run_id !== agentRunId) {
268
- throw new Error("Agent Service run payload does not match requested run");
269
- }
270
- clearAgentServiceControlEnv();
271
- const runtimes = new Map();
272
- for (const mod of RUNTIME_MODULES) {
273
- if (mod.hidden && !fakeRuntimeEnabled())
274
- continue;
275
- runtimes.set(mod.id, mod.create());
276
- }
277
- const dispatcher = new RunDispatcher(client, runtimes);
278
- const heartbeat = setInterval(() => {
279
- void client.heartbeat().catch((err) => {
280
- log.warn("Agent Service heartbeat failed", {
281
- agentRunId,
282
- error: err instanceof Error ? redactSecretString(err.message) : String(err),
283
- });
284
- });
285
- }, 20_000);
286
- if (typeof heartbeat.unref === "function")
287
- heartbeat.unref();
288
- try {
289
- await client.heartbeat();
290
- await dispatcher.dispatch(payload);
291
- }
292
- finally {
293
- clearInterval(heartbeat);
294
- }
295
- return 0;
296
- }
297
250
  async function readSandboxBootstrapFromStdin() {
298
251
  const chunks = [];
299
252
  let size = 0;
@@ -422,9 +375,6 @@ export async function runCli(argv) {
422
375
  return 1;
423
376
  }
424
377
  }
425
- if (command === "agent-service" && sub === "run") {
426
- return cmdAgentServiceRun();
427
- }
428
378
  if (command === "agent-service" && sub === "session") {
429
379
  return cmdAgentServiceSession(args);
430
380
  }
package/dist/index.d.ts CHANGED
@@ -5,16 +5,11 @@
5
5
  export * from "./types.js";
6
6
  export * from "./auth-store.js";
7
7
  export * from "./course-client.js";
8
- export * from "./agent-service-client.js";
9
8
  export * from "./agent-service-sandbox.js";
10
9
  export * from "./agent-service-ws-protocol.js";
11
10
  export * from "./run-dispatcher.js";
12
11
  export * from "./run-queue.js";
13
12
  export * from "./workspace.js";
14
- export * from "./workspace-entry-set.js";
15
- export * from "./workspace-snapshot-staging.js";
16
- export * from "./workspace-snapshot-policy.js";
17
- export * from "./workspace-snapshot-control.js";
18
13
  export * from "./transcript.js";
19
14
  export * from "./file-candidates.js";
20
15
  export * from "./doctor.js";
package/dist/index.js CHANGED
@@ -5,16 +5,11 @@
5
5
  export * from "./types.js";
6
6
  export * from "./auth-store.js";
7
7
  export * from "./course-client.js";
8
- export * from "./agent-service-client.js";
9
8
  export * from "./agent-service-sandbox.js";
10
9
  export * from "./agent-service-ws-protocol.js";
11
10
  export * from "./run-dispatcher.js";
12
11
  export * from "./run-queue.js";
13
12
  export * from "./workspace.js";
14
- export * from "./workspace-entry-set.js";
15
- export * from "./workspace-snapshot-staging.js";
16
- export * from "./workspace-snapshot-policy.js";
17
- export * from "./workspace-snapshot-control.js";
18
13
  export * from "./transcript.js";
19
14
  export * from "./file-candidates.js";
20
15
  export * from "./doctor.js";
@@ -1,19 +1 @@
1
- export interface WorkspaceWriterFreezeProof {
2
- readonly proofVersion: "workspace-writer-freeze-proof/1";
3
- readonly sandboxId: string;
4
- readonly sandboxGeneration: number;
5
- readonly runtimeSessionId: string;
6
- readonly checkpointId: string;
7
- readonly allWritersFrozen: true;
8
- }
9
- export declare function freezeRuntimeWriters(): Promise<void>;
10
- export declare function thawRuntimeWriters(): Promise<void>;
11
- export declare function assertWorkspaceWriterFreezeSupported(): void;
12
1
  export declare function quiesceRuntimeWriters(activationId: string | null): Promise<void>;
13
- export declare function issueWorkspaceWriterFreezeProof(scope: {
14
- sandboxId: string;
15
- sandboxGeneration: number;
16
- runtimeSessionId: string;
17
- checkpointId: string;
18
- }): WorkspaceWriterFreezeProof;
19
- export declare function isWorkspaceWriterFreezeProof(value: object): value is WorkspaceWriterFreezeProof;
@@ -1,96 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
- import { accessSync, constants as fsConstants } from "node:fs";
3
- import { readFile, readdir, writeFile } from "node:fs/promises";
4
- import path from "node:path";
5
2
  import { promisify } from "node:util";
6
3
  const execFileAsync = promisify(execFile);
7
4
  const RUNTIME_LAUNCHER = "/opt/botlearn/bin/botlearn-runtime-launcher";
8
- const RUNTIME_CGROUP_ROOT = "/sys/fs/cgroup/botlearn-runtime";
9
- const RUNTIME_CGROUP_UNAVAILABLE = "/run/botlearn-runtime-cgroup-unavailable";
10
- const proofs = new WeakSet();
11
- const sleep = (milliseconds) => new Promise((resolve) => {
12
- setTimeout(resolve, milliseconds);
13
- });
14
- async function setDirectCgroupsFrozen(frozen) {
15
- try {
16
- accessSync(RUNTIME_CGROUP_UNAVAILABLE, fsConstants.F_OK);
17
- await execFileAsync(RUNTIME_LAUNCHER, [frozen ? "--freeze-all" : "--thaw-all"], {
18
- timeout: 10_000,
19
- });
20
- return;
21
- }
22
- catch (error) {
23
- if (error.code !== "ENOENT")
24
- throw error;
25
- }
26
- let entries;
27
- try {
28
- entries = await readdir(RUNTIME_CGROUP_ROOT, { withFileTypes: true });
29
- }
30
- catch (error) {
31
- if (error.code === "ENOENT")
32
- return;
33
- throw error;
34
- }
35
- for (const entry of entries) {
36
- if (!entry.isDirectory())
37
- continue;
38
- const directory = path.join(RUNTIME_CGROUP_ROOT, entry.name);
39
- await writeFile(path.join(directory, "cgroup.freeze"), frozen ? "1" : "0");
40
- for (let attempt = 0; attempt < 100; attempt += 1) {
41
- const events = await readFile(path.join(directory, "cgroup.events"), "utf8");
42
- if (events.includes(`frozen ${frozen ? 1 : 0}`))
43
- break;
44
- if (attempt === 99)
45
- throw new Error("workspace_runtime_freeze_timeout");
46
- await sleep(50);
47
- }
48
- }
49
- }
50
- async function setRuntimeWritersFrozen(frozen) {
51
- const mode = process.env.BOTLEARN_RUNTIME_LAUNCH_MODE;
52
- if (mode === "direct-uid") {
53
- await setDirectCgroupsFrozen(frozen);
54
- return;
55
- }
56
- if (mode === "sudo") {
57
- await execFileAsync("/usr/bin/sudo", ["-n", "--", RUNTIME_LAUNCHER, frozen ? "--freeze-all" : "--thaw-all"], { timeout: 10_000 });
58
- return;
59
- }
60
- if (process.env.BOTLEARN_DAEMON_ENABLE_FAKE_RUNTIME === "1" || process.env.NODE_ENV === "test") {
61
- return;
62
- }
63
- throw new Error("workspace_runtime_cgroup_unavailable");
64
- }
65
- export async function freezeRuntimeWriters() {
66
- await setRuntimeWritersFrozen(true);
67
- }
68
- export async function thawRuntimeWriters() {
69
- await setRuntimeWritersFrozen(false);
70
- }
71
- export function assertWorkspaceWriterFreezeSupported() {
72
- const mode = process.env.BOTLEARN_RUNTIME_LAUNCH_MODE;
73
- if (mode === "direct-uid") {
74
- try {
75
- accessSync(RUNTIME_CGROUP_UNAVAILABLE, fsConstants.F_OK);
76
- accessSync(RUNTIME_LAUNCHER, fsConstants.X_OK);
77
- }
78
- catch (error) {
79
- if (error.code !== "ENOENT")
80
- throw error;
81
- accessSync(RUNTIME_CGROUP_ROOT, fsConstants.R_OK | fsConstants.W_OK);
82
- }
83
- return;
84
- }
85
- if (mode === "sudo") {
86
- accessSync(RUNTIME_LAUNCHER, fsConstants.X_OK);
87
- return;
88
- }
89
- if (process.env.BOTLEARN_DAEMON_ENABLE_FAKE_RUNTIME === "1" || process.env.NODE_ENV === "test") {
90
- return;
91
- }
92
- throw new Error("workspace_runtime_cgroup_unavailable");
93
- }
94
5
  function managedQuiescenceCommand(activationId) {
95
6
  const mode = process.env.BOTLEARN_RUNTIME_LAUNCH_MODE;
96
7
  if (mode === "direct-uid") {
@@ -116,15 +27,3 @@ export async function quiesceRuntimeWriters(activationId) {
116
27
  }
117
28
  await execFileAsync(command[0], command[1], { timeout: 10_000 });
118
29
  }
119
- export function issueWorkspaceWriterFreezeProof(scope) {
120
- const proof = Object.freeze({
121
- proofVersion: "workspace-writer-freeze-proof/1",
122
- ...scope,
123
- allWritersFrozen: true,
124
- });
125
- proofs.add(proof);
126
- return proof;
127
- }
128
- export function isWorkspaceWriterFreezeProof(value) {
129
- return proofs.has(value);
130
- }