react-native-agentic-ai 0.0.2 → 0.2.0

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.
Files changed (70) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +253 -14
  3. package/lib/module/components/AIAgent.js +185 -0
  4. package/lib/module/components/AIAgent.js.map +1 -0
  5. package/lib/module/components/AgentChatBar.js +268 -0
  6. package/lib/module/components/AgentChatBar.js.map +1 -0
  7. package/lib/module/components/AgentOverlay.js +53 -0
  8. package/lib/module/components/AgentOverlay.js.map +1 -0
  9. package/lib/module/core/AgentRuntime.js +640 -0
  10. package/lib/module/core/AgentRuntime.js.map +1 -0
  11. package/lib/module/core/FiberTreeWalker.js +362 -0
  12. package/lib/module/core/FiberTreeWalker.js.map +1 -0
  13. package/lib/module/core/MCPBridge.js +98 -0
  14. package/lib/module/core/MCPBridge.js.map +1 -0
  15. package/lib/module/core/ScreenDehydrator.js +46 -0
  16. package/lib/module/core/ScreenDehydrator.js.map +1 -0
  17. package/lib/module/core/systemPrompt.js +164 -0
  18. package/lib/module/core/systemPrompt.js.map +1 -0
  19. package/lib/module/core/types.js +2 -0
  20. package/lib/module/core/types.js.map +1 -0
  21. package/lib/module/hooks/useAction.js +32 -0
  22. package/lib/module/hooks/useAction.js.map +1 -0
  23. package/lib/module/index.js +17 -0
  24. package/lib/module/index.js.map +1 -0
  25. package/lib/module/package.json +1 -0
  26. package/lib/module/providers/GeminiProvider.js +294 -0
  27. package/lib/module/providers/GeminiProvider.js.map +1 -0
  28. package/lib/module/utils/logger.js +17 -0
  29. package/lib/module/utils/logger.js.map +1 -0
  30. package/lib/typescript/package.json +1 -0
  31. package/lib/typescript/src/components/AIAgent.d.ts +65 -0
  32. package/lib/typescript/src/components/AIAgent.d.ts.map +1 -0
  33. package/lib/typescript/src/components/AgentChatBar.d.ts +15 -0
  34. package/lib/typescript/src/components/AgentChatBar.d.ts.map +1 -0
  35. package/lib/typescript/src/components/AgentOverlay.d.ts +10 -0
  36. package/lib/typescript/src/components/AgentOverlay.d.ts.map +1 -0
  37. package/lib/typescript/src/core/AgentRuntime.d.ts +53 -0
  38. package/lib/typescript/src/core/AgentRuntime.d.ts.map +1 -0
  39. package/lib/typescript/src/core/FiberTreeWalker.d.ts +31 -0
  40. package/lib/typescript/src/core/FiberTreeWalker.d.ts.map +1 -0
  41. package/lib/typescript/src/core/MCPBridge.d.ts +23 -0
  42. package/lib/typescript/src/core/MCPBridge.d.ts.map +1 -0
  43. package/lib/typescript/src/core/ScreenDehydrator.d.ts +20 -0
  44. package/lib/typescript/src/core/ScreenDehydrator.d.ts.map +1 -0
  45. package/lib/typescript/src/core/systemPrompt.d.ts +9 -0
  46. package/lib/typescript/src/core/systemPrompt.d.ts.map +1 -0
  47. package/lib/typescript/src/core/types.d.ts +176 -0
  48. package/lib/typescript/src/core/types.d.ts.map +1 -0
  49. package/lib/typescript/src/hooks/useAction.d.ts +13 -0
  50. package/lib/typescript/src/hooks/useAction.d.ts.map +1 -0
  51. package/lib/typescript/src/index.d.ts +10 -0
  52. package/lib/typescript/src/index.d.ts.map +1 -0
  53. package/lib/typescript/src/providers/GeminiProvider.d.ts +43 -0
  54. package/lib/typescript/src/providers/GeminiProvider.d.ts.map +1 -0
  55. package/lib/typescript/src/utils/logger.d.ts +7 -0
  56. package/lib/typescript/src/utils/logger.d.ts.map +1 -0
  57. package/package.json +135 -12
  58. package/src/components/AIAgent.tsx +262 -0
  59. package/src/components/AgentChatBar.tsx +258 -0
  60. package/src/components/AgentOverlay.tsx +48 -0
  61. package/src/core/AgentRuntime.ts +661 -0
  62. package/src/core/FiberTreeWalker.ts +404 -0
  63. package/src/core/MCPBridge.ts +110 -0
  64. package/src/core/ScreenDehydrator.ts +53 -0
  65. package/src/core/systemPrompt.ts +162 -0
  66. package/src/core/types.ts +233 -0
  67. package/src/hooks/useAction.ts +40 -0
  68. package/src/index.ts +22 -0
  69. package/src/providers/GeminiProvider.ts +283 -0
  70. package/src/utils/logger.ts +21 -0
