@blade-hq/agent-client 2610.0.0-beta.4 → 2610.0.0-beta.41

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
@@ -2,16 +2,21 @@
2
2
 
3
3
  Blade Agent 的框架无关客户端。浏览器和 Node.js 都能用;用 Vue、Svelte 或自建 UI 的团队直接用这个包,React 团队一般用上层的 `@blade-hq/agent-react`。
4
4
 
5
- 它做三件事:
5
+ 它做四件事:
6
6
 
7
7
  1. **实时会话**(`AgentSession`):把 Socket.IO 协议、历史加载、流式合流、断线重连全部封装掉,你只面对"状态快照 + 动作 + 事件"。
8
8
  2. **登录**:`client.auth.login()` 弹窗授权,用户点一下"许可授权"就拿到访问令牌,不用手工复制粘贴。
9
9
  3. **REST**:类型化会话和模型目录(`client.sessions.*`、`client.models.list()`)。其他长尾接口对照 Swagger 用原生 `fetch` + `client.token` 调用。
10
+ 4. **部署端点**:从同源 `config.json` 读取其他 Blade 服务的公开地址,不根据主机名和固定端口猜测拓扑。
10
11
 
11
12
  ```bash
12
13
  npm install @blade-hq/agent-client
13
14
  ```
14
15
 
16
+ 默认装到的是当前长期支持版(LTS),厂内离线交付按它开发。要跟两周一发的公网版本,改用 `@next`。
17
+
18
+ 最稳妥的做法是先读目标 Server 的 `GET /api/version`,按返回的版本号在 `package.json` 里钉死——NPM 的 `latest` 不一定和目标环境跑的版本一致。
19
+
15
20
  ## 快速开始
16
21
 
17
22
  ```html
@@ -47,6 +52,27 @@ const client = new BladeClient({
47
52
  })
48
53
  ```
49
54
 
55
+ ## 部署端点
56
+
57
+ Blade 平台前端需要跳转其他服务时,读取当前 origin 的公开配置:
58
+
59
+ ```ts
60
+ import { loadPlatformEndpoints, resolveServiceUrl } from "@blade-hq/agent-client"
61
+
62
+ const endpoints = await loadPlatformEndpoints()
63
+ const hubUrl = resolveServiceUrl(endpoints, "hub", "/skills/42")
64
+ if (hubUrl) window.open(hubUrl)
65
+ ```
66
+
67
+ `loadPlatformEndpoints()` 请求 `config.json`,超过 3 秒、网络失败或配置非法时返回空配置;
68
+ 调用方应隐藏对应入口。文件只能放浏览器可访问的公开地址,不能写 Docker 服务名、令牌或
69
+ 其他内部配置。应用部署在子路径时,通过 `baseUrl` 显式传入部署根路径。
70
+ `resolveServiceUrl()` 的 `path` 只接受服务内相对路径;绝对 URL、反斜杠和越出服务
71
+ base path 的路径返回 `null`。
72
+
73
+ 公开类型为 `PlatformEndpoints`、`PlatformServiceName`、`LoadPlatformEndpointsOptions`;
74
+ 需要同步初始化时可直接使用 `EMPTY_PLATFORM_ENDPOINTS`。
75
+
50
76
  ## BladeClient
51
77
 
52
78
  ### 构造
@@ -56,10 +82,12 @@ new BladeClient({
56
82
  baseUrl: "https://blade.example.com", // 后端地址;同域部署可传 ""
57
83
  token: "sk-blade-xxx", // 可选:PAT。不传则用 cookie 或 login()
58
84
  tokenStorage: "local", // 可选:login() 的令牌存哪("local" 默认 / "memory")
59
- streamTokens: false, // 可选:只接收完成态内容,不订阅逐 token 增量
60
85
  })
61
86
  ```
62
87
 
88
+ SDK 会固定订阅普通聊天所需的完整实时事件。产品内置 Web 的精简/开发者展示模式不属于
89
+ 公共 SDK 契约,也没有对应的构造参数或 Socket.IO 字段。
90
+
63
91
  > **`baseUrl` 填哪个地址?** 必须是 Blade Agent 后端的地址(形如 `http://<主机>:8020`),只要域名和端口、不带路径。
