@blade-hq/agent-client 2612.0.0-beta.76 → 2612.0.0-beta.78

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
@@ -1,5 +1,7 @@
1
1
  # @blade-hq/agent-client
2
2
 
3
+ 百变包的记录 API 与隔离页面桥见 [Pack pages](docs/pack-pages.md)。
4
+
3
5
  Blade Agent 的框架无关客户端。浏览器和 Node.js 都能用;用 Vue、Svelte 或自建 UI 的团队直接用这个包,React 团队一般用上层的 `@blade-hq/agent-react`。
4
6
 
5
7
  它做三件事:
@@ -832,6 +834,7 @@ chat.renderers = {
832
834
 
833
835
  - **客户端与登录**:`BladeClient`、`BladeClientOptions`、`UploadProgress`、`BladeApiError`、`LoginOptions`、`LoginResult`、`TokenStorageMode`、`AuthResource`、`ExchangeCodeParams`、`ExchangeCodeResult`、`ProvidersResponse`、`UserInfo`
834
836
  - **SDK 身份**:`SDK_NAME`、`SDK_VERSION`
837
+ - **百变包与共享数据**:`ProfileResource`、`PacksResource`、`PackRecordsResource`、`PackProfile`、`ProfileComponent`、`PackManifest`、`PackLayoutOperation`、`InstalledPack`、`PackRecord`、`PackRecordQuery`;隔离页面宿主使用 `attachPackPageBridge`,协议与生命周期见 [Pack pages](docs/pack-pages.md)。
835
838
  - **实时会话**:`AgentSession`、`AgentSessionError`、`AgentSessionEvents`、`AgentSessionEventName`、`SessionState`、`WorkflowRunState`、`WorkflowRunEntry`(`SessionState.workflowRuns` 的形态)、`ConnectionStatus`、`SendOptions`、`AttachAppOptions`、`AskUserAnswerData`、`AgentLoopInfo`、`ActiveCompactionState`、`ReplaySnapshot`
836
839
  - **声明式会话**:`SessionDefinition`、`SolutionDefinition`、`SkillDefinition`、`SkillFile`、`SessionConfig`、`TextFile`、`SessionSetupError`、`SessionSetupStage`
837
840
  - **会话消息队列**:`SessionQueueSnapshot`、`QueuedMessage`、`QueuedMessageStatus`、`QueueOperationResult`
@@ -1070,3 +1073,24 @@ session.prepareSend("继续处理", {
1070
1073
  (`update_format: "snapshot"` 或 `"diff"`)。可靠请求重试应复用原 `requestId`,不能换 ID 重发。
1071
1074
 
1072
1075
  BA 默认提供内置定时任务。应用自行管理定时安排时,可在声明式会话的 `config.disableTools`(或 SDK profile 的 `disableTools`)传入 `["platform:schedule"]`;底层创建与配置更新请求使用 `disable_tools: ["platform:schedule"]`。该配置隐藏 BA 定时工具并阻止调用,不影响应用自己的定时安排,也不会停止已有 BA 任务。
1076
+
1077
+ ### 连接器说明书与使用规则
1078
+
1079
+ `client.connectors.guide(name)` 读取当前可用连接器的说明书;传第二参数 `"first-connection"` 读取首次引导小节。可传第三参数 `{signal}` 取消读取。断开后不可读。
1080
+
1081
+ `client.connectors.rules(name)` 返回 `ConnectorRules`,其中 `groups` 为 `ConnectorRuleGroup[]`;`ConnectorRuleValue` 为 `"allow" | "ask" | "off"`。使用 `client.connectors.updateRules(name, {send: "off"})` 按组部分更新,返回最新完整视图;恢复默认时提交该组的 `default`。设置按当前用户跨会话保存,不改变服务授权。
1082
+
1083
+ 关闭后调用立即被拒绝,本轮搜索缓存允许保留,下一轮执行反映新设置。“问我”由工具描述提示先征得用户同意,不产生平台审批暂停。未知组或无效值会拒绝整个更新。
1084
+
1085
+ ### 连接器推送设置
1086
+
1087
+ `client.connectors.pushSettings(name)` 返回 `ConnectorPushSettingsResult`:`available:false` 是未配置服务或未绑定托管连接等正常能力缺失;`available:true` 包含 `ConnectorPushSettings`。其中每条 `ConnectorPushSetting` 的 `options` 由服务提供,界面按返回值展示;`next_push_at` 只是预计汇总窗口截止,不保证送达,实时档不展示汇总时间。
1088
+
1089
+ `client.connectors.setPushSettings(name, {group_digest: "1h"}, {expectedConnectionId})` 部分更新频率;飞书也可独立提交 `{ack_reaction:true}`,省略字段保持原值。`ack_reaction_available` 只读,表示机器人回应表情的能力,false仍可保存偏好。开关只适用于私聊机器人/群@机器人,由网关以机器人身份先回表情,不改用户授权或工具规则。凭据由BA保存,宿主通过BladeClient调用。
1090
+
1091
+ ### 百变包与界面清单
1092
+
1093
+ `client.profile.get()` 读取服务端合成的账号清单;宿主按 `regions` 选择自己支持的组件,不在浏览器里重新叠加布局。`client.profile.onChanged(refresh)` 返回取消订阅函数,并在重连后通知宿主刷新。`client.packs.list()`、`enable(name)`、`disable(name)` 和 `reset()` 管理当前账号的百变包,`file(name, path)` 使用同一鉴权身份读取已启用包的页面。包页面由宿主使用隔离 iframe 承载。内置 Web 提供页面与设置入口,扩展和嵌入 SDK 暂不显示包页面。
1094
+
1095
+
1096
+ `ProfileResource` 与 `PacksResource` 分别提供上述清单和包操作;`PackProfile`、`ProfileComponent` 描述最终界面,`PackManifest`、`PackLayoutOperation` 和 `InstalledPack` 描述保存/安装的数据形状。完整字段见同目录生成的 `public-api.md` 与 `src/resources/profile.ts`。
@@ -3,6 +3,7 @@ import { SandboxResource } from "./resources/sandbox";
3
3
  import { ToolProvider, type ToolProviderOptions } from "./tool-provider";
4
4
  import { type LoginOptions, type LoginResult, type TokenStorageMode } from "./auth-login";
5
5
  import { type BladeFetchInit, type HttpMethod } from "./rest";
6
+ import { ProfileResource, PacksResource } from "./resources/profile";
6
7
  import { AuthResource } from "./resources/auth";
7
8
  import { HeadlessResource } from "./resources/headless";
8
9
  import { ComputersResource } from "./resources/computers";
@@ -51,6 +52,8 @@ export declare class BladeClient {
51
52
  private readonly socketReplacementListeners;
52
53
  private runtimeToken;
53
54
  readonly options: BladeClientOptions;
55
+ readonly profile: ProfileResource;
56
+ readonly packs: PacksResource;
54
57
  readonly sandbox: SandboxResource;
55
58
  readonly auth: AuthResource;
56
59
  readonly headless: HeadlessResource;
@@ -227,7 +227,7 @@ var ToolProvider = class {
227
227
 
228
228
  // src/version.ts
229
229
  var SDK_NAME = "agent-client";
230
- var SDK_VERSION = true ? "2612.0.0-beta.76" : "1.1.1";
230
+ var SDK_VERSION = true ? "2612.0.0-beta.78" : "1.1.1";
231
231
 
232
232
  // src/auth-login.ts
233
233
  function isAuthCallbackMessage(value) {
@@ -355,6 +355,119 @@ async function loginWithPopup(client, options = {}) {
355
355
  });
356
356
  }
357
357
 
358
+ // src/resources/pack-records.ts
359
+ var PackRecordsResource = class {
360
+ constructor(client) {
361
+ this.client = client;
362
+ }
363
+ client;
364
+ list(pack, collection, query = {}, init) {
365
+ const params = new URLSearchParams();
366
+ if (query.filter) params.set("filter", JSON.stringify(query.filter));
367
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
368
+ if (query.offset !== void 0) params.set("offset", String(query.offset));
369
+ return this.client.jsonFromInit(`${this.path(pack, collection)}?${params}`, init);
370
+ }
371
+ upsert(pack, collection, data, id) {
372
+ return this.client.json("POST", this.path(pack, collection), { id, data });
373
+ }
374
+ delete(pack, collection, id) {
375
+ return this.client.json("DELETE", `${this.path(pack, collection)}/${encodeURIComponent(id)}`);
376
+ }
377
+ /** Events are invalidations. Refresh the list on reconnect as well. */
378
+ onChanged(pack, collection, listener) {
379
+ let socket = this.client.socket();
380
+ const changed = (value) => {
381
+ if (value.pack === pack && value.collection === collection) listener();
382
+ };
383
+ const bind = () => {
384
+ socket.on("pack:records_changed", changed);
385
+ socket.on("connect", listener);
386
+ };
387
+ const unbind = () => {
388
+ socket.off("pack:records_changed", changed);
389
+ socket.off("connect", listener);
390
+ };
391
+ bind();
392
+ const off = this.client.onSocketReplaced(() => {
393
+ unbind();
394
+ socket = this.client.socket();
395
+ bind();
396
+ listener();
397
+ });
398
+ return () => {
399
+ off();
400
+ unbind();
401
+ };
402
+ }
403
+ path(pack, collection) {
404
+ return `/api/packs/${encodeURIComponent(pack)}/records/${encodeURIComponent(collection)}`;
405
+ }
406
+ };
407
+
408
+ // src/resources/profile.ts
409
+ var ProfileResource = class {
410
+ constructor(client) {
411
+ this.client = client;
412
+ }
413
+ client;
414
+ get(init) {
415
+ return this.client.jsonFromInit("/api/profile", init);
416
+ }
417
+ /** Also refresh after reconnect, since changes may have happened offline. */
418
+ onChanged(listener) {
419
+ let socket = this.client.socket();
420
+ const bind = () => {
421
+ socket.on("profile:changed", listener);
422
+ socket.on("connect", listener);
423
+ };
424
+ const unbind = () => {
425
+ socket.off("profile:changed", listener);
426
+ socket.off("connect", listener);
427
+ };
428
+ bind();
429
+ const off = this.client.onSocketReplaced(() => {
430
+ unbind();
431
+ socket = this.client.socket();
432
+ bind();
433
+ listener();
434
+ });
435
+ return () => {
436
+ off();
437
+ unbind();
438
+ };
439
+ }
440
+ };
441
+ var PacksResource = class {
442
+ constructor(client) {
443
+ this.client = client;
444
+ this.records = new PackRecordsResource(client);
445
+ }
446
+ client;
447
+ records;
448
+ sessionByTag(name, tag, init) {
449
+ return this.client.jsonFromInit(`/api/packs/${encodeURIComponent(name)}/sessions/by-tag?${new URLSearchParams({ tag })}`, init);
450
+ }
451
+ list() {
452
+ return this.client.json("GET", "/api/packs");
453
+ }
454
+ save(manifest, files = {}) {
455
+ return this.client.json("POST", "/api/packs", { manifest, files });
456
+ }
457
+ enable(name) {
458
+ return this.client.json("POST", `/api/packs/${encodeURIComponent(name)}/enable`);
459
+ }
460
+ disable(name) {
461
+ return this.client.json("POST", `/api/packs/${encodeURIComponent(name)}/disable`);
462
+ }
463
+ reset() {
464
+ return this.client.json("POST", "/api/packs/reset");
465
+ }
466
+ file(name, path, init) {
467
+ return this.client.textFromInit(`/api/packs/${encodeURIComponent(name)}/files/${path.split("/").map(encodeURIComponent).join("/")}`, init);
468
+ }
469
+ };
470
+
358
471
  // src/resources/auth.ts
359
472
  var AuthResource = class {
360
473
  constructor(client) {
@@ -498,6 +611,24 @@ function normalizeContextAttachments(value) {
498
611
  return Array.isArray(value) ? value : [];
499
612
  }
500
613
 
614
+ // src/shared/pack-events.ts
615
+ function packEventNotification(source) {
616
+ if (!isRecord(source) || typeof source.pack !== "string" || !source.pack || typeof source.event_id !== "string" || !source.event_id || typeof source.title !== "string") return null;
617
+ return { type: "system_notification", content: {
618
+ notification_type: "pack:event",
619
+ status: "received",
620
+ title: `\u6765\u81EA\u300E${source.title}\u300F\u7684\u4E8B\u4EF6`,
621
+ detail: null,
622
+ metadata: source
623
+ } };
624
+ }
625
+ function packEventTitle(message) {
626
+ for (const block of message.blocks ?? []) {
627
+ if (block.type === "system_notification" && isRecord(block.content) && block.content.notification_type === "pack:event" && typeof block.content.title === "string") return block.content.title;
628
+ }
629
+ return null;
630
+ }
631
+
501
632
  // src/schemas/plugin-refs.ts
502
633
  function normalizePluginRefs(value) {
503
634
  if (!Array.isArray(value)) return [];
@@ -1790,6 +1921,8 @@ var ClientProjectionBuilder = class {
1790
1921
  if (payload.start_reason === "background-completion") {
1791
1922
  turn.blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
1792
1923
  }
1924
+ const packEvent = packEventNotification(payload.pack_event);
1925
+ if (packEvent) turn.blocks.push(packEvent);
1793
1926
  this.latestTurns.set("root", turn);
1794
1927
  return [{ kind: "upsert", turn }];
1795
1928
  }
@@ -2452,6 +2585,8 @@ function projectHistory(entries) {
2452
2585
  if (role === "user" && message._start_reason === "background-completion") {
2453
2586
  blocks.push({ type: "system_notification", content: { notification_type: "bg:wakeup" } });
2454
2587
  }
2588
+ const packEvent = role === "user" ? packEventNotification(message._pack_event) : null;
2589
+ if (packEvent) blocks.push(packEvent);
2455
2590
  const turn = {
2456
2591
  id,
2457
2592
  sequence: ++sequence,
@@ -3286,7 +3421,7 @@ function sortPhones(phones) {
3286
3421
  });
3287
3422
  }
3288
3423
  function phoneSerialLabel(phone) {
3289
- return phone.serial.trim();
3424
+ return (phone.serial ?? phone.machine_id ?? phone.id ?? "").trim();
3290
3425
  }
3291
3426
  var PhonesResource = class {
3292
3427
  constructor(client) {
@@ -3390,6 +3525,15 @@ var ConnectorsResource = class {
3390
3525
  this.client = client;
3391
3526
  }
3392
3527
  client;
3528
+ rules(name) {
3529
+ return this.client.json("GET", `/api/connectors/${encodeURIComponent(name)}/rules`);
3530
+ }
3531
+ updateRules(name, set) {
3532
+ return this.client.json("PUT", `/api/connectors/${encodeURIComponent(name)}/rules`, { set });
3533
+ }
3534
+ guide(name, section, init) {
3535
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/guide${section ? `?section=${encodeURIComponent(section)}` : ""}`, init);
3536
+ }
3393
3537
  /** Stage an explicit attachment in the current user's SW connection. Reuse requestId on retry. */
3394
3538
  async uploadFile(name, file, fileName, requestId) {
3395
3539
  const form = new FormData();
@@ -3402,6 +3546,17 @@ var ConnectorsResource = class {
3402
3546
  downloadFile(name, artifactId) {
3403
3547
  return this.client.blob("GET", `/api/connectors/${encodeURIComponent(name)}/files/${encodeURIComponent(artifactId)}`);
3404
3548
  }
3549
+ pushSettings(name, init) {
3550
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/push-settings`, { ...init, method: "GET" });
3551
+ }
3552
+ setPushSettings(name, changes, init) {
3553
+ const query = init?.expectedConnectionId ? `?expected_connection_id=${encodeURIComponent(init.expectedConnectionId)}` : "";
3554
+ return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/push-settings${query}`, {
3555
+ ...init,
3556
+ method: "PUT",
3557
+ body: JSON.stringify(changes)
3558
+ });
3559
+ }
3405
3560
  authorization(name, init) {
3406
3561
  return this.client.jsonFromInit(`/api/connectors/${encodeURIComponent(name)}/authorization`, init);
3407
3562
  }
@@ -3982,7 +4137,19 @@ var SessionsResource = class {
3982
4137
  items: index.items.map((item) => ({
3983
4138
  entryId: item.entry_id,
3984
4139
  preview: item.preview,
3985
- createdAt: item.created_at
4140
+ recaption: item.recaption,
4141
+ artifacts: item.artifacts?.map((artifact) => ({
4142
+ kind: artifact.kind === "link" ? "link" : "file",
4143
+ target: artifact.target,
4144
+ label: artifact.label
4145
+ })),
4146
+ createdAt: item.created_at,
4147
+ entries: item.entries?.map((entry) => ({
4148
+ entryId: entry.entry_id,
4149
+ preview: entry.preview,
4150
+ createdAt: entry.created_at,
4151
+ answer: entry.answer
4152
+ }))
3986
4153
  }))
3987
4154
  };
3988
4155
  }
@@ -4762,6 +4929,7 @@ function toQueuedMessage(value) {
4762
4929
  updated_at: value.updated_at
4763
4930
  };
4764
4931
  if (typeof value.target_run_id === "string") item.target_run_id = value.target_run_id;
4932
+ if (typeof value.next_turn_only === "boolean") item.next_turn_only = value.next_turn_only;
4765
4933
  if (typeof value.error === "string") item.error = value.error;
4766
4934
  return item;
4767
4935
  }
@@ -4843,7 +5011,7 @@ function canCancelQueuedMessage(item) {
4843
5011
  return item.status === "pending";
4844
5012
  }
4845
5013
  function canDeliverQueuedMessage(item) {
4846
- return item.status === "pending";
5014
+ return item.status === "pending" && !item.next_turn_only;
4847
5015
  }
4848
5016
  var QUEUED_MESSAGE_STATUS_LABELS = {
4849
5017
  pending: "\u5F85\u6267\u884C",
@@ -8243,6 +8411,8 @@ var BladeClient = class _BladeClient {
8243
8411
  socketReplacementListeners = /* @__PURE__ */ new Set();
8244
8412
  runtimeToken = void 0;
8245
8413
  options;
8414
+ profile;
8415
+ packs;
8246
8416
  sandbox;
8247
8417
  auth;
8248
8418
  headless;
@@ -8271,6 +8441,8 @@ var BladeClient = class _BladeClient {
8271
8441
  ...options,
8272
8442
  baseUrl: normalizeBaseUrl(options.baseUrl)
8273
8443
  };
8444
+ this.profile = new ProfileResource(this);
8445
+ this.packs = new PacksResource(this);
8274
8446
  this.sandbox = new SandboxResource(this);
8275
8447
  this.auth = new AuthResource(this);
8276
8448
  this.headless = new HeadlessResource(this);
@@ -9344,13 +9516,90 @@ function normalizeOptionItem(value) {
9344
9516
  };
9345
9517
  }
9346
9518
 
9519
+ // src/pack-page-bridge.ts
9520
+ function attachPackPageBridge(options) {
9521
+ const { client, frame, pack, collections, openSession } = options;
9522
+ const host = options.host ?? window;
9523
+ const controller = new AbortController();
9524
+ const subscriptions = /* @__PURE__ */ new Map();
9525
+ const send = (value) => {
9526
+ if (!controller.signal.aborted) frame.postMessage(value, "*");
9527
+ };
9528
+ const changed = (collection) => send({ type: "blade:pack:records_changed", collection });
9529
+ const receive = async (event) => {
9530
+ if (event.source !== frame || controller.signal.aborted) return;
9531
+ const request = event.data;
9532
+ if (!request || typeof request !== "object") return;
9533
+ const { type: type2, id, method, params } = request;
9534
+ if (type2 !== "blade:pack:request" || typeof id !== "string" || !id || id.length > 128) return;
9535
+ const reply = (result) => send({ type: "blade:pack:response", id, result });
9536
+ try {
9537
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548");
9538
+ const input = params;
9539
+ if (method === "session.openByTag") {
9540
+ if (typeof input.tag !== "string" || !input.tag || input.tag.length > 256) throw new Error("\u6848\u4EF6\u6807\u8BB0\u65E0\u6548");
9541
+ const result = await client.packs.sessionByTag(pack, input.tag, { signal: controller.signal });
9542
+ if (controller.signal.aborted) return;
9543
+ reply(result);
9544
+ openSession(result.session_id);
9545
+ return;
9546
+ }
9547
+ if (typeof input.collection !== "string" || !collections.includes(input.collection)) throw new Error("\u6B64\u9875\u9762\u65E0\u6CD5\u8BBF\u95EE\u8BE5\u6570\u636E\u8868");
9548
+ const collection = input.collection;
9549
+ switch (method) {
9550
+ case "records.list": {
9551
+ const query = {};
9552
+ if (input.filter !== void 0) {
9553
+ if (!input.filter || typeof input.filter !== "object" || Array.isArray(input.filter) || Object.values(input.filter).some((v) => !["string", "number", "boolean"].includes(typeof v))) throw new Error("\u7B5B\u9009\u6761\u4EF6\u65E0\u6548");
9554
+ query.filter = input.filter;
9555
+ }
9556
+ for (const key of ["limit", "offset"]) {
9557
+ if (input[key] !== void 0) {
9558
+ if (typeof input[key] !== "number" || !Number.isInteger(input[key])) throw new Error("\u67E5\u8BE2\u8303\u56F4\u65E0\u6548");
9559
+ query[key] = input[key];
9560
+ }
9561
+ }
9562
+ reply(await client.packs.records.list(pack, collection, query, { signal: controller.signal }));
9563
+ return;
9564
+ }
9565
+ case "records.subscribe":
9566
+ if (!subscriptions.has(collection)) subscriptions.set(collection, client.packs.records.onChanged(pack, collection, () => changed(collection)));
9567
+ reply({ subscribed: true });
9568
+ changed(collection);
9569
+ return;
9570
+ case "records.unsubscribe":
9571
+ subscriptions.get(collection)?.();
9572
+ subscriptions.delete(collection);
9573
+ reply({ subscribed: false });
9574
+ return;
9575
+ default:
9576
+ throw new Error("\u6B64\u9875\u9762\u4E0D\u652F\u6301\u8BE5\u64CD\u4F5C");
9577
+ }
9578
+ } catch (error) {
9579
+ send({ type: "blade:pack:response", id, error: error instanceof Error ? error.message : "\u64CD\u4F5C\u6682\u65F6\u65E0\u6CD5\u5B8C\u6210" });
9580
+ }
9581
+ };
9582
+ host.addEventListener("message", receive);
9583
+ send({ type: "blade:pack:ready" });
9584
+ return () => {
9585
+ controller.abort();
9586
+ host.removeEventListener("message", receive);
9587
+ for (const off of subscriptions.values()) off();
9588
+ subscriptions.clear();
9589
+ };
9590
+ }
9591
+
9347
9592
  export {
9348
9593
  SandboxResource,
9349
9594
  BladeApiError,
9350
9595
  ToolProvider,
9351
9596
  SDK_NAME,
9352
9597
  SDK_VERSION,
9598
+ PackRecordsResource,
9599
+ ProfileResource,
9600
+ PacksResource,
9353
9601
  isRecord,
9602
+ packEventTitle,
9354
9603
  normalizePluginRefs,
9355
9604
  normalizeMessageRefs,
9356
9605
  normalizeTopicAssetRefs,
@@ -9440,6 +9689,7 @@ export {
9440
9689
  BladeClient,
9441
9690
  BladeApplicationClient,
9442
9691
  parseAskUserQuestion,
9443
- formatAskUserAnswer
9692
+ formatAskUserAnswer,
9693
+ attachPackPageBridge
9444
9694
  };
9445
- //# sourceMappingURL=chunk-TT3SAXSF.js.map
9695
+ //# sourceMappingURL=chunk-5KC2WZOP.js.map