imprint-mcp 0.6.6 → 0.7.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.
- package/CHANGELOG.md +22 -0
- package/README.md +278 -16
- package/package.json +2 -2
- package/prompts/audit-agent.md +25 -4
- package/prompts/auth-compile-agent.md +28 -12
- package/prompts/build-planning.md +3 -3
- package/prompts/compile-agent.md +895 -180
- package/prompts/live-verifier-agent.md +10 -3
- package/prompts/master-teach-api-researcher.md +813 -0
- package/prompts/master-teach-baseline-mvp-review.md +217 -0
- package/prompts/master-teach-completion-review.md +188 -0
- package/prompts/master-teach-decision.md +885 -0
- package/prompts/master-teach-focused-planner.md +764 -0
- package/prompts/master-teach-parameter-advisor.md +58 -0
- package/prompts/master-teach-recording-evidence.md +19 -0
- package/prompts/master-teach-refine-plan.md +7 -0
- package/prompts/master-teach-tool-advisor.md +130 -0
- package/prompts/playbook-compilation.md +45 -54
- package/prompts/prereq-builder.md +28 -6
- package/prompts/prereq-planner.md +2 -2
- package/prompts/tool-candidate-detection.md +70 -39
- package/prompts/tool-planning.md +3 -3
- package/src/cli.ts +190 -150
- package/src/imprint/agent.ts +47 -33
- package/src/imprint/api-research-agent.ts +933 -0
- package/src/imprint/audit.ts +49 -2
- package/src/imprint/auth-compile-agent.ts +125 -55
- package/src/imprint/auth-compile-tools.ts +20 -48
- package/src/imprint/auth-verifier.ts +8 -19
- package/src/imprint/backend-ladder.ts +499 -367
- package/src/imprint/body-structure.ts +656 -0
- package/src/imprint/build-plan.ts +33 -323
- package/src/imprint/cdp-browser-fetch.ts +734 -29
- package/src/imprint/cdp-jar-cache.ts +7 -12
- package/src/imprint/claude-cli-compile.ts +276 -320
- package/src/imprint/codex-cli-compile.ts +476 -350
- package/src/imprint/codex-sdk-turn.ts +102 -0
- package/src/imprint/compile-agent-types.ts +49 -10
- package/src/imprint/compile-agent.ts +189 -274
- package/src/imprint/compile-done-sentinel.ts +211 -0
- package/src/imprint/compile-provider-control.ts +401 -0
- package/src/imprint/compile-provider-recovery.ts +142 -0
- package/src/imprint/compile-strategy.ts +5 -0
- package/src/imprint/compile-tools.ts +1695 -3097
- package/src/imprint/compile-verification.ts +9 -1
- package/src/imprint/compile.ts +107 -29
- package/src/imprint/compiler-log.ts +12 -0
- package/src/imprint/compiler-process.ts +440 -0
- package/src/imprint/concurrency.ts +43 -58
- package/src/imprint/credential-extract.ts +1 -88
- package/src/imprint/emit.ts +18 -2
- package/src/imprint/evidence-inspection.ts +55 -0
- package/src/imprint/freeform-redact.ts +34 -234
- package/src/imprint/import-module-fresh.ts +30 -0
- package/src/imprint/live-finesse-runner.ts +299 -0
- package/src/imprint/live-verifier.ts +299 -358
- package/src/imprint/llm.ts +466 -422
- package/src/imprint/log.ts +1 -9
- package/src/imprint/master-teach-agent-contracts.ts +875 -0
- package/src/imprint/master-teach-agents.ts +2850 -0
- package/src/imprint/master-teach-checks.ts +341 -0
- package/src/imprint/master-teach-controller.ts +7159 -0
- package/src/imprint/master-teach-plan.ts +1410 -0
- package/src/imprint/master-teach-prompt-projections.ts +347 -0
- package/src/imprint/master-teach-store.ts +961 -0
- package/src/imprint/mcp-cdp-sessions.ts +60 -0
- package/src/imprint/mcp-compile-server.ts +519 -668
- package/src/imprint/mcp-live-verifier-server.ts +246 -190
- package/src/imprint/mcp-server.ts +46 -57
- package/src/imprint/native-agent-pass.ts +260 -0
- package/src/imprint/native-agent-usage.ts +141 -0
- package/src/imprint/native-teach-agents.ts +495 -0
- package/src/imprint/param-grounding.ts +488 -347
- package/src/imprint/playbook-runner.ts +254 -63
- package/src/imprint/prereq-builder.ts +55 -543
- package/src/imprint/private-file.ts +18 -0
- package/src/imprint/probe-backends.ts +129 -33
- package/src/imprint/provider-retry.ts +501 -0
- package/src/imprint/provider-terminal.ts +214 -0
- package/src/imprint/recording-request.ts +290 -1
- package/src/imprint/recording-verification.ts +444 -0
- package/src/imprint/redact.ts +33 -749
- package/src/imprint/refine-worker.ts +326 -0
- package/src/imprint/refine.ts +241 -0
- package/src/imprint/replay-capture.ts +41 -12
- package/src/imprint/replay-evidence.ts +1007 -0
- package/src/imprint/research-response-evidence.ts +45 -0
- package/src/imprint/runtime.ts +514 -106
- package/src/imprint/sensitive-keys.ts +0 -6
- package/src/imprint/session-merge.ts +103 -7
- package/src/imprint/stealth-fetch.ts +25 -8
- package/src/imprint/stealth-token-cache.ts +16 -16
- package/src/imprint/teach-plan.ts +0 -242
- package/src/imprint/teach-research-memory.ts +229 -0
- package/src/imprint/teach-state.ts +47 -625
- package/src/imprint/teach.ts +12 -3699
- package/src/imprint/tool-candidates.ts +58 -210
- package/src/imprint/tool-loader.ts +3 -0
- package/src/imprint/tool-plan.ts +1 -134
- package/src/imprint/tracing.ts +24 -7
- package/src/imprint/types.ts +68 -4
- package/src/imprint/endpoint-key.ts +0 -23
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
resolve as pathResolve,
|
|
8
8
|
} from 'node:path';
|
|
9
9
|
import type { Browser, BrowserContext, Frame, Locator as PWLocator, Page } from 'playwright';
|
|
10
|
+
import { TimeoutError, abortSignalError, withAbortSignal } from './concurrency.ts';
|
|
10
11
|
import { extractAt } from './json-path.ts';
|
|
11
12
|
import { createLog } from './log.ts';
|
|
12
13
|
import { imprintHomeDir } from './paths.ts';
|
|
@@ -33,6 +34,10 @@ interface RunPlaybookOptions {
|
|
|
33
34
|
stepTimeoutMs?: number;
|
|
34
35
|
/** Whole-playbook timeout in ms. Default unbounded for direct playbook runs. */
|
|
35
36
|
maxDurationMs?: number;
|
|
37
|
+
/** Cancel the complete browser lifecycle, including setup and result extraction. */
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
/** Best-effort browser teardown grace. Default 2000ms. */
|
|
40
|
+
cleanupTimeoutMs?: number;
|
|
36
41
|
/** Timeout for diagnostic screenshots in ms. Default 5000. */
|
|
37
42
|
screenshotTimeoutMs?: number;
|
|
38
43
|
/** Screenshot after every step (not just on failure). */
|
|
@@ -55,14 +60,90 @@ interface RunPlaybookOptions {
|
|
|
55
60
|
const log = createLog('playbook');
|
|
56
61
|
const DEFAULT_STEP_TIMEOUT_MS = 30000;
|
|
57
62
|
const DEFAULT_SCREENSHOT_TIMEOUT_MS = 5000;
|
|
63
|
+
export const DEFAULT_PLAYBOOK_CLEANUP_TIMEOUT_MS = 2000;
|
|
64
|
+
|
|
65
|
+
interface PlaybookLifecycleControl {
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
dispose(): void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function playbookLifecycleControl(
|
|
71
|
+
parent: AbortSignal | undefined,
|
|
72
|
+
maxDurationMs: number | undefined,
|
|
73
|
+
): PlaybookLifecycleControl {
|
|
74
|
+
if (!parent && maxDurationMs === undefined) return { dispose: () => {} };
|
|
75
|
+
const controller = new AbortController();
|
|
76
|
+
const abortFromParent = (): void => {
|
|
77
|
+
controller.abort(
|
|
78
|
+
parent ? abortSignalError(parent) : new DOMException('Cancelled', 'AbortError'),
|
|
79
|
+
);
|
|
80
|
+
};
|
|
81
|
+
if (parent?.aborted) abortFromParent();
|
|
82
|
+
else parent?.addEventListener('abort', abortFromParent, { once: true });
|
|
83
|
+
const durationMs = maxDurationMs === undefined ? undefined : positiveMs(maxDurationMs, 1);
|
|
84
|
+
const timer =
|
|
85
|
+
durationMs === undefined
|
|
86
|
+
? undefined
|
|
87
|
+
: setTimeout(
|
|
88
|
+
() => controller.abort(new TimeoutError('Playbook lifecycle', durationMs)),
|
|
89
|
+
durationMs,
|
|
90
|
+
);
|
|
91
|
+
return {
|
|
92
|
+
signal: controller.signal,
|
|
93
|
+
dispose: () => {
|
|
94
|
+
if (timer) clearTimeout(timer);
|
|
95
|
+
parent?.removeEventListener('abort', abortFromParent);
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Close browser resources without allowing a dead Playwright transport to
|
|
101
|
+
* keep a foreground command alive. Both closes start immediately and share a
|
|
102
|
+
* short grace that is deliberately independent of the teach-run deadline. */
|
|
103
|
+
export async function closePlaybookResources(
|
|
104
|
+
context: Pick<BrowserContext, 'close'> | undefined,
|
|
105
|
+
browser: Pick<Browser, 'close'> | undefined,
|
|
106
|
+
timeoutMs = DEFAULT_PLAYBOOK_CLEANUP_TIMEOUT_MS,
|
|
107
|
+
): Promise<void> {
|
|
108
|
+
const graceMs = positiveMs(timeoutMs, DEFAULT_PLAYBOOK_CLEANUP_TIMEOUT_MS);
|
|
109
|
+
const boundedClose = async (label: string, close: () => Promise<unknown>): Promise<void> => {
|
|
110
|
+
try {
|
|
111
|
+
await withTimeout(Promise.resolve().then(close), graceMs, label);
|
|
112
|
+
} catch {
|
|
113
|
+
// Cleanup is best effort. The original execution result or lifecycle
|
|
114
|
+
// failure remains the factual outcome returned to the controller.
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
await Promise.all([
|
|
118
|
+
...(context ? [boundedClose('Playbook context cleanup', () => context.close())] : []),
|
|
119
|
+
...(browser ? [boundedClose('Playbook browser cleanup', () => browser.close())] : []),
|
|
120
|
+
]);
|
|
121
|
+
}
|
|
58
122
|
|
|
59
123
|
export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult> {
|
|
124
|
+
const lifecycleDurationMs =
|
|
125
|
+
opts.maxDurationMs === undefined ? undefined : positiveMs(opts.maxDurationMs, 1);
|
|
126
|
+
const lifecycle = playbookLifecycleControl(opts.signal, lifecycleDurationMs);
|
|
127
|
+
const controlled = async <T>(operation: () => Promise<T>): Promise<T> =>
|
|
128
|
+
await withAbortSignal(operation, lifecycle.signal);
|
|
129
|
+
const callerCancelled = (): boolean => opts.signal?.aborted === true;
|
|
130
|
+
const lifecycleFailure = (phase: string): ToolResult => ({
|
|
131
|
+
ok: false,
|
|
132
|
+
error: 'NETWORK',
|
|
133
|
+
message: `${phase}: ${errMsg(abortSignalError(lifecycle.signal as AbortSignal))}`,
|
|
134
|
+
});
|
|
60
135
|
let playbook: Playbook;
|
|
61
136
|
let params: Record<string, string | number | boolean>;
|
|
62
137
|
try {
|
|
63
|
-
playbook = await loadPlaybook(opts.playbook);
|
|
138
|
+
playbook = await controlled(async () => await loadPlaybook(opts.playbook));
|
|
64
139
|
params = coerceParams(opts.params, playbook);
|
|
65
140
|
} catch (err) {
|
|
141
|
+
if (lifecycle.signal?.aborted) {
|
|
142
|
+
lifecycle.dispose();
|
|
143
|
+
if (callerCancelled()) throw abortSignalError(lifecycle.signal);
|
|
144
|
+
return lifecycleFailure('Playbook setup failed');
|
|
145
|
+
}
|
|
146
|
+
lifecycle.dispose();
|
|
66
147
|
return { ok: false, error: 'UNKNOWN', message: errMsg(err) };
|
|
67
148
|
}
|
|
68
149
|
// Generous default — Akamai sensor JS, A/B loaders, lazy bundles all
|
|
@@ -70,8 +151,7 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
70
151
|
// worse than they are.
|
|
71
152
|
const stepTimeoutMs = positiveMs(opts.stepTimeoutMs, DEFAULT_STEP_TIMEOUT_MS);
|
|
72
153
|
const screenshotTimeoutMs = positiveMs(opts.screenshotTimeoutMs, DEFAULT_SCREENSHOT_TIMEOUT_MS);
|
|
73
|
-
const deadlineAt =
|
|
74
|
-
opts.maxDurationMs !== undefined ? Date.now() + positiveMs(opts.maxDurationMs, 1) : null;
|
|
154
|
+
const deadlineAt = lifecycleDurationMs !== undefined ? Date.now() + lifecycleDurationMs : null;
|
|
75
155
|
|
|
76
156
|
// Resolve the site once (used for cookie injection, credential resolution in
|
|
77
157
|
// login playbooks, and post-run session persistence).
|
|
@@ -88,8 +168,14 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
88
168
|
} else {
|
|
89
169
|
let chromium: typeof import('playwright').chromium;
|
|
90
170
|
try {
|
|
91
|
-
chromium = await getStealthChromium
|
|
171
|
+
chromium = await controlled(getStealthChromium);
|
|
92
172
|
} catch (innerErr) {
|
|
173
|
+
if (lifecycle.signal?.aborted) {
|
|
174
|
+
lifecycle.dispose();
|
|
175
|
+
if (callerCancelled()) throw abortSignalError(lifecycle.signal);
|
|
176
|
+
return lifecycleFailure('Playwright setup failed');
|
|
177
|
+
}
|
|
178
|
+
lifecycle.dispose();
|
|
93
179
|
return {
|
|
94
180
|
ok: false,
|
|
95
181
|
error: 'UNKNOWN',
|
|
@@ -100,33 +186,67 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
100
186
|
// Use the same full Chrome binary as `imprint record` — NOT
|
|
101
187
|
// chrome-headless-shell, which Akamai detects at the binary level
|
|
102
188
|
// regardless of stealth-plugin JS patches.
|
|
103
|
-
|
|
189
|
+
const launch = chromium.launch({
|
|
104
190
|
headless: !opts.headed,
|
|
105
191
|
executablePath: getStealthExecutablePath(),
|
|
106
192
|
});
|
|
193
|
+
void launch.then(
|
|
194
|
+
async (launched) => {
|
|
195
|
+
if (lifecycle.signal?.aborted) {
|
|
196
|
+
await closePlaybookResources(undefined, launched, opts.cleanupTimeoutMs);
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
() => {},
|
|
200
|
+
);
|
|
201
|
+
browser = await controlled(async () => await launch);
|
|
107
202
|
} catch (err) {
|
|
203
|
+
if (lifecycle.signal?.aborted) {
|
|
204
|
+
lifecycle.dispose();
|
|
205
|
+
if (callerCancelled()) throw abortSignalError(lifecycle.signal);
|
|
206
|
+
return lifecycleFailure('Chromium launch failed');
|
|
207
|
+
}
|
|
208
|
+
lifecycle.dispose();
|
|
108
209
|
return {
|
|
109
210
|
ok: false,
|
|
110
211
|
error: 'UNKNOWN',
|
|
111
212
|
message: `Could not launch Chromium: ${errMsg(err)}. Run: bunx playwright install chromium`,
|
|
112
213
|
};
|
|
113
214
|
}
|
|
114
|
-
|
|
115
|
-
|
|
215
|
+
try {
|
|
216
|
+
const launchedBrowser = browser;
|
|
217
|
+
if (!launchedBrowser) throw new Error('Playwright did not launch a browser');
|
|
218
|
+
context = await controlled(async () => await launchedBrowser.newContext());
|
|
219
|
+
const initializedContext = context;
|
|
220
|
+
page = await controlled(async () => await initializedContext.newPage());
|
|
221
|
+
} catch (err) {
|
|
222
|
+
await closePlaybookResources(context, browser, opts.cleanupTimeoutMs);
|
|
223
|
+
lifecycle.dispose();
|
|
224
|
+
if (lifecycle.signal?.aborted) {
|
|
225
|
+
if (callerCancelled()) throw abortSignalError(lifecycle.signal);
|
|
226
|
+
return lifecycleFailure('Chromium initialization failed');
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
ok: false,
|
|
230
|
+
error: 'UNKNOWN',
|
|
231
|
+
message: `Could not initialize Chromium: ${errMsg(err)}`,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
116
234
|
|
|
117
235
|
// Inject credentials.cookies into the browser so the playbook can navigate
|
|
118
236
|
// an authenticated flow (e.g., my-trips → reservation → seat map), and load
|
|
119
237
|
// credential values for ${credential.X} placeholders in login playbooks.
|
|
120
238
|
if (site) {
|
|
121
239
|
try {
|
|
122
|
-
const { loadSiteCredentials } = await
|
|
123
|
-
|
|
240
|
+
const { loadSiteCredentials } = await controlled(
|
|
241
|
+
async () => await import('./credential-store.ts'),
|
|
242
|
+
);
|
|
243
|
+
const view = await controlled(async () => await loadSiteCredentials(site));
|
|
124
244
|
credValues = view.values ?? {};
|
|
125
245
|
const playwrightCookies = view.cookies
|
|
126
246
|
.map((c) => ({ name: c.name, value: c.value, domain: c.domain, path: c.path }))
|
|
127
247
|
.filter((c) => c.name && c.value);
|
|
128
248
|
if (playwrightCookies.length > 0) {
|
|
129
|
-
await context
|
|
249
|
+
await controlled(async () => await context?.addCookies(playwrightCookies));
|
|
130
250
|
log(`injected ${playwrightCookies.length} cookies for site ${site}`);
|
|
131
251
|
}
|
|
132
252
|
// Rehydrate persisted localStorage (Option B): a prior `initiate` run may
|
|
@@ -144,27 +264,36 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
144
264
|
byOrigin.set(rec.origin, list);
|
|
145
265
|
}
|
|
146
266
|
for (const [origin, entries] of byOrigin) {
|
|
147
|
-
await
|
|
148
|
-
(
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
267
|
+
await controlled(
|
|
268
|
+
async () =>
|
|
269
|
+
await context?.addInitScript(
|
|
270
|
+
({ origin: o, entries: e }) => {
|
|
271
|
+
// Runs in the browser; type the needed globals locally since the
|
|
272
|
+
// Node typecheck has no DOM lib.
|
|
273
|
+
const w = globalThis as unknown as {
|
|
274
|
+
location: { origin: string };
|
|
275
|
+
localStorage: { setItem(k: string, v: string): void };
|
|
276
|
+
};
|
|
277
|
+
try {
|
|
278
|
+
if (w.location.origin !== o) return;
|
|
279
|
+
for (const { key, value } of e) w.localStorage.setItem(key, value);
|
|
280
|
+
} catch {
|
|
281
|
+
/* storage may be unavailable (sandboxed frame) — skip */
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
{ origin, entries },
|
|
285
|
+
),
|
|
163
286
|
);
|
|
164
287
|
}
|
|
165
288
|
log(`seeded ${localStorageRecords.length} localStorage keys for site ${site}`);
|
|
166
289
|
}
|
|
167
290
|
} catch (err) {
|
|
291
|
+
if (lifecycle.signal?.aborted) {
|
|
292
|
+
await closePlaybookResources(context, browser, opts.cleanupTimeoutMs);
|
|
293
|
+
lifecycle.dispose();
|
|
294
|
+
if (callerCancelled()) throw abortSignalError(lifecycle.signal);
|
|
295
|
+
return lifecycleFailure('Browser credential setup failed');
|
|
296
|
+
}
|
|
168
297
|
log(`failed to inject cookies: ${errMsg(err)} (proceeding without)`);
|
|
169
298
|
}
|
|
170
299
|
}
|
|
@@ -200,8 +329,9 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
200
329
|
log(`step ${i + 1}/${playbook.steps.length}: ${step.action}`);
|
|
201
330
|
await withTimeout(
|
|
202
331
|
executeStep(page, step, params, credValues, budgetMs),
|
|
203
|
-
|
|
332
|
+
stepTimeoutMs,
|
|
204
333
|
`Playbook step ${lastStep}/${playbook.steps.length} (${step.action})`,
|
|
334
|
+
lifecycle.signal,
|
|
205
335
|
);
|
|
206
336
|
if (opts.trace) {
|
|
207
337
|
const traceShot = await screenshot(
|
|
@@ -209,6 +339,7 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
209
339
|
`${playbook.toolName}-trace`,
|
|
210
340
|
lastStep,
|
|
211
341
|
screenshotTimeoutMs,
|
|
342
|
+
lifecycle.signal,
|
|
212
343
|
);
|
|
213
344
|
log(` url=${page.url()}`);
|
|
214
345
|
if (traceShot) log(` trace screenshot: ${traceShot}`);
|
|
@@ -223,8 +354,9 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
223
354
|
Promise.allSettled(pendingBodyReads),
|
|
224
355
|
bodyReadBudgetMs,
|
|
225
356
|
'Playbook captured-response drain',
|
|
357
|
+
lifecycle.signal,
|
|
226
358
|
);
|
|
227
|
-
const data = await extractResult(page, playbook.result, captured);
|
|
359
|
+
const data = await controlled(async () => await extractResult(page, playbook.result, captured));
|
|
228
360
|
// Best-effort 2FA-chain captures: pull named tokens (e.g. a single-use
|
|
229
361
|
// SecurityCode minted during an OTP-send) out of the run so the ladder can
|
|
230
362
|
// echo them as twoFactorContext for a later submit_otp. Missing captures are
|
|
@@ -238,19 +370,23 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
238
370
|
// caller (the ladder sets this only for toolKind==='authenticate').
|
|
239
371
|
if (opts.persistCookies && site && context) {
|
|
240
372
|
try {
|
|
241
|
-
const harvested = (await context
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
373
|
+
const harvested = ((await controlled(async () => await context?.cookies())) ?? []).map(
|
|
374
|
+
(c) => ({
|
|
375
|
+
name: c.name,
|
|
376
|
+
value: c.value,
|
|
377
|
+
domain: c.domain,
|
|
378
|
+
path: c.path,
|
|
379
|
+
expires: c.expires,
|
|
380
|
+
httpOnly: c.httpOnly,
|
|
381
|
+
secure: c.secure,
|
|
382
|
+
sameSite: c.sameSite,
|
|
383
|
+
}),
|
|
384
|
+
);
|
|
251
385
|
if (harvested.length > 0) {
|
|
252
|
-
const { saveSiteCookies } = await
|
|
253
|
-
|
|
386
|
+
const { saveSiteCookies } = await controlled(
|
|
387
|
+
async () => await import('./credential-store.ts'),
|
|
388
|
+
);
|
|
389
|
+
await controlled(async () => await saveSiteCookies(site, harvested));
|
|
254
390
|
log(`persisted ${harvested.length} session cookies for site ${site}`);
|
|
255
391
|
}
|
|
256
392
|
// Also harvest localStorage (Option B): serialize the post-login
|
|
@@ -258,7 +394,8 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
258
394
|
// the same session state. storageState() captures cookies + localStorage;
|
|
259
395
|
// we already persist cookies above, so take only the localStorage here.
|
|
260
396
|
// sessionStorage is not captured by storageState() — a documented gap.
|
|
261
|
-
const state = await context
|
|
397
|
+
const state = await controlled(async () => await context?.storageState());
|
|
398
|
+
if (!state) throw new Error('Playwright context closed before storage capture');
|
|
262
399
|
const storageRecords = state.origins.flatMap((o) =>
|
|
263
400
|
o.localStorage.map((entry) => ({
|
|
264
401
|
origin: o.origin,
|
|
@@ -268,19 +405,49 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
268
405
|
})),
|
|
269
406
|
);
|
|
270
407
|
if (storageRecords.length > 0) {
|
|
271
|
-
const { saveSiteStorage } = await
|
|
272
|
-
|
|
408
|
+
const { saveSiteStorage } = await controlled(
|
|
409
|
+
async () => await import('./credential-store.ts'),
|
|
410
|
+
);
|
|
411
|
+
await controlled(async () => await saveSiteStorage(site, storageRecords));
|
|
273
412
|
log(`persisted ${storageRecords.length} localStorage keys for site ${site}`);
|
|
274
413
|
}
|
|
275
414
|
} catch (err) {
|
|
415
|
+
if (lifecycle.signal?.aborted) throw abortSignalError(lifecycle.signal);
|
|
276
416
|
log(`failed to persist session cookies: ${errMsg(err)} (proceeding)`);
|
|
277
417
|
}
|
|
278
418
|
}
|
|
279
419
|
return { ok: true, data };
|
|
280
420
|
} catch (err) {
|
|
281
|
-
|
|
421
|
+
if (lifecycle.signal?.aborted && callerCancelled()) {
|
|
422
|
+
throw abortSignalError(lifecycle.signal);
|
|
423
|
+
}
|
|
424
|
+
let screenshotPath: string | null = null;
|
|
425
|
+
if (!lifecycle.signal?.aborted) {
|
|
426
|
+
try {
|
|
427
|
+
screenshotPath = await controlled(
|
|
428
|
+
async () =>
|
|
429
|
+
await screenshot(
|
|
430
|
+
page,
|
|
431
|
+
playbook.toolName,
|
|
432
|
+
lastStep,
|
|
433
|
+
screenshotTimeoutMs,
|
|
434
|
+
lifecycle.signal,
|
|
435
|
+
),
|
|
436
|
+
);
|
|
437
|
+
} catch {
|
|
438
|
+
// The whole-playbook deadline may expire while a best-effort failure
|
|
439
|
+
// screenshot is pending. Classify that deadline below instead of
|
|
440
|
+
// allowing the diagnostic step to replace the execution result.
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (lifecycle.signal?.aborted && callerCancelled()) {
|
|
444
|
+
throw abortSignalError(lifecycle.signal);
|
|
445
|
+
}
|
|
446
|
+
const lifecycleTimedOut = lifecycle.signal?.aborted === true;
|
|
282
447
|
const suffix = screenshotPath ? `\nscreenshot: ${screenshotPath}` : '';
|
|
283
|
-
const errStr =
|
|
448
|
+
const errStr = lifecycleTimedOut
|
|
449
|
+
? errMsg(abortSignalError(lifecycle.signal as AbortSignal))
|
|
450
|
+
: errMsg(err);
|
|
284
451
|
// Classify the failure mode honestly: a missing locator, a step
|
|
285
452
|
// timeout, or a `forResponse` wait that didn't resolve are
|
|
286
453
|
// transient page-state signals (the DOM rendered differently than
|
|
@@ -291,6 +458,7 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
291
458
|
// transient-shape errors to NETWORK so they count as `infra`
|
|
292
459
|
// (re-runnable) rather than `tool_broken` (permanent defect).
|
|
293
460
|
const isTransient =
|
|
461
|
+
lifecycleTimedOut ||
|
|
294
462
|
/No locator matched|Timeout \d+ms exceeded|timed out after|exceeded max duration|forResponse|waiting for/i.test(
|
|
295
463
|
errStr,
|
|
296
464
|
);
|
|
@@ -301,9 +469,9 @@ export async function runPlaybook(opts: RunPlaybookOptions): Promise<ToolResult>
|
|
|
301
469
|
};
|
|
302
470
|
} finally {
|
|
303
471
|
if (!opts.pageOverride) {
|
|
304
|
-
await context
|
|
305
|
-
await browser?.close().catch(() => {});
|
|
472
|
+
await closePlaybookResources(context, browser, opts.cleanupTimeoutMs);
|
|
306
473
|
}
|
|
474
|
+
lifecycle.dispose();
|
|
307
475
|
}
|
|
308
476
|
}
|
|
309
477
|
|
|
@@ -312,13 +480,19 @@ async function screenshot(
|
|
|
312
480
|
toolName: string,
|
|
313
481
|
stepNum: number,
|
|
314
482
|
timeoutMs: number,
|
|
483
|
+
signal?: AbortSignal,
|
|
315
484
|
): Promise<string | null> {
|
|
316
485
|
try {
|
|
317
486
|
const { tmpdir } = await import('node:os');
|
|
318
487
|
const { join } = await import('node:path');
|
|
319
488
|
const ts = new Date().toISOString().replace(/[:.]/g, '-');
|
|
320
489
|
const path = join(tmpdir(), `imprint-playbook-${toolName}-step${stepNum}-${ts}.png`);
|
|
321
|
-
await withTimeout(
|
|
490
|
+
await withTimeout(
|
|
491
|
+
page.screenshot({ path, fullPage: true }),
|
|
492
|
+
timeoutMs,
|
|
493
|
+
'Playbook screenshot',
|
|
494
|
+
signal,
|
|
495
|
+
);
|
|
322
496
|
return path;
|
|
323
497
|
} catch {
|
|
324
498
|
return null;
|
|
@@ -341,22 +515,39 @@ function budgetedTimeoutMs(
|
|
|
341
515
|
return Math.max(1, Math.min(configuredMs, Math.floor(remainingMs)));
|
|
342
516
|
}
|
|
343
517
|
|
|
344
|
-
async function withTimeout<T>(
|
|
518
|
+
async function withTimeout<T>(
|
|
519
|
+
promise: Promise<T>,
|
|
520
|
+
timeoutMs: number,
|
|
521
|
+
label: string,
|
|
522
|
+
signal?: AbortSignal,
|
|
523
|
+
): Promise<T> {
|
|
345
524
|
const boundedMs = positiveMs(timeoutMs, 1);
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
525
|
+
if (signal?.aborted) throw abortSignalError(signal);
|
|
526
|
+
return await new Promise<T>((resolve, reject) => {
|
|
527
|
+
const cleanup = (): void => {
|
|
528
|
+
clearTimeout(timer);
|
|
529
|
+
signal?.removeEventListener('abort', abort);
|
|
530
|
+
};
|
|
531
|
+
const abort = (): void => {
|
|
532
|
+
cleanup();
|
|
533
|
+
reject(abortSignalError(signal as AbortSignal));
|
|
534
|
+
};
|
|
535
|
+
const timer = setTimeout(() => {
|
|
536
|
+
cleanup();
|
|
537
|
+
reject(new Error(`${label} timed out after ${boundedMs}ms`));
|
|
538
|
+
}, boundedMs);
|
|
539
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
540
|
+
promise.then(
|
|
541
|
+
(value) => {
|
|
542
|
+
cleanup();
|
|
543
|
+
resolve(value);
|
|
544
|
+
},
|
|
545
|
+
(error) => {
|
|
546
|
+
cleanup();
|
|
547
|
+
reject(error);
|
|
548
|
+
},
|
|
549
|
+
);
|
|
550
|
+
});
|
|
360
551
|
}
|
|
361
552
|
|
|
362
553
|
async function loadPlaybook(input: string | Playbook): Promise<Playbook> {
|