64
92
  > 注意别填成你平时打开的 Blade OS 地址(同主机的 `:80`)—— 那是另一套接口,SDK 连不上。
65
93
 
@@ -139,6 +167,8 @@ await client.sessions.getSession(id) // 会话详情
139
167
  await client.sessions.updateSession(id, { intent: "新标题" })
140
168
  await client.sessions.deleteSession(id)
141
169
  await client.sessions.getSessionTurns(id) // 历史消息(投影格式,与实时流同构)
170
+ const page = await client.sessions.getSessionTurnsPage(id) // 聊天首屏 recent page
171
+ await client.sessions.getSessionTurnsPage(id, { before: page.nextBefore! })
142
172
  ```
143
173
 
144
174
  ### 会话回放(演示 / 彩排)
@@ -261,6 +291,57 @@ const body = { model: defaultServiceModel, messages, stream: true }
261
291
  没问题,直接交给浏览器就指向用户自己的机器了。默认形态是后端透传(密钥本来也不该进浏览器),
262
292
  浏览器直连只适合这个地址对浏览器同样可达的场景。
263
293
 
294
+ ### 远程电脑:client.computers
295
+
296
+ 一个会话除了自己的运行时,还可以操作用户接入的其他电脑(`blade daemon connect` 接进来的机器)。
297
+ **默认一台都不能用**,要先为这次会话启动它。
298
+
299
+ ```ts
300
+ const { computers } = await client.computers.list(sessionId)
301
+ // SessionComputerList → { computers: SessionComputer[] }
302
+ // SessionComputer: { id, label, os, arch, home, workspace, allowed_paths,
303
+ // online, enabled, is_primary, last_seen_at, ... }
304
+
305
+ await client.computers.setEnabled(sessionId, computer.id, true) // 启动
306
+ await client.computers.setEnabled(sessionId, computer.id, false) // 停用
307
+ ```
308
+
309
+ `online` 和 `enabled` 是**两件独立的事**:前者指那台电脑此刻连着后端,后者指这次会话已经启动了它。
310
+ 离线的电脑也能先启动,等它连上就直接可用。`online` 由服务端读心跳时间判定,不做实时探测,
311
+ 所以电脑离线时列表照样返回它——你拿得到「它离线了」这个结论。
312
+
313
+ `is_primary` 表示这次会话本身就跑在这台电脑上。这种电脑恒为可用,也不能停用——
314
+ 那是会话自己的工作目录所在。
315
+
316
+ 做电脑选择器时用这几个纯函数,别自己重算状态:
317
+
318
+ ```ts
319
+ import {
320
+ canToggleComputer, computerState, sortComputers,
321
+ computerOS, computerPlatformLabel, computerDaemonVersion,
322
+ } from "@blade-hq/agent-client"
323
+
324
+ sortComputers(computers) // 按接入时间,顺序稳定不随状态变化
325
+ computerState(computer) // ComputerState: "primary" | "enabled" | "offline" | "idle"
326
+ canToggleComputer(computer) // 主运行时返回 false
327
+
328
+ computerOS(computer) // ComputerOS: "macos" | "windows" | "linux" | "unknown"
329
+ computerPlatformLabel(computer) // "darwin/arm64"
330
+ computerDaemonVersion(computer) // "dev (bc3ad71d1)",未知时是空串
331
+ ```
332
+
333
+ `sortComputers` **刻意不按在线/可用排序**:那样排看着"手边的在前面",代价是电脑
334
+ 上下线、勾选状态一变整个列表就重排,用户正要点的那一项会在手指底下跑掉。改名也
335
+ 不会挪位置,新接入的稳定排在末尾。
336
+
337
+ `computerOS` 判定的是 daemon 上报的 `runtime.GOOS`,各处自己 `startsWith` 一遍必然会分叉;
338
+ 图标怎么画交给界面,这里只回答"是哪一类系统"。
339
+
340
+ `computerDaemonVersion` 返回的是服务端存的完整串——dev 构建带 commit,
341
+ 因为 dev 的版本号全都是 `dev`,光看它分不出是哪次构建的二进制。**不要在前端另拼一套格式。**
342
+
343
+ `ComputersResource` 是 `client.computers` 的类型。
344
+
264
345
  ## AgentSession
265
346
 
266
347
  一个会话的实时状态机。**状态归属实例**:同一页面建多个会话互不干扰。
@@ -279,6 +360,7 @@ chat.getState()
279
360
  // errorMessage, 最近一次运行错误
280
361
  // replay, 回放状态:{ isReplay, speed, sourceSessionId } | null
281
362
  // viewerRole, "owner" | "viewer" | null(只读身份改不动会话)
363
+ // nextBefore, loadingOlder, 历史分页游标与加载状态
282
364
  // turns, askAnswers, agentLoops, activeCompaction 进阶字段
283
365
  // }
284
366
 
@@ -295,6 +377,7 @@ await chat.send("换个方案", { mode: "planning" }) // 指定模式/模型等
295
377
  chat.append("补充:预算不超过 5 万") // 智能体运行中追加说明
296
378
  await chat.stop() // 停止当前回复
297
379
  await chat.compact() // 手动压缩上下文
380
+ if (chat.hasOlderHistory) await chat.loadOlderHistory()
298
381
  chat.dispose() // 彻底释放(什么时候该调见下方说明)
299
382
  ```
