@flowy-agent-store/client 0.1.0-beta.3 → 0.1.0-beta.4

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/dist/index.mjs CHANGED
@@ -237,6 +237,532 @@ var WebSocketTransport = class {
237
237
  }
238
238
  };
239
239
  //#endregion
240
+ //#region src/http-transport.ts
241
+ /**
242
+ * HTTP transport binding (doc `16` R2 / `05` §2.1.1).
243
+ *
244
+ * ## What this is
245
+ *
246
+ * The App Server exposes one method semantics over two bindings. This class is
247
+ * the **request/response** binding: it maps a protocol method name onto the
248
+ * server's hand-written REST route and returns the same result body the
249
+ * WebSocket binding would.
250
+ *
251
+ * ## What this is not
252
+ *
253
+ * - **No server push.** HTTP has no notification channel, so `onNotification`
254
+ * hands back a no-op unsubscribe and `notify` throws. Live conversation / run
255
+ * events and subscription methods (`conversation/subscribe`, `run/subscribe`)
256
+ * exist **only** over `WebSocketTransport`; an `HttpTransport` is not a
257
+ * drop-in replacement for it. Consumers that need events must connect over
258
+ * WS (or run both).
259
+ * - **One-shot handshake per call.** `05` §2.1.1: *each* HTTP call performs its
260
+ * own `POST /initialize` → `POST /initialized` → business call, after which
261
+ * the connection id expires. `connect()` therefore has nothing to hold open
262
+ * and is a no-op; it does not warm anything up.
263
+ * - **Host file services stay out.** `/api/fs/*` (browse / list / read /
264
+ * metadata) is a host file service on the server *root*, explicitly not a
265
+ * protocol method (`05` §2.1.1), so it is not reachable through this class.
266
+ *
267
+ * ## The route table
268
+ *
269
+ * Every entry was read out of the handler bodies in
270
+ * `crates/backend/nomifun-app-server/src/lib.rs` — the `source` field records
271
+ * which handler (and, where one exists, which shared `*_impl`) proves the two
272
+ * bindings run the same operation. Methods with no entry throw
273
+ * `TransportError("send", …)` instead of silently degrading.
274
+ */
275
+ /** Header the server mints the per-call connection id under. */
276
+ const CONNECTION_HEADER = "x-app-server-connection-id";
277
+ /** Protocol version this binding announces on the one-shot handshake. */
278
+ const PROTOCOL_VERSION = "fp-1";
279
+ /**
280
+ * Protocol method → REST route. Verified from handler bodies, not from the
281
+ * route list (a route existing does not prove which method it mirrors).
282
+ */
283
+ const HTTP_ROUTES = {
284
+ ping: {
285
+ verb: "POST",
286
+ path: "/ping",
287
+ source: "ping() -> registry.require_ready"
288
+ },
289
+ "workspace/list": {
290
+ verb: "GET",
291
+ path: "/workspaces",
292
+ source: "workspace_list() -> owner-scoped active rows"
293
+ },
294
+ "workspace/revoke": {
295
+ verb: "DELETE",
296
+ path: "/workspaces/:workspace_id",
297
+ source: "workspace_delete() -> workspace_revoke_impl (shared with the WS arm)"
298
+ },
299
+ "conversation/create": {
300
+ verb: "POST",
301
+ path: "/conversations",
302
+ source: "conversation_create() -> create_conversation_for_user (shared)"
303
+ },
304
+ "conversation/list": {
305
+ verb: "GET",
306
+ path: "/conversations",
307
+ query: ["limit"],
308
+ source: "conversation_list() -> list_app_server_chats (shared); Query<limit>"
309
+ },
310
+ "conversation/get": {
311
+ verb: "GET",
312
+ path: "/conversations/:conversation_id",
313
+ source: "conversation_get() -> project_conversation_view (shared)"
314
+ },
315
+ "conversation/delete": {
316
+ verb: "DELETE",
317
+ path: "/conversations/:conversation_id",
318
+ source: "conversation_delete() -> conversation/delete arm semantics"
319
+ },
320
+ "conversation/messages": {
321
+ verb: "GET",
322
+ path: "/conversations/:conversation_id/messages",
323
+ query: [
324
+ "page",
325
+ "page_size",
326
+ "cursor"
327
+ ],
328
+ source: "conversation_messages() -> list_conversation_messages_for_user (shared)"
329
+ },
330
+ "conversation/send": {
331
+ verb: "POST",
332
+ path: "/conversations/:conversation_id/messages",
333
+ body: [
334
+ "content",
335
+ "idempotency_key",
336
+ "attachments"
337
+ ],
338
+ source: "conversation_send() -> send_conversation_message_for_user (shared with the WS arm)"
339
+ },
340
+ "conversation/cancel": {
341
+ verb: "POST",
342
+ path: "/conversations/:conversation_id/cancel",
343
+ source: "conversation_cancel() -> cancel arm semantics"
344
+ },
345
+ "agent/run": {
346
+ verb: "POST",
347
+ path: "/agent/run",
348
+ source: "agent_run() -> same request/receipt as the `agent/run` arm"
349
+ },
350
+ "team/run": {
351
+ verb: "POST",
352
+ path: "/team/run",
353
+ source: "team_run() -> execute_team_run() (same as the WS arm); Leader Conversation + planned delegation, `TeamRunReceipt`"
354
+ },
355
+ "run/get": {
356
+ verb: "GET",
357
+ path: "/run/:run_id",
358
+ source: "run_get()"
359
+ },
360
+ "run/result": {
361
+ verb: "GET",
362
+ path: "/run/:run_id/result",
363
+ source: "run_result()"
364
+ },
365
+ "run/plan": {
366
+ verb: "GET",
367
+ path: "/run/:run_id/plan",
368
+ source: "run_plan() -> get_run_plan_for_user() (same as the WS arm)"
369
+ },
370
+ "run/events": {
371
+ verb: "GET",
372
+ path: "/run/:run_id/events",
373
+ query: ["after_sequence", "limit"],
374
+ source: "run_events() -> runtime.list_events(after_sequence, limit) (same as the WS arm)"
375
+ },
376
+ "run/cancel": {
377
+ verb: "POST",
378
+ path: "/run/:run_id/cancel",
379
+ body: [
380
+ "expected_version",
381
+ "reason",
382
+ "idempotency_key"
383
+ ],
384
+ source: "run_cancel() -> same CancelRunRequest as the WS arm"
385
+ },
386
+ "run/steer": {
387
+ verb: "POST",
388
+ path: "/run/:run_id/steer",
389
+ body: [
390
+ "text",
391
+ "expected_version",
392
+ "command_id",
393
+ "idempotency_key"
394
+ ],
395
+ source: "run_steer() -> execute_steer_run (shared with the WS arm)"
396
+ },
397
+ "run/answer-decision": {
398
+ verb: "POST",
399
+ path: "/run/:run_id/answer-decision",
400
+ body: [
401
+ "step_id",
402
+ "attempt_id",
403
+ "answer",
404
+ "expected_execution_version",
405
+ "expected_step_version",
406
+ "expected_attempt_version"
407
+ ],
408
+ source: "run_answer_decision() -> execute_answer_decision (shared with the WS arm; engine answer gate, no always_allow)"
409
+ },
410
+ "skill/list": {
411
+ verb: "GET",
412
+ path: "/skills",
413
+ source: "list_skills_route() -> list_skills_impl"
414
+ },
415
+ "skill/get": {
416
+ verb: "GET",
417
+ path: "/skills/:skill_id",
418
+ source: "get_skill_route() -> get_skill_impl"
419
+ },
420
+ "skill/files": {
421
+ verb: "GET",
422
+ path: "/skills/:skill_id/files",
423
+ source: "list_skill_files_route() -> list_skill_files_impl"
424
+ },
425
+ "connector/list": {
426
+ verb: "GET",
427
+ path: "/connectors",
428
+ source: "list_connectors_route() -> list_connectors_impl"
429
+ },
430
+ "models/list": {
431
+ verb: "GET",
432
+ path: "/models",
433
+ source: "list_models_route() -> list_models_impl"
434
+ },
435
+ "connector/get": {
436
+ verb: "GET",
437
+ path: "/connectors/:connector_id",
438
+ source: "get_connector_route() -> get_connector_impl"
439
+ },
440
+ "connector/status": {
441
+ verb: "GET",
442
+ path: "/connectors/:connector_id/status",
443
+ source: "connector_status_route() -> connector_status_impl"
444
+ },
445
+ "connector/test": {
446
+ verb: "POST",
447
+ path: "/connectors/:connector_id/test",
448
+ source: "connector_test_route() -> connector_test_impl"
449
+ },
450
+ "connector/call": {
451
+ verb: "POST",
452
+ path: "/connectors/:connector_id/call",
453
+ source: "connector_call_route() -> connector_call_impl"
454
+ },
455
+ "connector/auth/start": {
456
+ verb: "POST",
457
+ path: "/connectors/:connector_id/auth-start",
458
+ source: "connector_auth_start_route() -> connector_auth_start_impl (WS name uses slashes)"
459
+ },
460
+ "connector/auth/status": {
461
+ verb: "GET",
462
+ path: "/connectors/:connector_id/auth-status",
463
+ source: "connector_auth_status_route() -> connector_auth_status_impl"
464
+ },
465
+ "connector/auth/logout": {
466
+ verb: "POST",
467
+ path: "/connectors/:connector_id/auth-logout",
468
+ source: "connector_auth_logout_route() -> connector_auth_logout_impl"
469
+ },
470
+ "import/run": {
471
+ verb: "POST",
472
+ path: "/imports",
473
+ source: "run_import_route() -> run_import_impl"
474
+ },
475
+ "import/list": {
476
+ verb: "GET",
477
+ path: "/imports",
478
+ source: "list_imports_route() -> list_imports_impl"
479
+ },
480
+ "import/get": {
481
+ verb: "GET",
482
+ path: "/imports/:snapshot_id",
483
+ source: "get_import_route() -> get_import_impl"
484
+ },
485
+ "install/run": {
486
+ verb: "POST",
487
+ path: "/installs",
488
+ source: "run_install_route() -> install_impl"
489
+ },
490
+ "install/status": {
491
+ verb: "GET",
492
+ path: "/installs/:snapshot_id",
493
+ source: "install_status_route() -> install_status_impl"
494
+ },
495
+ "install/disable": {
496
+ verb: "POST",
497
+ path: "/installs/:snapshot_id/disable",
498
+ body: ["component_ids"],
499
+ source: "install_disable_route() -> install_disable_impl; body `component_ids`"
500
+ },
501
+ "install/enable": {
502
+ verb: "POST",
503
+ path: "/installs/:snapshot_id/enable",
504
+ body: ["component_ids"],
505
+ source: "install_enable_route() -> install_enable_impl; body `component_ids`"
506
+ },
507
+ "install/uninstall": {
508
+ verb: "POST",
509
+ path: "/installs/:snapshot_id/uninstall",
510
+ body: ["component_ids"],
511
+ source: "install_uninstall_route() -> install_uninstall_impl; body `component_ids`"
512
+ },
513
+ "market/add": {
514
+ verb: "POST",
515
+ path: "/markets",
516
+ source: "market_add_route() -> market_add_impl"
517
+ },
518
+ "market/list": {
519
+ verb: "GET",
520
+ path: "/markets",
521
+ source: "market_list_route() -> market_list_impl"
522
+ },
523
+ "market/get": {
524
+ verb: "GET",
525
+ path: "/markets/:marketplace_id",
526
+ source: "market_get_route() -> market_get_impl"
527
+ },
528
+ "market/remove": {
529
+ verb: "POST",
530
+ path: "/markets/:marketplace_id/remove",
531
+ body: ["cascade"],
532
+ source: "market_remove_route() -> market_remove_impl; body `cascade` defaults to true"
533
+ },
534
+ "market/auto-update": {
535
+ verb: "POST",
536
+ path: "/markets/:marketplace_id/auto-update",
537
+ body: ["enabled"],
538
+ source: "market_auto_update_route() -> market_auto_update_impl; body `enabled` defaults to true"
539
+ },
540
+ "market/refresh": {
541
+ verb: "POST",
542
+ path: "/markets/:marketplace_id/refresh",
543
+ source: "market_refresh_route() -> market_refresh_impl"
544
+ },
545
+ "market/entry-import": {
546
+ verb: "POST",
547
+ path: "/markets/:marketplace_id/entries/:entry_name/import",
548
+ source: "market_entry_import_route() -> market_entry_import_impl"
549
+ },
550
+ "store/list": {
551
+ verb: "GET",
552
+ path: "/store",
553
+ source: "store_list_route() -> store_list_impl"
554
+ },
555
+ "store/install-entry": {
556
+ verb: "POST",
557
+ path: "/store/:marketplace_id/entries/:entry_name/install",
558
+ source: "store_install_entry_route() -> store_install_entry_impl"
559
+ }
560
+ };
561
+ /** Methods that are WebSocket-only by design — named so the error explains itself. */
562
+ const WS_ONLY_METHODS = /* @__PURE__ */ new Set([
563
+ "initialize",
564
+ "initialized",
565
+ "conversation/subscribe",
566
+ "conversation/unsubscribe",
567
+ "run/subscribe",
568
+ "run/unsubscribe"
569
+ ]);
570
+ var HttpTransport = class {
571
+ routes;
572
+ options;
573
+ closed = false;
574
+ constructor(options, routes = HTTP_ROUTES) {
575
+ this.options = options;
576
+ this.routes = routes;
577
+ }
578
+ /**
579
+ * No-op: the HTTP binding handshakes per call (`05` §2.1.1), so there is no
580
+ * connection to open. Kept for `Transport` compatibility.
581
+ */
582
+ async connect() {
583
+ this.closed = false;
584
+ }
585
+ /**
586
+ * Perform one business call over its own handshake.
587
+ *
588
+ * Throws `TransportError("send", …)` for a method with no HTTP binding —
589
+ * never a silent fallback to another binding.
590
+ */
591
+ async request(method, params) {
592
+ if (this.closed) throw new TransportError("connect", "http transport is closed");
593
+ const route = this.routes[method];
594
+ if (!route) {
595
+ const reason = WS_ONLY_METHODS.has(method) ? `"${method}" is WebSocket-only (doc 05 §2.1.1); use WebSocketTransport for subscriptions and live events` : `"${method}" has no HTTP binding in this SDK (doc 16 R2 route table)`;
596
+ throw new TransportError("send", reason);
597
+ }
598
+ const { path, query, body } = this.splitParams(route, params);
599
+ const connectionId = await this.openConnection();
600
+ const response = await this.fetchWithTimeout(route.verb, path, {
601
+ query,
602
+ body,
603
+ connectionId
604
+ });
605
+ return await this.readResult(response, method);
606
+ }
607
+ /**
608
+ * Not supported: HTTP carries no server-push. Throws instead of pretending.
609
+ */
610
+ notify(method, _params) {
611
+ throw new TransportError("send", `HTTP binding cannot notify ("${method}"): notifications are WebSocket-only (doc 05 §2.1.1)`);
612
+ }
613
+ /**
614
+ * Returns a no-op unsubscribe: this binding receives **no** notifications.
615
+ *
616
+ * Not equivalent to the WebSocket binding — callers that need live events
617
+ * must use `WebSocketTransport` (or run both).
618
+ */
619
+ onNotification(_listener) {
620
+ return () => void 0;
621
+ }
622
+ /** No-op: every call is independent, so nothing is held open. */
623
+ close() {
624
+ this.closed = true;
625
+ }
626
+ /**
627
+ * One-shot handshake: `POST /initialize` (connection id header) →
628
+ * `POST /initialized`. Returns the connection id.
629
+ *
630
+ * Public because host-side services that sit *outside* the protocol surface
631
+ * (`/api/fs/*`, the HTTP-only `POST /workspaces` register route) still need a
632
+ * ready connection id; they are not protocol methods, so they cannot go
633
+ * through `request()`.
634
+ */
635
+ async openConnection() {
636
+ const connectionId = (await this.fetchWithTimeout("POST", "/initialize", { body: {
637
+ protocol_version: PROTOCOL_VERSION,
638
+ client: this.options.client ?? {
639
+ name: "flowy-agent-store-client",
640
+ version: "0.1.0"
641
+ },
642
+ ...this.options.capabilities === void 0 ? {} : { capabilities: this.options.capabilities }
643
+ } })).headers.get(CONNECTION_HEADER);
644
+ if (!connectionId) throw new TransportError("connect", `handshake response is missing the ${CONNECTION_HEADER} header`, { retryable: true });
645
+ await this.fetchWithTimeout("POST", "/initialized", { connectionId });
646
+ return connectionId;
647
+ }
648
+ splitParams(route, params) {
649
+ const source = isRecord(params) ? params : {};
650
+ const pathParams = [...route.path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]);
651
+ const path = route.path.replace(/:([A-Za-z0-9_]+)/g, (_full, name) => {
652
+ const value = source[name];
653
+ if (value === void 0 || value === null) throw new TransportError("send", `missing required path param "${name}" for ${route.verb} ${route.path}`);
654
+ return encodeURIComponent(String(value));
655
+ });
656
+ const query = {};
657
+ for (const key of route.query ?? []) {
658
+ const value = source[key];
659
+ if (value !== void 0 && value !== null) query[key] = String(value);
660
+ }
661
+ if (route.verb === "GET" || route.verb === "DELETE") return {
662
+ path,
663
+ query,
664
+ body: void 0
665
+ };
666
+ const carried = route.body ?? [];
667
+ const body = {};
668
+ for (const key of Object.keys(source)) {
669
+ if (pathParams.includes(key) || (route.query ?? []).includes(key)) continue;
670
+ if (carried.length > 0 && !carried.includes(key)) continue;
671
+ body[key] = source[key];
672
+ }
673
+ return {
674
+ path,
675
+ query,
676
+ body
677
+ };
678
+ }
679
+ async fetchWithTimeout(verb, path, request) {
680
+ const url = new URL(`${this.baseUrl()}${path}`);
681
+ for (const [key, value] of Object.entries(request.query ?? {})) url.searchParams.set(key, value);
682
+ const headers = { accept: "application/json" };
683
+ if (request.body !== void 0) headers["content-type"] = "application/json";
684
+ if (request.connectionId) headers[CONNECTION_HEADER] = request.connectionId;
685
+ if (this.options.token) headers.authorization = `Bearer ${this.options.token}`;
686
+ const controller = new AbortController();
687
+ const timeoutMs = this.options.requestTimeoutMs ?? 3e4;
688
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
689
+ try {
690
+ const fetchImpl = this.options.fetch ?? globalThis.fetch;
691
+ if (!fetchImpl) throw new TransportError("connect", "no fetch implementation available");
692
+ return await fetchImpl(url.toString(), {
693
+ method: verb,
694
+ headers,
695
+ body: request.body === void 0 ? void 0 : JSON.stringify(request.body),
696
+ signal: controller.signal
697
+ });
698
+ } catch (error) {
699
+ if (error instanceof TransportError) throw error;
700
+ const aborted = error?.name === "AbortError";
701
+ throw new TransportError("send", aborted ? `${verb} ${path} timed out after ${timeoutMs}ms` : `${verb} ${path} failed: ${String(error)}`, {
702
+ retryable: true,
703
+ cause: error
704
+ });
705
+ } finally {
706
+ clearTimeout(timer);
707
+ }
708
+ }
709
+ /** 2xx → result body; otherwise the server's wire error becomes an `AppServerError`. */
710
+ async readResult(response, method) {
711
+ let payload = void 0;
712
+ const text = await response.text();
713
+ if (text.length > 0) try {
714
+ payload = JSON.parse(text);
715
+ } catch {
716
+ if (response.ok) throw new TransportError("receive", `${method}: response is not JSON`, { retryable: true });
717
+ }
718
+ if (response.ok) return payload;
719
+ throw appServerErrorFromWire(payload, response.status, method);
720
+ }
721
+ baseUrl() {
722
+ return this.options.baseUrl.replace(/\/+$/, "").replace(/\/ws$/, "");
723
+ }
724
+ };
725
+ function isRecord(value) {
726
+ return typeof value === "object" && value !== null && !Array.isArray(value);
727
+ }
728
+ /**
729
+ * Turn an HTTP failure body into the SDK error model.
730
+ *
731
+ * Shared by this transport and by host-side helpers (webui `lib/client.ts`) so
732
+ * a second spelling of the wire-error mapping cannot drift. Two wire contracts
733
+ * reach this function, both of them `AppError` on the server:
734
+ *
735
+ * - the App Server emits `{code, message, retryable, details, request_id}`
736
+ * (`into_wire_error`), which is exactly the `AppServerError` shape;
737
+ * - the standalone host file service (`/api/fs/*`) emits the `ErrorResponse`
738
+ * envelope `{success: false, error, code, details?}` — same error, another
739
+ * spelling: `error` carries the human message, and there is no retry hint, so
740
+ * a 5xx status stays the retry signal.
741
+ *
742
+ * Anything else becomes a retryable-on-5xx `TransportError`.
743
+ */
744
+ function appServerErrorFromWire(payload, status, context = "request") {
745
+ if (isRecord(payload) && typeof payload.code === "string" && typeof payload.message === "string") return new AppServerError({
746
+ code: payload.code,
747
+ message: payload.message,
748
+ retryable: payload.retryable === true,
749
+ request_id: payload.request_id ?? null,
750
+ details: isRecord(payload.details) ? payload.details : {}
751
+ });
752
+ if (isRecord(payload) && payload.success === false && typeof payload.code === "string" && typeof payload.error === "string") return new AppServerError({
753
+ code: payload.code,
754
+ message: payload.error,
755
+ retryable: status >= 500,
756
+ request_id: null,
757
+ details: isRecord(payload.details) ? payload.details : {}
758
+ });
759
+ return new TransportError("receive", `${context}: HTTP ${status} without a wire error body`, { retryable: status >= 500 });
760
+ }
761
+ /** Exposed for tests and docs (R5): the verified method → route table. */
762
+ function httpRouteTable() {
763
+ return HTTP_ROUTES;
764
+ }
765
+ //#endregion
240
766
  //#region src/agents.ts
