keymaster-connect 0.1.2 → 0.1.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.js CHANGED
@@ -1,5 +1,7 @@
1
- import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-W2TNWBLP.js';
2
- export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-W2TNWBLP.js';
1
+ import { parseToolDefinitions, assertToolPayload, isAiToolMessage, validateToolArguments } from './chunk-VVOTW5ZT.js';
2
+ export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-VVOTW5ZT.js';
3
+ import { PROTOCOL_METHODS, PROTOCOL_VERSION, sameNetworkIdentity, validateNetworkIdentity } from './chunk-2EYARFS3.js';
4
+ export { MSFILE_BLOCK_SIZE_BYTES, MSFILE_DIGEST_SIZE_BYTES, MSFILE_LOCAL_SOURCE_ID, MSFILE_MAX_BLOCK_BYTES, MSFILE_MAX_CONTENT_BYTES, MSFILE_MAX_ERROR_MESSAGE_BYTES, MSFILE_MAX_HEADER_BYTES, MSFILE_MAX_SEED_BYTES, MSFILE_PROTOCOL_ID, PROTOCOL_METHODS, PROTOCOL_VERSION, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, STORAGE_MAX_PAYLOAD_BYTES, isValidMsFileSourceId, sameNetworkIdentity, validateBsvNetwork, validateNetworkIdentity } from './chunk-2EYARFS3.js';
3
5
 
4
6
  // src/binary.ts
