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/protocol.js CHANGED
@@ -1,3 +1,3 @@
1
- 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
+ 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';
2
2
  //# sourceMappingURL=protocol.js.map
3
3
  //# sourceMappingURL=protocol.js.map
package/dist/server.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { ProtocolErrorCode, P2pkhTransferAssetId, ProtocolRequestMessage, NetworkIdentity, ProtocolMethod, MethodParams, AppIdentityProofV1, VerifiedAppIdentity, ProtocolResultMessage, ProtocolReadyMessage, ProtocolClosingMessage, MethodResult, ProtocolError, ProtocolEventPayload, ProtocolReconnectMessage } from './protocol.js';
1
+ import { Y as ProtocolErrorCode, aB as P2pkhTransferAssetId, aM as ProtocolRequestMessage, N as NetworkIdentity, b as ProtocolMethod, M as MethodParams, a1 as AppIdentityProofV1, aT as VerifiedAppIdentity, $ as AiToolMessage, _ as AiToolDefinition, ae as JSONValue, aN as ProtocolResultMessage, aK as ProtocolReadyMessage, aG as ProtocolClosingMessage, c as MethodResult, aH as ProtocolError, aJ as ProtocolEventPayload, aL as ProtocolReconnectMessage } from './protocol-NcRDmEKZ.js';
2
+ export { Z as AI_TOOLS_MAX_JSON_CHARS, A as AiTool, a0 as AiToolSchema, a as AiToolsRegistered, aU as assertToolJson, aV as assertToolPayload, aW as isAiToolMessage, aY as parseToolDefinitions, b0 as validateToolArguments } from './protocol-NcRDmEKZ.js';
2
3
 
3
4
  /** 校验失败:抛出的对象。service 会捕获并组装 ProtocolError。 */