@@ -0,0 +1,640 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * AgentRuntime — The main agent loop, inspired by page-agent.js.
5
+ *
6
+ * Flow:
7
+ * 1. Walk Fiber tree → detect interactive elements
8
+ * 2. Dehydrate screen → text for LLM
9
+ * 3. Send to AI provider with tools
10
+ * 4. Parse tool call → execute (tap, type, navigate, done)
11
+ * 5. If not done, repeat from step 1 (re-dehydrate after UI change)
12
+ */
13
+
14
+ import { logger } from "../utils/logger.js";
15
+ import { walkFiberTree } from "./FiberTreeWalker.js";
16
+ import { dehydrateScreen } from "./ScreenDehydrator.js";
17
+ import { buildSystemPrompt } from "./systemPrompt.js";
18
+ const DEFAULT_MAX_STEPS = 10;
19
+
20
+ // ─── Agent Runtime ─────────────────────────────────────────────
21
+
22
+ export class AgentRuntime {
23
+ tools = new Map();
24
+ actions = new Map();
25
+ history = [];
26
+ isRunning = false;
27
+ lastAskUserQuestion = null;
28
+ constructor(provider, config, rootRef, navRef) {
29
+ this.provider = provider;
30
+ this.config = config;
31
+ this.rootRef = rootRef;
32
+ this.navRef = navRef;
33
+ this.registerBuiltInTools();
34
+
35
+ // Apply customTools — mirrors page-agent: null = remove, otherwise override
36
+ if (config.customTools) {
37
+ for (const [name, tool] of Object.entries(config.customTools)) {
38
+ if (tool === null) {
39
+ this.tools.delete(name);
40
+ logger.info('AgentRuntime', `Removed tool: ${name}`);
41
+ } else {
42
+ this.tools.set(name, tool);
43
+ logger.info('AgentRuntime', `Overrode tool: ${name}`);
44
+ }
45
+ }
46
+ }
47
+ }
48
+
49
+ // ─── Tool Registration ─────────────────────────────────────
50
+
51
+ registerBuiltInTools() {
52
+ // tap — universal interaction (mirrors RNTL's dispatchEvent pattern)
53
+ this.tools.set('tap', {
54
+ name: 'tap',
55
+ description: 'Tap an interactive element by its index. Works universally on buttons, switches, and custom components.',
56
+ parameters: {
57
+ index: {
58
+ type: 'number',
59
+ description: 'The index of the element to tap',
60
+ required: true
61
+ }
62
+ },
63
+ execute: async args => {
64
+ const {
65
+ interactives: elements
66
+ } = walkFiberTree(this.rootRef, this.getWalkConfig());
67
+ const element = elements.find(el => el.index === args.index);
68
+ if (!element) {
69
+ return `❌ Element with index ${args.index} not found. Available indexes: ${elements.map(e => e.index).join(', ')}`;
70
+ }
71
+
72
+ // Strategy 1: Switch — call onValueChange (like RNTL's fireEvent('valueChange'))
73
+ if (element.type === 'switch' && element.props.onValueChange) {
74
+ try {
75
+ element.props.onValueChange(!element.props.value);
76
+ await new Promise(resolve => setTimeout(resolve, 500));
77
+ return `✅ Toggled [${args.index}] "${element.label}" to ${!element.props.value}`;
78
+ } catch (error) {
79
+ return `❌ Error toggling [${args.index}]: ${error.message}`;
80
+ }
81
+ }
82
+
83
+ // Strategy 2: Direct onPress (covers Pressable, Button, custom components)
84
+ if (element.props.onPress) {
85
+ try {
86
+ element.props.onPress();
87
+ await new Promise(resolve => setTimeout(resolve, 500));
88
+ return `✅ Tapped [${args.index}] "${element.label}"`;
89
+ } catch (error) {
90
+ return `❌ Error tapping [${args.index}]: ${error.message}`;
91
+ }
92
+ }
93
+
94
+ // Strategy 3: Bubble up Fiber tree (like RNTL's findEventHandler → element.parent)
95
+ let fiber = element.fiberNode?.return;
96
+ let bubbleDepth = 0;
97
+ while (fiber && bubbleDepth < 5) {
98
+ const parentProps = fiber.memoizedProps || {};
99
+ if (parentProps.onPress && typeof parentProps.onPress === 'function') {
100
+ try {
101
+ parentProps.onPress();
102
+ await new Promise(resolve => setTimeout(resolve, 500));
103
+ return `✅ Tapped parent of [${args.index}] "${element.label}"`;
104
+ } catch (error) {
105
+ return `❌ Error tapping parent of [${args.index}]: ${error.message}`;
106
+ }
107
+ }
108
+ fiber = fiber.return;
109
+ bubbleDepth++;
110
+ }
111
+ return `❌ Element [${args.index}] "${element.label}" has no tap handler (no onPress or onValueChange found).`;
112
+ }
113
+ });
114
+
115
+ // type — type text into a TextInput
116
+ this.tools.set('type', {
117
+ name: 'type',
118
+ description: 'Type text into a text-input element by its index.',
119
+ parameters: {
120
+ index: {
121
+ type: 'number',
122
+ description: 'The index of the text-input element',
123
+ required: true
124
+ },
125
+ text: {
126
+ type: 'string',
127
+ description: 'The text to type',
128
+ required: true
129
+ }
130
+ },
131
+ execute: async args => {
132
+ const {
133
+ interactives: elements
134
+ } = walkFiberTree(this.rootRef, this.getWalkConfig());
135
+ const element = elements.find(el => el.index === args.index);
136
+ if (!element) {
137
+ return `❌ Element with index ${args.index} not found.`;
138
+ }
139
+ if (!element.props.onChangeText) {
140
+ return `❌ Element [${args.index}] "${element.label}" is not a text input.`;
141
+ }
142
+ try {
143
+ element.props.onChangeText(args.text);
144
+ return `✅ Typed "${args.text}" into [${args.index}] "${element.label}"`;
145
+ } catch (error) {
146
+ return `❌ Error typing: ${error.message}`;
147
+ }
148
+ }
149
+ });
150
+
151
+ // navigate — navigate to a screen (supports React Navigation + Expo Router)
152
+ this.tools.set('navigate', {
153
+ name: 'navigate',
154
+ description: 'Navigate to a specific screen in the app.',
155
+ parameters: {
156
+ screen: {
157
+ type: 'string',
158
+ description: 'Screen name or path to navigate to',
159
+ required: true
160
+ },
161
+ params: {
162
+ type: 'string',
163
+ description: 'Optional JSON params object',
164
+ required: false
165
+ }
166
+ },
167
+ execute: async args => {
168
+ // Expo Router path: use router.push()
169
+ if (this.config.router) {
170
+ try {
171
+ const path = args.screen.startsWith('/') ? args.screen : `/${args.screen}`;
172
+ this.config.router.push(path);
173
+ await new Promise(resolve => setTimeout(resolve, 500));
174
+ return `✅ Navigated to "${path}"`;
175
+ } catch (error) {
176
+ return `❌ Navigation error: ${error.message}`;
177
+ }
178
+ }
179
+
180
+ // React Navigation path: use navRef.navigate()
181
+ if (!this.navRef) {
182
+ return '❌ Navigation ref not available.';
183
+ }
184
+ if (!this.navRef.isReady()) {
185
+ await new Promise(resolve => setTimeout(resolve, 1000));
186
+ if (!this.navRef.isReady()) {
187
+ return '❌ Navigation is not ready yet.';
188
+ }
189
+ }
190
+ try {
191
+ const params = args.params ? typeof args.params === 'string' ? JSON.parse(args.params) : args.params : undefined;
192
+ this.navRef.navigate(args.screen, params);
193
+ await new Promise(resolve => setTimeout(resolve, 500));
194
+ return `✅ Navigated to "${args.screen}"${params ? ` with params: ${JSON.stringify(params)}` : ''}`;
195
+ } catch (error) {
196
+ return `❌ Navigation error: ${error.message}. Available screens: ${this.getRouteNames().join(', ')}`;
197
+ }
198
+ }
199
+ });
200
+
201
+ // done — complete the task
202
+ this.tools.set('done', {
203
+ name: 'done',
204
+ description: 'Complete the task with a message to the user.',
205
+ parameters: {
206
+ text: {
207
+ type: 'string',
208
+ description: 'Response message to the user',
209
+ required: true
210
+ },
211
+ success: {
212
+ type: 'boolean',
213
+ description: 'Whether the task was completed successfully',
214
+ required: true
215
+ }
216
+ },
217
+ execute: async args => {
218
+ return args.text;
219
+ }
220
+ });
221
+
222
+ // ask_user — ask for clarification (mirrors page-agent: blocks until user responds)
223
+ this.tools.set('ask_user', {
224
+ name: 'ask_user',
225
+ description: 'Ask the user a question and wait for their answer. Use this if you need more information or clarification.',
226
+ parameters: {
227
+ question: {
228
+ type: 'string',
229
+ description: 'Question to ask the user',
230
+ required: true
231
+ }
232
+ },
233
+ execute: async args => {
234
+ if (this.config.onAskUser) {
235
+ // Page-agent pattern: block until user responds, then continue the loop
236
+ this.config.onStatusUpdate?.('Waiting for your answer...');
237
+ const answer = await this.config.onAskUser(args.question);
238
+ return `User answered: ${answer}`;
239
+ }
240
+ // Legacy fallback: break the loop (context will be lost)
241
+ return `❓ ${args.question}`;
242
+ }
243
+ });
244
+ }
245
+
246
+ // ─── Action Registration (useAction hook) ──────────────────
247
+
248
+ registerAction(action) {
249
+ this.actions.set(action.name, action);
250
+ logger.info('AgentRuntime', `Registered action: ${action.name}`);
251
+ }
252
+ unregisterAction(name) {
253
+ this.actions.delete(name);
254
+ }
255
+
256
+ // ─── Navigation Helpers ────────────────────────────────────
257
+
258
+ /**
259
+ * Recursively collect ALL screen names from the navigation state tree.
260
+ * This handles tabs, drawers, and nested stacks.
261
+ */
262
+ getRouteNames() {
263
+ try {
264
+ if (!this.navRef?.isReady?.()) return [];
265
+ const state = this.navRef?.getRootState?.() || this.navRef?.getState?.();
266
+ if (!state) return [];
267
+ return this.collectRouteNames(state);
268
+ } catch {
269
+ return [];
270
+ }
271
+ }
272
+ collectRouteNames(state) {
273
+ const names = [];
274
+ if (state?.routes) {
275
+ for (const route of state.routes) {
276
+ names.push(route.name);
277
+ // Recurse into nested navigator states
278
+ if (route.state) {
279
+ names.push(...this.collectRouteNames(route.state));
280
+ }
281
+ }
282
+ }
283
+ return [...new Set(names)];
284
+ }
285
+
286
+ /**
287
+ * Recursively find the deepest active screen name.
288
+ * For tabs: follows active tab → active screen inside that tab.
289
+ */
290
+ getCurrentScreenName() {
291
+ // Expo Router: use pathname
292
+ if (this.config.pathname) {
293
+ const segments = this.config.pathname.split('/').filter(Boolean);
294
+ return segments[segments.length - 1] || 'Unknown';
295
+ }
296
+ try {
297
+ if (!this.navRef?.isReady?.()) return 'Unknown';
298
+ const state = this.navRef?.getRootState?.() || this.navRef?.getState?.();
299
+ if (!state) return 'Unknown';
300
+ return this.getDeepestScreenName(state);
301
+ } catch {
302
+ return 'Unknown';
303
+ }
304
+ }
305
+ getDeepestScreenName(state) {
306
+ if (!state?.routes || state.index == null) return 'Unknown';
307
+ const route = state.routes[state.index];
308
+ if (!route) return 'Unknown';
309
+ // If this route has a nested state, recurse deeper
310
+ if (route.state) {
311
+ return this.getDeepestScreenName(route.state);
312
+ }
313
+ return route.name || 'Unknown';
314
+ }
315
+
316
+ /** Maps a tool call to a user-friendly status label for the loading overlay. */
317
+ getToolStatusLabel(toolName, args) {
318
+ switch (toolName) {
319
+ case 'tap':
320
+ return `Tapping element ${args.index ?? ''}...`;
321
+ case 'type':
322
+ return `Typing into field...`;
323
+ case 'navigate':
324
+ return `Navigating to ${args.screen || 'screen'}...`;
325
+ case 'done':
326
+ return 'Wrapping up...';
327
+ case 'ask_user':
328
+ return 'Asking you a question...';
329
+ default:
330
+ return `Running ${toolName}...`;
331
+ }
332
+ }
333
+
334
+ // ─── Build Tools Array for Provider ────────────────────────
335
+
336
+ buildToolsForProvider() {
337
+ const allTools = [...this.tools.values()];
338
+
339
+ // Add registered actions as tools
340
+ for (const action of this.actions.values()) {
341
+ allTools.push({
342
+ name: action.name,
343
+ description: action.description,
344
+ parameters: Object.fromEntries(Object.entries(action.parameters).map(([key, typeStr]) => [key, {
345
+ type: typeStr,
346
+ description: key,
347
+ required: true
348
+ }])),
349
+ execute: async args => {
350
+ try {
351
+ const result = action.handler(args);
352
+ return typeof result === 'string' ? result : JSON.stringify(result);
353
+ } catch (error) {
354
+ return `❌ Action "${action.name}" failed: ${error.message}`;
355
+ }
356
+ }
357
+ });
358
+ }
359
+ return allTools;
360
+ }
361
+
362
+ // ─── Walk Config (passes security settings to FiberTreeWalker) ─
363
+
364
+ getWalkConfig() {
365
+ return {
366
+ interactiveBlacklist: this.config.interactiveBlacklist,
367
+ interactiveWhitelist: this.config.interactiveWhitelist
368
+ };
369
+ }
370
+
371
+ // ─── Instructions (mirrors page-agent #getInstructions) ───────
372
+
373
+ getInstructions(screenName) {
374
+ const {
375
+ instructions
376
+ } = this.config;
377
+ if (!instructions) return '';
378
+ let result = '';
379
+ if (instructions.system?.trim()) {
380
+ result += `<system_instructions>\n${instructions.system.trim()}\n</system_instructions>\n`;
381
+ }
382
+ if (instructions.getScreenInstructions) {
383
+ try {
384
+ const screenInstructions = instructions.getScreenInstructions(screenName)?.trim();
385
+ if (screenInstructions) {
386
+ result += `<screen_instructions>\n${screenInstructions}\n</screen_instructions>\n`;
387
+ }
388
+ } catch (error) {
389
+ logger.error('AgentRuntime', 'Failed to get screen instructions:', error);
390
+ }
391
+ }
392
+ return result ? `<instructions>\n${result}</instructions>\n\n` : '';
393
+ }
394
+
395
+ // ─── Observation System (mirrors PageAgentCore.#handleObservations) ──
396
+
397
+ observations = [];
398
+ lastScreenName = '';
399
+ handleObservations(step, maxSteps, screenName) {
400
+ // Screen change detection
401
+ if (this.lastScreenName && screenName !== this.lastScreenName) {
402
+ this.observations.push(`Screen navigated to → ${screenName}`);
403
+ }
404
+ this.lastScreenName = screenName;
405
+
406
+ // Remaining steps warning
407
+ const remaining = maxSteps - step;
408
+ if (remaining === 5) {
409
+ this.observations.push(`⚠️ Only ${remaining} steps remaining. Consider wrapping up or calling done with partial results.`);
410
+ } else if (remaining === 2) {
411
+ this.observations.push(`⚠️ Critical: Only ${remaining} steps left! You must finish the task or call done immediately.`);
412
+ }
413
+ }
414
+
415
+ // ─── User Prompt Assembly (mirrors PageAgentCore.#assembleUserPrompt) ──
416
+
417
+ assembleUserPrompt(step, maxSteps, contextualMessage, screenName, screenContent) {
418
+ let prompt = '';
419
+
420
+ // 1. <instructions> (optional system/screen instructions)
421
+ prompt += this.getInstructions(screenName);
422
+
423
+ // 2. <agent_state> — user request + step info (mirrors page-agent)
424
+ prompt += '<agent_state>\n';
425
+ prompt += '<user_request>\n';
426
+ prompt += `${contextualMessage}\n`;
427
+ prompt += '</user_request>\n';
428
+ prompt += '<step_info>\n';
429
+ prompt += `Step ${step + 1} of ${maxSteps} max possible steps\n`;
430
+ prompt += '</step_info>\n';
431
+ prompt += '</agent_state>\n\n';
432
+
433
+ // 3. <agent_history> — structured per-step history (mirrors page-agent)
434
+ prompt += '<agent_history>\n';
435
+ let stepIndex = 0;
436
+ for (const event of this.history) {
437
+ stepIndex++;
438
+ prompt += `<step_${stepIndex}>\n`;
439
+ prompt += `Previous Goal Eval: ${event.reflection.previousGoalEval}\n`;
440
+ prompt += `Memory: ${event.reflection.memory}\n`;
441
+ prompt += `Plan: ${event.reflection.plan}\n`;
442
+ prompt += `Action Result: ${event.action.output}\n`;
443
+ prompt += `</step_${stepIndex}>\n`;
444
+ }
445
+
446
+ // Inject system observations
447
+ for (const obs of this.observations) {
448
+ prompt += `<sys>${obs}</sys>\n`;
449
+ }
450
+ this.observations = [];
451
+ prompt += '</agent_history>\n\n';
452
+
453
+ // 4. <screen_state> — dehydrated screen content
454
+ prompt += '<screen_state>\n';
455
+ prompt += `Current Screen: ${screenName}\n`;
456
+ prompt += screenContent + '\n';
457
+ prompt += '</screen_state>\n';
458
+ return prompt;
459
+ }
460
+
461
+ // ─── Main Execution Loop ──────────────────────────────────────
462
+
463
+ async execute(userMessage) {
464
+ if (this.isRunning) {
465
+ return {
466
+ success: false,
467
+ message: 'Agent is already running.',
468
+ steps: []
469
+ };
470
+ }
471
+ this.isRunning = true;
472
+ this.history = [];
473
+ this.observations = [];
474
+ this.lastScreenName = '';
475
+ const maxSteps = this.config.maxSteps || DEFAULT_MAX_STEPS;
476
+ const stepDelay = this.config.stepDelay ?? 300;
477
+
478
+ // Inject conversational context if we are answering the AI's question
479
+ let contextualMessage = userMessage;
480
+ if (this.lastAskUserQuestion) {
481
+ contextualMessage = `(Note: You just asked the user: "${this.lastAskUserQuestion}")\n\nUser replied: ${userMessage}`;
482
+ this.lastAskUserQuestion = null; // Consume the question
483
+ }
484
+ logger.info('AgentRuntime', `Starting execution: "${contextualMessage}"`);
485
+
486
+ // Lifecycle: onBeforeTask (mirrors page-agent)
487
+ await this.config.onBeforeTask?.();
488
+ try {
489
+ for (let step = 0; step < maxSteps; step++) {
490
+ logger.info('AgentRuntime', `===== Step ${step + 1}/${maxSteps} =====`);
491
+
492
+ // Lifecycle: onBeforeStep (mirrors page-agent)
493
+ await this.config.onBeforeStep?.(step);
494
+
495
+ // 1. Walk Fiber tree with security config and dehydrate screen
496
+ const walkResult = walkFiberTree(this.rootRef, this.getWalkConfig());
497
+ const screenName = this.getCurrentScreenName();
498
+ const screen = dehydrateScreen(screenName, this.getRouteNames(), walkResult.elementsText, walkResult.interactives);
499
+ logger.info('AgentRuntime', `Screen: ${screen.screenName}`);
500
+ logger.debug('AgentRuntime', `Dehydrated:\n${screen.elementsText}`);
501
+
502
+ // 2. Apply transformScreenContent (mirrors page-agent transformPageContent)
503
+ let screenContent = screen.elementsText;
504
+ if (this.config.transformScreenContent) {
505
+ screenContent = await this.config.transformScreenContent(screenContent);
506
+ }
507
+
508
+ // 3. Handle observations (mirrors page-agent #handleObservations)
509
+ this.handleObservations(step, maxSteps, screenName);
510
+
511
+ // 4. Assemble structured user prompt (mirrors page-agent #assembleUserPrompt)
512
+ const contextMessage = this.assembleUserPrompt(step, maxSteps, contextualMessage, screenName, screenContent);
513
+
514
+ // 5. Send to AI provider
515
+ this.config.onStatusUpdate?.('Analyzing screen...');
516
+ const systemPrompt = buildSystemPrompt(this.config.language || 'en');
517
+ const tools = this.buildToolsForProvider();
518
+ logger.info('AgentRuntime', `Sending to AI with ${tools.length} tools...`);
519
+ const response = await this.provider.generateContent(systemPrompt, contextMessage, tools, this.history);
520
+
521
+ // 6. Process tool calls
522
+ if (!response.toolCalls || response.toolCalls.length === 0) {
523
+ logger.warn('AgentRuntime', 'No tool calls in response. Text:', response.text);
524
+ const result = {
525
+ success: true,
526
+ message: response.text || 'Task completed.',
527
+ steps: this.history
528
+ };
529
+ await this.config.onAfterTask?.(result);
530
+ return result;
531
+ }
532
+
533
+ // 7. Structured reasoning from provider (no regex parsing needed)
534
+ const {
535
+ reasoning
536
+ } = response;
537
+ logger.info('AgentRuntime', `🧠 Plan: ${reasoning.plan}`);
538
+ if (reasoning.memory) {
539
+ logger.debug('AgentRuntime', `💾 Memory: ${reasoning.memory}`);
540
+ }
541
+
542
+ // Only process the FIRST tool call per step (one action per step).
543
+ // After one action, the loop re-reads the screen with fresh indexes.
544
+ const toolCall = response.toolCalls[0];
545
+ if (response.toolCalls.length > 1) {
546
+ logger.warn('AgentRuntime', `AI returned ${response.toolCalls.length} tool calls, executing only the first one.`);
547
+ }
548
+ logger.info('AgentRuntime', `Tool: ${toolCall.name}(${JSON.stringify(toolCall.args)})`);
549
+
550
+ // Dynamic status update based on tool being executed
551
+ const statusLabel = this.getToolStatusLabel(toolCall.name, toolCall.args);
552
+ this.config.onStatusUpdate?.(statusLabel);
553
+
554
+ // Find and execute the tool
555
+ const tool = this.tools.get(toolCall.name) || this.buildToolsForProvider().find(t => t.name === toolCall.name);
556
+ let output;
557
+ if (tool) {
558
+ output = await tool.execute(toolCall.args);
559
+ } else {
560
+ output = `❌ Unknown tool: ${toolCall.name}`;
561
+ }
562
+ logger.info('AgentRuntime', `Result: ${output}`);
563
+
564
+ // Record step with structured reasoning
565
+ const agentStep = {
566
+ stepIndex: step,
567
+ reflection: reasoning,
568
+ action: {
569
+ name: toolCall.name,
570
+ input: toolCall.args,
571
+ output
572
+ }
573
+ };
574
+ this.history.push(agentStep);
575
+
576
+ // Lifecycle: onAfterStep (mirrors page-agent)
577
+ await this.config.onAfterStep?.(this.history);
578
+
579
+ // Check if done
580
+ if (toolCall.name === 'done') {
581
+ const result = {
582
+ success: toolCall.args.success !== false,
583
+ message: toolCall.args.text || output,
584
+ steps: this.history
585
+ };
586
+ logger.info('AgentRuntime', `Task completed: ${result.message}`);
587
+ await this.config.onAfterTask?.(result);
588
+ return result;
589
+ }
590
+
591
+ // Check if asking user (legacy path — only breaks loop when onAskUser is NOT set)
592
+ if (toolCall.name === 'ask_user' && !this.config.onAskUser) {
593
+ this.lastAskUserQuestion = toolCall.args.question || output;
594
+ const result = {
595
+ success: true,
596
+ message: output,
597
+ steps: this.history
598
+ };
599
+ await this.config.onAfterTask?.(result);
600
+ return result;
601
+ }
602
+
603
+ // Step delay (mirrors page-agent stepDelay)
604
+ await new Promise(resolve => setTimeout(resolve, stepDelay));
605
+ }
606
+
607
+ // Max steps reached
608
+ const result = {
609
+ success: false,
610
+ message: `Reached maximum steps (${maxSteps}) without completing the task.`,
611
+ steps: this.history
612
+ };
613
+ await this.config.onAfterTask?.(result);
614
+ return result;
615
+ } catch (error) {
616
+ logger.error('AgentRuntime', 'Execution error:', error);
617
+ const result = {
618
+ success: false,
619
+ message: `Error: ${error.message}`,
620
+ steps: this.history
621
+ };
622
+ await this.config.onAfterTask?.(result);
623
+ return result;
624
+ } finally {
625
+ this.isRunning = false;
626
+ }
627
+ }
628
+
629
+ /** Update refs (called when component re-renders) */
630
+ updateRefs(rootRef, navRef) {
631
+ this.rootRef = rootRef;
632
+ this.navRef = navRef;
633
+ }
634
+
635
+ /** Check if agent is currently executing */
636
+ getIsRunning() {
637
+ return this.isRunning;
638
+ }
639
+ }
640
+ //# sourceMappingURL=AgentRuntime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["logger","walkFiberTree","dehydrateScreen","buildSystemPrompt","DEFAULT_MAX_STEPS","AgentRuntime","tools","Map","actions","history","isRunning","lastAskUserQuestion","constructor","provider","config","rootRef","navRef","registerBuiltInTools","customTools","name","tool","Object","entries","delete","info","set","description","parameters","index","type","required","execute","args","interactives","elements","getWalkConfig","element","find","el","map","e","join","props","onValueChange","value","Promise","resolve","setTimeout","label","error","message","onPress","fiber","fiberNode","return","bubbleDepth","parentProps","memoizedProps","text","onChangeText","screen","params","router","path","startsWith","push","isReady","JSON","parse","undefined","navigate","stringify","getRouteNames","success","question","onAskUser","onStatusUpdate","answer","registerAction","action","unregisterAction","state","getRootState","getState","collectRouteNames","names","routes","route","Set","getCurrentScreenName","pathname","segments","split","filter","Boolean","length","getDeepestScreenName","getToolStatusLabel","toolName","buildToolsForProvider","allTools","values","fromEntries","key","typeStr","result","handler","interactiveBlacklist","interactiveWhitelist","getInstructions","screenName","instructions","system","trim","getScreenInstructions","screenInstructions","observations","lastScreenName","handleObservations","step","maxSteps","remaining","assembleUserPrompt","contextualMessage","screenContent","prompt","stepIndex","event","reflection","previousGoalEval","memory","plan","output","obs","userMessage","steps","stepDelay","onBeforeTask","onBeforeStep","walkResult","elementsText","debug","transformScreenContent","contextMessage","systemPrompt","language","response","generateContent","toolCalls","warn","onAfterTask","reasoning","toolCall","statusLabel","get","t","agentStep","input","onAfterStep","updateRefs","getIsRunning"],"sourceRoot":"../../../src","sources":["core/AgentRuntime.ts"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,MAAM,QAAQ,oBAA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