@applica-software-guru/persona-sdk 0.1.61 → 0.1.63

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.
@@ -72,9 +72,16 @@ function Chat() {
72
72
  <PersonaRuntimeProvider
73
73
  dev
74
74
  logger={logger}
75
+ context={{
76
+ data: {
77
+ username: 'Bruno Trimone Agent',
78
+ userAgent: navigator.userAgent,
79
+ },
80
+ }}
75
81
  tools={{
76
82
  get_user_agent: () => {
77
- return navigator.userAgent || 'unknown';
83
+ const userAgent = 'Bruno Trimone Agent';
84
+ return { userAgent };
78
85
  },
79
86
  get_client_date: () => {
80
87
  const date = new Date();
@@ -83,8 +90,6 @@ function Chat() {
83
90
  }}
84
91
  protocols={{
85
92
  rest: true,
86
- webrtc: true,
87
- websocket: true,
88
93
  }}
89
94
  session={session}
90
95
  apiKey="2398utf8g$9pahwv8#93q8.h8349q*!ty89w4uefghwqh849tg934yg894hq3g89q34h9"
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  MessageListenerCallback,
3
- PersonaMessage,
4
- PersonaPayload,
3
+ PersonaPacket,
5
4
  PersonaProtocol,
6
5
  PersonaTransaction,
7
6
  ProtocolStatus,
@@ -21,17 +20,17 @@ abstract class PersonaProtocolBase implements PersonaProtocol {
21
20
  this.statusChangeCallbacks.push(callback);
22
21
  }
23
22
 
24
- public addMessageListener(callback: MessageListenerCallback) {
23
+ public addPacketListener(callback: MessageListenerCallback) {
25
24
  this.messageCallbacks.push(callback);
26
25
  }
27
26
  public async syncSession(session: Session): Promise<void> {
28
27
  this.session = session;
29
28
  }
30
29
 
31
- public async notifyMessage(message: PersonaPayload): Promise<void> {
30
+ public async notifyPacket(message: PersonaPacket): Promise<void> {
32
31
  this.messageCallbacks.forEach((callback) => callback(message));
33
32
  }
34
- public async notifyMessages(messages: PersonaPayload[]): Promise<void> {
33
+ public async notifyPackets(messages: PersonaPacket[]): Promise<void> {
35
34
  messages.forEach((message) => {
36
35
  this.messageCallbacks.forEach((callback) => callback(message));
37
36
  });
@@ -58,7 +57,7 @@ abstract class PersonaProtocolBase implements PersonaProtocol {
58
57
  abstract getPriority(): number;
59
58
  abstract connect(session?: Session): Promise<Session>;
60
59
  abstract disconnect(): Promise<void>;
61
- abstract send(message: Array<PersonaMessage> | PersonaMessage): Promise<void>;
60
+ abstract sendPacket(packet: PersonaPacket): Promise<void>;
62
61
 
63
62
  public onTransaction(_: PersonaTransaction) {}
64
63
  }
@@ -1,5 +1,13 @@
1
1
  import { PersonaProtocolBase } from './base';
2
- import { PersonaResponse, Session, ProtocolStatus, PersonaProtocolBaseConfig, PersonaMessage } from '../types';
2
+ import {
3
+ PersonaResponse,
4
+ Session,
5
+ ProtocolStatus,
6
+ PersonaProtocolBaseConfig,
7
+ PersonaMessage,
8
+ PersonaPacket,
9
+ PersonaCommand,
10
+ } from '../types';
3
11
 
4
12
  type PersonaRESTProtocolConfig = PersonaProtocolBaseConfig & {
5
13
  apiUrl: string;
@@ -11,6 +19,7 @@ class PersonaRESTProtocol extends PersonaProtocolBase {
11
19
  session: Session;
12
20
  config: PersonaRESTProtocolConfig;
13
21
  notify: boolean = true;
22
+ context: Record<string, any> = {};
14
23
 
15
24
  constructor(config: PersonaRESTProtocolConfig) {
16
25
  super();
@@ -41,22 +50,24 @@ class PersonaRESTProtocol extends PersonaProtocolBase {
41
50
  this.session = session;
42
51
  }
43
52
 
44
- public async send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {
53
+ public async sendPacket(packet: PersonaPacket): Promise<void> {
45
54
  const { apiUrl, apiKey, agentId } = this.config;
46
55
  const sessionId = this.session ?? 'new';
47
- const input = message;
48
-
49
- const response = await fetch(`${apiUrl}/agents/${agentId}/sessions/${sessionId}/messages`, {
50
- body: JSON.stringify({ userMessage: input }),
56
+ if (packet.type === 'command' && (packet?.payload as PersonaCommand)?.command == 'set_initial_context') {
57
+ this.context = (packet?.payload as PersonaCommand)?.arguments;
58
+ return;
59
+ }
60
+ const input = packet.payload as PersonaMessage;
61
+ const response = await fetch(`${apiUrl}/sessions/${sessionId}/messages`, {
62
+ body: JSON.stringify({ agentId, userMessage: input, initial_context: this.context }),
51
63
  method: 'POST',
52
64
  headers: {
53
65
  'Content-Type': 'application/json',
54
- 'x-fox-apikey': apiKey,
55
66
  'x-persona-apikey': apiKey,
56
67
  },
57
68
  });
58
69
  const personaResponse = (await response.json()) as PersonaResponse;
59
- this.notifyMessages(
70
+ this.notifyPackets(
60
71
  personaResponse.response.messages.map((payload) => ({
61
72
  type: 'message',
62
73
  payload,
@@ -6,7 +6,7 @@ import {
6
6
  PersonaTransaction,
7
7
  FunctionCall,
8
8
  ReadonlyJSONObject,
9
- PersonaMessage,
9
+ PersonaPacket,
10
10
  } from '../types';
11
11
 
12
12
  type FinishTransactionRequest = {
@@ -134,10 +134,7 @@ class PersonaTransactionProtocol extends PersonaProtocolBase {
134
134
  this.session = session;
135
135
  }
136
136
 
137
- public async send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {
138
- this.config.logger?.debug('Sending message:', message);
139
- throw new Error('Not implemented');
140
- }
137
+ public async sendPacket(_: PersonaPacket): Promise<void> {}
141
138
 
142
139
  public onTransaction(transaction: PersonaTransaction): void {
143
140
  if (!this.config.onTransaction) {
@@ -1,5 +1,5 @@
1
1
  import { PersonaProtocolBase } from './base';
2
- import { PersonaMessage, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';
2
+ import { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';
3
3
 
4
4
  type AudioAnalysisData = {
5
5
  localAmplitude: number;
@@ -187,14 +187,14 @@ class PersonaWebRTCClient {
187
187
  };
188
188
  }
189
189
 
190
- public sendMessage(message: Array<PersonaMessage> | PersonaMessage): void {
190
+ public sendPacket(packet: PersonaPacket): void {
191
191
  if (!this.dataChannel) {
192
192
  this.config.logger?.warn('Data channel is not open, cannot send message');
193
193
  return;
194
194
  }
195
195
 
196
- this.dataChannel.send(JSON.stringify({ type: 'request', payload: message }));
197
- this.config.logger?.info('Sent message:', message);
196
+ this.dataChannel.send(JSON.stringify(packet));
197
+ this.config.logger?.info('Sent message:', packet);
198
198
  }
199
199
 
200
200
  private _startAnalyzers(): void {
@@ -274,8 +274,8 @@ class PersonaWebRTCProtocol extends PersonaProtocolBase {
274
274
  this.autostart = config?.autostart ?? false;
275
275
  this.webRTCClient = new PersonaWebRTCClient(config);
276
276
  this.webRTCClient.addMessageCallback((msg: MessageEvent) => {
277
- const data = JSON.parse(msg.data) as PersonaPayload;
278
- this.notifyMessage(data);
277
+ const data = JSON.parse(msg.data) as PersonaPacket;
278
+ this.notifyPacket(data);
279
279
  });
280
280
  }
281
281
 
@@ -322,12 +322,12 @@ class PersonaWebRTCProtocol extends PersonaProtocolBase {
322
322
  this.config?.logger?.debug('Disconnected from WebRTC');
323
323
  }
324
324
 
325
- public send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {
325
+ public sendPacket(packet: PersonaPacket): Promise<void> {
326
326
  if (this.status !== 'connected') {
327
327
  return Promise.reject(new Error('Not connected'));
328
328
  }
329
329
 
330
- this.webRTCClient.sendMessage(message);
330
+ this.webRTCClient.sendPacket(packet);
331
331
  return Promise.resolve();
332
332
  }
333
333
  }
@@ -1,4 +1,4 @@
1
- import { PersonaMessage, PersonaPayload, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';
1
+ import { PersonaPacket, PersonaProtocolBaseConfig, ProtocolStatus, Session } from '../types';
2
2
  import { PersonaProtocolBase } from './base';
3
3
 
4
4
  type PersonaWebSocketProtocolConfig = PersonaProtocolBaseConfig & {
@@ -56,8 +56,8 @@ class PersonaWebSocketProtocol extends PersonaProtocolBase {
56
56
  this.setStatus('connected');
57
57
  });
58
58
  this.webSocket.addEventListener('message', (event) => {
59
- const data = JSON.parse(event.data) as PersonaPayload;
60
- this.notifyMessage(data);
59
+ const data = JSON.parse(event.data) as PersonaPacket;
60
+ this.notifyPacket(data);
61
61
  });
62
62
  this.webSocket.addEventListener('close', () => {
63
63
  this.setStatus('disconnected');
@@ -86,9 +86,9 @@ class PersonaWebSocketProtocol extends PersonaProtocolBase {
86
86
  return Promise.resolve();
87
87
  }
88
88
 
89
- public send(message: Array<PersonaMessage> | PersonaMessage): Promise<void> {
89
+ public sendPacket(packet: PersonaPacket): Promise<void> {
90
90
  if (this.webSocket && this.status === 'connected') {
91
- this.webSocket.send(JSON.stringify({ type: 'request', payload: message }));
91
+ this.webSocket.send(JSON.stringify(packet));
92
92
  return Promise.resolve();
93
93
  } else {
94
94
  return Promise.reject(new Error('WebSocket is not connected'));
package/src/runtime.tsx CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  PersonaConfig,
11
11
  PersonaMessage,
12
- PersonaPayload,
12
+ PersonaPacket,
13
13
  PersonaProtocol,
14
14
  PersonaProtocolBaseConfig,
15
15
  PersonaReasoning,
@@ -58,6 +58,7 @@ function fileToBase64(file: File): Promise<string> {
58
58
 
59
59
  function PersonaRuntimeProviderInner({
60
60
  dev = false,
61
+ baseUrl,
61
62
  protocols: _protocols,
62
63
  logger,
63
64
  children,
@@ -76,7 +77,7 @@ function PersonaRuntimeProviderInner({
76
77
  }
77
78
 
78
79
  if (typeof _protocols === 'object' && _protocols !== null) {
79
- const baseEndpoint = dev ? 'localhost:8000' : 'persona.applica.guru/api';
80
+ const baseEndpoint = dev ? 'localhost:8000' : baseUrl || 'persona.applica.guru/api';
80
81
  const baseEndpointProtocol = dev ? 'http' : 'https';
81
82
  const baseWebSocketProtocol = dev ? 'ws' : 'wss';
82
83
  let availableProtocols = Object.keys(_protocols)
@@ -162,9 +163,18 @@ function PersonaRuntimeProviderInner({
162
163
  protocol.addStatusChangeListener((status: ProtocolStatus) => {
163
164
  logger?.debug(`${protocol.getName()} has notified new status: ${status}`);
164
165
  protocolsStatus.set(protocol.getName(), status);
166
+ if (status === 'connected' && config.context) {
167
+ protocol.sendPacket({
168
+ type: 'command',
169
+ payload: {
170
+ command: 'set_initial_context',
171
+ arguments: config.context,
172
+ },
173
+ });
174
+ }
165
175
  setProtocolsStatus(new Map(protocolsStatus));
166
176
  });
167
- protocol.addMessageListener((message: PersonaPayload) => {
177
+ protocol.addPacketListener((message: PersonaPacket) => {
168
178
  if (message.type === 'message') {
169
179
  const personaMessage = message.payload as PersonaMessage;
170
180
  setMessages((currentConversation) =>
@@ -227,7 +237,7 @@ function PersonaRuntimeProviderInner({
227
237
  });
228
238
  }
229
239
  logger?.debug('Sending message:', content);
230
- await protocol?.send(content);
240
+ await protocol?.sendPacket({ type: 'request', payload: content });
231
241
 
232
242
  setIsRunning(false);
233
243
  };
@@ -302,10 +312,10 @@ function usePersonaRuntimeProtocol(protocol: string): PersonaProtocol | null {
302
312
  ...protocolInstance,
303
313
  connect: protocolInstance.connect.bind(protocolInstance),
304
314
  disconnect: protocolInstance.disconnect.bind(protocolInstance),
305
- send: protocolInstance.send.bind(protocolInstance),
315
+ sendPacket: protocolInstance.sendPacket.bind(protocolInstance),
306
316
  setSession: protocolInstance.setSession.bind(protocolInstance),
307
317
  addStatusChangeListener: protocolInstance.addStatusChangeListener.bind(protocolInstance),
308
- addMessageListener: protocolInstance.addMessageListener.bind(protocolInstance),
318
+ addPacketListener: protocolInstance.addPacketListener.bind(protocolInstance),
309
319
  getName: protocolInstance.getName.bind(protocolInstance),
310
320
  getPriority: protocolInstance.getPriority.bind(protocolInstance),
311
321
  status: status || protocolInstance.status,
package/src/types.ts CHANGED
@@ -38,9 +38,9 @@ export type PersonaSession = {
38
38
  };
39
39
 
40
40
  export type PersonaAgentContext = {
41
- data: unknown;
42
- files: PersonaFile[];
43
- session: PersonaSession;
41
+ data: Record<string, unknown>;
42
+ files?: PersonaFile[];
43
+ session?: PersonaSession;
44
44
  };
45
45
 
46
46
  export type PersonaTransaction = {
@@ -78,13 +78,27 @@ export type PersonaSource = {
78
78
  mostRelevant?: boolean;
79
79
  };
80
80
 
81
+ export type PersonaCommand = {
82
+ command: 'get_mcp_assets' | 'set_initial_context';
83
+ arguments: Record<string, unknown>;
84
+ };
85
+
86
+ export type PersonaRequest = PersonaMessage | Array<PersonaMessage> | string;
87
+
88
+ export type PersonaPacketPayload = PersonaRequest | PersonaCommand | PersonaReasoning | PersonaTransaction;
89
+
90
+ export type PersonaPacket = {
91
+ type: 'request' | 'message' | 'command' | 'reasoning' | 'mcp_assets' | 'transaction';
92
+ payload?: PersonaPacketPayload;
93
+ };
94
+
81
95
  export type PersonaMessage = {
82
96
  id?: string | null;
83
97
  protocol?: string;
84
98
  thought?: string;
85
99
  text: string; //todo: puo essere null
86
100
  image?: PersonaImage;
87
- type: 'reasoning' | 'text' | 'transaction';
101
+ type: 'reasoning' | 'text' | 'transaction' | 'command';
88
102
  role: 'user' | 'assistant' | 'function';
89
103
  files?: PersonaFile[];
90
104
  sources?: PersonaSource[];
@@ -94,11 +108,6 @@ export type PersonaMessage = {
94
108
  functionResponse?: FunctionResponse;
95
109
  };
96
110
 
97
- export type PersonaPayload = {
98
- type: 'message' | 'transaction' | 'reasoning';
99
- payload: PersonaMessage | PersonaTransaction | PersonaReasoning;
100
- };
101
-
102
111
  export type ModelResponse = {
103
112
  messages: PersonaMessage[];
104
113
  };
@@ -120,7 +129,7 @@ export type PersonaWebRTCConfig = PersonaBaseConfig & {
120
129
 
121
130
  export type Session = string | null | undefined;
122
131
 
123
- export type MessageListenerCallback = (message: PersonaPayload) => void;
132
+ export type MessageListenerCallback = (message: PersonaPacket) => void;
124
133
  export type StatusChangeCallback = (status: ProtocolStatus) => void;
125
134
 
126
135
  export type ProtocolStatus = 'disconnected' | 'connecting' | 'connected';
@@ -144,10 +153,10 @@ export interface PersonaProtocol {
144
153
 
145
154
  setSession: (session: Session) => Promise<void>;
146
155
 
147
- send: (content: Array<PersonaMessage> | PersonaMessage) => Promise<void>;
156
+ sendPacket: (packet: PersonaPacket) => Promise<void>;
148
157
  clearListeners: () => void;
149
158
  addStatusChangeListener: (callback: StatusChangeCallback) => void;
150
- addMessageListener: (callback: MessageListenerCallback) => void;
159
+ addPacketListener: (callback: MessageListenerCallback) => void;
151
160
  }
152
161
 
153
162
  export type PersonaConfig = PersonaBaseConfig &
@@ -157,8 +166,14 @@ export type PersonaConfig = PersonaBaseConfig &
157
166
  * use it only for development purposes.
158
167
  */
159
168
  dev?: boolean;
169
+ /**
170
+ * The base URL of the API.
171
+ * @default 'persona.applica.guru/api'
172
+ */
173
+ baseUrl?: string;
160
174
  session?: Session;
161
175
  children: ReactNode;
176
+ context?: PersonaAgentContext;
162
177
  protocols:
163
178
  | PersonaProtocol[]
164
179
  | {