300
383
 
@@ -369,7 +452,9 @@ chat.on("chatEnd", (e) => console.log("回复结束", e.status))
369
452
  chat.on("error", (e) => console.error(e.message))
370
453
  ```
371
454
 
372
- 完整事件表见 `AgentSessionEvents` 类型定义(含 `modeChange` / `workspaceChanged` / `artifact` / `notification` / `backgroundTask` / `taskListUpdated` / `rewind` / `replayMismatch` 等)。`on()` 返回取消函数;handler 抛异常只告警,不影响会话。
455
+ 完整事件表见 `AgentSessionEvents` 类型定义(含 `modeChange` / `workspaceChanged` / `artifact` / `notification` / `backgroundTask` / `taskListUpdated` / `rewind` / `replayMismatch` 等)。`toolResult.source` 区分实时结果、首次连接回放和断线重连回放;`on()` 返回取消函数,handler 抛异常只告警、不影响会话。
456
+
457
+ 分页响应是 `SessionTurnsPage`,其中 `nextBefore: string | null` 是唯一的“还有更早历史”真值。历史页面指令通过独立的 `HistoricalCommand` 日志恢复,不混进展示页。自定义状态容器可复用 `prependOlder`、`replaceWindow` 与 `LiveRevisionState`,但一般直接使用 `AgentSession` 即可。
373
458
 
374
459
  ## iframe 嵌入形态:connectEmbedded
375
460
 
@@ -456,6 +541,9 @@ groupMessagesByLoop(messages) // 按主/子智能体分组(智能体
456
541
  contentPreview(message.content, 80) // 截断预览
457
542
  ```
458
543
 
544
+ 错误消息在普通聊天界面展示前用 `chatErrorForDisplay(message)` 转成稳定的业务文案,
545
+ 避免把内部路径或传输诊断暴露给用户;仅开发者界面显式传入第二个参数 `true` 保留原文。
546
+
459
547
  一个完整的渲染示例:
460
548
 
