๐Ÿ“ฆ microsoft / playwright

๐Ÿ“„ pageAgent.ts ยท 217 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from 'fs';
import path from 'path';

import { toolsForLoop } from './tool';
import { debug } from '../../utilsBundle';
import { Loop, z as zod } from '../../mcpBundle';
import { runAction } from './actionRunner';
import { Context } from './context';
import performTools from './performTools';
import expectTools from './expectTools';

import * as actions from './actions';
import type { ToolDefinition } from './tool';
import type * as loopTypes from '@lowire/loop';
import type { Progress } from '../progress';

export type CallParams = {
  cacheKey?: string;
  maxTokens?: number;
  maxActions?: number;
  maxActionRetries?: number;
};

export async function pageAgentPerform(progress: Progress, context: Context, userTask: string, callParams: CallParams) {
  const cacheKey = (callParams.cacheKey ?? userTask).trim();
  if (await cachedPerform(progress, context, cacheKey))
    return;

  const task = `
### Instructions
- Perform the following task on the page.
- Your reply should be a tool call that performs action the page".

### Task
${userTask}
`;

  await runLoop(progress, context, performTools, task, undefined, callParams);
  await updateCache(context, cacheKey);
}

export async function pageAgentExpect(progress: Progress, context: Context, expectation: string, callParams: CallParams) {
  const cacheKey = (callParams.cacheKey ?? expectation).trim();
  if (await cachedPerform(progress, context, cacheKey))
    return;

  const task = `
### Instructions
- Call one of the "browser_expect_*" tools to verify / assert the condition.
- You can call exactly one tool and it can't be report_results, must be one of the assertion tools.

### Expectation
${expectation}
`;

  await runLoop(progress, context, expectTools, task, undefined, callParams);
  await updateCache(context, cacheKey);
}

export async function pageAgentExtract(progress: Progress, context: Context, query: string, schema: loopTypes.Schema, callParams: CallParams): Promise<any> {

  const task = `
### Instructions
Extract the following information from the page. Do not perform any actions, just extract the information.

### Query
${query}`;
  const { result } = await runLoop(progress, context, [], task, schema, callParams);
  return result;
}

async function runLoop(progress: Progress, context: Context, toolDefinitions: ToolDefinition[], userTask: string, resultSchema: loopTypes.Schema | undefined, params: CallParams): Promise<{
  result: any
}> {
  const { page } = context;
  if (!context.agentParams.api || !context.agentParams.model)
    throw new Error(`This action requires the API and API key to be set on the page agent. Did you mean to --run-agents=missing?`);
  if (!context.agentParams.apiKey)
    throw new Error(`This action requires API key to be set on the page agent.`);

  const { full } = await page.snapshotForAI(progress);
  const { tools, callTool, reportedResult, refusedToPerformReason } = toolsForLoop(progress, context, toolDefinitions, { resultSchema, refuseToPerform: 'allow' });
  const secrets = Object.fromEntries((context.agentParams.secrets || [])?.map(s => ([s.name, s.value])));

  const apiCacheTextBefore = context.agentParams.apiCacheFile ?
    await fs.promises.readFile(context.agentParams.apiCacheFile, 'utf-8').catch(() => '{}') : '{}';
  const apiCacheBefore = JSON.parse(apiCacheTextBefore);

  const loop = new Loop({
    api: context.agentParams.api as any,
    apiEndpoint: context.agentParams.apiEndpoint,
    apiKey: context.agentParams.apiKey,
    apiTimeout: context.agentParams.apiTimeout ?? 0,
    model: context.agentParams.model,
    maxTokens: params.maxTokens ?? context.maxTokensRemaining(),
    maxToolCalls: params.maxActions ?? context.agentParams.maxActions ?? 10,
    maxToolCallRetries: params.maxActionRetries ?? context.agentParams.maxActionRetries ?? 3,
    summarize: true,
    debug,
    callTool,
    tools,
    secrets,
    cache: apiCacheBefore,
    ...context.events,
  });

  const task: string[] = [];
  if (context.agentParams.systemPrompt) {
    task.push('### System');
    task.push(context.agentParams.systemPrompt);
    task.push('');
  }

  task.push('### Task');
  task.push(userTask);

  if (context.history().length) {
    task.push('### Context history');
    task.push(context.history().map(h => `- ${h.type}: ${h.description}`).join('\n'));
    task.push('');
  }
  task.push('### Page snapshot');
  task.push(full);
  task.push('');

  const { error, usage } = await loop.run(task.join('\n'), { signal: progress.signal });
  context.consumeTokens(usage.input + usage.output);
  if (context.agentParams.apiCacheFile) {
    const apiCacheAfter = { ...apiCacheBefore, ...loop.cache() };
    const sortedCache = Object.fromEntries(Object.entries(apiCacheAfter).sort(([a], [b]) => a.localeCompare(b)));
    const apiCacheTextAfter = JSON.stringify(sortedCache, undefined, 2);
    if (apiCacheTextAfter !== apiCacheTextBefore) {
      await fs.promises.mkdir(path.dirname(context.agentParams.apiCacheFile), { recursive: true });
      await fs.promises.writeFile(context.agentParams.apiCacheFile, apiCacheTextAfter);
    }
  }

  if (refusedToPerformReason())
    throw new Error(`Agent refused to perform action: ${refusedToPerformReason()}`);

  if (error)
    throw new Error(`Agentic loop failed: ${error}`);

  return { result: reportedResult ? reportedResult() : undefined };
}

