@blade-hq/agent-client 2612.0.0-beta.97 → 2612.0.0-beta.98

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
@@ -948,7 +948,7 @@ await account.sessions.deleteAnonymousSession(retained[0].id)
948
948
 
949
949
  工具包含 `name`、`description`、`inputSchema` 与异步 `handler(arguments, { sessionId, signal })`;结果为 `content`、可选 `structuredContent` 与 `isError`。sessionId 来自 BA 已授权调用,应用还应校验它对应自身业务会话。AbortSignal 表示取消请求,不保证业务回滚。连接恢复不重放调用;业务动作应使用应用自己的幂等 ID。`provider.dispose()` 关闭连接。SDK 退出登录/更换后端也会关闭来源。
950
950
 
951
- 连接使用 `/api/app-tools/connect`,HTTP 后端对应 ws,HTTPS 对应 wss;不要求应用暴露回调地址。需要支持此入口的 BA,未加入 SDK/Server 版本校验。
951
+ 直连使用 `/api/app-tools/connect`,HTTP 后端对应 ws,HTTPS 对应 wss。应用主动连接 BA,每 20 秒发送一次文本心跳,无需暴露回调地址。BA 确认请求尚未投递时会短暂等待应用重连,最长 8 秒。投递结果未知时,仅声明 `annotations.idempotentHint` 的工具允许 BA 重试。业务处理函数可以返回 `isError`,抛出的 `Error` 会以脱敏后的短消息反馈。
952
952
 
953
953
  ### 可恢复的统一发送
954
954
 
@@ -1003,7 +1003,7 @@ await session.send(input.content, input.options)
1003
1003
 
1004
1004
  ## 后端应用共享连接
1005
1005
 
1006
- PA 等后端服务使用 `BladeApplicationClient`,全部用户共享两条按需建立的 WebSocket。
1006
+ PA 等后端服务使用 `BladeApplicationClient`,全部用户共享按需建立的 `/api/app-channels/connect` WebSocket。心跳在这条物理连接上发送一次,同一连接上的工具注册共用它。
1007
1007
  每个用户仍使用自己的 bearer token;REST 请求和会话权限按用户隔离。
1008
1008
 
