@jdr377/mapapp-agent-connector 0.1.0-pre.8 → 0.1.0-pre.9
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 +6 -4
- package/dist/{chunk-2z3hggm4.js → chunk-8061dj3y.js} +1 -1
- package/dist/{chunk-b04ecsf5.js → chunk-961w3fz4.js} +1 -1
- package/dist/{chunk-1yn5h5zx.js → chunk-esdsjfvs.js} +4 -4
- package/dist/{chunk-1qfba14s.js → chunk-r3qpjc6c.js} +4 -4
- package/dist/chunk-v1y901rb.js +3 -0
- package/dist/chunk-w3ywvqy2.js +3 -0
- package/dist/{chunk-2c4gc3ws.js → chunk-y9q3s55d.js} +1 -1
- package/dist/participant-mcp-server.js +5 -5
- package/distribution.json +27 -15
- package/package.json +1 -1
- package/dist/chunk-576jrq3v.js +0 -3
- package/dist/chunk-zfr69r1n.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{__require}from"./chunk-btwmey1h.js";var POST_GEOHASH_MIN_PRECISION=8;var POST_GEOHASH_MAX_PRECISION=16;var POST_GEOHASH_DEFAULT_PRECISION=9;var POST_GEOHASH_PATTERN=/^[0123456789bcdefghjkmnpqrstuvwxyz]{8,16}$/;var BASE32="0123456789bcdefghjkmnpqrstuvwxyz";function encodeGeohash(lat,lng,precision=6){const safePrecision=Math.max(4,Math.min(16,Math.trunc(precision)));const latRange=[-90,90];const lngRange=[-180,180];const bits=[16,8,4,2,1];let isEven=true;let bit=0;let ch=0;let geohash="";const safeLat=clampFinite(lat,-90,90);const safeLng=clampFinite(lng,-180,180);while(geohash.length<safePrecision){if(isEven){const mid=(lngRange[0]+lngRange[1])/2;if(safeLng>=mid){ch|=bits[bit]??0;lngRange[0]=mid}else{lngRange[1]=mid}}else{const mid=(latRange[0]+latRange[1])/2;if(safeLat>=mid){ch|=bits[bit]??0;latRange[0]=mid}else{latRange[1]=mid}}isEven=!isEven;if(bit<4){bit+=1}else{geohash+=BASE32[ch]??"0";bit=0;ch=0}}return geohash}function geohashBounds(geohash){const safeGeohash=geohash.trim().toLowerCase();if(!safeGeohash)return null;const latRange=[-90,90];const lngRange=[-180,180];let isEven=true;for(const character of safeGeohash){const value=BASE32.indexOf(character);if(value<0)return null;for(const mask of[16,8,4,2,1]){if(isEven){bisectRange(lngRange,(value&mask)!==0)}else{bisectRange(latRange,(value&mask)!==0)}isEven=!isEven}}return{west:lngRange[0],south:latRange[0],east:lngRange[1],north:latRange[1]}}function bisectRange(range,useUpperHalf){const mid=(range[0]+range[1])/2;if(useUpperHalf){range[0]=mid}else{range[1]=mid}}function clampFinite(value,min,max){if(value===Number.POSITIVE_INFINITY)return max;if(value===Number.NEGATIVE_INFINITY)return min;if(!Number.isFinite(value))return min;return Math.min(max,Math.max(min,value))}var MEDIA_RELAY_SAFE_MAX_BYTES=99*1024;function readWebpDimensions(bytes){if(bytes.length<20||text4(bytes,0)!=="RIFF"||text4(bytes,8)!=="WEBP"||u32(bytes,4)+8!==bytes.length)return null;let offset=12;let extended=null;let image=null;while(offset<bytes.length){if(offset+8>bytes.length)return null;const kind=text4(bytes,offset);const length=u32(bytes,offset+4);const payload=offset+8;const end=payload+length;const paddedEnd=end+(length&1);if(end>bytes.length||paddedEnd>bytes.length)return null;if(!extended&&kind==="VP8X"){if(length!==10)return null;extended={width:1+u24(bytes,payload+4),height:1+u24(bytes,payload+7)}}else if(!image&&kind==="VP8 "){if(length<10||bytes[payload+3]!==157||bytes[payload+4]!==1||bytes[payload+5]!==42)return null;image={width:(bytes[payload+6]|bytes[payload+7]<<8)&16383,height:(bytes[payload+8]|bytes[payload+9]<<8)&16383}}else if(!image&&kind==="VP8L"){if(length<5||bytes[payload]!==47)return null;const bits=u32(bytes,payload+1);image={width:1+(bits&16383),height:1+(bits>>>14&16383)}}offset=paddedEnd}if(offset!==bytes.length||!image)return null;if(extended&&(extended.width!==image.width||extended.height!==image.height))return null;return extended??image}function text4(bytes,offset){return String.fromCharCode(...bytes.slice(offset,offset+4))}function u24(bytes,offset){return bytes[offset]|bytes[offset+1]<<8|bytes[offset+2]<<16}function u32(bytes,offset){return(bytes[offset]|bytes[offset+1]<<8|bytes[offset+2]<<16|bytes[offset+3]<<24)>>>0}var AGENT_MEDIA_MAX_BASE64_LENGTH=4*Math.ceil(MEDIA_RELAY_SAFE_MAX_BYTES/3);class AgentMediaError extends Error{code;constructor(code){super(code);this.code=code}}function fail(code){throw new AgentMediaError(code)}function validAgentMediaInput(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const media=value;return Object.keys(media).length===4&&Object.keys(media).every((key)=>["contentType","base64","byteSize","sha256"].includes(key))&&["image/webp","video/webm"].includes(media.contentType)&&typeof media.base64==="string"&&media.base64.length>0&&media.base64.length<=AGENT_MEDIA_MAX_BASE64_LENGTH&&media.base64.length%4===0&&/^[A-Za-z0-9+/]*={0,2}$/.test(media.base64)&&Number.isSafeInteger(media.byteSize)&&media.byteSize>0&&media.byteSize<=MEDIA_RELAY_SAFE_MAX_BYTES&&typeof media.sha256==="string"&&/^[0-9a-f]{64}$/.test(media.sha256)}async function inspectAgentMedia(value){if(!validAgentMediaInput(value))fail("invalid_media_input");const binary=atob(value.base64);if(btoa(binary)!==value.base64)fail("invalid_media_base64");const bytes=Uint8Array.from(binary,(character)=>character.charCodeAt(0));if(bytes.length!==value.byteSize)fail("media_size_mismatch");const hash=new Uint8Array(await crypto.subtle.digest("SHA-256",bytes.buffer));const sha256=Array.from(hash,(byte)=>byte.toString(16).padStart(2,"0")).join("");if(sha256!==value.sha256)fail("media_hash_mismatch");const dimensions=value.contentType==="image/webp"?await inspectImage(bytes):await inspectVideo(bytes);return{media:value.contentType==="image/webp"?{kind:"image",contentType:"image/webp",bytes}:{kind:"video",contentType:"video/webm",bytes},summary:{contentType:value.contentType,byteSize:bytes.length,sha256,...dimensions}}}async function inspectImage(bytes){const dimensions=readWebpDimensions(bytes);if(!dimensions)fail("invalid_media_container");if(dimensions.width<1||dimensions.height<1||dimensions.width>1024||dimensions.height>1024)fail("media_dimensions_too_large");try{const{default:decode}=await import("@jsquash/webp/decode.js");const decoded=await decode(Uint8Array.from(bytes).buffer);if(decoded.width!==dimensions.width||decoded.height!==dimensions.height)fail("invalid_media_container");return dimensions}catch{return fail("invalid_media_container")}}async function inspectVideo(bytes){const{Input,BufferSource,WEBM}=await import("mediabunny");const input=new Input({source:new BufferSource(bytes),formats:[WEBM]});let timeout;try{return await Promise.race([(async()=>{const[videos,audios,tracks]=await Promise.all([input.getVideoTracks(),input.getAudioTracks(),input.getTracks()]);if(videos.length!==1||audios.length>1||tracks.length!==videos.length+audios.length)fail("media_tracks_unsupported");const track=videos[0];const[codec,width,height,displayWidth,displayHeight,duration,stats]=await Promise.all([track.getCodec(),track.getCodedWidth(),track.getCodedHeight(),track.getDisplayWidth(),track.getDisplayHeight(),input.computeDuration(),track.computePacketStats(1)]);if(codec!=="vp8"&&codec!=="vp9")fail("media_codec_unsupported");if([width,height,displayWidth,displayHeight].some((size)=>!Number.isFinite(size)||size<1||size>512))fail("media_dimensions_too_large");if(!Number.isFinite(duration)||duration<=0||duration>30)fail("media_video_duration_invalid");if(stats.packetCount<1)fail("invalid_media_container");if(audios[0]&&!["opus","vorbis"].includes(await audios[0].getCodec()??""))fail("media_codec_unsupported");return{width,height,durationMs:Math.ceil(duration*1000)}})(),new Promise((_,reject)=>{timeout=setTimeout(()=>{input.dispose();reject(new AgentMediaError("media_inspection_timeout"))},5000)})])}catch(error){if(error instanceof AgentMediaError)throw error;return fail("invalid_media_container")}finally{clearTimeout(timeout);input.dispose()}}var MAPAPP_CATEGORY_TOKENS=["\uD83C\uDF31","\uD83D\uDCCD","\uD83E\uDDED","\uD83C\uDFA8","\uD83C\uDFB5","\uD83C\uDF7D\uFE0F","\u2615","\uD83D\uDED2","\uD83C\uDFC0","\uD83C\uDFAE","\uD83D\uDCF0","\uD83D\uDCAC","\uD83D\uDCF8","\uD83C\uDFAC","\uD83D\uDCBB","\uD83D\uDEE0\uFE0F","\uD83C\uDFE0","\uD83D\uDE97","\uD83C\uDF0A","\u26F0\uFE0F","\uD83C\uDF33","\uD83D\uDC3E","\uD83C\uDF93","\uD83C\uDFE5","\u26A0\uFE0F","\uD83C\uDF89","\uD83D\uDCBC","\uD83D\uDD2C","\u2708\uFE0F","\uD83E\uDDD8","\uD83E\uDE99","\u2764\uFE0F"];var DEFAULT_MAPAPP_CATEGORY=MAPAPP_CATEGORY_TOKENS[0];import{sendAllBsv,sendBsv}from"@1sat/actions";import{P2PKH,Transaction,Utils}from"@bsv/sdk";var MAX_DIRECT_BSV_SEND_SATOSHIS=2099999999999998;function validateDirectBsvInput(input){const address=input.to.trim();let decoded;try{decoded=Utils.fromBase58Check(address)}catch{return{ok:false,code:"bsv_address_invalid",message:"Enter a valid mainnet BSV address."}}if(decoded.data.length!==20){return{ok:false,code:"bsv_address_invalid",message:"Enter a valid mainnet P2PKH address."}}if(decoded.prefix.length!==1||decoded.prefix[0]!==0){return{ok:false,code:"bsv_address_wrong_network",message:"Direct sends require a mainnet BSV address."}}if(!("satoshis"in input))return{ok:true,address,max:true};if(!Number.isSafeInteger(input.satoshis)||input.satoshis<1||input.satoshis>MAX_DIRECT_BSV_SEND_SATOSHIS){return{ok:false,code:"bsv_amount_invalid",message:`Amount must be a whole number from 1 to ${MAX_DIRECT_BSV_SEND_SATOSHIS} satoshis.`}}return{ok:true,address,satoshis:input.satoshis}}function inspectDirectBsvEvidence(atomicBeef,address){try{const tx=Transaction.fromBEEF(atomicBeef);const script=new P2PKH().lock(address).toHex();const matching=tx.outputs.filter((output)=>output.lockingScript.toHex()===script);if(matching.length!==1)return null;const satoshis=matching[0]?.satoshis;if(typeof satoshis!=="number"||!Number.isSafeInteger(satoshis)||satoshis<1)return null;const inputSatoshis=tx.inputs.map((input)=>input.sourceTransaction?.outputs[input.sourceOutputIndex]?.satoshis);const fee=inputSatoshis.every((value)=>Number.isSafeInteger(value))?inputSatoshis.reduce((sum,value)=>sum+(value??0),0)-tx.outputs.reduce((sum,output)=>sum+(output.satoshis??0),0):null;return{satoshis,fee:fee!==null&&Number.isSafeInteger(fee)&&fee>=0?fee:null}}catch{return null}}import{Hash,Utils as Utils2}from"@bsv/sdk";var MESSAGING_IDENTITY_VERSION="mapapp-messaging-identity-v1";var MESSAGING_IDENTITY_MUTATION_VERSION="mapapp-messaging-identity-mutation-v1";var MAPAPP_MESSAGE_VERSION="mapapp-message-v1";var MAPAPP_MESSAGE_BOX_NAME="mapapp-messaging-v1";var MESSAGEBOX_PROTOCOL=[1,"messagebox"];var MESSAGEBOX_KEY_ID="1";var DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES=8*1024;var MAPAPP_MESSAGE_ID_MAX_BYTES=256;function serializeMessagingIdentityMutationV1(input){const mutation=assertMessagingIdentityMutationV1(input);return new TextEncoder().encode(JSON.stringify({version:mutation.version,operation:mutation.operation,bapId:mutation.bapId,walletIdentityKey:mutation.walletIdentityKey,messageBoxHost:mutation.messageBoxHost,deployment:mutation.deployment,canonicalOrigin:mutation.canonicalOrigin,network:mutation.network,expectedProfileOutpoint:mutation.expectedProfileOutpoint,expectedEvidenceHash:mutation.expectedEvidenceHash,acceptedSequence:mutation.acceptedSequence,projectionVersion:mutation.projectionVersion,clientOperationId:mutation.clientOperationId}))}function serializeMapAppMessageV1(input,maxPlaintextBytes=DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES){const message=assertMapAppMessageV1(input,maxPlaintextBytes);return JSON.stringify({version:message.version,messageId:message.messageId,senderIdentityKey:message.senderIdentityKey,recipientIdentityKey:message.recipientIdentityKey,conversationId:message.conversationId,sentAt:message.sentAt,text:message.text})}function conversationIdForIdentityKeys(first,second){assertCompressedIdentityKey(first,"first identity key");assertCompressedIdentityKey(second,"second identity key");if(first.toLowerCase()===second.toLowerCase())throw new TypeError("Self-messaging is not allowed.");const[left,right]=[first.toLowerCase(),second.toLowerCase()].sort();return Utils2.toHex(Hash.sha256(Array.from(new TextEncoder().encode(`mapapp-messaging/conversation/v1\\0${left}\\0${right}`))))}function assertMapAppMessageV1(value,maxPlaintextBytes=DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES){const record=strictRecord(value,["version","messageId","senderIdentityKey","recipientIdentityKey","conversationId","sentAt","text"],"MapAppMessageV1");if(record.version!==MAPAPP_MESSAGE_VERSION)throw new TypeError("Unsupported MapApp message version.");const messageId=stringField(record,"messageId");if(messageId.trim()===""||new TextEncoder().encode(messageId).byteLength>MAPAPP_MESSAGE_ID_MAX_BYTES)throw new TypeError("messageId must be a bounded non-empty string.");assertCanonicalIsoTimestamp(stringField(record,"sentAt"),"sentAt");const senderIdentityKey=stringField(record,"senderIdentityKey");const recipientIdentityKey=stringField(record,"recipientIdentityKey");assertCompressedIdentityKey(senderIdentityKey,"sender identity key");assertCompressedIdentityKey(recipientIdentityKey,"recipient identity key");if(senderIdentityKey.toLowerCase()===recipientIdentityKey.toLowerCase())throw new TypeError("Self-messaging is not allowed.");const expectedConversationId=conversationIdForIdentityKeys(senderIdentityKey,recipientIdentityKey);if(stringField(record,"conversationId")!==expectedConversationId)throw new TypeError("Message conversation ID does not match its participants.");if(!Number.isSafeInteger(maxPlaintextBytes)||maxPlaintextBytes<=0)throw new TypeError("Plaintext maximum must be a positive safe integer.");const text=stringField(record,"text");if(text.trim()==="")throw new TypeError("Message text must not be blank.");if(new TextEncoder().encode(text).byteLength>maxPlaintextBytes)throw new RangeError("Message text exceeds the plaintext maximum.");return record}function assertMessagingIdentityMutationV1(value){const record=strictRecord(value,["version","operation","bapId","walletIdentityKey","messageBoxHost","deployment","canonicalOrigin","network","expectedProfileOutpoint","expectedEvidenceHash","acceptedSequence","projectionVersion","clientOperationId"],"MessagingIdentityMutationV1");if(record.version!==MESSAGING_IDENTITY_MUTATION_VERSION)throw new TypeError("Unsupported messaging identity mutation version.");if(record.operation!=="register"&&record.operation!=="rotate"&&record.operation!=="revoke")throw new TypeError("Unsupported messaging identity operation.");for(const key of["bapId","messageBoxHost","deployment","canonicalOrigin","clientOperationId"])assertNonEmptyString(record[key],key);assertCompressedIdentityKey(stringField(record,"walletIdentityKey"),"wallet identity key");if(record.network!=="mainnet"&&record.network!=="testnet")throw new TypeError("Unsupported messaging network.");assertProfileEvidenceGroup(record);assertHttpsUrl(stringField(record,"messageBoxHost"),"messageBoxHost");assertHttpsUrl(stringField(record,"canonicalOrigin"),"canonicalOrigin");return record}function assertMessagingIdentityV1(value){const record=strictRecord(value,["version","bapId","walletIdentityKey","messageBoxHost","deployment","canonicalOrigin","network","expectedProfileOutpoint","expectedEvidenceHash","acceptedSequence","projectionVersion"],"MessagingIdentityV1");if(record.version!==MESSAGING_IDENTITY_VERSION)throw new TypeError("Unsupported messaging identity version.");for(const key of["bapId","messageBoxHost","deployment","canonicalOrigin"])assertNonEmptyString(record[key],key);assertCompressedIdentityKey(stringField(record,"walletIdentityKey"),"wallet identity key");if(record.network!=="mainnet"&&record.network!=="testnet")throw new TypeError("Unsupported messaging network.");assertProfileEvidenceGroup(record);assertHttpsUrl(stringField(record,"messageBoxHost"),"messageBoxHost");assertHttpsUrl(stringField(record,"canonicalOrigin"),"canonicalOrigin");return record}function assertCompressedIdentityKey(value,field="identity key"){if(!/^(02|03)[0-9a-fA-F]{64}$/.test(value))throw new TypeError(`${field} must be a compressed public key.`)}function strictRecord(value,keys,name){if(!value||typeof value!=="object"||Array.isArray(value))throw new TypeError(`${name} must be an object.`);const record=value;if(Object.keys(record).length!==keys.length||keys.some((key)=>!(key in record)))throw new TypeError(`${name} has unsupported or missing fields.`);return record}function stringField(record,key){const value=record[key];if(typeof value!=="string")throw new TypeError(`${key} must be a string.`);return value}function numberField(record,key){const value=record[key];if(typeof value!=="number"||!Number.isSafeInteger(value))throw new TypeError(`${key} must be a non-negative safe integer.`);return value}function assertProfileEvidenceGroup(record){const fields=[record.expectedProfileOutpoint,record.expectedEvidenceHash,record.acceptedSequence,record.projectionVersion];if(fields.every((value)=>value===null))return;if(fields.some((value)=>value===null))throw new TypeError("Profile evidence must be entirely present or absent.");assertNonEmptyString(record.expectedProfileOutpoint,"expectedProfileOutpoint");assertNonEmptyString(record.expectedEvidenceHash,"expectedEvidenceHash");if(numberField(record,"acceptedSequence")<1)throw new TypeError("acceptedSequence must be positive.");if(numberField(record,"projectionVersion")<0)throw new TypeError("projectionVersion must be non-negative.")}function assertNonEmptyString(value,field){if(typeof value!=="string"||value.trim()==="")throw new TypeError(`${field} must be a non-empty string.`)}function assertHttpsUrl(value,field){try{const parsed=new URL(String(value));if(parsed.protocol!=="https:"||parsed.username||parsed.password||parsed.pathname!=="/"||parsed.search||parsed.hash)throw new Error}catch{throw new TypeError(`${field} must be an HTTPS origin without a path.`)}}function assertCanonicalIsoTimestamp(value,field="timestamp"){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)||!Number.isFinite(Date.parse(value))||new Date(value).toISOString()!==value)throw new TypeError(`${field} must be a canonical ISO-8601 UTC timestamp.`)}
|
|
3
|
+
export{POST_GEOHASH_MIN_PRECISION,POST_GEOHASH_MAX_PRECISION,POST_GEOHASH_DEFAULT_PRECISION,POST_GEOHASH_PATTERN,encodeGeohash,geohashBounds,MEDIA_RELAY_SAFE_MAX_BYTES,AGENT_MEDIA_MAX_BASE64_LENGTH,AgentMediaError,validAgentMediaInput,inspectAgentMedia,MAPAPP_CATEGORY_TOKENS,MAX_DIRECT_BSV_SEND_SATOSHIS,validateDirectBsvInput,inspectDirectBsvEvidence,MESSAGING_IDENTITY_MUTATION_VERSION,MAPAPP_MESSAGE_VERSION,MAPAPP_MESSAGE_BOX_NAME,MESSAGEBOX_PROTOCOL,MESSAGEBOX_KEY_ID,DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES,MAPAPP_MESSAGE_ID_MAX_BYTES,serializeMessagingIdentityMutationV1,serializeMapAppMessageV1,conversationIdForIdentityKeys,assertMapAppMessageV1,assertMessagingIdentityV1,assertCompressedIdentityKey,assertCanonicalIsoTimestamp};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import*as z from"zod/v4";var diagnosticSchema=z.object({code:z.string(),remedy:z.string()}).describe("Allow-listed failure code and fixed remedy. Contains no upstream error text, credentials, private paths or message content.");var remedies=new Map;function group(remedy,codes){for(const code of codes)remedies.set(code,remedy)}group("Check the selected tool schema, command options and retained connection metadata. Preserve the original wallet binding.",["participant_configuration_invalid","participant_configuration_too_large","participant_invocation_invalid","participant_tool_not_found","participant_arguments_invalid","participant_arguments_too_large","participant_services_configuration_invalid","participant_wallet_target_invalid","payment_input_invalid","invalid_agent_wallet_connection_configuration","setup_deployment_invalid","setup_state_invalid","invalid_operation_id"]);group("Check retained state and input file paths. Reuse the original wallet or its recovery material; do not replace its root.",["participant_existing_wallet_required","participant_arguments_unavailable","setup_existing_directory_unrecognized","setup_file_invalid","setup_recovery_archive_invalid","restore_operations_invalid","local_intent_database_incompatible"]);group("Wait for the active connection or original operation to settle, then reopen the same state. Do not force an unlock or start a replacement action.",["local_intent_repository_busy","execution_in_progress","participant_closing","read_in_progress"]);group("Verify private-file access, writable storage and free space. Keep original files and keys; do not broaden access or recreate the wallet.",["local_intent_repository_open_failed","local_intent_durability_unavailable","local_intent_namespace_limit","wallet_backup_unavailable"]);group("Check the selected provider, unlock state and app permissions. Keep its expected identity and network; do not substitute a wallet.",["wallet_unauthenticated","permission_denied","read_failed","read_timeout","required_method_missing","invalid_read_response","setup_provider_locked","setup_provider_denied","setup_provider_unavailable","setup_provider_binding_changed","participant_connection_changed","participant_wallet_identity_changed","participant_wallet_network_changed","provider_binding_changed","network_binding_changed","identity_binding_changed","caller_mismatch","setup_deployment_changed","setup_identity_changed","setup_wallet_binding_changed"]);group("Use a new nonexistent destination for a new setup/restore. For recovery, retain the exact root, matching ZIP/binding and a closed checkpointed operation copy.",["restore_requires_new_directory","restore_operations_not_checkpointed","restore_outcome_unknown"]);group("Use the original operationId with this workflow's status/reconcile tools. Preserve original evidence; do not create a replacement spend or message.",["original_intake_unavailable","original_identity_unavailable","original_identity_interrupted","original_sponsor_evidence_unavailable","original_sponsor_or_intake_unavailable","original_sponsor_operation_interrupted","original_operation_interrupted","original_payment_evidence_unavailable","payment_evidence_mismatch","payment_binding_changed","wallet_commit_unverified","wallet_evidence_conflict","recovery_binding_conflict","exact_evidence_invalid","exact_evidence_unavailable","operation_already_started","unresolved_operation","original_identity_attempt_unresolved","operation_not_prepared","participant_operation_unavailable","setup_operation_unavailable","messaging_operation_unavailable","participant_invocation_unavailable","request_cancelled"]);group("The original operation is prepared. Execute that same ID only within user authority; do not create a replacement.",["operation_not_started"]);group("Reuse the existing published identity and check readiness. Do not publish another identity.",["identity_already_published"]);group("Check retained wallet configuration and prerequisite availability. Keep original state; after an uncertain action, use its original operationId with status/reconcile.",["participant_startup_unavailable","participant_setup_unavailable","participant_close_unavailable","participant_prerequisite_unavailable","participant_prerequisite_invalid","identity_sponsor_unavailable","identity_prerequisite_changed","payment_services_unavailable"]);function participantDiagnostic(reason,fallback="participant_operation_unavailable"){const safeFallback=remedies.has(fallback)?fallback:"participant_operation_unavailable";const code=typeof reason==="string"&&remedies.has(reason)?reason:safeFallback;return{code,remedy:remedies.get(code)??remedies.get("participant_operation_unavailable")}}function participantErrorDiagnostic(error,fallback){const value=error&&typeof error==="object"?error:{};const filesystem={ENOENT:"participant_existing_wallet_required",EEXIST:"setup_existing_directory_unrecognized",EACCES:"local_intent_repository_open_failed",EPERM:"local_intent_repository_open_failed",ENOSPC:"local_intent_repository_open_failed"};const code=typeof value.code==="string"&&remedies.has(value.code)?value.code:typeof value.message==="string"&&remedies.has(value.message)?value.message:typeof value.code==="string"&&Object.hasOwn(filesystem,value.code)?filesystem[value.code]:value.name==="SyntaxError"||value.name==="ZodError"?"participant_configuration_invalid":undefined;return participantDiagnostic(code,fallback)}function outcomeDiagnostic(outcome){return outcome.kind==="blocked"||outcome.kind==="recovery_required"?{diagnostic:participantDiagnostic(outcome.reason)}:{}}function silenceParticipantConsole(){const methods=["log","info","warn","error","debug"];const originals=methods.map((method)=>console[method]);for(const method of methods)console[method]=()=>{};return()=>{methods.forEach((method,index)=>{console[method]=originals[index]})}}
|
|
3
|
+
export{diagnosticSchema,participantErrorDiagnostic,outcomeDiagnostic,silenceParticipantConsole};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{participantErrorDiagnostic}from"./chunk-
|
|
2
|
+
import{participantErrorDiagnostic}from"./chunk-w3ywvqy2.js";import"./chunk-btwmey1h.js";import{createReadStream}from"fs";import{Client,InMemoryTransport}from"@modelcontextprotocol/client";class ParticipantInvocationError extends Error{code;constructor(code){super(code);this.code=code}}function readParticipantInvocation(args){const command=args[0];if(command!=="tools"&&command!=="call")return null;const result={command,walletArgs:[]};for(let index=1;index<args.length;index+=2){const key=args[index],value=args[index+1];if(!key||!value||value.startsWith("--"))throw new ParticipantInvocationError("participant_invocation_invalid");if(key==="--tool"){if(result.tool||!/^mapapp_[a-z0-9_]+$/u.test(value))throw new ParticipantInvocationError("participant_invocation_invalid");result.tool=value}else if(key==="--arguments-file"){if(command!=="call"||result.argumentsFile)throw new ParticipantInvocationError("participant_invocation_invalid");result.argumentsFile=value}else result.walletArgs.push(key,value)}if(command==="call"&&!result.tool)throw new ParticipantInvocationError("participant_invocation_invalid");return result}async function readInvocationArguments(filename,maxBytes){if(!filename)return{};const chunks=[];let length=0;try{const input=filename==="-"?process.stdin:createReadStream(filename,{end:maxBytes});for await(const chunk of input){const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);length+=bytes.length;if(length>maxBytes)throw new ParticipantInvocationError("participant_arguments_too_large");chunks.push(bytes)}}catch(error){if(error instanceof ParticipantInvocationError)throw error;throw new ParticipantInvocationError("participant_arguments_unavailable")}try{const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks,length)));if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("not_object");return value}catch{throw new ParticipantInvocationError("participant_arguments_invalid")}}async function invokeParticipant(server,invocation,args={}){const client=new Client({name:"mapapp-participant-command",version:"1"});const[left,right]=InMemoryTransport.createLinkedPair();try{await server.connect(right);await client.connect(left);const listed=await client.listTools();const selected=invocation.tool?listed.tools.find((tool)=>tool.name===invocation.tool):undefined;if(invocation.tool&&!selected)throw new ParticipantInvocationError("participant_tool_not_found");if(invocation.command==="tools")return selected?{tools:[selected]}:{tools:listed.tools.map((tool)=>({name:tool.name,description:tool.description})),next:"Use tools --tool <name> for the selected input/output schemas."};return await client.callTool({name:invocation.tool,arguments:args})}finally{await client.close()}}function invocationFailure(error){const diagnostic=participantErrorDiagnostic(error,"participant_invocation_unavailable");return{isError:true,error:diagnostic,next:"Check tool schemas and retained configuration. After an uncertain action, use its original operationId with status/reconcile. Do not create a replacement."}}export{readParticipantInvocation,readInvocationArguments,invokeParticipant,invocationFailure,ParticipantInvocationError};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{participantErrorDiagnostic,silenceParticipantConsole}from"./chunk-
|
|
3
|
+
import{participantErrorDiagnostic,silenceParticipantConsole}from"./chunk-w3ywvqy2.js";import{__require}from"./chunk-btwmey1h.js";import{StdioServerTransport}from"@modelcontextprotocol/server/stdio";var invocationUsage=`Tools: mapapp-participant tools --wallet-dir <existing-state> [--tool <name>]
|
|
4
4
|
Call: mapapp-participant call --wallet-dir <existing-state> --tool <name> [--arguments-file <utf8-json-file-or->]
|
|
5
5
|
Omit --arguments-file for {}. Use - to read JSON from stdin. Calls use the same MCP tools; retain original operation IDs after uncertainty.
|
|
6
6
|
`;var usage=`Usage: mapapp-participant --wallet-dir <existing-protected-wallet>
|
|
@@ -10,10 +10,10 @@ Connect: mapapp-participant connect --wallet-dir <new-connector-directory> --dep
|
|
|
10
10
|
First setup/connect/restore: the final destination must not already exist, even empty. Keep the MCP host/client session open until awaited calls finish.
|
|
11
11
|
One local stdio MCP provides discovery, paid/sponsored/social actions and private messaging. No HTTP listener. Delegation belongs to the user and agent; connected wallets enforce their own permissions. Preserve original operation IDs after uncertainty. Read /developers?guide=agent-setup.
|
|
12
12
|
`;function readParticipantSetupCommand(args){if(!["setup","restore","connect"].includes(args[0]??""))return null;const fields={};const allowed=args[0]==="restore"?["--wallet-dir","--deployment","--root-file","--backup-file","--connection-file","--operations-file"]:args[0]==="connect"?["--wallet-dir","--deployment","--wallet-endpoint","--identity-key"]:["--wallet-dir","--deployment"];for(let i=1;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!allowed.includes(key)||fields[key]||!value||value.startsWith("--"))throw new Error("participant_configuration_invalid");fields[key]=value}if(allowed.some((key)=>!fields[key]))throw new Error("participant_configuration_invalid");return{walletDirectory:fields["--wallet-dir"],deployment:fields["--deployment"],...args[0]==="connect"?{walletEndpoint:fields["--wallet-endpoint"],identityKey:fields["--identity-key"]}:{},...args[0]==="restore"?{restore:{rootFile:fields["--root-file"],backupFile:fields["--backup-file"],connectionFile:fields["--connection-file"],operationsFile:fields["--operations-file"]}}:{}}}function readParticipantMcpConfig(args){if(args.length===1&&["--help","-h"].includes(args[0]))return null;let walletDirectory;let connectionFile;const seen=new Set;for(let i=0;i<args.length;i++){const key=args[i];if(seen.has(key))throw new Error("participant_configuration_invalid");seen.add(key);const value=args[++i];if(!value||value.startsWith("--"))throw new Error("participant_configuration_invalid");if(key==="--wallet-dir")walletDirectory=value;else if(key==="--connection-file")connectionFile=value;else throw new Error("participant_configuration_invalid")}if(!walletDirectory)throw new Error("participant_configuration_invalid");return{walletDirectory,...connectionFile?{connectionFile}:{}}}if(import.meta.main){silenceParticipantConsole();let runtime;let participant;let closing;const setupMode=["setup","restore","connect"].includes(process.argv[2]??"");const invocationMode=["tools","call"].includes(process.argv[2]??"");const close=()=>closing??=(async()=>{try{await participant?.close()}finally{await runtime?.close()}})();const closeInvocation=async()=>{try{await close()}catch{process.stderr.write(JSON.stringify({error:participantErrorDiagnostic(null,"participant_close_unavailable")})+`
|
|
13
|
-
`);process.exitCode=1}};try{const args=process.argv.slice(2);const invocation=invocationMode?(await import("./chunk-
|
|
14
|
-
`)}else if(!config)process.stderr.write(usage+invocationUsage);else{const[{openAgentParticipantRuntime},{createMapAppParticipantServer,PARTICIPANT_MCP_MAX_MESSAGE_BYTES}]=await Promise.all([import("./chunk-
|
|
15
|
-
`);process.exit(1)})};process.once("SIGINT",stop);process.once("SIGTERM",stop);if(invocation){try{const outcome=await(await import("./chunk-
|
|
16
|
-
`);process.exitCode="isError"in outcome&&outcome.isError?1:0}finally{await closeInvocation();process.off("SIGINT",stop);process.off("SIGTERM",stop)}}else{process.stdin.once("end",stop);await participant.server.connect(new StdioServerTransport(process.stdin,process.stdout,{maxBufferSize:PARTICIPANT_MCP_MAX_MESSAGE_BYTES}))}}}catch(error){if(invocationMode){process.stdout.write(JSON.stringify((await import("./chunk-
|
|
13
|
+
`);process.exitCode=1}};try{const args=process.argv.slice(2);const invocation=invocationMode?(await import("./chunk-y9q3s55d.js")).readParticipantInvocation(args):null;const setup=readParticipantSetupCommand(args);const config=setup?null:readParticipantMcpConfig(invocation?.walletArgs??args);if(setup){const{setupParticipantWallet,connectParticipantWallet}=await import("./chunk-8061dj3y.js");const outcome=setup.walletEndpoint&&setup.identityKey?await connectParticipantWallet({...setup,walletEndpoint:setup.walletEndpoint,identityKey:setup.identityKey}):await setupParticipantWallet(setup);process.stdout.write(JSON.stringify(outcome)+`
|
|
14
|
+
`)}else if(!config)process.stderr.write(usage+invocationUsage);else{const[{openAgentParticipantRuntime},{createMapAppParticipantServer,PARTICIPANT_MCP_MAX_MESSAGE_BYTES}]=await Promise.all([import("./chunk-961w3fz4.js"),import("./chunk-esdsjfvs.js")]);const invocationArgs=invocation?await(await import("./chunk-y9q3s55d.js")).readInvocationArguments(invocation.argumentsFile,PARTICIPANT_MCP_MAX_MESSAGE_BYTES):undefined;runtime=await openAgentParticipantRuntime(config);participant=createMapAppParticipantServer(runtime);const stop=()=>{close().then(()=>process.exit(invocation?130:0),()=>{process.stderr.write(JSON.stringify({error:participantErrorDiagnostic(null,"participant_close_unavailable")})+`
|
|
15
|
+
`);process.exit(1)})};process.once("SIGINT",stop);process.once("SIGTERM",stop);if(invocation){try{const outcome=await(await import("./chunk-y9q3s55d.js")).invokeParticipant(participant.server,invocation,invocationArgs);process.stdout.write(JSON.stringify(outcome)+`
|
|
16
|
+
`);process.exitCode="isError"in outcome&&outcome.isError?1:0}finally{await closeInvocation();process.off("SIGINT",stop);process.off("SIGTERM",stop)}}else{process.stdin.once("end",stop);await participant.server.connect(new StdioServerTransport(process.stdin,process.stdout,{maxBufferSize:PARTICIPANT_MCP_MAX_MESSAGE_BYTES}))}}}catch(error){if(invocationMode){process.stdout.write(JSON.stringify((await import("./chunk-y9q3s55d.js")).invocationFailure(error))+`
|
|
17
17
|
`);await closeInvocation();process.exitCode=1}else{const diagnostic=participantErrorDiagnostic(error,setupMode?"participant_setup_unavailable":"participant_startup_unavailable");if(setupMode){process.stdout.write(JSON.stringify({state:"blocked",reason:diagnostic.code,diagnostic})+`
|
|
18
18
|
`)}process.stderr.write(JSON.stringify({error:diagnostic})+`
|
|
19
19
|
`);await closeInvocation();process.exitCode=1}}}export{readParticipantSetupCommand,readParticipantMcpConfig};
|
package/distribution.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": "mapapp-agent-connector-distribution/v1",
|
|
3
3
|
"name": "@jdr377/mapapp-agent-connector",
|
|
4
|
-
"version": "0.1.0-pre.
|
|
4
|
+
"version": "0.1.0-pre.9",
|
|
5
5
|
"runtime": {
|
|
6
6
|
"bun": "1.3.11",
|
|
7
7
|
"requirement": ">=1.3.11 <2.0.0",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
},
|
|
40
40
|
{
|
|
41
41
|
"path": "scripts/lib/agentParticipantRuntime.ts",
|
|
42
|
-
"sha256": "
|
|
42
|
+
"sha256": "c8a038d2509d2157a83f9672ef8351c31e0b090b1323a60e899274c7901dd342"
|
|
43
43
|
},
|
|
44
44
|
{
|
|
45
45
|
"path": "scripts/lib/agentParticipantSetup.ts",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
},
|
|
64
64
|
{
|
|
65
65
|
"path": "server/agent/mcp/diagnostics.ts",
|
|
66
|
-
"sha256": "
|
|
66
|
+
"sha256": "2c24aa5bef3b67b74f6b3c192eca711e3803a3b553331c9e08769f84403f6151"
|
|
67
67
|
},
|
|
68
68
|
{
|
|
69
69
|
"path": "server/agent/mcp/invoke.ts",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
},
|
|
72
72
|
{
|
|
73
73
|
"path": "server/agent/mcp/participant.ts",
|
|
74
|
-
"sha256": "
|
|
74
|
+
"sha256": "9e08a758f6e2a0d2fcd4b8662d31c4cc8381822c3630380108289f37f7583394"
|
|
75
75
|
},
|
|
76
76
|
{
|
|
77
77
|
"path": "server/agent/mcp/publication.ts",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
},
|
|
80
80
|
{
|
|
81
81
|
"path": "server/agent/onboarding.ts",
|
|
82
|
-
"sha256": "
|
|
82
|
+
"sha256": "8834579ec8747c9b9e2b26eba9361d0674c09ef15c528e1913cad38e662abd79"
|
|
83
83
|
},
|
|
84
84
|
{
|
|
85
85
|
"path": "server/agent/parser.ts",
|
|
@@ -149,6 +149,10 @@
|
|
|
149
149
|
"path": "src/bitcoin/agentParticipantBinding.ts",
|
|
150
150
|
"sha256": "6dfdb3686685f2b97e003b48ce2a79a30e6d314a2f5913498e6418d85becc73f"
|
|
151
151
|
},
|
|
152
|
+
{
|
|
153
|
+
"path": "src/bitcoin/agentPayment.ts",
|
|
154
|
+
"sha256": "32d0b9abcc9838606d0c7bf6e6eb4b1cb082ee954228f71e7b8adbff3ed1d7b6"
|
|
155
|
+
},
|
|
152
156
|
{
|
|
153
157
|
"path": "src/bitcoin/agentSocialAction.ts",
|
|
154
158
|
"sha256": "15db1009f84777e1fa3c97066f9d531c1c7606ee6b2d107e218139a2876748c4"
|
|
@@ -161,6 +165,10 @@
|
|
|
161
165
|
"path": "src/bitcoin/agentWalletConnection.ts",
|
|
162
166
|
"sha256": "030095304a7950488b711df3f7a2b31c0472aeea812dd5e7fe86bee2e9e3407f"
|
|
163
167
|
},
|
|
168
|
+
{
|
|
169
|
+
"path": "src/bitcoin/directBsv.ts",
|
|
170
|
+
"sha256": "398a35474174d9abb768c33b3c1d9e0dd41e03f52bb34b612f8090b42557c001"
|
|
171
|
+
},
|
|
164
172
|
{
|
|
165
173
|
"path": "src/bitcoin/localIntentStore.ts",
|
|
166
174
|
"sha256": "7947218dcd2bb30f0ff3fb3b77d925bc2fe894aa966013b1c2e972f14822a3c8"
|
|
@@ -201,6 +209,10 @@
|
|
|
201
209
|
"path": "src/bitcoin/messaging/sessionCache.ts",
|
|
202
210
|
"sha256": "529823120d74b8d04b179e01f202098016c96e038eb8c5ef509eecab2b88e07a"
|
|
203
211
|
},
|
|
212
|
+
{
|
|
213
|
+
"path": "src/bitcoin/nativeEvidenceRecovery.ts",
|
|
214
|
+
"sha256": "64dd4719c1a856b07cda80be0a6a06cff947d53bccf0dd4466adccb1beaab88c"
|
|
215
|
+
},
|
|
204
216
|
{
|
|
205
217
|
"path": "src/bitcoin/nativeManagedAction.ts",
|
|
206
218
|
"sha256": "d3d89f4776b25794c5f32cbcd5a624c1ec6426fc5fc81d98c325705d9263b441"
|
|
@@ -243,20 +255,20 @@
|
|
|
243
255
|
}
|
|
244
256
|
],
|
|
245
257
|
"files": {
|
|
246
|
-
"README.md": "
|
|
258
|
+
"README.md": "249efad35d1c5ad4615f864a218d9ff5cb6365ffde1dc6100f7c2465e27d2ea3",
|
|
247
259
|
"bun.lock": "70b49fe644812578e2c365f4600fa57b694710f16a8095dc05e4dbc257b3c58a",
|
|
248
|
-
"dist/chunk-
|
|
249
|
-
"dist/chunk-
|
|
250
|
-
"dist/chunk-2c4gc3ws.js": "835c82f9f8a0a9a0f7763628390ddcaf307620fa5d42af6885abc58572b05965",
|
|
251
|
-
"dist/chunk-2z3hggm4.js": "808b1d6a4378c6a0be0817df098de278c77a35556ef3b317159ee2d8ae75085e",
|
|
252
|
-
"dist/chunk-576jrq3v.js": "d9feca2aaf0e3dc49bee60f611782d5b91cfd2fbf37da962289ef6502352b97c",
|
|
253
|
-
"dist/chunk-b04ecsf5.js": "79fd5a5561a9d7910f1588768c8e6a079d24099c3ed38906b7fc3970fda181e7",
|
|
260
|
+
"dist/chunk-8061dj3y.js": "c0381b214c983113be3b15289d36aafbe77b4c52393262c6ecdae965e05650cf",
|
|
261
|
+
"dist/chunk-961w3fz4.js": "f7a1b84455cdb9d04e87b39b91fa442dae4c82c6f574fac6b4bae02333c6423d",
|
|
254
262
|
"dist/chunk-btwmey1h.js": "4e3cec1f9adaea9464cd99ea40ea0b7a693d800040e59540856f6c2b8ff013ee",
|
|
255
263
|
"dist/chunk-c74qq5ek.js": "36c949a5d21a3a2ac2c0e7a1020ebc995f1b665194ea43e8e29244eb8e166257",
|
|
256
264
|
"dist/chunk-e6y2yzbj.js": "4be64909a0536718a794f3d7bd11c4b5af95097ca7295c05cde1394a80027b38",
|
|
257
|
-
"dist/chunk-
|
|
258
|
-
"dist/
|
|
259
|
-
"
|
|
265
|
+
"dist/chunk-esdsjfvs.js": "8b82b924b10c75572583b7d0efef41bdcab4a963a3a8ae265344e814a69b6f43",
|
|
266
|
+
"dist/chunk-r3qpjc6c.js": "f67bba0127453f065c7928c80042859b3a67e5eb6c3f8a26c85b1071e0828e66",
|
|
267
|
+
"dist/chunk-v1y901rb.js": "15dcac0514ced3cec54a8475dfcf6990c300078af1256cea5adb79dc7fc69914",
|
|
268
|
+
"dist/chunk-w3ywvqy2.js": "f07eb86ce5e8d42f873c0af3882c7b7913047dd69fd4e18df5470bd2ccf194de",
|
|
269
|
+
"dist/chunk-y9q3s55d.js": "7a350d3e97ee4721fe7c282db1abba21cda65c40dd6b5253a8d5267b13130529",
|
|
270
|
+
"dist/participant-mcp-server.js": "da79034abe940da7647c898e114f61a40b39233a0f91d33794aaadd134f993d7",
|
|
271
|
+
"package.json": "79fe6a278bdc535e3471978c61d4026e08dd02a782e2a579870eaf443b17fe64"
|
|
260
272
|
},
|
|
261
273
|
"dependencies": {
|
|
262
274
|
"@1sat/actions": "0.0.224",
|
package/package.json
CHANGED
package/dist/chunk-576jrq3v.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{__require}from"./chunk-btwmey1h.js";var POST_GEOHASH_MIN_PRECISION=8;var POST_GEOHASH_MAX_PRECISION=16;var POST_GEOHASH_DEFAULT_PRECISION=9;var POST_GEOHASH_PATTERN=/^[0123456789bcdefghjkmnpqrstuvwxyz]{8,16}$/;var BASE32="0123456789bcdefghjkmnpqrstuvwxyz";function encodeGeohash(lat,lng,precision=6){const safePrecision=Math.max(4,Math.min(16,Math.trunc(precision)));const latRange=[-90,90];const lngRange=[-180,180];const bits=[16,8,4,2,1];let isEven=true;let bit=0;let ch=0;let geohash="";const safeLat=clampFinite(lat,-90,90);const safeLng=clampFinite(lng,-180,180);while(geohash.length<safePrecision){if(isEven){const mid=(lngRange[0]+lngRange[1])/2;if(safeLng>=mid){ch|=bits[bit]??0;lngRange[0]=mid}else{lngRange[1]=mid}}else{const mid=(latRange[0]+latRange[1])/2;if(safeLat>=mid){ch|=bits[bit]??0;latRange[0]=mid}else{latRange[1]=mid}}isEven=!isEven;if(bit<4){bit+=1}else{geohash+=BASE32[ch]??"0";bit=0;ch=0}}return geohash}function geohashBounds(geohash){const safeGeohash=geohash.trim().toLowerCase();if(!safeGeohash)return null;const latRange=[-90,90];const lngRange=[-180,180];let isEven=true;for(const character of safeGeohash){const value=BASE32.indexOf(character);if(value<0)return null;for(const mask of[16,8,4,2,1]){if(isEven){bisectRange(lngRange,(value&mask)!==0)}else{bisectRange(latRange,(value&mask)!==0)}isEven=!isEven}}return{west:lngRange[0],south:latRange[0],east:lngRange[1],north:latRange[1]}}function bisectRange(range,useUpperHalf){const mid=(range[0]+range[1])/2;if(useUpperHalf){range[0]=mid}else{range[1]=mid}}function clampFinite(value,min,max){if(value===Number.POSITIVE_INFINITY)return max;if(value===Number.NEGATIVE_INFINITY)return min;if(!Number.isFinite(value))return min;return Math.min(max,Math.max(min,value))}var MEDIA_RELAY_SAFE_MAX_BYTES=99*1024;function readWebpDimensions(bytes){if(bytes.length<20||text4(bytes,0)!=="RIFF"||text4(bytes,8)!=="WEBP"||u32(bytes,4)+8!==bytes.length)return null;let offset=12;let extended=null;let image=null;while(offset<bytes.length){if(offset+8>bytes.length)return null;const kind=text4(bytes,offset);const length=u32(bytes,offset+4);const payload=offset+8;const end=payload+length;const paddedEnd=end+(length&1);if(end>bytes.length||paddedEnd>bytes.length)return null;if(!extended&&kind==="VP8X"){if(length!==10)return null;extended={width:1+u24(bytes,payload+4),height:1+u24(bytes,payload+7)}}else if(!image&&kind==="VP8 "){if(length<10||bytes[payload+3]!==157||bytes[payload+4]!==1||bytes[payload+5]!==42)return null;image={width:(bytes[payload+6]|bytes[payload+7]<<8)&16383,height:(bytes[payload+8]|bytes[payload+9]<<8)&16383}}else if(!image&&kind==="VP8L"){if(length<5||bytes[payload]!==47)return null;const bits=u32(bytes,payload+1);image={width:1+(bits&16383),height:1+(bits>>>14&16383)}}offset=paddedEnd}if(offset!==bytes.length||!image)return null;if(extended&&(extended.width!==image.width||extended.height!==image.height))return null;return extended??image}function text4(bytes,offset){return String.fromCharCode(...bytes.slice(offset,offset+4))}function u24(bytes,offset){return bytes[offset]|bytes[offset+1]<<8|bytes[offset+2]<<16}function u32(bytes,offset){return(bytes[offset]|bytes[offset+1]<<8|bytes[offset+2]<<16|bytes[offset+3]<<24)>>>0}var AGENT_MEDIA_MAX_BASE64_LENGTH=4*Math.ceil(MEDIA_RELAY_SAFE_MAX_BYTES/3);class AgentMediaError extends Error{code;constructor(code){super(code);this.code=code}}function fail(code){throw new AgentMediaError(code)}function validAgentMediaInput(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const media=value;return Object.keys(media).length===4&&Object.keys(media).every((key)=>["contentType","base64","byteSize","sha256"].includes(key))&&["image/webp","video/webm"].includes(media.contentType)&&typeof media.base64==="string"&&media.base64.length>0&&media.base64.length<=AGENT_MEDIA_MAX_BASE64_LENGTH&&media.base64.length%4===0&&/^[A-Za-z0-9+/]*={0,2}$/.test(media.base64)&&Number.isSafeInteger(media.byteSize)&&media.byteSize>0&&media.byteSize<=MEDIA_RELAY_SAFE_MAX_BYTES&&typeof media.sha256==="string"&&/^[0-9a-f]{64}$/.test(media.sha256)}async function inspectAgentMedia(value){if(!validAgentMediaInput(value))fail("invalid_media_input");const binary=atob(value.base64);if(btoa(binary)!==value.base64)fail("invalid_media_base64");const bytes=Uint8Array.from(binary,(character)=>character.charCodeAt(0));if(bytes.length!==value.byteSize)fail("media_size_mismatch");const hash=new Uint8Array(await crypto.subtle.digest("SHA-256",bytes.buffer));const sha256=Array.from(hash,(byte)=>byte.toString(16).padStart(2,"0")).join("");if(sha256!==value.sha256)fail("media_hash_mismatch");const dimensions=value.contentType==="image/webp"?await inspectImage(bytes):await inspectVideo(bytes);return{media:value.contentType==="image/webp"?{kind:"image",contentType:"image/webp",bytes}:{kind:"video",contentType:"video/webm",bytes},summary:{contentType:value.contentType,byteSize:bytes.length,sha256,...dimensions}}}async function inspectImage(bytes){const dimensions=readWebpDimensions(bytes);if(!dimensions)fail("invalid_media_container");if(dimensions.width<1||dimensions.height<1||dimensions.width>1024||dimensions.height>1024)fail("media_dimensions_too_large");try{const{default:decode}=await import("@jsquash/webp/decode.js");const decoded=await decode(Uint8Array.from(bytes).buffer);if(decoded.width!==dimensions.width||decoded.height!==dimensions.height)fail("invalid_media_container");return dimensions}catch{return fail("invalid_media_container")}}async function inspectVideo(bytes){const{Input,BufferSource,WEBM}=await import("mediabunny");const input=new Input({source:new BufferSource(bytes),formats:[WEBM]});let timeout;try{return await Promise.race([(async()=>{const[videos,audios,tracks]=await Promise.all([input.getVideoTracks(),input.getAudioTracks(),input.getTracks()]);if(videos.length!==1||audios.length>1||tracks.length!==videos.length+audios.length)fail("media_tracks_unsupported");const track=videos[0];const[codec,width,height,displayWidth,displayHeight,duration,stats]=await Promise.all([track.getCodec(),track.getCodedWidth(),track.getCodedHeight(),track.getDisplayWidth(),track.getDisplayHeight(),input.computeDuration(),track.computePacketStats(1)]);if(codec!=="vp8"&&codec!=="vp9")fail("media_codec_unsupported");if([width,height,displayWidth,displayHeight].some((size)=>!Number.isFinite(size)||size<1||size>512))fail("media_dimensions_too_large");if(!Number.isFinite(duration)||duration<=0||duration>30)fail("media_video_duration_invalid");if(stats.packetCount<1)fail("invalid_media_container");if(audios[0]&&!["opus","vorbis"].includes(await audios[0].getCodec()??""))fail("media_codec_unsupported");return{width,height,durationMs:Math.ceil(duration*1000)}})(),new Promise((_,reject)=>{timeout=setTimeout(()=>{input.dispose();reject(new AgentMediaError("media_inspection_timeout"))},5000)})])}catch(error){if(error instanceof AgentMediaError)throw error;return fail("invalid_media_container")}finally{clearTimeout(timeout);input.dispose()}}var MAPAPP_CATEGORY_TOKENS=["\uD83C\uDF31","\uD83D\uDCCD","\uD83E\uDDED","\uD83C\uDFA8","\uD83C\uDFB5","\uD83C\uDF7D\uFE0F","\u2615","\uD83D\uDED2","\uD83C\uDFC0","\uD83C\uDFAE","\uD83D\uDCF0","\uD83D\uDCAC","\uD83D\uDCF8","\uD83C\uDFAC","\uD83D\uDCBB","\uD83D\uDEE0\uFE0F","\uD83C\uDFE0","\uD83D\uDE97","\uD83C\uDF0A","\u26F0\uFE0F","\uD83C\uDF33","\uD83D\uDC3E","\uD83C\uDF93","\uD83C\uDFE5","\u26A0\uFE0F","\uD83C\uDF89","\uD83D\uDCBC","\uD83D\uDD2C","\u2708\uFE0F","\uD83E\uDDD8","\uD83E\uDE99","\u2764\uFE0F"];var DEFAULT_MAPAPP_CATEGORY=MAPAPP_CATEGORY_TOKENS[0];import{Hash,Utils}from"@bsv/sdk";var MESSAGING_IDENTITY_VERSION="mapapp-messaging-identity-v1";var MESSAGING_IDENTITY_MUTATION_VERSION="mapapp-messaging-identity-mutation-v1";var MAPAPP_MESSAGE_VERSION="mapapp-message-v1";var MAPAPP_MESSAGE_BOX_NAME="mapapp-messaging-v1";var MESSAGEBOX_PROTOCOL=[1,"messagebox"];var MESSAGEBOX_KEY_ID="1";var DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES=8*1024;var MAPAPP_MESSAGE_ID_MAX_BYTES=256;function serializeMessagingIdentityMutationV1(input){const mutation=assertMessagingIdentityMutationV1(input);return new TextEncoder().encode(JSON.stringify({version:mutation.version,operation:mutation.operation,bapId:mutation.bapId,walletIdentityKey:mutation.walletIdentityKey,messageBoxHost:mutation.messageBoxHost,deployment:mutation.deployment,canonicalOrigin:mutation.canonicalOrigin,network:mutation.network,expectedProfileOutpoint:mutation.expectedProfileOutpoint,expectedEvidenceHash:mutation.expectedEvidenceHash,acceptedSequence:mutation.acceptedSequence,projectionVersion:mutation.projectionVersion,clientOperationId:mutation.clientOperationId}))}function serializeMapAppMessageV1(input,maxPlaintextBytes=DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES){const message=assertMapAppMessageV1(input,maxPlaintextBytes);return JSON.stringify({version:message.version,messageId:message.messageId,senderIdentityKey:message.senderIdentityKey,recipientIdentityKey:message.recipientIdentityKey,conversationId:message.conversationId,sentAt:message.sentAt,text:message.text})}function conversationIdForIdentityKeys(first,second){assertCompressedIdentityKey(first,"first identity key");assertCompressedIdentityKey(second,"second identity key");if(first.toLowerCase()===second.toLowerCase())throw new TypeError("Self-messaging is not allowed.");const[left,right]=[first.toLowerCase(),second.toLowerCase()].sort();return Utils.toHex(Hash.sha256(Array.from(new TextEncoder().encode(`mapapp-messaging/conversation/v1\\0${left}\\0${right}`))))}function assertMapAppMessageV1(value,maxPlaintextBytes=DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES){const record=strictRecord(value,["version","messageId","senderIdentityKey","recipientIdentityKey","conversationId","sentAt","text"],"MapAppMessageV1");if(record.version!==MAPAPP_MESSAGE_VERSION)throw new TypeError("Unsupported MapApp message version.");const messageId=stringField(record,"messageId");if(messageId.trim()===""||new TextEncoder().encode(messageId).byteLength>MAPAPP_MESSAGE_ID_MAX_BYTES)throw new TypeError("messageId must be a bounded non-empty string.");assertCanonicalIsoTimestamp(stringField(record,"sentAt"),"sentAt");const senderIdentityKey=stringField(record,"senderIdentityKey");const recipientIdentityKey=stringField(record,"recipientIdentityKey");assertCompressedIdentityKey(senderIdentityKey,"sender identity key");assertCompressedIdentityKey(recipientIdentityKey,"recipient identity key");if(senderIdentityKey.toLowerCase()===recipientIdentityKey.toLowerCase())throw new TypeError("Self-messaging is not allowed.");const expectedConversationId=conversationIdForIdentityKeys(senderIdentityKey,recipientIdentityKey);if(stringField(record,"conversationId")!==expectedConversationId)throw new TypeError("Message conversation ID does not match its participants.");if(!Number.isSafeInteger(maxPlaintextBytes)||maxPlaintextBytes<=0)throw new TypeError("Plaintext maximum must be a positive safe integer.");const text=stringField(record,"text");if(text.trim()==="")throw new TypeError("Message text must not be blank.");if(new TextEncoder().encode(text).byteLength>maxPlaintextBytes)throw new RangeError("Message text exceeds the plaintext maximum.");return record}function assertMessagingIdentityMutationV1(value){const record=strictRecord(value,["version","operation","bapId","walletIdentityKey","messageBoxHost","deployment","canonicalOrigin","network","expectedProfileOutpoint","expectedEvidenceHash","acceptedSequence","projectionVersion","clientOperationId"],"MessagingIdentityMutationV1");if(record.version!==MESSAGING_IDENTITY_MUTATION_VERSION)throw new TypeError("Unsupported messaging identity mutation version.");if(record.operation!=="register"&&record.operation!=="rotate"&&record.operation!=="revoke")throw new TypeError("Unsupported messaging identity operation.");for(const key of["bapId","messageBoxHost","deployment","canonicalOrigin","clientOperationId"])assertNonEmptyString(record[key],key);assertCompressedIdentityKey(stringField(record,"walletIdentityKey"),"wallet identity key");if(record.network!=="mainnet"&&record.network!=="testnet")throw new TypeError("Unsupported messaging network.");assertProfileEvidenceGroup(record);assertHttpsUrl(stringField(record,"messageBoxHost"),"messageBoxHost");assertHttpsUrl(stringField(record,"canonicalOrigin"),"canonicalOrigin");return record}function assertMessagingIdentityV1(value){const record=strictRecord(value,["version","bapId","walletIdentityKey","messageBoxHost","deployment","canonicalOrigin","network","expectedProfileOutpoint","expectedEvidenceHash","acceptedSequence","projectionVersion"],"MessagingIdentityV1");if(record.version!==MESSAGING_IDENTITY_VERSION)throw new TypeError("Unsupported messaging identity version.");for(const key of["bapId","messageBoxHost","deployment","canonicalOrigin"])assertNonEmptyString(record[key],key);assertCompressedIdentityKey(stringField(record,"walletIdentityKey"),"wallet identity key");if(record.network!=="mainnet"&&record.network!=="testnet")throw new TypeError("Unsupported messaging network.");assertProfileEvidenceGroup(record);assertHttpsUrl(stringField(record,"messageBoxHost"),"messageBoxHost");assertHttpsUrl(stringField(record,"canonicalOrigin"),"canonicalOrigin");return record}function assertCompressedIdentityKey(value,field="identity key"){if(!/^(02|03)[0-9a-fA-F]{64}$/.test(value))throw new TypeError(`${field} must be a compressed public key.`)}function strictRecord(value,keys,name){if(!value||typeof value!=="object"||Array.isArray(value))throw new TypeError(`${name} must be an object.`);const record=value;if(Object.keys(record).length!==keys.length||keys.some((key)=>!(key in record)))throw new TypeError(`${name} has unsupported or missing fields.`);return record}function stringField(record,key){const value=record[key];if(typeof value!=="string")throw new TypeError(`${key} must be a string.`);return value}function numberField(record,key){const value=record[key];if(typeof value!=="number"||!Number.isSafeInteger(value))throw new TypeError(`${key} must be a non-negative safe integer.`);return value}function assertProfileEvidenceGroup(record){const fields=[record.expectedProfileOutpoint,record.expectedEvidenceHash,record.acceptedSequence,record.projectionVersion];if(fields.every((value)=>value===null))return;if(fields.some((value)=>value===null))throw new TypeError("Profile evidence must be entirely present or absent.");assertNonEmptyString(record.expectedProfileOutpoint,"expectedProfileOutpoint");assertNonEmptyString(record.expectedEvidenceHash,"expectedEvidenceHash");if(numberField(record,"acceptedSequence")<1)throw new TypeError("acceptedSequence must be positive.");if(numberField(record,"projectionVersion")<0)throw new TypeError("projectionVersion must be non-negative.")}function assertNonEmptyString(value,field){if(typeof value!=="string"||value.trim()==="")throw new TypeError(`${field} must be a non-empty string.`)}function assertHttpsUrl(value,field){try{const parsed=new URL(String(value));if(parsed.protocol!=="https:"||parsed.username||parsed.password||parsed.pathname!=="/"||parsed.search||parsed.hash)throw new Error}catch{throw new TypeError(`${field} must be an HTTPS origin without a path.`)}}function assertCanonicalIsoTimestamp(value,field="timestamp"){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)||!Number.isFinite(Date.parse(value))||new Date(value).toISOString()!==value)throw new TypeError(`${field} must be a canonical ISO-8601 UTC timestamp.`)}
|
|
3
|
-
export{POST_GEOHASH_MIN_PRECISION,POST_GEOHASH_MAX_PRECISION,POST_GEOHASH_DEFAULT_PRECISION,POST_GEOHASH_PATTERN,encodeGeohash,geohashBounds,MEDIA_RELAY_SAFE_MAX_BYTES,AGENT_MEDIA_MAX_BASE64_LENGTH,AgentMediaError,validAgentMediaInput,inspectAgentMedia,MAPAPP_CATEGORY_TOKENS,MESSAGING_IDENTITY_MUTATION_VERSION,MAPAPP_MESSAGE_VERSION,MAPAPP_MESSAGE_BOX_NAME,MESSAGEBOX_PROTOCOL,MESSAGEBOX_KEY_ID,DEFAULT_MESSAGE_PLAINTEXT_MAX_BYTES,MAPAPP_MESSAGE_ID_MAX_BYTES,serializeMessagingIdentityMutationV1,serializeMapAppMessageV1,conversationIdForIdentityKeys,assertMapAppMessageV1,assertMessagingIdentityV1,assertCompressedIdentityKey,assertCanonicalIsoTimestamp};
|
package/dist/chunk-zfr69r1n.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import*as z from"zod/v4";var diagnosticSchema=z.object({code:z.string(),remedy:z.string()}).describe("Allow-listed failure code and fixed remedy. Contains no upstream error text, credentials, private paths or message content.");var remedies=new Map;function group(remedy,codes){for(const code of codes)remedies.set(code,remedy)}group("Check the selected tool schema, command options and retained connection metadata. Preserve the original wallet binding.",["participant_configuration_invalid","participant_configuration_too_large","participant_invocation_invalid","participant_tool_not_found","participant_arguments_invalid","participant_arguments_too_large","participant_services_configuration_invalid","participant_wallet_target_invalid","invalid_agent_wallet_connection_configuration","setup_deployment_invalid","setup_state_invalid","invalid_operation_id"]);group("Check retained state and input file paths. Reuse the original wallet or its recovery material; do not replace its root.",["participant_existing_wallet_required","participant_arguments_unavailable","setup_existing_directory_unrecognized","setup_file_invalid","setup_recovery_archive_invalid","restore_operations_invalid","local_intent_database_incompatible"]);group("Wait for the active connection or original operation to settle, then reopen the same state. Do not force an unlock or start a replacement action.",["local_intent_repository_busy","execution_in_progress","participant_closing","read_in_progress"]);group("Verify private-file access, writable storage and free space. Keep original files and keys; do not broaden access or recreate the wallet.",["local_intent_repository_open_failed","local_intent_durability_unavailable","local_intent_namespace_limit","wallet_backup_unavailable"]);group("Check the selected provider, unlock state and app permissions. Keep its expected identity and network; do not substitute a wallet.",["wallet_unauthenticated","permission_denied","read_failed","read_timeout","required_method_missing","invalid_read_response","setup_provider_locked","setup_provider_denied","setup_provider_unavailable","setup_provider_binding_changed","participant_connection_changed","participant_wallet_identity_changed","participant_wallet_network_changed","provider_binding_changed","network_binding_changed","identity_binding_changed","caller_mismatch","setup_deployment_changed","setup_identity_changed","setup_wallet_binding_changed"]);group("Use a new nonexistent destination for a new setup/restore. For recovery, retain the exact root, matching ZIP/binding and a closed checkpointed operation copy.",["restore_requires_new_directory","restore_operations_not_checkpointed","restore_outcome_unknown"]);group("Use the original operationId with this workflow's status/reconcile tools. Preserve original evidence; do not create a replacement spend or message.",["original_intake_unavailable","original_identity_unavailable","original_identity_interrupted","original_sponsor_evidence_unavailable","original_sponsor_or_intake_unavailable","original_sponsor_operation_interrupted","original_operation_interrupted","operation_already_started","unresolved_operation","original_identity_attempt_unresolved","operation_not_prepared","participant_operation_unavailable","setup_operation_unavailable","messaging_operation_unavailable","participant_invocation_unavailable","request_cancelled"]);group("The original operation is prepared. Execute that same ID only within user authority; do not create a replacement.",["operation_not_started"]);group("Reuse the existing published identity and check readiness. Do not publish another identity.",["identity_already_published"]);group("Check retained wallet configuration and prerequisite availability. Keep original state; after an uncertain action, use its original operationId with status/reconcile.",["participant_startup_unavailable","participant_setup_unavailable","participant_close_unavailable","participant_prerequisite_unavailable","participant_prerequisite_invalid","identity_sponsor_unavailable","identity_prerequisite_changed"]);function participantDiagnostic(reason,fallback="participant_operation_unavailable"){const safeFallback=remedies.has(fallback)?fallback:"participant_operation_unavailable";const code=typeof reason==="string"&&remedies.has(reason)?reason:safeFallback;return{code,remedy:remedies.get(code)??remedies.get("participant_operation_unavailable")}}function participantErrorDiagnostic(error,fallback){const value=error&&typeof error==="object"?error:{};const filesystem={ENOENT:"participant_existing_wallet_required",EEXIST:"setup_existing_directory_unrecognized",EACCES:"local_intent_repository_open_failed",EPERM:"local_intent_repository_open_failed",ENOSPC:"local_intent_repository_open_failed"};const code=typeof value.code==="string"&&remedies.has(value.code)?value.code:typeof value.message==="string"&&remedies.has(value.message)?value.message:typeof value.code==="string"&&Object.hasOwn(filesystem,value.code)?filesystem[value.code]:value.name==="SyntaxError"||value.name==="ZodError"?"participant_configuration_invalid":undefined;return participantDiagnostic(code,fallback)}function outcomeDiagnostic(outcome){return outcome.kind==="blocked"||outcome.kind==="recovery_required"?{diagnostic:participantDiagnostic(outcome.reason)}:{}}function silenceParticipantConsole(){const methods=["log","info","warn","error","debug"];const originals=methods.map((method)=>console[method]);for(const method of methods)console[method]=()=>{};return()=>{methods.forEach((method,index)=>{console[method]=originals[index]})}}
|
|
3
|
-
export{diagnosticSchema,participantErrorDiagnostic,outcomeDiagnostic,silenceParticipantConsole};
|