async function cachedPerform(progress: Progress, context: Context, cacheKey: string): Promise<actions.ActionWithCode[] | undefined> {
  if (!context.agentParams?.cacheFile)
    return;

  const cache = await cachedActions(context.agentParams?.cacheFile);
  const entry = cache.actions[cacheKey];
  if (!entry)
    return;

  for (const action of entry.actions)
    await runAction(progress, 'run', context.page, action, context.agentParams.secrets ?? []);
  return entry.actions;
}

async function updateCache(context: Context, cacheKey: string) {
  const cacheFile = context.agentParams?.cacheFile;
  const cacheOutFile = context.agentParams?.cacheOutFile;
  const cacheFileKey = cacheFile ?? cacheOutFile;

  const cache = cacheFileKey ? await cachedActions(cacheFileKey) : { actions: {}, newActions: {} };
  const newEntry = { actions: context.actions() };
  cache.actions[cacheKey] = newEntry;
  cache.newActions[cacheKey] = newEntry;

  if (cacheOutFile) {
    const entries = Object.entries(cache.newActions);
    entries.sort((e1, e2) => e1[0].localeCompare(e2[0]));
    await fs.promises.writeFile(cacheOutFile, JSON.stringify(Object.fromEntries(entries), undefined, 2));
  } else if (cacheFile) {
    const entries = Object.entries(cache.actions);
    entries.sort((e1, e2) => e1[0].localeCompare(e2[0]));
    await fs.promises.writeFile(cacheFile, JSON.stringify(Object.fromEntries(entries), undefined, 2));
  }
}

type Cache = {
  actions: actions.CachedActions;
  newActions: actions.CachedActions;
};

const allCaches = new Map<string, Cache>();

async function cachedActions(cacheFile: string): Promise<Cache> {
  let cache = allCaches.get(cacheFile);
  if (!cache) {
    const json = await fs.promises.readFile(cacheFile, 'utf-8').then(text => JSON.parse(text)).catch(() => ({}));
    const parsed = actions.cachedActionsSchema.safeParse(json);
    if (parsed.error)
      throw new Error(`Failed to parse cache file ${cacheFile}:\n${zod.prettifyError(parsed.error)}`);
    cache = { actions: parsed.data, newActions: {} };
    allCaches.set(cacheFile, cache);
  }
  return cache;
}