461
549
  ```tsx
@@ -518,9 +606,9 @@ transformSlashCommand(skillId, prompt, { local: false, installed: false })
518
606
  - **模型目录**:`ModelsResource`、`ModelCatalog`、`ModelOption`
519
607
  - **会话资源(REST)**:`SessionsResource`、`CreateSessionRequest`、`ImportSessionOptions`、`AppCliDefinition`、`AppCliAttachment`、`AttachAppOptions`、`PaginatedSessionsResult`、`GlobalSearchResult`、`GlobalSearchResultItem`、`GlobalSearchConversationResult`、`GlobalSearchFileResult`、`SessionHistory`、`SessionContextStats`、`ResultFeedback`、`ResultFeedbackReason`、`ShareLinkResult`、`FileEntry`、`UploadFileEntry`、`UploadFilesOptions`、`SessionProfile`、`SessionDetail`、`SessionInfo`、`SessionStatus`、`SessionPortMapping`、`ModeId`、`TemplateId`、`PrimarySkillSnapshot`、`PrimarySkillParallelMode`
520
608
  - **会话回放**:`ReplayState`、`ReplaySpeed`、`ReplayPreview`、`ReplaySnapshot`、`toReplaySnapshot`、`DEFAULT_REPLAY_SPEED`
521
- - **会话状态机**:`SessionHub`、`SessionState`、`SendOptions`、`ConnectionStatus`、`AskUserAnswerData`、`AgentLoopInfo`、`ActiveCompactionState`、`createInitialSessionState`、`AgentSessionEventName`
609
+ - **会话状态机**:`SessionHub`、`SessionConnectOptions`、`SessionState`、`SendOptions`、`ConnectionStatus`、`AskUserAnswerData`、`AgentLoopInfo`、`ActiveCompactionState`、`createInitialSessionState`、`AgentSessionEventName`
522
610
  - **页面协作**:`EmbeddedChat`、`EmbeddedChatOptions`、`CommandHandler`、`CommandEnvelope`、`InboundAction`、`InboundEnvelope`、`isCommandEnvelope`、`isInboundEnvelope`
523
- - **消息与投影协议**:`MessageContent`、`MessageContentPart`、`TextContentPart`、`ImageUrlContentPart`、`FileContentPart`、`ToolCallInfo`、`ToolBridgeContent`、`CompactionInfo`、`MemoryRefInfo`、`ArchivedFileInfo`、`ArchivedToolCallInfo`、`TurnProjection`、`ContentBlock`、`PatchEnvelope`、`MemoryRef`、`PostChatFollowup`、`FinalArtifact`、`latestPostChatFollowup`、`buildMessageContent`、`normalizeMessageContent`、`isHiddenInternalMessage`、`transformSlashCommand`、`SkillMentionAvailability`、`extractTextAttachments`、`ParsedTextAttachment`、`ParsedTextContext`
611
+ - **消息与投影协议**:`MessageContent`、`MessageContentPart`、`TextContentPart`、`ImageUrlContentPart`、`FileContentPart`、`ToolCallInfo`、`ToolBridgeContent`、`CompactionInfo`、`ContextProjectionData`、`ContextProjectionFields`、`ContextDisplayState`、`ContextGroupDisplayState`、`ContextAction`、`ContextSourceInfo`、`MemoryRefInfo`、`ArchivedFileInfo`、`ArchivedToolCallInfo`、`TurnProjection`、`ContentBlock`、`PatchEnvelope`、`MemoryRef`、`PostChatFollowup`、`FinalArtifact`、`contextProjectionData`、`getContextDisplayState`、`getContextGroupDisplayState`、`groupAdjacentContextRuns`、`latestPostChatFollowup`、`buildMessageContent`、`normalizeMessageContent`、`isHiddenInternalMessage`、`transformSlashCommand`、`SkillMentionAvailability`、`extractTextAttachments`、`ParsedTextAttachment`、`ParsedTextContext`
524
612
  - **Solution / 任务协议**:`Solution`、`SolutionAppField`、`SolutionAppState`、`SolutionAppUiConfig`、`SolutionRef`、`PublishedSolutionRef`、`ExistingSolutionRef`、`PreparedSolution`、`PreparedSolutionAsset`、`LayoutType`、`BizRole`、`TaskStatus`、`BackgroundTask`、`BackgroundTaskStopResult`
525
613
  - **Headless**:`HeadlessResource`、`RunOptions`、`RunResult`、`RunTrace`
526
- - **低层通道(apps/web 等高级集成)**:`createSocket`、`CreateSocketOptions`、`TypedSocket`、`AsrAudioPayload`、`ClientProjectionBuilder`、`RawEvent`、`acceptedPostChatFollowupCompletesLatestRun`
614
+ - **低层通道(apps/web 等高级集成)**:`createSocket`、`CreateSocketOptions`、`TypedSocket`、`AsrAudioPayload`、`ClientProjectionBuilder`、`RawEvent`、`acknowledgeTurnEvents`、`hasChatRunEvent`、`acceptedPostChatFollowupCompletesLatestRun`、`reconcileOptimisticUserTurns`、`reconcileHistoricalUserTurns`
package/dist/auth.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  export interface AuthOptions {
2
2
  token?: string | (() => string | null | undefined);
3
3
  }
4
- export declare function buildAuthHeaders(options: AuthOptions): Record<string, string>;
5
4
  export declare function buildSocketAuth(options: AuthOptions): {
6
5
  token: string;
7
6
  } | undefined;
@@ -2,6 +2,7 @@ import { type LoginOptions, type LoginResult, type TokenStorageMode } from "./au
2
2
  import { type BladeFetchInit, type HttpMethod } from "./rest";
3
3
  import { AuthResource } from "./resources/auth";
4
4
  import { HeadlessResource } from "./resources/headless";
5
+ import { ComputersResource } from "./resources/computers";
5
6
  import { ModelsResource } from "./resources/models";
6
7
  import { SessionsResource } from "./resources/sessions";
7
8
  import { SessionHub } from "./session/hub";
@@ -23,8 +24,6 @@ export interface BladeClientOptions {
23
24
  tokenStorage?: TokenStorageMode;
24
25
  fetchImpl?: typeof fetch;
25
26
  onRefreshSuccess?: () => void | Promise<void>;
26
- /** 是否订阅逐 token 增量,默认 true。关闭后仍接收完整消息和语义事件。 */
27
- streamTokens?: boolean;
28
27
  }
29
28
  export declare class BladeClient {
30
29
  private refreshPromise;
@@ -35,6 +34,7 @@ export declare class BladeClient {
35
34
  readonly options: BladeClientOptions;
36
35
  readonly auth: AuthResource;
37
36
  readonly headless: HeadlessResource;
37
+ readonly computers: ComputersResource;
38
38
  readonly models: ModelsResource;
39
39
  readonly sessions: SessionsResource;
40
40
  /** 实时会话中枢:client.sessions.connect() 内部使用,一般不直接访问。 */
package/dist/index.d.ts CHANGED
@@ -2,14 +2,17 @@ export { BladeClient } from "./blade-client";
2
2
  export type { BladeClientOptions, UploadProgress } from "./blade-client";
3
3
  export { BladeApiError } from "./rest";
4
4
  export type { LoginOptions, LoginResult, TokenStorageMode } from "./auth-login";
5
+ export { EMPTY_PLATFORM_ENDPOINTS, loadPlatformEndpoints, resolveServiceUrl, } from "./platform-endpoints";
6
+ export type { LoadPlatformEndpointsOptions, PlatformEndpoints, PlatformServiceName, } from "./platform-endpoints";
5
7
  export { SDK_NAME, SDK_VERSION } from "./version";
6
8
  export { AgentSession } from "./session/agent-session";
7
9
  export type { AttachAppOptions, SendOptions } from "./session/agent-session";
8
10
  export { SessionHub } from "./session/hub";
11
+ export type { SessionConnectOptions } from "./session/hub";
9
12
  export type { AgentSessionEvents, AgentSessionEventName } from "./session/events";
10
13
  export { SessionSetupError } from "./session/definition";
11
14
  export type { SessionConfig, SessionDefinition, SessionSetupStage, SkillDefinition, TextFile, SolutionDefinition, } from "./session/definition";
12
- export { createInitialSessionState, toReplaySnapshot } from "./session/state";
15
+ export { createInitialSessionState, reconcileHistoricalUserTurns, reconcileOptimisticUserTurns, toReplaySnapshot, } from "./session/state";
13
16
  export type { AskUserAnswerData, AgentLoopInfo, ActiveCompactionState, ConnectionStatus, ReplaySnapshot, SessionState, } from "./session/state";
14
17
  export { connectEmbedded } from "./commands/embedded";
15
18
  export type { EmbeddedChat, EmbeddedChatOptions } from "./commands/embedded";
@@ -18,15 +21,23 @@ export type { CommandEnvelope, InboundAction, InboundEnvelope } from "./commands
18
21
  export { isCommandEnvelope, isInboundEnvelope } from "./commands/protocol";
19
22
  export type { AuthResource, ExchangeCodeParams, ExchangeCodeResult, ProvidersResponse, UserInfo, } from "./resources/auth";
20
23
  export type { HeadlessResource } from "./resources/headless";
24
+ export { ComputersResource } from "./resources/computers";
25
+ export { canToggleComputer, computerDaemonVersion, computerOS, computerPlatformLabel, computerState, sortComputers, } from "./resources/computers";
26
+ export type { ComputerOS, ComputerState, SessionComputer, SessionComputerList, } from "./resources/computers";
21
27
  export { ModelsResource } from "./resources/models";
22
28
  export type { ModelCatalog, ModelOption } from "./resources/models";
23
29
  export type { SessionsResource } from "./resources/sessions";
24
- export type { CreateSessionRequest, AppCliAttachment, AppCliDefinition, FileEntry, ImportSessionOptions, PaginatedSessionsResult, GlobalSearchConversationResult, GlobalSearchFileResult, GlobalSearchResult, GlobalSearchResultItem, ResultFeedback, ResultFeedbackReason, SessionContextStats, SessionHistory, ShareLinkResult, UploadFileEntry, UploadFilesOptions, } from "./resources/sessions";
30
+ export { hasChatRunEvent } from "./shared/projection";
31
+ export type { CreateSessionRequest, AppCliAttachment, AppCliDefinition, FileEntry, ImportSessionOptions, PaginatedSessionsResult, GlobalSearchConversationResult, GlobalSearchFileResult, GlobalSearchResult, GlobalSearchResultItem, ResultFeedback, ResultFeedbackReason, HistoricalCommand, SessionContextStats, SessionHistory, SessionTurnsPage, ShareLinkResult, UploadFileEntry, UploadFilesOptions, } from "./resources/sessions";
25
32
  export type { ArchivedFileInfo, ArchivedToolCallInfo, ChatMessage, CompactionInfo, FileContentPart, ImageUrlContentPart, MemoryRefInfo, MessageContent, MessageContentPart, TextContentPart, ToolBridgeContent, ToolCallInfo, } from "./schemas/message";
26
- export { buildMessageContent, contentPreview, extractTextAttachments, getFileParts, getImageParts, getTextContent, groupMessagesByLoop, isHiddenInternalMessage, normalizeMessageContent, transformSlashCommand, } from "./schemas/message-utils";
33
+ export { buildMessageContent, chatErrorForDisplay, contentPreview, extractTextAttachments, getFileParts, getImageParts, getTextContent, groupMessagesByLoop, isHiddenInternalMessage, normalizeMessageContent, transformSlashCommand, } from "./schemas/message-utils";
34
+ export { contextProjectionData, getContextDisplayState, getContextGroupDisplayState, groupAdjacentContextRuns, } from "./schemas/context";
35
+ export type { ContextAction, ContextDisplayState, ContextGroupDisplayState, ContextProjectionData, ContextProjectionFields, ContextSourceInfo, } from "./schemas/context";
27
36
  export type { ParsedTextAttachment, ParsedTextContext, SkillMentionAvailability, } from "./schemas/message-utils";
28
37
  export type { ContentBlock, FinalArtifact, MemoryRef, PatchEnvelope, PostChatFollowup, TurnProjection, } from "./schemas/projection";
29
38
  export { latestPostChatFollowup } from "./schemas/projection-utils";
39
+ export { prependOlder, replaceWindow } from "./session/history-page";
40
+ export type { LiveRevisionState } from "./session/history-page";
30
41
  export { DEFAULT_REPLAY_SPEED } from "./schemas/session";
31
42
  export { SessionInfo, SessionStatus } from "./schemas/session";
32
43
  export type { ModeId, PrimarySkillParallelMode, PrimarySkillSnapshot, ReplayPreview, ReplaySpeed, ReplayState, SessionDetail, SessionPortMapping, PublishedSolutionRef, TemplateId, } from "./schemas/session";
@@ -34,7 +45,7 @@ export { LayoutType } from "./schemas/solution";
34
45
  export type { BizRole, Solution, SolutionAppField, SolutionAppState, SolutionAppUiConfig, } from "./schemas/solution";
35
46
  export { Task, TaskStatus } from "./schemas/task";
36
47
  export type { BackgroundTask, BackgroundTaskStopResult } from "./schemas/background";
37
- export { acceptedPostChatFollowupCompletesLatestRun, ClientProjectionBuilder } from "./shared/projection";
48
+ export { acceptedPostChatFollowupCompletesLatestRun, acknowledgeTurnEvents, ClientProjectionBuilder, } from "./shared/projection";
38
49
  export type { RawEvent } from "./shared/projection";
39
50
  export { createSocket } from "./socket";
40
51
  export type { CreateSocketOptions, TypedSocket } from "./socket";