@botlearn-course/daemon 0.0.21-beta.1 → 0.0.21-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,6 +92,12 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
92
92
  getRunRuntimeProfile(agentRunId: string): Promise<CourseRuntimeProfile>;
93
93
  private connectOnce;
94
94
  private handleHello;
95
+ /**
96
+ * The server is the durable authority after a reconnect. Reconcile only the
97
+ * fields that are explicitly present so an older server cannot erase local
98
+ * recovery state during a rolling upgrade.
99
+ */
100
+ private reconcileHelloState;
95
101
  private forwardOperationalLog;
96
102
  private queueRuntimeLog;
97
103
  private assertServerFrame;
@@ -122,6 +128,10 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
122
128
  private matchesTurnScope;
123
129
  private assertTurnScope;
124
130
  private ackEventOrFile;
131
+ private discardSpooledTurnEvents;
132
+ private resolvePendingEventAck;
133
+ private resolvePendingEventAcksForSession;
134
+ private rejectPendingFilesForSession;
125
135
  private replaySpool;
126
136
  private sendHeartbeat;
127
137
  private sendCommandAck;
@@ -887,6 +887,7 @@ export class AgentServiceSandboxClient {
887
887
  this.connectionEpoch = frame.connection_epoch;
888
888
  this.inboundSeq = frame.seq;
889
889
  this.outboundSeq = frame.connection_epoch * SEQ_EPOCH_BASE;
890
+ await this.reconcileHelloState(frame.payload);
890
891
  await this.recoverPendingActivationCleanups();
891
892
  const heartbeatSeconds = Number(frame.payload.heartbeat_seconds ?? 15);
892
893
  this.heartbeatMs = Math.max(1_000, Math.min(60_000, heartbeatSeconds * 1000));
@@ -922,6 +923,51 @@ export class AgentServiceSandboxClient {
922
923
  });
923
924
  this.runtimeLogHandshakeReady = true;
924
925
  }