241
767
  var AgentClient = class {
242
768
  transport;
@@ -299,11 +825,19 @@ var ConversationClient = class {
299
825
  cursor: query.cursor
300
826
  });
301
827
  }
302
- send(conversationId, content, idempotencyKey) {
828
+ /**
829
+ * R15(W10):`attachments` 是**会话工作区内的绝对路径**(图片附件)。
830
+ *
831
+ * 缺省不传,保持老调用方的 wire 形状逐字不变;服务端只接受会话工作区内的真实
832
+ * 文件(越界 / 相对路径 / 不存在一律拒),具体准入见
833
+ * `nomifun-app-server` 的 `resolve_conversation_attachments`。
834
+ */
835
+ send(conversationId, content, idempotencyKey, attachments = []) {
303
836
  return this.transport.request("conversation/send", {
304
837
  conversation_id: conversationId,
305
838
  content,
306
- idempotency_key: idempotencyKey
839
+ idempotency_key: idempotencyKey,
840
+ ...attachments.length > 0 ? { attachments } : {}
307
841
  });
308
842
  }
309
843
  cancel(conversationId) {
@@ -312,35 +846,92 @@ var ConversationClient = class {
312
846
  delete(conversationId) {
313
847
  return this.transport.request("conversation/delete", { conversation_id: conversationId });
314
848
  }
315
- async follow(conversationId) {
849
+ /**
850
+ * Subscribe to one conversation's realtime stream (doc `16` R1).
851
+ *
852
+ * `options.fetchMessages` is what makes auto catch-up possible: a detected
853
+ * sequence gap or a `conversation/resync-required` triggers one transcript
854
+ * fetch whose result is handed to `onBackfill`. Conversations have no event
855
+ * replay API (`05` §「V1 不提供 after_cursor 事件追平」), so the transcript is
856
+ * the recovery medium — unlike Runs, where `run/events` replays the events
857
+ * themselves.
858
+ */
859
+ async follow(conversationId, options = {}) {
316
860
  await this.transport.request("conversation/subscribe", { conversation_id: conversationId });
317
- return new ConversationSubscription(this.transport, conversationId);
861
+ return new ConversationSubscription(this.transport, conversationId, {
862
+ fetchMessages: (id) => this.messages({
863
+ conversationId: id,
864
+ pageSize: 50
865
+ }),
866
+ ...options
867
+ });
318
868
  }
319
869
  };
870
+ /** Events held before the first listener attaches (see `pendingLimit`). */
871
+ const DEFAULT_PENDING_LIMIT = 256;
320
872
  var ConversationSubscription = class {
321
873
  transport;
322
874
  conversationId;
875
+ options;
323
876
  events = /* @__PURE__ */ new Set();
324
877
  resyncs = /* @__PURE__ */ new Set();
878
+ errors = /* @__PURE__ */ new Set();
879
+ backfills = /* @__PURE__ */ new Set();
325
880
  closed = false;
326
881
  lastSeenSequence = 0;
327
882
  removeListener;
328
- constructor(transport, conversationId) {
883
+ /**
884
+ * `follow()` resolves as soon as the server acknowledged the subscription,
885
+ * but the caller attaches listeners one tick later. Events landing in that
886
+ * window used to be dropped silently; they are held here (oldest first) and
887
+ * flushed to the first `onEvent` listener.
888
+ */
889
+ pending = [];
890
+ pendingDropped = 0;
891
+ backfillInFlight = null;
892
+ constructor(transport, conversationId, options = {}) {
329
893
  this.transport = transport;
330
894
  this.conversationId = conversationId;
895
+ this.options = options;
331
896
  this.removeListener = transport.onNotification((notification) => this.dispatch(notification));
332
897
  }
333
898
  get lastSequence() {
334
899
  return this.lastSeenSequence;
335
900
  }
901
+ /** Events dropped because nobody was listening and the buffer was full. */
902
+ get droppedPendingCount() {
903
+ return this.pendingDropped;
904
+ }
336
905
  onEvent(listener) {
337
906
  this.events.add(listener);
907
+ if (this.events.size === 1 && this.pending.length > 0) {
908
+ const queued = this.pending;
909
+ this.pending = [];
910
+ for (const event of queued) this.deliver(event);
911
+ }
338
912
  return () => this.events.delete(listener);
339
913
  }
340
914
  onResync(listener) {
341
915
  this.resyncs.add(listener);
342
916
  return () => this.resyncs.delete(listener);
343
917
  }
918
+ /**
919
+ * Auto catch-up result (R1). Fires only when `autoResync` is on and the
920
+ * transcript fetch succeeded; the listener owns replacing the transcript.
921
+ */
922
+ onBackfill(listener) {
923
+ this.backfills.add(listener);
924
+ return () => this.backfills.delete(listener);
925
+ }
926
+ /**
927
+ * Failures that used to be swallowed: the catch-up fetch, and a failed
928
+ * re-subscribe during `rearm()`. Listener isolation keeps one bad listener
929
+ * from hiding the error from the others.
930
+ */
931
+ onError(listener) {
932
+ this.errors.add(listener);
933
+ return () => this.errors.delete(listener);
934
+ }
344
935
  async close() {
345
936
  if (this.closed) return;
346
937
  this.closed = true;
@@ -348,6 +939,9 @@ var ConversationSubscription = class {
348
939
  this.removeListener = null;
349
940
  this.events.clear();
350
941
  this.resyncs.clear();
942
+ this.errors.clear();
943
+ this.backfills.clear();
944
+ this.pending = [];
351
945
  try {
352
946
  await this.transport.request("conversation/unsubscribe", { conversation_id: this.conversationId });
353
947
  } catch {}
@@ -355,35 +949,99 @@ var ConversationSubscription = class {
355
949
  /**
356
950
  * Re-arm after a reconnect (docs/agent-store/16 T8): re-register the
357
951
  * notification listener, reset the cursor and re-issue
358
- * `conversation/subscribe`. This subscription has no event-replay API, so the
359
- * caller must still backfill the transcript for the outage window
360
- * (`conversation/messages`). Call it once the handshake completed; a no-op
361
- * once closed.
952
+ * `conversation/subscribe`. The server restarts a conversation's sequence at
953
+ * 1 for a fresh subscription, which is exactly why the cursor resets. On a
954
+ * failed re-subscribe the error reaches `onError` and the caller can still
955
+ * backfill the outage window via `conversation/messages`.
362
956
  */
363
957
  async rearm() {
364
958
  if (this.closed) return;
365
959
  this.removeListener?.();
366
960
  this.removeListener = this.transport.onNotification((notification) => this.dispatch(notification));
367
961
  this.lastSeenSequence = 0;
368
- await this.transport.request("conversation/subscribe", { conversation_id: this.conversationId });
962
+ try {
963
+ await this.transport.request("conversation/subscribe", { conversation_id: this.conversationId });
964
+ } catch (error) {
965
+ this.emitError(error);
966
+ throw error;
967
+ }
369
968
  }
370
969
  dispatch(notification) {
371
970
  if (notification.method === "conversation/event") {
372
971
  const event = notification.params;
373
- if (event.conversation_id !== this.conversationId || event.sequence <= this.lastSeenSequence) return;
972
+ if (event.conversation_id !== this.conversationId) return;
973
+ if (!Number.isFinite(event.sequence)) return;
974
+ if (event.sequence <= this.lastSeenSequence) return;
975
+ const gap = this.lastSeenSequence > 0 && event.sequence > this.lastSeenSequence + 1;
374
976
  this.lastSeenSequence = event.sequence;
375
- for (const listener of [...this.events]) try {
376
- listener(event);
377
- } catch {}
977
+ if (this.events.size === 0) this.buffer(event);
978
+ else this.deliver(event);
979
+ if (gap) {
980
+ this.emitResync("gap");
981
+ this.requestBackfill("gap");
982
+ }
378
983
  return;
379
984
  }
380
985
  if (notification.method === "conversation/resync-required") {
381
986
  if (!notification.params.conversation_ids.includes(this.conversationId)) return;
382
- for (const listener of [...this.resyncs]) try {
383
- listener(notification.params.reason);
384
- } catch {}
987
+ this.emitResync(notification.params.reason);
988
+ this.requestBackfill(notification.params.reason);
385
989
  }
386
990
  }
991
+ buffer(event) {
992
+ const limit = this.options.pendingLimit ?? DEFAULT_PENDING_LIMIT;
993
+ this.pending.push(event);
994
+ while (this.pending.length > limit) {
995
+ this.pending.shift();
996
+ this.pendingDropped += 1;
997
+ }
998
+ }
999
+ deliver(event) {
1000
+ for (const listener of [...this.events]) try {
1001
+ listener(event);
1002
+ } catch {}
1003
+ }
1004
+ emitResync(reason) {
1005
+ for (const listener of [...this.resyncs]) try {
1006
+ listener(reason);
1007
+ } catch {}
1008
+ }
1009
+ emitError(error) {
1010
+ for (const listener of [...this.errors]) try {
1011
+ listener(error);
1012
+ } catch {}
1013
+ }
1014
+ /**
1015
+ * One in-flight catch-up at a time: a burst of resync signals collapses into
1016
+ * a single transcript fetch (the fetch itself returns the newest page, so the
1017
+ * result supersedes every signal that arrived before it).
1018
+ */
1019
+ requestBackfill(reason) {
1020
+ if (this.closed || this.options.autoResync === false) return;
1021
+ const fetchMessages = this.options.fetchMessages;
1022
+ if (!fetchMessages || this.backfillInFlight) return;
1023
+ const task = (async () => {
1024
+ try {
1025
+ const page = await fetchMessages(this.conversationId);
1026
+ if (this.closed) return;
1027
+ const backfill = {
1028
+ conversationId: this.conversationId,
1029
+ reason,
1030
+ messages: page?.items ?? [],
1031
+ hasMore: page?.has_more === true
1032
+ };
1033
+ for (const listener of [...this.backfills]) try {
1034
+ listener(backfill);
1035
+ } catch {}
1036
+ } catch (error) {
1037
+ this.emitError(error);
1038
+ }
1039
+ })();
1040
+ this.backfillInFlight = task;
1041
+ task.finally(() => {
1042
+ if (this.backfillInFlight === task) this.backfillInFlight = null;
1043
+ });
1044
+ }
387
1045
  };
388
1046
  //#endregion
389
1047
  //#region src/connectors.ts
@@ -423,6 +1081,28 @@ var ConnectorClient = class {
423
1081
  logout(connectorId) {
424
1082
  return this.transport.request("connector/auth/logout", { connector_id: connectorId }).then(() => void 0);
425
1083
  }
1084
+ /**
1085
+ * Run one tool on a registered connector, through the host's own connection.
1086
+ *
1087
+ * The host holds the transport, its headers and its OAuth token; this sends a
1088
+ * tool name and an argument object and nothing else — you cannot name a URL,
1089
+ * a command or a header. Whether the pair is callable at all is the host's
1090
+ * `[connector_proxy]` allowlist, so expect `policy_denied` on a host whose
1091
+ * operator has not listed this tool (that is the default, not a
1092
+ * misconfiguration).
1093
+ *
1094
+ * Resolves even when the tool itself failed — check `is_error`. It rejects
1095
+ * only when the call never reached the tool: `connector_call_timeout`,
1096
+ * `connector_call_failed`, `response_too_large`, `connector_unavailable`,
1097
+ * `policy_denied`, `not_found`.
1098
+ */
1099
+ call(connectorId, tool, args = {}) {
1100
+ return this.transport.request("connector/call", {
1101
+ connector_id: connectorId,
1102
+ tool,
1103
+ arguments: args
1104
+ });
1105
+ }
426
1106
  };
427
1107
  //#endregion
428
1108
  //#region src/runs.ts
@@ -439,6 +1119,18 @@ var RunClient = class {
439
1119
  agent(input) {
440
1120
  return this.transport.request("agent/run", toWire(input));
441
1121
  }
1122
+ /**
1123
+ * Start a Team run (`16` §7 决策 3): the server creates the Leader
1124
+ * Conversation, materializes/binds the Team's execution template and returns
1125
+ * the public run id of the execution the Leader started.
1126
+ *
1127
+ * The receipt is `TeamRunReceipt`, not `RunReceipt` — a Team Run has no lead
1128
+ * preset revision/digest to report. Member pool and concurrency limits are not
1129
+ * inputs; sending `planning` is rejected as `invalid_request`.
1130
+ */
1131
+ team(input) {
1132
+ return this.transport.request("team/run", toTeamWire(input));
1133
+ }
442
1134
  /** Read the authoritative run state. */
443
1135
  get(runId) {
444
1136
  return this.transport.request("run/get", { run_id: runId });
@@ -447,6 +1139,14 @@ var RunClient = class {
447
1139
  result(runId) {
448
1140
  return this.transport.request("run/result", { run_id: runId });
449
1141
  }
1142
+ /**
1143
+ * Read the authoritative plan / step snapshot (W4 / W6, resolves D-W6-1):
1144
+ * titles, statuses, retries with their reason, errors and timings — none of
1145
+ * which the append-only event log carries.
1146
+ */
1147
+ plan(runId) {
1148
+ return this.transport.request("run/plan", { run_id: runId });
1149
+ }
450
1150
  /** Replay persisted events after a cursor. */
451
1151
  events(query) {
452
1152
  return this.transport.request("run/events", {
@@ -477,6 +1177,26 @@ var RunClient = class {
477
1177
  idempotency_key: input.idempotencyKey
478
1178
  });
479
1179
  }
1180
+ /**
1181
+ * Answer the pending decision of a `waiting_input` attempt.
1182
+ *
1183
+ * The three `expected*Version` tokens are mandatory CAS inputs, normally the
1184
+ * ones projected on the pending `approval.requested` event. The server passes
1185
+ * them straight to the engine's single answer gate, so a stale token is a
1186
+ * `conflict`, never a silent overwrite. There is no `always_allow` here: the
1187
+ * desktop confirmation route's approve-all flag is not part of this protocol.
1188
+ */
1189
+ answerDecision(input) {
1190
+ return this.transport.request("run/answer-decision", {
1191
+ run_id: input.runId,
1192
+ step_id: input.stepId,
1193
+ attempt_id: input.attemptId,
1194
+ answer: input.answer,
1195
+ expected_execution_version: input.expectedExecutionVersion,
1196
+ expected_step_version: input.expectedStepVersion,
1197
+ expected_attempt_version: input.expectedAttemptVersion
1198
+ });
1199
+ }
480
1200
  /** Subscribe to best-effort realtime events for one run. */
481
1201
  async follow(runId, options) {
482
1202
  const params = { run_id: runId };
@@ -671,6 +1391,17 @@ function toWire(input) {
671
1391
  mentions: input.mentions
672
1392
  };
673
1393
  }
1394
+ function toTeamWire(input) {
1395
+ return {
1396
+ team_id: input.teamId,
1397
+ team_version: input.teamVersion,
1398
+ goal: input.goal,
1399
+ input: input.input,
1400
+ workspace: input.workspaceId ? { id: input.workspaceId } : void 0,
1401
+ command_id: input.commandId,
1402
+ idempotency_key: input.idempotencyKey
1403
+ };
1404
+ }
674
1405
  //#endregion
675
1406
  //#region src/skills.ts
676
1407
  var SkillClient = class {
@@ -686,6 +1417,309 @@ var SkillClient = class {
686
1417
  get(skillId) {
687
1418
  return this.transport.request("skill/get", { skill_id: skillId });
688
1419
  }
1420
+ /**
1421
+ * Every readable file inside a Skill's directory, with a tree digest.
1422
+ *
1423
+ * This is the only way to learn what a Skill actually ships: `get()` returns
1424
+ * a bounded summary of `SKILL.md` and says nothing about the `references/`,
1425
+ * `scripts/`, `templates/` and `assets/` beside it. Check
1426
+ * `capabilities.skill_files` first — a host may wire the catalog without
1427
+ * this face, in which case it answers `unsupported_operation`.
1428
+ */
1429
+ files(skillId) {
1430
+ return this.transport.request("skill/files", { skill_id: skillId });
1431
+ }
1432
+ /**
1433
+ * One skill file's bytes, over the WebSocket binding.
1434
+ *
1435
+ * The wire carries base64 because JSON has no byte string, so this decodes
1436
+ * back to `Uint8Array` for you. The HTTP route
1437
+ * (`GET /api/app-server/skills/{id}/files/{path}`) returns the raw body
1438
+ * instead, but that is deliberately not on the typed client's JSON
1439
+ * transport — use this method, or `fetch` the route directly if you are on a
1440
+ * host token.
1441
+ */
1442
+ async readFile(skillId, path) {
1443
+ return decodeBase64((await this.transport.request("skill/file", {
1444
+ skill_id: skillId,
1445
+ path
1446
+ })).content);
1447
+ }
1448
+ /** Same as {@link readFile}, but also returns the server's content type. */
1449
+ readFileWithType(skillId, path) {
1450
+ return this.transport.request("skill/file", {
1451
+ skill_id: skillId,
1452
+ path
1453
+ });
1454
+ }
1455
+ };
1456
+ /**
1457
+ * Decode base64 to bytes.
1458
+ *
1459
+ * `atob` is used when present (browsers, Bun, Node 16+) and a manual decode
1460
+ * otherwise, so the package keeps working on a bare Node without a DOM lib.
1461
+ */
1462
+ function decodeBase64(content) {
1463
+ if (typeof atob === "function") {
1464
+ const binary = atob(content);
1465
+ const bytes = new Uint8Array(binary.length);
1466
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
1467
+ return bytes;
1468
+ }
1469
+ const bufferCtor = globalThis.Buffer;
1470
+ if (bufferCtor) return bufferCtor.from(content, "base64");
1471
+ throw new Error("no base64 decoder available in this environment");
1472
+ }
1473
+ //#endregion
1474
+ //#region src/store.ts
1475
+ var StoreError = class extends Error {
1476
+ code;
1477
+ constructor(code, message) {
1478
+ super(message);
1479
+ this.code = code;
1480
+ this.name = "StoreError";
1481
+ }
1482
+ };
1483
+ const DEFAULT_READY_TIMEOUT_MS = 3e4;
1484
+ const DEFAULT_READY_POLL_MS = 400;
1485
+ const DEFAULT_READY_POLL_MAX_MS = 4e3;
1486
+ /** Every string a `LocalizedText` carries, for haystack building. */
1487
+ function localizedValues(text) {
1488
+ if (typeof text === "string") return [text];
1489
+ if (!text || typeof text !== "object") return [];
1490
+ return Object.values(text).filter((value) => typeof value === "string");
1491
+ }
1492
+ function haystack(item) {
1493
+ return [
1494
+ item.entry_name,
1495
+ item.name,
1496
+ item.id,
1497
+ item.description ?? "",
1498
+ item.version,
1499
+ ...localizedValues(item.display_name),
1500
+ ...localizedValues(item.display_description),
1501
+ ...localizedValues(item.profession),
1502
+ ...(item.tags ?? []).flatMap(localizedValues)
1503
+ ].join("\n").toLowerCase();
1504
+ }
1505
+ function abortableDelay(ms, signal) {
1506
+ return new Promise((resolve, reject) => {
1507
+ if (signal?.aborted) {
1508
+ reject(new StoreError("aborted", "the operation was aborted"));
1509
+ return;
1510
+ }
1511
+ const timer = setTimeout(() => {
1512
+ signal?.removeEventListener("abort", onAbort);
1513
+ resolve();
1514
+ }, ms);
1515
+ const onAbort = () => {
1516
+ clearTimeout(timer);
1517
+ reject(new StoreError("aborted", "the operation was aborted"));
1518
+ };
1519
+ signal?.addEventListener("abort", onAbort, { once: true });
1520
+ });
1521
+ }
1522
+ var StoreClient = class {
1523
+ host;
1524
+ readyTimeoutMs;
1525
+ readyPollMs;
1526
+ readyPollMaxMs;
1527
+ constructor(host, options = {}) {
1528
+ this.host = host;
1529
+ this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
1530
+ this.readyPollMs = options.readyPollMs ?? DEFAULT_READY_POLL_MS;
1531
+ this.readyPollMaxMs = options.readyPollMaxMs ?? DEFAULT_READY_POLL_MAX_MS;
1532
+ }
1533
+ /** Every item across enabled marketplaces, with install state. */
1534
+ async list() {
1535
+ return (await this.host.listStore()).items;
1536
+ }
1537
+ /** Case-insensitive substring search over the fields a user can see. */
1538
+ async search(query, filter = {}) {
1539
+ const needle = query.trim().toLowerCase();
1540
+ return (await this.list()).filter((item) => {
1541
+ if (filter.kind && item.kind !== filter.kind) return false;
1542
+ if (!needle) return true;
1543
+ return haystack(item).includes(needle);
1544
+ });
1545
+ }
1546
+ /** Items currently installed on this host. */
1547
+ async installed() {
1548
+ return (await this.list()).filter((item) => item.installed);
1549
+ }
1550
+ /**
1551
+ * Installed items whose marketplace offers a different version.
1552
+ *
1553
+ * Both conditions matter: `update_available` is computed from the imported
1554
+ * snapshot even when nothing is installed, so filtering on it alone would
1555
+ * report an "update" for an entry the user has never installed.
1556
+ */
1557
+ async checkUpdates() {
1558
+ return (await this.list()).filter((item) => item.installed && item.update_available);
1559
+ }
1560
+ /**
1561
+ * What a caller can offer for an item's pending update.
1562
+ *
1563
+ * `"none"` means there is nothing to do; `"uninstall_reinstall"` means the
1564
+ * entry is installed at a different version and the only path the wire offers
1565
+ * is to release it and install again (the version-aware re-import then picks
1566
+ * up the current version). `"unknown"` is returned rather than guessing when
1567
+ * the item carries no snapshot to release.
1568
+ */
1569
+ updateHint(item) {
1570
+ if (!item.installed || !item.update_available) return "none";
1571
+ return item.snapshot_id ? "uninstall_reinstall" : "unknown";
1572
+ }
1573
+ /**
1574
+ * Import (when needed) and install one store item, then wait until it is
1575
+ * usable.
1576
+ */
1577
+ async install(item, options = {}) {
1578
+ this.assertUsable(item, options.signal);
1579
+ const result = await this.host.installStoreEntry(item.marketplace_id, item.entry_name);
1580
+ const components = result.outcomes ?? [];
1581
+ const outcome = {
1582
+ snapshotId: result.snapshot_id,
1583
+ reused: result.reused,
1584
+ components,
1585
+ ok: result.errors.length === 0 && components.every((component) => component.ok)
1586
+ };
1587
+ if (options.waitForReady === false) return outcome;
1588
+ return this.awaitReady(outcome, options);
1589
+ }
1590
+ /**
1591
+ * Release an item's runtime artifacts and clear its install record.
1592
+ *
1593
+ * The server only clears the record for components it actually released, so a
1594
+ * partial failure leaves `ok: false` with the failing component named — and
1595
+ * the item stays installed, which is what makes a retry meaningful.
1596
+ */
1597
+ async uninstall(item, options = {}) {
1598
+ const snapshotId = this.requireSnapshot(item);
1599
+ const componentIds = options.componentIds ?? await this.installedComponentIds(snapshotId);
1600
+ if (componentIds.length === 0) return {
1601
+ snapshotId,
1602
+ reused: true,
1603
+ components: [],
1604
+ ok: true
1605
+ };
1606
+ const status = await this.host.uninstallInstall(snapshotId, componentIds);
1607
+ return this.outcomeFromStatus(snapshotId, status, false);
1608
+ }
1609
+ /**
1610
+ * Switch an item's components on or off.
1611
+ *
1612
+ * Idempotent: the server sets the state it is asked for instead of toggling.
1613
+ * A skill reports `skill_disable_flag_only` because the skill corpus has no
1614
+ * enable state — that code is passed through, not swallowed, so a caller can
1615
+ * tell "switched off" from "marked in the catalogue".
1616
+ */
1617
+ async setEnabled(item, enabled, options = {}) {
1618
+ const snapshotId = this.requireSnapshot(item);
1619
+ const componentIds = options.componentIds ?? await this.installedComponentIds(snapshotId);
1620
+ if (componentIds.length === 0) return {
1621
+ snapshotId,
1622
+ reused: true,
1623
+ components: [],
1624
+ ok: true
1625
+ };
1626
+ const status = enabled ? await this.host.enableInstall(snapshotId, componentIds) : await this.host.disableInstall(snapshotId, componentIds);
1627
+ return this.outcomeFromStatus(snapshotId, status, false);
1628
+ }
1629
+ assertUsable(item, signal) {
1630
+ if (signal?.aborted) throw new StoreError("aborted", "the operation was aborted before it started");
1631
+ if (item.blocked_reason) throw new StoreError("item_blocked", item.blocked_reason);
1632
+ }
1633
+ requireSnapshot(item) {
1634
+ const snapshotId = item.snapshot_id;
1635
+ if (!snapshotId) throw new StoreError("not_installed", `store item ${item.id} has no imported snapshot to act on`);
1636
+ return snapshotId;
1637
+ }
1638
+ async installedComponentIds(snapshotId) {
1639
+ return (await this.host.getInstallStatus(snapshotId)).components.filter((component) => component.state !== "not-installed").map((component) => component.id);
1640
+ }
1641
+ outcomeFromStatus(snapshotId, status, reused) {
1642
+ const components = status.outcomes ?? [];
1643
+ return {
1644
+ snapshotId,
1645
+ reused,
1646
+ components,
1647
+ ok: (status.errors ?? []).length === 0 && components.every((component) => component.ok)
1648
+ };
1649
+ }
1650
+ /**
1651
+ * Poll until every component of the snapshot is usable.
1652
+ *
1653
+ * A timeout does **not** discard the install: the caller gets the successful
1654
+ * install plus `ready: false` and `readyIssue: "ready_timeout"`, so a slow
1655
+ * connector never turns into "the install failed".
1656
+ */
1657
+ async awaitReady(outcome, options) {
1658
+ const snapshotId = outcome.snapshotId;
1659
+ if (!snapshotId) return outcome;
1660
+ const status = await this.host.getInstallStatus(snapshotId);
1661
+ const connectors = status.components.filter((component) => component.kind === "connector" && component.state !== "not-installed");
1662
+ if (connectors.length > 0) await this.host.enableInstall(snapshotId, connectors.map((component) => component.id));
1663
+ const deadline = Date.now() + (options.timeoutMs ?? this.readyTimeoutMs);
1664
+ let interval = this.readyPollMs;
1665
+ let last = status.components;
1666
+ for (;;) {
1667
+ const blocked = (await Promise.all(last.filter((component) => component.state !== "not-installed").map(async (component) => ({
1668
+ component,
1669
+ verdict: await this.readiness(component)
1670
+ })))).find((entry) => !entry.verdict.ready);
1671
+ if (!blocked) return {
1672
+ ...outcome,
1673
+ ready: true
1674
+ };
1675
+ if (!blocked.verdict.ready && blocked.verdict.terminal) return {
1676
+ ...outcome,
1677
+ ready: false,
1678
+ readyIssue: blocked.verdict.terminal,
1679
+ readyComponentId: blocked.component.id
1680
+ };
1681
+ if (Date.now() >= deadline) return {
1682
+ ...outcome,
1683
+ ready: false,
1684
+ readyIssue: "ready_timeout",
1685
+ readyComponentId: blocked.component.id
1686
+ };
1687
+ await abortableDelay(interval, options.signal);
1688
+ interval = Math.min(interval * 2, this.readyPollMaxMs);
1689
+ last = (await this.host.getInstallStatus(snapshotId)).components;
1690
+ }
1691
+ }
1692
+ /**
1693
+ * Is this one component usable yet?
1694
+ *
1695
+ * Each kind answers with the narrowest read the protocol already offers. An
1696
+ * unknown kind is reported ready rather than blocking: this layer cannot judge
1697
+ * a component it does not understand, and a false timeout on a future kind
1698
+ * would be worse than passing it through.
1699
+ */
1700
+ async readiness(component) {
1701
+ try {
1702
+ switch (component.kind) {
1703
+ case "skill": return (await this.host.skills.list()).some((skill) => skill.name === component.name) ? { ready: true } : { ready: false };
1704
+ case "agent": return (await this.host.agents.get(component.id)).preset_id ? { ready: true } : { ready: false };
1705
+ case "team":
1706
+ await this.host.teams.get(component.id);
1707
+ return { ready: true };
1708
+ case "connector": {
1709
+ if ((await this.host.connectors.test(component.id)).success) return { ready: true };
1710
+ const status = await this.host.connectors.status(component.id);
1711
+ if (status.status === "authorization_required" || status.status === "reauthorization_required") return {
1712
+ ready: false,
1713
+ terminal: "authorization_required"
1714
+ };
1715
+ return { ready: false };
1716
+ }
1717
+ default: return { ready: true };
1718
+ }
1719
+ } catch {
1720
+ return { ready: false };
1721
+ }
1722
+ }
689
1723
  };
690
1724
  //#endregion
691
1725
  //#region src/teams.ts
@@ -775,6 +1809,12 @@ var AppServerClient = class {
775
1809
  teams;
776
1810
  /** Public model directory (`models/list`, REQ-PAR-05b). */
777
1811
  models;
1812
+ /**
1813
+ * Agent Store lifecycle as one state machine: search → install (wait until
1814
+ * usable) → enable/disable → uninstall. Composes the flat methods below; it
1815
+ * adds no wire surface.
1816
+ */
1817
+ store;
778
1818
  clientInfo;
779
1819
  capabilities;
780
1820
  initializeResult = null;
@@ -793,6 +1833,7 @@ var AppServerClient = class {
793
1833
  this.agents = new AgentClient(this.transport);
794
1834
  this.teams = new TeamClient(this.transport);
795
1835
  this.models = new ModelClient(this.transport);
1836
+ this.store = new StoreClient(this, options.store);
796
1837
  this.bridgeNotifications();
797
1838
  }
798
1839
  /**
@@ -862,7 +1903,14 @@ var AppServerClient = class {
862
1903
  async getInstallStatus(snapshotId) {
863
1904
  return this.transport.request("install/status", { snapshot_id: snapshotId });
864
1905
  }
865
- /** Disable installed components (runtime artifacts stay). */
1906
+ /**
1907
+ * Disable installed components.
1908
+ *
1909
+ * The runtime state moves with the flag — a connector's MCP server is switched
1910
+ * off, an expert's Preset is disabled — while the artifacts stay on disk. A
1911
+ * skill is the documented exception: the corpus has no enable state, so it
1912
+ * reports `skill_disable_flag_only` and the flag stays a catalogue marker.
1913
+ */
866
1914
  async disableInstall(snapshotId, componentIds) {
867
1915
  return this.transport.request("install/disable", {
868
1916
  snapshot_id: snapshotId,
@@ -1322,4 +2370,4 @@ async function withRetry(operation, options = {}) {
1322
2370
  throw lastError;
1323
2371
  }
1324
2372
  //#endregion
1325
- export { AgentClient, AgentRunHandle, AppServerClient, ConnectorClient, ConversationClient, ConversationHandle, ConversationSubscription, EventSubscription, ModelClient, RunClient, SkillClient, TeamClient, WebSocketTransport, WorkspaceClient, aggregateTurnResult, conversationMessages, isLoopbackUrl, launchRun, withRetry };
2373
+ export { AgentClient, AgentRunHandle, AppServerClient, ConnectorClient, ConversationClient, ConversationHandle, ConversationSubscription, EventSubscription, HttpTransport, ModelClient, RunClient, SkillClient, StoreClient, StoreError, TeamClient, WebSocketTransport, WorkspaceClient, aggregateTurnResult, appServerErrorFromWire, conversationMessages, httpRouteTable, isLoopbackUrl, launchRun, withRetry };