5
7
  function binary(bytes, mime) {
@@ -25,6 +27,122 @@ function binaryToText(field) {
25
27
  return new TextDecoder().decode(binaryBytes(field));
26
28
  }
27
29
 
30
+ // src/toolClient.ts
31
+ var AiToolClient = class {
32
+ constructor(current, send, uuid) {
33
+ this.current = current;
34
+ this.send = send;
35
+ this.uuid = uuid;
36
+ }
37
+ current;
38
+ send;
39
+ uuid;
40
+ callbacks = /* @__PURE__ */ new Map();
41
+ pending;
42
+ running = /* @__PURE__ */ new Map();
43
+ seen = /* @__PURE__ */ new Set();
44
+ register(tools, options = {}) {
45
+ const bindingId = this.current();
46
+ if (!bindingId) return Promise.reject(new Error("Connect before registering AI tools"));
47
+ if (this.pending) return Promise.reject(new Error("Tool registration is already pending"));
48
+ if (tools.length && this.running.size) return Promise.reject(new Error("Cannot replace tools while callbacks are running"));
49
+ const definitions = parseToolDefinitions(tools.map(({ name, description, parameters }) => ({ name, description, parameters })));
50
+ if (tools.some((tool) => typeof tool.execute !== "function")) throw new TypeError("Tool execute must be a function");
51
+ if (options.signal?.aborted) return Promise.reject(options.signal.reason ?? new Error("Registration aborted"));
52
+ const timeout = options.timeoutMs ?? 3e4;
53
+ if (!Number.isFinite(timeout) || timeout <= 0) throw new TypeError("Invalid registration timeout");
54
+ const id = this.uuid();
55
+ const callbacks = new Map(definitions.map((definition, index) => [definition.name, { ...definition, execute: tools[index].execute }]));
56
+ return new Promise((resolve, reject) => {
57
+ const fail = (reason) => {
58
+ if (this.pending?.id !== id) return;
59
+ clearTimeout(this.pending.timer);
60
+ this.pending.off();
61
+ this.pending = void 0;
62
+ this.callbacks.clear();
63
+ reject(reason);
64
+ };
65
+ const abort = () => fail(options.signal?.reason ?? new Error("Registration aborted; registration outcome is unknown"));
66
+ options.signal?.addEventListener("abort", abort, { once: true });
67
+ this.pending = { id, tools: callbacks, resolve, reject, timer: setTimeout(() => fail(new Error("AI tool registration timed out; outcome is unknown")), timeout), off: () => options.signal?.removeEventListener("abort", abort) };
68
+ try {
69
+ const message = { v: 1, type: "tools.register", id, bindingId, tools: definitions };
70
+ assertToolPayload(message);
71
+ this.send(message);
72
+ } catch (error) {
73
+ fail(error);
74
+ }
75
+ });
76
+ }
77
+ handle(value) {
78
+ if (!isAiToolMessage(value)) return false;
79
+ if (value.bindingId !== this.current()) return true;
80
+ if (value.type === "tools.registered") {
81
+ const pending = this.pending;
82
+ if (!pending || pending.id !== value.id) return true;
83
+ clearTimeout(pending.timer);
84
+ pending.off();
85
+ this.pending = void 0;
86
+ if (value.ok) {
87
+ if (!pending.tools.size) {
88
+ for (const controller of this.running.values()) controller.abort(new Error("Tools unregistered"));
89
+ }
90
+ this.callbacks = pending.tools;
91
+ pending.resolve({ names: value.names });
92
+ } else pending.reject(new Error(value.error));
93
+ } else if (value.type === "tools.cancel") {
94
+ this.running.get(value.id)?.abort(new Error("Wallet cancelled tool invocation"));
95
+ } else if (value.type === "tools.invoke") {
96
+ if (this.seen.has(value.id)) return true;
97
+ if (this.seen.size >= 1e4 || this.running.size >= 16) {
98
+ this.reply(value.bindingId, value.id, { ok: false, error: "Too many tool invocations; reconnect explicitly" });
99
+ return true;
100
+ }
101
+ this.seen.add(value.id);
102
+ const tool = this.callbacks.get(value.name);
103
+ if (!tool) {
104
+ this.reply(value.bindingId, value.id, { ok: false, error: "Tool is not registered on this connection" });
105
+ return true;
106
+ }
107
+ const controller = new AbortController();
108
+ this.running.set(value.id, controller);
109
+ void (async () => {
110
+ try {
111
+ validateToolArguments(value.arguments, tool.parameters);
112
+ const result = await tool.execute(structuredClone(value.arguments), { signal: controller.signal });
113
+ controller.signal.throwIfAborted();
114
+ assertToolPayload({ v: 1, type: "tools.result", bindingId: value.bindingId, id: value.id, ok: true, result });
115
+ this.reply(value.bindingId, value.id, { ok: true, result });
116
+ } catch {
117
+ this.reply(value.bindingId, value.id, { ok: false, error: controller.signal.aborted ? "Tool invocation cancelled; side effects may already have occurred" : "App tool execution failed" });
118
+ } finally {
119
+ this.running.delete(value.id);
120
+ }
121
+ })();
122
+ }
123
+ return true;
124
+ }
125
+ reply(bindingId, id, payload) {
126
+ if (this.current() !== bindingId) return;
127
+ try {
128
+ this.send({ v: 1, type: "tools.result", bindingId, id, ...payload });
129
+ } catch {
130
+ }
131
+ }
132
+ clear(reason) {
133
+ if (this.pending) {
134
+ clearTimeout(this.pending.timer);
135
+ this.pending.off();
136
+ this.pending.reject(reason);
137
+ this.pending = void 0;
138
+ }
139
+ for (const controller of this.running.values()) controller.abort(reason);
140
+ this.running.clear();
141
+ this.callbacks.clear();
142
+ this.seen.clear();
143
+ }
144
+ };
145
+
28
146
  // src/client.ts
29
147
  var KeymasterTransportError = class extends Error {
30
148
  constructor(code, message) {
@@ -48,11 +166,24 @@ var DEFAULT_CLOSE_POLL_MS = 500;
48
166
  var KeymasterConnectClient = class {
49
167
  identityValue = null;
50
168
  bindingId = null;
169
+ aiTools = new AiToolClient(
170
+ () => this.stateValue === "connected" ? this.bindingId : null,
171
+ (message) => {
172
+ if (!this.sessionWindow || isWindowClosed(this.sessionWindow)) throw new Error("Wallet unavailable");
173
+ this.sessionWindow.postMessage(message, this.targetOrigin);
174
+ },
175
+ () => this.environment.randomUUID()
176
+ );
177
+ /** Replace this connection's tool set. Empty array unregisters all tools. Re-register explicitly after reconnect. */
178
+ registerTools(tools, options = {}) {
179
+ return this.aiTools.register(tools, options);
180
+ }
51
181
  /** Identity returned by the authenticated wallet, or null before establishment. */
52
182
  get networkIdentity() {
53
183
  return this.identityValue;
54
184
  }
55
185
  targetOrigin;
186
+ mode;
56
187
  environment;
57
188
  options;
58
189
  pending = /* @__PURE__ */ new Map();
@@ -71,9 +202,11 @@ var KeymasterConnectClient = class {
71
202
  constructor(options) {
72
203
  if ("networkIdentity" in options) throw new TypeError("networkIdentity option has been removed; read identity from the connection result");
73
204
  this.targetOrigin = normalizeHttpOrigin(options.targetOrigin);
74
- if (options.mode !== void 0 && options.mode !== "appView") throw new TypeError("Connect apps must be launched inside the wallet");
205
+ this.mode = options.mode ?? "popup";
206
+ if (!["iframe", "appView", "popup"].includes(this.mode)) throw new TypeError("Invalid Connect transport mode");
75
207
  this.options = {
76
208
  ...options,
209
+ popupPath: options.popupPath ?? "/",
77
210
  readyTimeoutMs: positiveNumber(options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, "readyTimeoutMs"),
78
211
  requestTimeoutMs: positiveNumber(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs"),
79
212
  closePollMs: positiveNumber(options.closePollMs ?? DEFAULT_CLOSE_POLL_MS, "closePollMs")
@@ -91,12 +224,12 @@ var KeymasterConnectClient = class {
91
224
  /**
92
225
  * Establishes the browser transport.
93
226
  *
94
- * 绑定浏览器真实父页面,精确校验来源;独立页面直接失败,不打开钱包窗口。
227
+ * iframe / appView 绑定真实 parent / opener;popup 打开完整钱包等待 ready。
95
228
  *
96
229
  * @group Transport
97
230
  */
98
231
  connect() {
99
- return this.connectAppView();
232
+ return this.mode === "popup" ? this.connectPopup() : this.connectAppView();
100
233
  }
101
234
  /**
102
235
  * Sends any public Connect method with compile-time parameter and result
@@ -373,6 +506,13 @@ var KeymasterConnectClient = class {
373
506
  * @group Transport
374
507
  */
375
508
  close() {
509
+ if (this.bindingId) {
510
+ try {
511
+ this.sessionWindow?.postMessage({ v: PROTOCOL_VERSION, type: "tools.register", bindingId: this.bindingId, id: this.environment.randomUUID(), tools: [] }, this.targetOrigin);
512
+ } catch {
513
+ }
514
+ }
515
+ this.aiTools.clear(new Error("Connect client closed"));
376
516
  for (const id of this.pending.keys()) this.postCancel(id);
377
517
  this.identityValue = null;
378
518
  this.bindingId = null;
@@ -389,13 +529,22 @@ var KeymasterConnectClient = class {
389
529
  this.finishRecovery(void 0, error);
390
530
  this.setState(this.authorizationId ? "paused" : "disconnected");
391
531
  }
392
- /** 恢复原父钱包连接;任何情况下都不另开窗口或重放旧业务。 */
532
+ /** 主动恢复可由 popup 重新打开钱包;后台恢复从不打开窗口或重放业务。 */
393
533
  continueConnection(options) {
394
534
  if (this.pending.size) return Promise.reject(new TypeError("Cannot resume while business requests are pending"));
395
535
  this.installListener();
396
- const parent = this.environment.parent();
397
- if (!parent || isWindowClosed(parent)) return Promise.reject(new KeymasterTransportError("appview_session_lost", "No wallet parent is available; relaunch from the wallet"));
398
- this.sessionWindow = parent;
536
+ if (this.mode === "popup") {
537
+ if (!this.sessionWindow || isWindowClosed(this.sessionWindow)) {
538
+ const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
539
+ if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
540
+ this.sessionWindow = this.environment.open(url.href, "_blank", "");
541
+ if (!this.sessionWindow) return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
542
+ }
543
+ } else {
544
+ const launcher = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
545
+ if (!launcher || isWindowClosed(launcher)) return Promise.reject(new KeymasterTransportError("appview_session_lost", "Wallet launcher unavailable; relaunch from the wallet"));
546
+ this.sessionWindow = launcher;
547
+ }
399
548
  this.pause(new KeymasterTransportError("wallet_paused", "Re-establishing the original wallet connection"));
400
549
  this.startClosePolling();
401
550
  return new Promise((resolve, reject) => {
@@ -414,15 +563,35 @@ var KeymasterConnectClient = class {
414
563
  this.sendRecovery();
415
564
  });
416
565
  }
566
+ connectPopup() {
567
+ if (this.isConnected()) return Promise.resolve();
568
+ if (this.readyPromise) return this.readyPromise;
569
+ const url = new URL(this.options.popupPath, `${this.targetOrigin}/`);
570
+ if (url.origin !== this.targetOrigin) return Promise.reject(new TypeError("popupPath must resolve inside targetOrigin"));
571
+ this.installListener();
572
+ this.setState("opening");
573
+ this.sessionWindow = this.environment.open(url.href, "_blank", "");
574
+ if (!this.sessionWindow) {
575
+ this.setState("disconnected");
576
+ return Promise.reject(new KeymasterTransportError("popup_blocked", "Keymaster wallet window was blocked"));
577
+ }
578
+ this.startClosePolling();
579
+ this.readyPromise = new Promise((resolve, reject) => {
580
+ this.readyResolve = resolve;
581
+ this.readyReject = reject;
582
+ this.readyTimer = this.environment.setTimeout(() => this.disconnect(new KeymasterTransportError("ready_timeout", "Timed out waiting for the wallet to initialize or unlock")), this.options.readyTimeoutMs);
583
+ });
584
+ return this.readyPromise;
585
+ }
417
586
  connectAppView() {
418
587
  if (this.isConnected()) return Promise.resolve();
419
- const parent = this.environment.parent();
588
+ const parent = this.mode === "iframe" ? this.environment.parent() : this.environment.opener();
420
589
  if (!parent || isWindowClosed(parent)) {
421
- const code = this.stateValue === "idle" ? "not_embedded" : "appview_session_lost";
590
+ const code = this.stateValue === "idle" ? this.mode === "iframe" ? "not_embedded" : "no_opener" : "appview_session_lost";
422
591
  this.setState("disconnected");
423
592
  return Promise.reject(new KeymasterTransportError(
424
593
  code,
425
- "No live wallet parent is available; launch the app from Keymaster"
594
+ "Wallet launcher unavailable; launch the app from Keymaster"
426
595
  ));
427
596
  }
428
597
  this.installListener();
@@ -446,7 +615,11 @@ var KeymasterConnectClient = class {
446
615
  if (value.type === "ready" || value.type === "result") this.disconnect(new KeymasterTransportError("unsupported_protocol", "Incompatible Keymaster protocol version"));
447
616
  return;
448
617
  }
449
- if (value.type === "ready") return;
618
+ if (this.aiTools.handle(value)) return;
619
+ if (value.type === "ready") {
620
+ if (this.mode === "popup" && this.readyPromise) this.finishReady();
621
+ return;
622
+ }
450
623
  if (value.type === "closing") {
451
624
  if (this.authorizationId) this.pause(new KeymasterTransportError("wallet_paused", "Wallet runtime is unavailable"));
452
625
  else this.disconnect(new KeymasterTransportError("wallet_closed", "Keymaster wallet connection is closing"));
@@ -519,6 +692,7 @@ var KeymasterConnectClient = class {
519
692
  if (["connect.login", "connect.resume", "connect.launch"].includes(pending.method)) {
520
693
  const connected = result.result;
521
694
  if (!sameNetworkIdentity(identity, validateNetworkIdentity(connected.networkIdentity)) || typeof value.bindingId !== "string" || !value.bindingId || typeof connected.authorizationId !== "string" || !connected.authorizationId) throw new Error("Invalid connection identity or binding");
695
+ this.aiTools.clear(new Error("Connection binding replaced; register tools again"));
522
696
  this.identityValue = Object.freeze({ ...identity });
523
697
  this.authorizedIdentity = this.identityValue;
524
698
  this.authorizationId = connected.authorizationId;
@@ -528,6 +702,7 @@ var KeymasterConnectClient = class {
528
702
  throw new Error("Keymaster connection identity mismatch");
529
703
  }
530
704
  if (pending.method === "connect.logout") {
705
+ this.aiTools.clear(new Error("Logged out"));
531
706
  this.identityValue = null;
532
707
  this.bindingId = null;
533
708
  this.authorizationId = null;
@@ -566,6 +741,7 @@ var KeymasterConnectClient = class {
566
741
  this.readyReject = null;
567
742
  }
568
743
  disconnect(reason) {
744
+ this.aiTools.clear(reason);
569
745
  for (const id of this.pending.keys()) this.postCancel(id);
570
746
  this.identityValue = null;
571
747
  this.bindingId = null;
@@ -577,6 +753,7 @@ var KeymasterConnectClient = class {
577
753
  }
578
754
  /** 暂停仅撤销瞬时绑定和旧请求,持久授权引用及原身份留作恢复校验。 */
579
755
  pause(reason) {
756
+ this.aiTools.clear(reason);
580
757
  this.identityValue = null;
581
758
  this.bindingId = null;
582
759
  this.rejectAll(reason);
@@ -650,6 +827,8 @@ function createBrowserEnvironment() {
650
827
  throw new TypeError("keymaster-connect requires a browser Window or an explicit environment");
651
828
  }
652
829
  return {
830
+ open: (url, target, features) => window.open(url, target, features),
831
+ opener: () => window.opener,
653
832
  parent: () => window.parent !== window ? window.parent : null,
654
833
  addMessageListener: (listener) => window.addEventListener("message", listener),
655
834
  removeMessageListener: (listener) => window.removeEventListener("message", listener),