|
| 1 | +/** |
| 2 | + * Copyright 2025 © BeeAI a Series of LF Projects, LLC |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +import { |
| 7 | + ClientFactory, |
| 8 | + ClientFactoryOptions, |
| 9 | + DefaultAgentCardResolver, |
| 10 | + JsonRpcTransportFactory, |
| 11 | +} from '@a2a-js/sdk/client'; |
| 12 | +import { type ContextToken, createAuthenticatedFetch, getAgentCardPath } from 'agentstack-sdk'; |
| 13 | +import { useEffect, useState } from 'react'; |
| 14 | + |
| 15 | +import { createContext, createContextToken } from './api'; |
| 16 | +import { BASE_URL, PROVIDER_ID } from './constants'; |
| 17 | +import type { Session } from './types'; |
| 18 | +import { extractTextFromMessage, resolveAgentMetadata } from './utils'; |
| 19 | + |
| 20 | +async function ensureSession() { |
| 21 | + if (!BASE_URL || !PROVIDER_ID) { |
| 22 | + throw new Error(`Missing required environment variables.`); |
| 23 | + } |
| 24 | + |
| 25 | + const context = await createContext(); |
| 26 | + const contextToken = await createContextToken(context.id); |
| 27 | + const client = await createClient(contextToken); |
| 28 | + const metadata = await resolveAgentMetadata({ client, contextToken }); |
| 29 | + |
| 30 | + return { |
| 31 | + client, |
| 32 | + contextId: context.id, |
| 33 | + metadata, |
| 34 | + }; |
| 35 | +} |
| 36 | + |
| 37 | +async function createClient(contextToken: ContextToken) { |
| 38 | + const fetchImpl = createAuthenticatedFetch(contextToken.token); |
| 39 | + |
| 40 | + const factory = new ClientFactory( |
| 41 | + ClientFactoryOptions.createFrom(ClientFactoryOptions.default, { |
| 42 | + transports: [new JsonRpcTransportFactory({ fetchImpl })], |
| 43 | + cardResolver: new DefaultAgentCardResolver({ fetchImpl }), |
| 44 | + }), |
| 45 | + ); |
| 46 | + |
| 47 | + const agentCardPath = getAgentCardPath(PROVIDER_ID); |
| 48 | + const client = await factory.createFromUrl(BASE_URL, agentCardPath); |
| 49 | + |
| 50 | + return client; |
| 51 | +} |
| 52 | + |
| 53 | +export function useAgent() { |
| 54 | + const [session, setSession] = useState<Session>(); |
| 55 | + const [isInitializing, setIsInitializing] = useState(false); |
| 56 | + const [error, setError] = useState(''); |
| 57 | + |
| 58 | + useEffect(() => { |
| 59 | + if (session) { |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + let cancelled = false; |
| 64 | + |
| 65 | + (async () => { |
| 66 | + try { |
| 67 | + setIsInitializing(true); |
| 68 | + |
| 69 | + const session = await ensureSession(); |
| 70 | + |
| 71 | + if (cancelled) { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + setSession(session); |
| 76 | + } catch (error) { |
| 77 | + if (cancelled) { |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + const message = error instanceof Error ? error.message : 'Failed to connect to agent.'; |
| 82 | + |
| 83 | + setError(message); |
| 84 | + } finally { |
| 85 | + if (!cancelled) { |
| 86 | + setIsInitializing(false); |
| 87 | + } |
| 88 | + } |
| 89 | + })(); |
| 90 | + |
| 91 | + return () => { |
| 92 | + cancelled = true; |
| 93 | + }; |
| 94 | + }, [session]); |
| 95 | + |
| 96 | + const sendMessage = async ({ text }: { text: string }) => { |
| 97 | + if (!session) { |
| 98 | + throw new Error('Agent is not ready yet.'); |
| 99 | + } |
| 100 | + |
| 101 | + const { client, contextId, metadata } = session; |
| 102 | + |
| 103 | + const runStream = async () => { |
| 104 | + const stream = client.sendMessageStream({ |
| 105 | + message: { |
| 106 | + kind: 'message', |
| 107 | + role: 'user', |
| 108 | + messageId: crypto.randomUUID(), |
| 109 | + contextId, |
| 110 | + parts: [{ kind: 'text', text }], |
| 111 | + metadata, |
| 112 | + }, |
| 113 | + }); |
| 114 | + |
| 115 | + let agentText = ''; |
| 116 | + |
| 117 | + for await (const event of stream) { |
| 118 | + if (event.kind === 'status-update' || event.kind === 'message') { |
| 119 | + const message = event.kind === 'message' ? event : event.status.message; |
| 120 | + const text = extractTextFromMessage(message); |
| 121 | + |
| 122 | + if (text) { |
| 123 | + agentText += text; |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + return { |
| 129 | + text: agentText, |
| 130 | + }; |
| 131 | + }; |
| 132 | + |
| 133 | + return await runStream(); |
| 134 | + }; |
| 135 | + |
| 136 | + return { |
| 137 | + session, |
| 138 | + isInitializing, |
| 139 | + error, |
| 140 | + sendMessage, |
| 141 | + }; |
| 142 | +} |
0 commit comments