4
5
  declare class ProtocolValidationError extends Error {
@@ -66,6 +67,33 @@ declare function verifyAppIdentityProof(raw: unknown): VerifiedAppIdentity;
66
67
  /** 校验 session 中已验证 proof 的不可变 snapshot。 */
67
68
  declare function isVerifiedAppIdentitySnapshot(value: unknown): value is VerifiedAppIdentity;
68
69
 
70
+ interface AiToolReceiverOptions {
71
+ /** Must verify the same Receiver's current binding, exact peer, origin and wallet lifecycle. */
72
+ isCurrent(bindingId: string): boolean;
73
+ send(message: AiToolMessage): void;
74
+ /** Host derives globally unique names and rejects conflicting live connection ownership. */
75
+ names(definitions: readonly AiToolDefinition[]): string[];
76
+ changed(): void;
77
+ randomUUID?(): string;
78
+ }
79
+ /** Protocol-only reverse-call endpoint; owns no App authorization, funds or persistence. */
80
+ declare class KeymasterAiToolReceiver {
81
+ private options;
82
+ private definitions;
83
+ private bindingId;
84
+ private pending;
85
+ private disposed;
86
+ constructor(options: AiToolReceiverOptions);
87
+ /** Host calls on connection changes; revoke stale in-flight calls without replay. */
88
+ sync(): void;
89
+ list(): readonly AiToolDefinition[];
90
+ available(name: string): boolean;
91
+ handle(value: unknown): boolean;
92
+ invoke(name: string, args: Record<string, JSONValue>, signal: AbortSignal, timeoutMs?: number): Promise<JSONValue>;
93
+ private clear;
94
+ dispose(): void;
95
+ }
96
+
69
97
  /** 窗口对象只作为消息源身份与发送目标;不读取跨源页面内容。 */
70
98
  interface ConnectPeer {
71
99
  postMessage(message: unknown, targetOrigin: string): void;
@@ -162,4 +190,4 @@ declare class KeymasterConnectReceiver {
162
190
  private send;
163
191
  }
164
192
 
165
- export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, type ConnectPeer, type ConnectReceiverOptions, KeymasterConnectReceiver, ProtocolEventPayload, ProtocolValidationError, type ReceiverLifecycle, type ReceiverMessage, type ReceiverPeerPolicy, type ReceiverRequest, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
193
+ export { APP_IDENTITY_DOMAIN_V1, AiToolDefinition, AiToolMessage, type AiToolReceiverOptions, AppIdentityValidationError, type ConnectPeer, type ConnectReceiverOptions, KeymasterAiToolReceiver, KeymasterConnectReceiver, ProtocolEventPayload, ProtocolValidationError, type ReceiverLifecycle, type ReceiverMessage, type ReceiverPeerPolicy, type ReceiverRequest, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
package/dist/server.js CHANGED
@@ -1,4 +1,6 @@
1
- import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-W2TNWBLP.js';
1
+ import { isAiToolMessage, parseToolDefinitions, validateToolArguments, assertToolPayload } from './chunk-VVOTW5ZT.js';
2
+ export { AI_TOOLS_MAX_JSON_CHARS, assertToolJson, assertToolPayload, isAiToolMessage, parseToolDefinitions, validateToolArguments } from './chunk-VVOTW5ZT.js';
3
+ import { PROTOCOL_VERSION, PROTOCOL_METHODS, validateNetworkIdentity, sameNetworkIdentity, STORAGE_MAX_PAYLOAD_BYTES, STORAGE_DEFAULT_LIST_LIMIT, STORAGE_MAX_LIST_LIMIT, isValidMsFileSourceId } from './chunk-2EYARFS3.js';
2
4
  import { secp256k1 } from '@noble/curves/secp256k1.js';
3
5
  import { sha256 } from '@noble/hashes/sha2.js';
4
6
 
@@ -789,6 +791,110 @@ function parseRequestMessage(raw, receiverIdentity) {
789
791
  return { id, method, params: normalized };
790
792
  }
791
793
 
794
+ // src/toolReceiver.ts
795
+ var KeymasterAiToolReceiver = class {
796
+ constructor(options) {
797
+ this.options = options;
798
+ }
799
+ options;
800
+ definitions = [];
801
+ bindingId = null;
802
+ pending = /* @__PURE__ */ new Map();
803
+ disposed = false;
804
+ /** Host calls on connection changes; revoke stale in-flight calls without replay. */
805
+ sync() {
806
+ if (this.bindingId && !this.options.isCurrent(this.bindingId)) this.clear();
807
+ }
808
+ list() {
809
+ return !this.disposed && this.bindingId && this.options.isCurrent(this.bindingId) ? structuredClone(this.definitions) : [];
810
+ }
811
+ available(name) {
812
+ return this.list().some((tool) => tool.name === name);
813
+ }
814
+ handle(value) {
815
+ if (this.disposed || !isAiToolMessage(value)) return false;
816
+ if (!this.options.isCurrent(value.bindingId)) return true;
817
+ if (value.type === "tools.register") {
818
+ try {
819
+ const definitions = parseToolDefinitions(value.tools);
820
+ if (this.pending.size && definitions.length) throw new Error("Cannot replace tools while calls are pending");
821
+ if (!definitions.length && this.pending.size) this.clear();
822
+ const names = this.options.names(definitions);
823
+ this.options.send({ v: 1, type: "tools.registered", bindingId: value.bindingId, id: value.id, ok: true, names });
824
+ this.definitions = definitions;
825
+ this.bindingId = value.bindingId;
826
+ this.options.changed();
827
+ } catch {
828
+ this.options.send({ v: 1, type: "tools.registered", bindingId: value.bindingId, id: value.id, ok: false, error: "Tool registration rejected: invalid schema, conflicting live connection or pending invocation" });
829
+ }
830
+ } else if (value.type === "tools.result") {
831
+ const pending = this.pending.get(value.id);
832
+ if (!pending || pending.bindingId !== value.bindingId) return true;
833
+ pending.cleanup();
834
+ this.pending.delete(value.id);
835
+ if (value.ok) pending.resolve(value.result);
836
+ else pending.reject(new Error(`App tool failed: ${value.error}`));
837
+ }
838
+ return true;
839
+ }
840
+ invoke(name, args, signal, timeoutMs = 12e4) {
841
+ const tool = this.list().find((tool2) => tool2.name === name), bindingId = this.bindingId;
842
+ if (!tool || !bindingId) return Promise.reject(new Error("App tool is offline"));
843
+ if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Tool call aborted"));
844
+ if (this.pending.size >= 16) return Promise.reject(new Error("Too many pending tool calls"));
845
+ validateToolArguments(args, tool.parameters);
846
+ const id = this.options.randomUUID?.() ?? crypto.randomUUID();
847
+ return new Promise((resolve, reject) => {
848
+ const fail = (error) => {
849
+ const pending = this.pending.get(id);
850
+ if (!pending) return;
851
+ pending.cleanup();
852
+ this.pending.delete(id);
853
+ if (this.options.isCurrent(bindingId)) {
854
+ try {
855
+ this.options.send({ v: 1, type: "tools.cancel", bindingId, id });
856
+ } catch {
857
+ }
858
+ }
859
+ reject(error);
860
+ };
861
+ const abort = () => fail(new Error("App tool cancelled; side effects may already have occurred"));
862
+ const timer = setTimeout(() => fail(new Error("App tool timed out; outcome unknown, not retried")), timeoutMs);
863
+ signal.addEventListener("abort", abort, { once: true });
864
+ this.pending.set(id, { bindingId, resolve, reject, cleanup: () => {
865
+ clearTimeout(timer);
866
+ signal.removeEventListener("abort", abort);
867
+ } });
868
+ try {
869
+ const message = { v: 1, type: "tools.invoke", bindingId, id, name, arguments: structuredClone(args) };
870
+ assertToolPayload(message);
871
+ this.options.send(message);
872
+ } catch {
873
+ fail(new Error("Unable to deliver App tool call; outcome unknown"));
874
+ }
875
+ });
876
+ }
877
+ clear() {
878
+ for (const [id, pending] of this.pending) {
879
+ try {
880
+ this.options.send({ v: 1, type: "tools.cancel", bindingId: pending.bindingId, id });
881
+ } catch {
882
+ }
883
+ pending.cleanup();
884
+ pending.reject(new Error("App connection lost; tool outcome unknown, not retried"));
885
+ }
886
+ this.pending.clear();
887
+ this.definitions = [];
888
+ this.bindingId = null;
889
+ this.options.changed();
890
+ }
891
+ dispose() {
892
+ if (this.disposed) return;
893
+ this.disposed = true;
894
+ this.clear();
895
+ }
896
+ };
897
+
792
898
  // src/server.ts
793
899
  function isEstablishing(method) {
794
900
  return ["connect.login", "connect.resume", "connect.launch"].includes(method);
@@ -993,6 +1099,6 @@ var KeymasterConnectReceiver = class {
993
1099
  }
994
1100
  };
995
1101
 
996
- export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
1102
+ export { APP_IDENTITY_DOMAIN_V1, AppIdentityValidationError, KeymasterAiToolReceiver, KeymasterConnectReceiver, ProtocolValidationError, assertCompressedPubkeyHex, assertMainnetP2pkhAddress, assertOriginMatches, assertP2pkhAddressForAsset, canonicalizeJson, identityDigestBytes, identityPayload, isEstablishing, isStructuredCloneRequestCandidate, isVerifiedAppIdentitySnapshot, parseCancelMessage, parseReconnectMessage, parseRequestMessage, validateExactChannel, verifyAppIdentityProof };
997
1103
  //# sourceMappingURL=server.js.map
998
1104
  //# sourceMappingURL=server.js.map