1009
1009
  ```ts
@@ -111,6 +111,7 @@ var ToolProvider = class {
111
111
  socket;
112
112
  timer;
113
113
  registrationTimer;
114
+ heartbeat;
114
115
  disposed = false;
115
116
  registered = false;
116
117
  attempts = 0;
@@ -143,6 +144,7 @@ var ToolProvider = class {
143
144
  }
144
145
  reset() {
145
146
  clearTimeout(this.registrationTimer);
147
+ clearInterval(this.heartbeat);
146
148
  this.registered = false;
147
149
  const socket = this.socket;
148
150
  this.socket = void 0;
@@ -220,11 +222,23 @@ var ToolProvider = class {
220
222
  }
221
223
  this.registered = true;
222
224
  this.attempts = 0;
225
+ if (!this.client.options.applicationTransport) {
226
+ this.heartbeat = setInterval(() => {
227
+ if (this.socket === socket && socket.readyState === WebSocket.OPEN) {
228
+ try {
229
+ socket.send(JSON.stringify({ jsonrpc: "2.0", method: "ping" }));
230
+ } catch {
231
+ socket.close();
232
+ }
233
+ }
234
+ }, 2e4);
235
+ }
223
236
  for (const waiter of this.waiters) waiter.resolve();
224
237
  this.waiters.clear();
225
238
  return;
226
239
  }
227
240
  if (!this.registered) throw new Error("Provider not registered");
241
+ if (message.method === "pong" && !message.id) return;
228
242
  if (message.method === "notifications/cancelled") {
229
243
  this.calls.get(String(message.params?.requestId))?.abort();
230
244
  return;
@@ -249,8 +263,13 @@ var ToolProvider = class {
249
263
  } else {
250
264
  response.error = { code: -32601, message: "Method not found" };
251
265
  }
252
- } catch {
253
- response = { jsonrpc: "2.0", id: message.id, error: { code: -32e3, message: "Application tool execution failed" } };
266
+ } catch (error) {
267
+ let detail = error instanceof Error ? error.message : "";
268
+ for (const secret of [this.options.capability, this.client.token]) {
269
+ if (secret) detail = detail.replaceAll(secret, "[redacted]");
270
+ }
271
+ detail = detail.replace(/\bBearer\s+[^\s,;]+|\bsk-[\w-]+|([?&](?:token|key|secret|password|api[_-]?key)=)[^&#\s]+/gi, "$1[redacted]").replace(/\p{Cc}/gu, " ").trim().slice(0, 500);
272
+ response = { jsonrpc: "2.0", id: message.id, error: { code: -32e3, message: detail || "Application tool execution failed" } };
254
273
  } finally {
255
274
  this.calls.delete(message.id);
256
275
  }
@@ -268,7 +287,7 @@ var ToolProvider = class {
268
287
 
269
288
  // src/version.ts
270
289
  var SDK_NAME = "agent-client";
271
- var SDK_VERSION = true ? "2612.0.0-beta.97" : "1.1.1";
290
+ var SDK_VERSION = true ? "2612.0.0-beta.98" : "1.1.1";
272
291
 
273
292
  // src/auth-login.ts
274
293
  function isAuthCallbackMessage(value) {
@@ -5087,7 +5106,8 @@ function withTurns(state, turns) {
5087
5106
  activeCompaction,
5088
5107
  askAnswers,
5089
5108
  mode: latestMode ?? state.mode,
5090
- status: isWaitingForInput ? "waiting_for_input" : state.status
5109
+ status: isWaitingForInput ? "waiting_for_input" : state.status,
5110
+ isStreaming: !isWaitingForInput && state.isStreaming
5091
5111
  };
5092
5112
  }
5093
5113
  function withQueue(state, snapshot2) {
@@ -5362,30 +5382,10 @@ var AgentSession = class _AgentSession {
5362
5382
  disposed = false;
5363
5383
  getAppContext = null;
5364
5384
  submissionWaits = /* @__PURE__ */ new Set();
5365
- manualCompactionRequest = null;
5385
+ compactionAck = null;
5366
5386
  epochReloadRequested = 0;
5367
5387
  epochReloadDone = 0;
5368
5388
  epochReloadRunning = false;
5369
- async reconcileManualCompaction() {
5370
- const request = this.manualCompactionRequest;
5371
- if (!request?.runId || !this.runtime.fetchRunResult) return;
5372
- const result = await this.runtime.fetchRunResult(this.sessionId, request.runId);
5373
- if (!this.disposed && this.manualCompactionRequest === request && result?.run_id === request.runId) {
5374
- this.setManualCompactionRequest(null);
5375
- }
5376
- }
5377
- setManualCompactionRequest(request) {
5378
- this.manualCompactionRequest = request;
5379
- const pending = request !== null;
5380
- if (this.state.compactionPending !== pending) this.update((s) => ({ ...s, compactionPending: pending }));
5381
- }
5382
- handleManualCompactionFinished(event) {
5383
- const request = this.manualCompactionRequest;
5384
- const runId = event.payload.run_id;
5385
- if (!request || !isCompactionFinished(event.type) || typeof runId !== "string" || !runId) return;
5386
- if (request.runId === null) request.finishedBeforeAck.add(runId);
5387
- else if (request.runId === runId) this.setManualCompactionRequest(null);
5388
- }
5389
5389
  workflowRunToolCalls = /* @__PURE__ */ new Map();
5390
5390
  desiredStreamTokens = null;
5391
5391
  joinedStreamTokens = null;
@@ -5892,66 +5892,38 @@ var AgentSession = class _AgentSession {
5892
5892
  }
5893
5893
  /** 停止当前回复。 */
5894
5894
  async stop(executionId) {
5895
+ let targetId = executionId;
5895
5896
  if (!executionId) for (const pending of this.submissionWaits) pending.abort(new AgentSessionError("\u5DF2\u505C\u6B62\u672C\u5730\u63D0\u4EA4\u7B49\u5F85\uFF1B\u539F\u8BF7\u6C42\u7684\u63A5\u6536\u72B6\u6001\u4ECD\u987B\u6838\u5BF9\u3002", "send_stopped"));
5896
- const request = this.manualCompactionRequest;
5897
- if (request && !executionId) {
5898
- const ack = await request.ack;
5897
+ if (this.compactionAck && !executionId) {
5898
+ const ack = await this.compactionAck;
5899
5899
  if (ack.status !== "accepted") return ack;
5900
- if (this.manualCompactionRequest !== request) return { status: "idle" };
5901
- return await this.runtime.emitWithAck("chat:stop", {
5902
- session_id: this.sessionId,
5903
- chat_run_id: request.runId
5904
- }, 35e3) ?? {};
5900
+ if (typeof ack.run_id === "string") targetId = ack.run_id;
5905
5901
  }
5906
- const response = await this.runtime.emitWithAck("chat:stop", { session_id: this.sessionId, ...executionId ? { chat_run_id: executionId } : {} }, 35e3) ?? {};
5902
+ const response = await this.runtime.emitWithAck("chat:stop", {
5903
+ session_id: this.sessionId,
5904
+ ...targetId ? { chat_run_id: targetId } : {}
5905
+ }, 35e3) ?? {};
5907
5906
  return response;
5908
5907
  }
5909
5908
  /** 手动触发上下文压缩。 */
5910
5909
  compact() {
5911
- if (this.state.isStreaming || this.state.activeCompaction || this.manualCompactionRequest) {
5910
+ if (this.state.isStreaming || this.state.activeCompaction || this.compactionAck) {
5912
5911
  return Promise.resolve({
5913
5912
  status: "error",
5914
5913
  message: "\u5F53\u524D\u56DE\u590D\u5C1A\u672A\u7ED3\u675F\u6216\u5BF9\u8BDD\u6B63\u5728\u6574\u7406\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002"
5915
5914
  });
5916
5915
  }
5917
- const request = {
5918
- runId: null,
5919
- finishedBeforeAck: /* @__PURE__ */ new Set(),
5920
- ack: Promise.resolve().then(() => this.runtime.emitWithAck("chat:compact", { session_id: this.sessionId }, 3e4)).then((response) => {
5921
- const result = response ?? {};
5922
- if (result.status !== "accepted") {
5923
- if (this.manualCompactionRequest === request) this.setManualCompactionRequest(null);
5924
- return result;
5925
- }
5926
- if (typeof result.run_id !== "string" || !result.run_id) {
5927
- throw new AgentSessionError("\u6574\u7406\u8BF7\u6C42\u786E\u8BA4\u7F3A\u5C11 run_id\uFF0C\u65E0\u6CD5\u786E\u8BA4\u8FD0\u884C\u72B6\u6001");
5928
- }
5929
- request.runId = result.run_id;
5930
- if (request.finishedBeforeAck.has(request.runId) && this.manualCompactionRequest === request) {
5931
- this.setManualCompactionRequest(null);
5932
- }
5933
- request.finishedBeforeAck.clear();
5934
- return result;
5935
- }).catch((error) => {
5936
- if (this.manualCompactionRequest === request) this.setManualCompactionRequest(null);
5937
- throw error;
5938
- }).finally(() => {
5939
- if ((!this.manualCompactionRequest || this.manualCompactionRequest === request) && this.state.activeCompaction?.compaction_id === "pending-manual-compaction") {
5940
- this.update((state) => ({ ...state, activeCompaction: null }));
5941
- }
5942
- })
5943
- };
5944
- this.setManualCompactionRequest(request);
5945
- this.update((state) => ({
5946
- ...state,
5947
- activeCompaction: {
5948
- turn_id: "pending-manual-compaction",
5949
- compaction_id: "pending-manual-compaction",
5950
- status: "streaming",
5951
- trigger: "manual"
5916
+ this.compactionAck = Promise.resolve().then(() => this.runtime.emitWithAck("chat:compact", { session_id: this.sessionId }, 3e4)).then((response) => {
5917
+ if (response?.status === "accepted" && (typeof response.run_id !== "string" || !response.run_id)) {
5918
+ throw new AgentSessionError("\u6574\u7406\u8BF7\u6C42\u786E\u8BA4\u7F3A\u5C11 run_id\uFF0C\u65E0\u6CD5\u786E\u8BA4\u8FD0\u884C\u72B6\u6001");
5952
5919
  }
5953
- }));
5954
- return request.ack;
5920
+ return response ?? {};
5921
+ }).finally(() => {
5922
+ this.compactionAck = null;
5923
+ this.update((state) => ({ ...state, compactionPending: false }));
5924
+ });
5925
+ this.update((state) => ({ ...state, compactionPending: true }));
5926
+ return this.compactionAck;
5955
5927
  }
5956
5928
  /**
5957
5929
  * 把一段业务数据作为附件放进聊天输入框(比如地图上选中的点位)。
@@ -6031,11 +6003,13 @@ var AgentSession = class _AgentSession {
6031
6003
  this.subscriptionReplaySource = null;
6032
6004
  this.scheduleHistoricalCommandRestore(commandRecoveryGeneration);
6033
6005
  }
6034
- const replaced = await this.refreshAuthoritativeHistory({
6035
- liveRevisionAtStart: reconnectLiveRevision,
6036
- modeRevisionAtStart: reconnectModeRevision
6037
- });
6038
- if (!replaced) await this.syncSessionFromDetail({ fresh: true });
6006
+ await Promise.all([
6007
+ this.refreshAuthoritativeHistory({
6008
+ liveRevisionAtStart: reconnectLiveRevision,
6009
+ modeRevisionAtStart: reconnectModeRevision
6010
+ }),
6011
+ this.syncSessionFromDetail({ fresh: true })
6012
+ ]);
6039
6013
  } catch {
6040
6014
  }
6041
6015
  });
@@ -6073,18 +6047,11 @@ var AgentSession = class _AgentSession {
6073
6047
  }
6074
6048
  async syncSessionFromDetail(options) {
6075
6049
  const statusRevisionAtRequest = this.statusRevision;
6076
- const compactionRevision = this.liveRevision;
6077
6050
  const epoch = this.timelineEpoch;
6078
6051
  try {
6079
6052
  const info = await this.runtime.fetchSessionInfo(this.sessionId, options);
6080
6053
  if (this.disposed || epoch !== this.timelineEpoch) return;
6081
6054
  this.applySessionDetail(info, statusRevisionAtRequest);
6082
- if (options.fresh && info.history_busy === false) {
6083
- this.update((state) => withTurns(state, state.turns.filter(
6084
- (turn) => turn.kind !== "compaction" || turn.status !== "streaming" || (this.liveRevisions.get(turn.turn_id) ?? 0) > compactionRevision
6085
- )));
6086
- this.projectionBuilder._seedTurns(this.state.turns);
6087
- }
6088
6055
  } catch {
6089
6056
  }
6090
6057
  }
@@ -6194,9 +6161,7 @@ var AgentSession = class _AgentSession {
6194
6161
  }
6195
6162
  if (event.type === "log:notification") {
6196
6163
  const notification = event.payload.event;
6197
- if (isCompactionFinished(notification.type)) {
6198
- this.handleManualCompactionFinished(notification);
6199
- } else if (notification.type === "artifact:created" || notification.type === "artifact:updated") {
6164
+ if (notification.type === "artifact:created" || notification.type === "artifact:updated") {
6200
6165
  this._handleArtifact(notification.payload, notification.type === "artifact:created" ? "created" : "updated", replayed);
6201
6166
  } else if (notification.type === "workspace:changed") {
6202
6167
  const change = notification.payload.workspace_change;
@@ -6227,7 +6192,11 @@ var AgentSession = class _AgentSession {
6227
6192
  }
6228
6193
  }
6229
6194
  events = events.flatMap((event) => {
6230
- if (event.type === "turn:snapshot" || event.type.startsWith("replay:")) return [];
6195
+ if (event.type === "turn:snapshot") {
6196
+ const turn = event.payload.turn;
6197
+ return turn.loop_id !== "root" && turn.blocks.some((block) => block.type === "ask_user_answer") ? [event] : [];
6198
+ }
6199
+ if (event.type.startsWith("replay:")) return [];
6231
6200
  if (event.type !== "log:notification") {
6232
6201
  if (event.type === "compaction:start") activeCompactionIds.add(String(event.payload.compaction_id));
6233
6202
  return [event];
@@ -6249,12 +6218,8 @@ var AgentSession = class _AgentSession {
6249
6218
  }
6250
6219
  processRawEventSlice(events, replayed) {
6251
6220
  if (!events.length) return;
6252
- for (const event of events) this.handleManualCompactionFinished(event);
6253
6221
  this.dispatchRawCommands(events);
6254
6222
  const terminalChatEndStatus = extractTerminalChatEndStatus(events);
6255
- if (!terminalChatEndStatus && hasChatRunEvent(events) && this.state.status !== "waiting_for_input") {
6256
- this.markRunningIfIdle();
6257
- }
6258
6223
  this.projectionBuilder._seedTurns(this.state.turns);
6259
6224
  const updates = this.projectionBuilder.processBatch(events);
6260
6225
  for (const update of updates) {
@@ -6271,14 +6236,20 @@ var AgentSession = class _AgentSession {
6271
6236
  }
6272
6237
  }
6273
6238
  this.applyWorkflowEvents(events);
6274
- if (events.some((event) => event.type === "loop:child_pause")) {
6275
- this.noteLiveStatus();
6276
- this.finishStreaming("paused");
6277
- } else if (events.some((event) => event.type === "loop:ask_user_answer")) {
6278
- this.markRunningIfIdle();
6279
- }
6280
6239
  if (terminalChatEndStatus || acceptedPostChatFollowupCompletesLatestRun(events, updates)) {
6281
6240
  this.completeChat(terminalChatEndStatus ?? "completed", replayed);
6241
+ return;
6242
+ }
6243
+ const lastControl = events.reduce((control, { type: type2 }) => type2 === "chat:start" || type2 === "loop:child_pause" || type2 === "loop:ask_user_answer" || type2 === "turn:snapshot" ? type2 : control, void 0);
6244
+ if (lastControl === "loop:child_pause") {
6245
+ this.noteLiveStatus();
6246
+ this.finishStreaming("paused");
6247
+ } else if (!this.hasPendingQuestion()) {
6248
+ if (lastControl === "chat:start") {
6249
+ this._handleChatStart();
6250
+ } else if (lastControl === "loop:ask_user_answer" || (this.state.status === "waiting_for_input" ? lastControl === "turn:snapshot" : hasChatRunEvent(events.filter((event) => event.type !== "turn:snapshot")))) {
6251
+ this.markRunningIfIdle();
6252
+ }
6282
6253
  }
6283
6254
  }
6284
6255
  _handleChatStart() {
@@ -6410,11 +6381,13 @@ var AgentSession = class _AgentSession {
6410
6381
  kind
6411
6382
  });
6412
6383
  }
6413
- _applyRunningState(isRunning, liveRevisionAtJoin = this.liveRevision) {
6414
- const hasPendingQuestion = this.state.turns.some(
6384
+ hasPendingQuestion() {
6385
+ return this.state.turns.some(
6415
6386
  (turn) => turn.tool_calls.some((call) => call.status === "awaiting_answer")
6416
6387
  );
6417
- if (isRunning && !hasPendingQuestion) {
6388
+ }
6389
+ _applyRunningState(isRunning, liveRevisionAtJoin = this.liveRevision) {
6390
+ if (isRunning && !this.hasPendingQuestion()) {
6418
6391
  this.noteLiveStatus();
6419
6392
  this.update((s) => ({ ...s, status: "running", isStreaming: true }));
6420
6393
  } else if (this.state.isStreaming) {
@@ -6763,13 +6736,6 @@ var AgentSession = class _AgentSession {
6763
6736
  });
6764
6737
  this.pruneOptimisticLiveRevisions();
6765
6738
  this.projectionBuilder._seedTurns(this.state.turns);
6766
- if (this.joined) await this.syncSessionFromDetail({ fresh: true });
6767
- try {
6768
- await this.reconcileManualCompaction();
6769
- } catch (error) {
6770
- options.onError?.(error);
6771
- if (options.suppressErrors === false) throw error;
6772
- }
6773
6739
  this.update((state) => ({ ...state, historyRevision: state.historyRevision + 1 }));
6774
6740
  return true;
6775
6741
  } catch (error) {
@@ -7256,18 +7222,14 @@ var PhonesResource = class {
7256
7222
  await this.client.fetch("DELETE", `/api/phone/devices/${encodeURIComponent(phoneId)}`);
7257
7223
  }
7258
7224
  /** 本次会话能用的手机 + 账号下的其他手机。 */
7259
- listForSession(sessionId) {
7260
- return this.client.json(
7261
- "GET",
7262
- `/api/sessions/${encodeURIComponent(sessionId)}/phones`
7263
- );
7225
+ async listForSession(sessionId) {
7226
+ const { computers } = await this.client.computers.list(sessionId);
7227
+ return {
7228
+ phones: computers.filter((item) => String(item.os ?? "").toLowerCase().startsWith("android"))
7229
+ };
7264
7230
  }
7265
7231
  setEnabled(sessionId, phoneId, enabled) {
7266
- return this.client.json(
7267
- "PUT",
7268
- `/api/sessions/${encodeURIComponent(sessionId)}/phones/${encodeURIComponent(phoneId)}/enabled`,
7269
- { enabled }
7270
- );
7232
+ return this.client.computers.setEnabled(sessionId, phoneId, enabled);
7271
7233
  }
7272
7234
  health(sessionId, phoneId) {
7273
7235
  return this.client.json(
@@ -8883,6 +8845,7 @@ var ApplicationChannel = class {
8883
8845
  socket;
8884
8846
  opening;
8885
8847
  timer;
8848
+ heartbeat;
8886
8849
  stopped = false;
8887
8850
  attempts = 0;
8888
8851
  controlCount = 0;
@@ -8955,6 +8918,15 @@ var ApplicationChannel = class {
8955
8918
  if (this.socket !== socket || this.stopped) return;
8956
8919
  clearTimeout(timeout);
8957
8920
  this.attempts = 0;
8921
+ this.heartbeat = setInterval(() => {
8922
+ if (this.socket === socket && socket.readyState === WebSocket.OPEN) {
8923
+ try {
8924
+ socket.send(JSON.stringify({ method: "ping" }));
8925
+ } catch {
8926
+ socket.close();
8927
+ }
8928
+ }
8929
+ }, 2e4);
8958
8930
  resolve();
8959
8931
  for (const user2 of this.users.values()) user2.restore();
8960
8932
  });
@@ -8974,6 +8946,7 @@ var ApplicationChannel = class {
8974
8946
  clearTimeout(timeout);
8975
8947
  reject(new Error("Application connection closed"));
8976
8948
  if (this.socket !== socket) return;
8949
+ clearInterval(this.heartbeat);
8977
8950
  this.socket = void 0;
8978
8951
  for (const request of this.pending.values()) {
8979
8952
  clearTimeout(request.timer);
@@ -8997,6 +8970,7 @@ var ApplicationChannel = class {
8997
8970
  );
8998
8971
  }
8999
8972
  receive(frame) {
8973
+ if (frame.method === "pong") return;
9000
8974
  if (frame.id) {
9001
8975
  const request = this.pending.get(frame.id);
9002
8976
  if (!request || request.user !== frame.user) return;
@@ -9049,6 +9023,7 @@ var ApplicationChannel = class {
9049
9023
  }
9050
9024
  dispose() {
9051
9025
  this.stopped = true;
9026
+ clearInterval(this.heartbeat);
9052
9027
  clearTimeout(this.timer);
9053
9028
  this.timer = void 0;
9054
9029
  for (const user of this.users.values()) user.lost();
@@ -9578,4 +9553,4 @@ export {
9578
9553
  formatAskUserAnswer,
9579
9554
  attachPackPageBridge
9580
9555
  };
9581
- //# sourceMappingURL=chunk-3XQ7HYKA.js.map
9556
+ //# sourceMappingURL=chunk-6MCDDBTU.js.map