926
+ /**
927
+ * The server is the durable authority after a reconnect. Reconcile only the
928
+ * fields that are explicitly present so an older server cannot erase local
929
+ * recovery state during a rolling upgrade.
930
+ */
931
+ async reconcileHelloState(payload) {
932
+ if (Object.hasOwn(payload, "committed_event_cursor")) {
933
+ const cursor = payload.committed_event_cursor;
934
+ if (typeof cursor !== "number" || !Number.isSafeInteger(cursor) || cursor < 0) {
935
+ throw new Error("invalid sandbox.hello committed_event_cursor");
936
+ }
937
+ this.discardSpooledTurnEvents((frame) => frame.seq <= cursor);
938
+ }
939
+ if (Object.hasOwn(payload, "active_agent_run_id")) {
940
+ const activeRunId = payload.active_agent_run_id;
941
+ if (activeRunId !== null && (typeof activeRunId !== "string" || !activeRunId)) {
942
+ throw new Error("invalid sandbox.hello active_agent_run_id");
943
+ }
944
+ this.discardSpooledTurnEvents((frame) => activeRunId === null || frame.agent_run_id !== activeRunId);
945
+ }
946
+ if (!Object.hasOwn(payload, "open_sessions"))
947
+ return;
948
+ const openSessions = payload.open_sessions;
949
+ if (!Array.isArray(openSessions)) {
950
+ throw new Error("invalid sandbox.hello open_sessions");
951
+ }
952
+ const authoritativeSessionIds = new Set();
953
+ for (const item of openSessions) {
954
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
955
+ throw new Error("invalid sandbox.hello open_sessions");
956
+ }
957
+ const runtimeSessionId = item.runtime_session_id;
958
+ if (typeof runtimeSessionId !== "string" || !runtimeSessionId) {
959
+ throw new Error("invalid sandbox.hello open_sessions");
960
+ }
961
+ authoritativeSessionIds.add(runtimeSessionId);
962
+ }
963
+ for (const sessionId of Object.keys(this.state.sessions)) {
964
+ if (!authoritativeSessionIds.has(sessionId)) {
965
+ // `sandbox.ready` has not been sent yet. The server has already declared this
966
+ // session closed, so local cleanup must not emit a stale `session.closed` frame.
967
+ await this.closeSession(sessionId, "hello_reconciled", undefined, undefined, false);
968
+ }
969
+ }
970
+ }
925
971
  forwardOperationalLog(entry) {
926
972
  const policy = this.runtimeLogPolicy;
927
973
  if (!policy.enabled || !this.runtimeLogHandshakeReady)
@@ -1550,10 +1596,12 @@ export class AgentServiceSandboxClient {
1550
1596
  * 幂等关闭一个 runtime session:终止其 runtime 子进程并清空 session-local state。
1551
1597
  * Durable Workspace 由独立身份拥有,关闭执行上下文不会删除学员文件。
1552
1598
  */
1553
- async closeSession(sessionId, reason, sourceFrame, fence) {
1599
+ async closeSession(sessionId, reason, sourceFrame, fence, reportClosed = true) {
1554
1600
  const session = this.state.sessions[sessionId];
1555
1601
  if (session) {
1556
1602
  const runIds = this.runIdsForSession(sessionId);
1603
+ this.resolvePendingEventAcksForSession(sessionId);
1604
+ this.rejectPendingFilesForSession(sessionId, new Error("Agent Service runtime session was closed"));
1557
1605
  this.activationContexts.delete(sessionId);
1558
1606
  this.sessionProfiles.delete(sessionId);
1559
1607
  for (const runId of runIds)
@@ -1574,13 +1622,19 @@ export class AgentServiceSandboxClient {
1574
1622
  this.activeSessionId = null;
1575
1623
  if (this.currentTurnSessionId === sessionId)
1576
1624
  this.currentTurnSessionId = null;
1577
- for (const runId of runIds)
1625
+ this.resolvePendingEventAcksForSession(sessionId);
1626
+ this.rejectPendingFilesForSession(sessionId, new Error("Agent Service runtime session was closed"));
1627
+ for (const runId of runIds) {
1578
1628
  this.turnScopes.delete(runId);
1629
+ this.runProfiles.delete(runId);
1630
+ }
1579
1631
  removeRuntimeSessionWorkspace(sessionId, this.sandboxGeneration, true, workspaceId);
1580
1632
  delete this.state.sessions[sessionId];
1581
1633
  this.persist();
1582
1634
  }
1583
- await this.sendSessionFrame("session.closed", sessionId, { reason }, sourceFrame);
1635
+ if (reportClosed) {
1636
+ await this.sendSessionFrame("session.closed", sessionId, { reason }, sourceFrame);
1637
+ }
1584
1638
  }
1585
1639
  async reconcileInterruptedCommand(sessionId, commandId, accepted) {
1586
1640
  try {
@@ -1706,9 +1760,24 @@ export class AgentServiceSandboxClient {
1706
1760
  fence.socket?.readyState === WebSocketClient.OPEN;
1707
1761
  }
1708
1762
  runIdsForSession(sessionId) {
1709
- return [...this.turnScopes]
1763
+ const runIds = new Set([...this.turnScopes]
1710
1764
  .filter(([, scope]) => scope.sessionId === sessionId)
1711
- .map(([runId]) => runId);
1765
+ .map(([runId]) => runId));
1766
+ const session = this.state.sessions[sessionId];
1767
+ if (!session)
1768
+ return [...runIds];
1769
+ for (const frame of session.spool) {
1770
+ if (typeof frame.agent_run_id === "string")
1771
+ runIds.add(frame.agent_run_id);
1772
+ }
1773
+ for (const command of Object.values(session.acceptedCommands)) {
1774
+ if (typeof command.agentRunId === "string")
1775
+ runIds.add(command.agentRunId);
1776
+ }
1777
+ if (session.pendingActivationCleanup !== null) {
1778
+ runIds.add(session.pendingActivationCleanup.agentRunId);
1779
+ }
1780
+ return [...runIds];
1712
1781
  }
1713
1782
  async deactivateSession(sessionId, terminateWriters = false) {
1714
1783
  const session = this.state.sessions[sessionId];
@@ -1811,6 +1880,45 @@ export class AgentServiceSandboxClient {
1811
1880
  : { disposition: "accepted" });
1812
1881
  }
1813
1882
  }
1883
+ discardSpooledTurnEvents(shouldDiscard) {
1884
+ let changed = false;
1885
+ for (const session of Object.values(this.state.sessions)) {
1886
+ const retained = [];
1887
+ for (const frame of session.spool) {
1888
+ if (frame.type === "turn.event" && shouldDiscard(frame)) {
1889
+ this.resolvePendingEventAck(frame.frame_id);
1890
+ changed = true;
1891
+ }
1892
+ else {
1893
+ retained.push(frame);
1894
+ }
1895
+ }
1896
+ session.spool = retained;
1897
+ }
1898
+ if (changed)
1899
+ this.persist();
1900
+ }
1901
+ resolvePendingEventAck(frameId) {
1902
+ const pending = this.pendingAcks.get(frameId);
1903
+ if (!pending)
1904
+ return;
1905
+ this.pendingAcks.delete(frameId);
1906
+ pending.resolve({ disposition: "accepted" });
1907
+ }
1908
+ resolvePendingEventAcksForSession(sessionId) {
1909
+ for (const [frameId, pending] of this.pendingAcks) {
1910
+ if (pending.scope.sessionId === sessionId)
1911
+ this.resolvePendingEventAck(frameId);
1912
+ }
1913
+ }
1914
+ rejectPendingFilesForSession(sessionId, error) {
1915
+ for (const [frameId, pending] of this.pendingFileReports) {
1916
+ if (pending.scope.sessionId !== sessionId)
1917
+ continue;
1918
+ this.pendingFileReports.delete(frameId);
1919
+ pending.reject(error);
1920
+ }
1921
+ }
1814
1922
  async replaySpool() {
1815
1923
  for (const session of Object.values(this.state.sessions)) {
1816
1924
  for (const original of session.spool) {
@@ -1821,9 +1929,7 @@ export class AgentServiceSandboxClient {
1821
1929
  seq: this.nextOutboundSeq(),
1822
1930
  sent_at: new Date().toISOString(),
1823
1931
  };
1824
- Object.assign(original, replay);
1825
- this.persist();
1826
- await this.sendFrame(original);
1932
+ await this.sendFrame(replay);
1827
1933
  }
1828
1934
  }
1829
1935
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botlearn-course/daemon",
3
- "version": "0.0.21-beta.1",
3
+ "version": "0.0.21-beta.2",
4
4
  "description": "Lightweight BotLearn Course daemon: run course tasks on your own machine with your own agent runtime (BYOA).",
5
5
  "type": "module",
6
6
  "bin": {