@nostop/page 0.1.0-rc.2 → 0.1.0-rc.3

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 (82) hide show
  1. package/README.md +25 -13
  2. package/dist/esm/{SimulatorMask-A9fOKtEZ.js → SimulatorMask-D6QhYREr.js} +11 -11
  3. package/dist/esm/SimulatorMask-D6QhYREr.js.map +1 -0
  4. package/dist/esm/{ax-core-oj-p6gBY.js → ax-core-BVXEU2Dk.js} +16 -3
  5. package/dist/esm/ax-core-BVXEU2Dk.js.map +1 -0
  6. package/dist/esm/page-agent.js +2720 -168
  7. package/dist/esm/page-agent.js.map +1 -1
  8. package/dist/esm/types/core/src/PageAgentCore.d.ts +105 -0
  9. package/dist/esm/types/core/src/confirmation.d.ts +2 -0
  10. package/dist/esm/types/core/src/contextMemory.d.ts +20 -0
  11. package/dist/esm/types/core/src/redactSensitiveUrls.d.ts +4 -0
  12. package/dist/esm/types/core/src/targetContext.d.ts +11 -0
  13. package/dist/esm/types/core/src/taskContext.d.ts +78 -0
  14. package/dist/esm/types/core/src/tools/index.d.ts +43 -0
  15. package/dist/esm/types/core/src/types.d.ts +317 -0
  16. package/dist/esm/types/core/src/utils/autoFixer.d.ts +14 -0
  17. package/dist/esm/types/core/src/utils/index.d.ts +26 -0
  18. package/dist/esm/types/llms/src/OpenAIClient.d.ts +10 -0
  19. package/dist/esm/types/llms/src/errors.d.ts +28 -0
  20. package/dist/esm/types/llms/src/index.d.ts +19 -0
  21. package/dist/esm/types/llms/src/types.d.ts +108 -0
  22. package/dist/esm/types/llms/src/utils.d.ts +59 -0
  23. package/dist/esm/types/page-agent/src/PageAgent.d.ts +17 -0
  24. package/dist/esm/types/page-agent/src/demo.d.ts +1 -0
  25. package/dist/esm/types/page-controller/src/PageController.d.ts +314 -0
  26. package/dist/esm/types/page-controller/src/actions.d.ts +45 -0
  27. package/dist/esm/types/page-controller/src/ax/AccessibilityController.d.ts +191 -0
  28. package/dist/esm/types/page-controller/src/ax/diagnosis.d.ts +42 -0
  29. package/dist/esm/types/page-controller/src/ax/diff.d.ts +74 -0
  30. package/dist/esm/types/page-controller/src/ax/domActivity.d.ts +33 -0
  31. package/dist/esm/types/page-controller/src/ax/domPath.d.ts +12 -0
  32. package/dist/esm/types/page-controller/src/ax/engine.d.ts +245 -0
  33. package/dist/esm/types/page-controller/src/ax/errors.d.ts +44 -0
  34. package/dist/esm/types/page-controller/src/ax/evidence.d.ts +30 -0
  35. package/dist/esm/types/page-controller/src/ax/format.d.ts +10 -0
  36. package/dist/esm/types/page-controller/src/ax/ids.d.ts +17 -0
  37. package/dist/esm/types/page-controller/src/ax/index.d.ts +11 -0
  38. package/dist/esm/types/page-controller/src/ax/observation.d.ts +6 -0
  39. package/dist/esm/types/page-controller/src/ax/types.d.ts +298 -0
  40. package/dist/esm/types/page-controller/src/ax/vendor/ax-core.d.ts +202 -0
  41. package/dist/esm/types/page-controller/src/ax/vendor/ax-standards.d.ts +27 -0
  42. package/dist/esm/types/page-controller/src/dom/dom_tree/index.d.ts +21 -0
  43. package/dist/esm/types/page-controller/src/dom/dom_tree/type.d.ts +41 -0
  44. package/dist/esm/types/page-controller/src/dom/getPageInfo.d.ts +16 -0
  45. package/dist/esm/types/page-controller/src/dom/index.d.ts +62 -0
  46. package/dist/esm/types/page-controller/src/geometry.d.ts +9 -0
  47. package/dist/esm/types/page-controller/src/mask/SimulatorMask.d.ts +20 -0
  48. package/dist/esm/types/page-controller/src/mask/siteColor.d.ts +38 -0
  49. package/dist/esm/types/page-controller/src/patches/antd.d.ts +2 -0
  50. package/dist/esm/types/page-controller/src/patches/react.d.ts +5 -0
  51. package/dist/esm/types/page-controller/src/redactSensitiveUrls.d.ts +2 -0
  52. package/dist/esm/types/page-controller/src/scriptResult.d.ts +8 -0
  53. package/dist/esm/types/page-controller/src/stateFreshness.d.ts +16 -0
  54. package/dist/esm/types/page-controller/src/utils/index.d.ts +25 -0
  55. package/dist/esm/types/ui/src/i18n/index.d.ts +12 -0
  56. package/dist/esm/types/ui/src/i18n/locales.d.ts +358 -0
  57. package/dist/esm/types/ui/src/index.d.ts +2 -0
  58. package/dist/esm/types/ui/src/panel/Panel.d.ts +60 -0
  59. package/dist/esm/types/ui/src/panel/feed.d.ts +31 -0
  60. package/dist/esm/types/ui/src/panel/fold.d.ts +2 -0
  61. package/dist/esm/types/ui/src/panel/highlight.d.ts +18 -0
  62. package/dist/esm/types/ui/src/panel/icons.d.ts +6 -0
  63. package/dist/esm/types/ui/src/panel/microphone.d.ts +21 -0
  64. package/dist/esm/types/ui/src/panel/recovery.d.ts +21 -0
  65. package/dist/esm/types/ui/src/panel/scriptCard.d.ts +25 -0
  66. package/dist/esm/types/ui/src/panel/toolVisual.d.ts +10 -0
  67. package/dist/esm/types/ui/src/panel/trace.d.ts +15 -0
  68. package/dist/esm/types/ui/src/panel/types.d.ts +92 -0
  69. package/dist/esm/types/ui/src/panel/voiceRuns.d.ts +26 -0
  70. package/dist/esm/types/ui/src/panel/voiceTaskRouting.d.ts +8 -0
  71. package/dist/esm/types/ui/src/utils.d.ts +5 -0
  72. package/dist/esm/types/ui/src/voice/gemini-client.d.ts +12 -0
  73. package/dist/esm/types/ui/src/voice/gemini-protocol.d.ts +52 -0
  74. package/dist/esm/types/ui/src/voice/realtime-client.d.ts +25 -0
  75. package/dist/esm/types/ui/src/voice/realtime-protocol.d.ts +97 -0
  76. package/dist/esm/types/ui/src/voice/voice-prompt.d.ts +11 -0
  77. package/dist/esm/types/ui/src/voice/voice-session.d.ts +76 -0
  78. package/dist/iife/page-agent.demo.js +189 -87
  79. package/package.json +6 -6
  80. package/dist/esm/PageAgent.d.ts +0 -39
  81. package/dist/esm/SimulatorMask-A9fOKtEZ.js.map +0 -1
  82. package/dist/esm/ax-core-oj-p6gBY.js.map +0 -1
@@ -0,0 +1,105 @@
1
+ import type { PageController } from "../../page-controller/src/PageController.js";
2
+ import { tools } from "./tools/index.js";
3
+ import type { AgentConfig, AgentStatus, ExecutionResult, HistoricalEvent } from "./types.js";
4
+ export { tool, type PageAgentTool, type ToolContext } from "./tools/index.js";
5
+ export type * from "./types.js";
6
+ export type PageAgentCoreConfig = AgentConfig & {
7
+ pageController: PageController;
8
+ };
9
+ /**
10
+ * AI agent for browser automation.
11
+ *
12
+ * @remarks
13
+ * ## Re-act Agent Loop
14
+ * - step
15
+ * - observe (gather information about current environment and context)
16
+ * - think (LLM calling)
17
+ * - reflection (evaluate history, generate memory, short-term planning)
18
+ * - action (give the action to approach the next goal)
19
+ * - act (execute the action)
20
+ * - loop
21
+ *
22
+ * ## Event System
23
+ * - `statuschange` - Agent status transitions (idle → running → completed/error/stopped)
24
+ * - `historychange` - History events updated (persistent, part of agent memory)
25
+ * - `activity` - Real-time activity feedback (transient, for UI only)
26
+ * - `dispose` - Agent cleanup triggered
27
+ *
28
+ * ## Information Streams
29
+ * 1. **History Events** (`history` array)
30
+ * - Persistent event stream that forms agent's memory
31
+ * - Included in LLM context across steps
32
+ * - Types: steps, observations, user takeovers, llm errors
33
+ *
34
+ * 2. **Activity Events** (via `activity` event)
35
+ * - Transient UI feedback during task execution
36
+ * - NOT included in LLM context
37
+ * - Types: thinking, executing, executed, retrying, error
38
+ */
39
+ export declare class PageAgentCore extends EventTarget {
40
+ #private;
41
+ readonly id: string;
42
+ readonly config: PageAgentCoreConfig & {
43
+ maxSteps: number;
44
+ };
45
+ readonly tools: typeof tools;
46
+ /** PageController for DOM operations */
47
+ readonly pageController: PageController;
48
+ task: string;
49
+ taskId: string;
50
+ /** History events */
51
+ history: HistoricalEvent[];
52
+ /** Whether this agent has been disposed */
53
+ disposed: boolean;
54
+ /**
55
+ * Called when the agent needs to ask the user questions.
56
+ * If unset, the `ask_user` tool will be disabled.
57
+ * Implementations should reject the promise when `signal` aborts.
58
+ * @example onAskUser: (q) => window.prompt(q) || ''
59
+ */
60
+ onAskUser?: (question: string, options?: {
61
+ signal: AbortSignal;
62
+ }) => Promise<string>;
63
+ constructor(config: PageAgentCoreConfig);
64
+ /** Get current agent status */
65
+ get status(): AgentStatus;
66
+ /** Result of the most recent run, or `null` before the first run completes. */
67
+ get lastResult(): ExecutionResult | null;
68
+ /** Whether the configured account identity still matches the last agent observation. */
69
+ isObservedAccountCurrent(): boolean;
70
+ /** Retain a refused confirmation as user input without retaining the action payload. */
71
+ recordConfirmationRefusal(answer: string): void;
72
+ /** Execute an agent tool through the same authorization path for text and voice. */
73
+ executeTool(name: string, input: any, signal: AbortSignal, options?: {
74
+ timeoutMs?: number;
75
+ onDispatch?: () => void;
76
+ onActionNotPerformed?: () => void;
77
+ onActionReportedFailure?: () => void;
78
+ expectedNestedControl?: Element | null;
79
+ expectedNestedDescription?: {
80
+ tag: string;
81
+ role: string;
82
+ label: string;
83
+ } | null;
84
+ expectedNestedSignature?: string | null;
85
+ verifyReviewedTarget?: () => Promise<boolean>;
86
+ }): Promise<string>;
87
+ /**
88
+ * Push an observation message to the history event stream.
89
+ * This will be visible in <agent_history> and remain persistent in memory across steps.
90
+ * @experimental @internal
91
+ * @note history change will be emitted before next step starts
92
+ */
93
+ pushObservation(content: string): void;
94
+ /**
95
+ * Stop the current task and wait until the run has fully settled (including lifecycle hooks).
96
+ * @note never await .stop() in a lifecycle hook.
97
+ */
98
+ stop(): Promise<void>;
99
+ /**
100
+ * external errors (pre-checks/config/hooks) will threw;
101
+ * agent errors will be caught and added to history, and return a failed result
102
+ */
103
+ execute(task: string): Promise<ExecutionResult>;
104
+ dispose(): void;
105
+ }
@@ -0,0 +1,2 @@
1
+ /** Accept explicit, immediate confirmations; defer ambiguous wording to another question. */
2
+ export declare function isExplicitConfirmation(answer: string): boolean;
@@ -0,0 +1,20 @@
1
+ /** Explicitly enabled sessionStorage recovery of user context; never replays actions. */
2
+ export interface ContextMemoryRecord {
3
+ id: string;
4
+ origin: string;
5
+ account: string;
6
+ task: string;
7
+ answers: {
8
+ question: string;
9
+ answer: string;
10
+ recordedAt?: number;
11
+ }[];
12
+ updatedAt: number;
13
+ status: 'interrupted' | 'finished';
14
+ }
15
+ type StoragePort = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
16
+ export declare function createContextMemory(storage: StoragePort, key: string, ttlMs: number, now?: () => number): {
17
+ load(origin: string, account: string): ContextMemoryRecord[];
18
+ save(record: ContextMemoryRecord): void;
19
+ };
20
+ export {};
@@ -0,0 +1,4 @@
1
+ /** Remove access-bearing URL parameters from text sent to models or diagnostic logs. */
2
+ export declare function redactSensitiveUrls(text: string): string;
3
+ /** Redact recognized credential fields in a serialized tool payload before displaying it. */
4
+ export declare function redactSensitiveToolPayload(serialized: string): string;
@@ -0,0 +1,11 @@
1
+ /** Return nearby observation lines as untrusted context, not a semantic identity claim. */
2
+ export declare function targetContext(observation: string, index: number): string[];
3
+ /** Structural hint only; a heading or collection does not establish the target's meaning. */
4
+ export declare function hasGroupedSelectionContext(observation: string, index: number): boolean;
5
+ /** Other controls are possible alternatives, not confirmed matches or actionable handles. */
6
+ export declare function targetAlternativesSummary(observation: string, index: number): {
7
+ items: string[];
8
+ omitted: number;
9
+ targetFound: boolean;
10
+ };
11
+ export declare function targetAlternatives(observation: string, index: number): string[];
@@ -0,0 +1,78 @@
1
+ /** Ephemeral, per-task records. These are evidence and expectations, not verified conclusions. */
2
+ export interface TaskContextSnapshot {
3
+ goal: string;
4
+ snapshotId: number;
5
+ referenceChecks: {
6
+ snapshot: number;
7
+ index: number;
8
+ quote?: string;
9
+ status: 'present' | 'missing' | 'stale' | 'quote-not-found';
10
+ }[];
11
+ answers: {
12
+ question: string;
13
+ answer: string;
14
+ snapshotId: number | null;
15
+ recordedAt: number;
16
+ }[];
17
+ evidenceChecks: {
18
+ text: string;
19
+ status: 'present' | 'not-found';
20
+ }[];
21
+ proposal: null | {
22
+ purpose: string;
23
+ evidence: string[];
24
+ alternatives: string[];
25
+ uncertainty: string;
26
+ };
27
+ /** Snapshot against which the proposal's evidence was checked, not the current snapshot. */
28
+ proposalSnapshotId: number | null;
29
+ /** A later user answer may clarify or contradict the last model proposal. */
30
+ proposalNeedsReconsideration: boolean;
31
+ lastUndispatchedAction: null | {
32
+ name: string;
33
+ reason: string;
34
+ snapshotId: number | null;
35
+ };
36
+ recentReportedFailures: {
37
+ name: string;
38
+ reason: string;
39
+ snapshotId: number | null;
40
+ }[];
41
+ lastAction: null | {
42
+ name: string;
43
+ expectedEffect: string;
44
+ status: 'unverified';
45
+ reportedFailure: boolean;
46
+ observationChanged: boolean | null;
47
+ expectedText: string;
48
+ expectedTextStatus: 'not-provided' | 'pending' | 'appeared' | 'already-present' | 'not-observed';
49
+ };
50
+ }
51
+ export declare class TaskContext {
52
+ private readonly state;
53
+ private observation;
54
+ private observationText;
55
+ private actionObservation;
56
+ private expectedTextPreviouslyPresent;
57
+ private expectedTextAbsentObserved;
58
+ private indexedLines;
59
+ constructor(goal: string);
60
+ /** Discard account-scoped details while retaining the goal and monotonic observation counter. */
61
+ resetForScopeChange(): void;
62
+ checkReferences(references: {
63
+ snapshot: number;
64
+ index: number;
65
+ quote?: string;
66
+ }[]): TaskContextSnapshot['referenceChecks'][number]['status'][];
67
+ recordReferences(references: {
68
+ snapshot: number;
69
+ index: number;
70
+ quote?: string;
71
+ }[]): void;
72
+ recordProposal(proposal: NonNullable<TaskContextSnapshot['proposal']>): void;
73
+ recordAnswer(question: string, answer: string): void;
74
+ recordAction(name: string, expectedEffect: string, outcome: string, expectedText?: string, reportedFailure?: boolean): void;
75
+ recordUndispatchedAction(name: string, reason: string): void;
76
+ observe(url: string, content: string): void;
77
+ snapshot(): TaskContextSnapshot;
78
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Internal tools for PageAgent.
3
+ * @note Adapted from browser-use
4
+ */
5
+ import * as z from 'zod/v4';
6
+ import type { PageAgentCore } from "../PageAgentCore.js";
7
+ /**
8
+ * Per-invocation context passed to every tool execution.
9
+ * Tools MUST honor `signal` to support cooperative cancellation.
10
+ */
11
+ export interface ToolContext {
12
+ signal: AbortSignal;
13
+ /** Report that a built-in tool stopped before dispatching its page action. */
14
+ onActionNotPerformed?: () => void;
15
+ /** The controller returned a failure; partial effects may still have occurred. */
16
+ onActionReportedFailure?: () => void;
17
+ /** Internal identity constraint for a reviewed DOM hit; undefined means no constraint. */
18
+ expectedNestedControl?: Element | null;
19
+ expectedNestedDescription?: {
20
+ tag: string;
21
+ role: string;
22
+ label: string;
23
+ } | null;
24
+ expectedNestedSignature?: string | null;
25
+ /** Internal recheck for a reviewed DOM target and its structural context. */
26
+ verifyReviewedTarget?: () => Promise<boolean>;
27
+ }
28
+ /**
29
+ * Internal tool definition that has access to PageAgent `this` context
30
+ */
31
+ export interface PageAgentTool<TParams = any> {
32
+ description: string;
33
+ inputSchema: z.ZodType<TParams>;
34
+ /** Declare consequential actions that require explicit user authorization. */
35
+ effect?: 'read' | 'write' | 'sensitive';
36
+ execute: (this: PageAgentCore, args: TParams, ctx: ToolContext) => Promise<string>;
37
+ }
38
+ export declare function tool<TParams>(options: PageAgentTool<TParams>): PageAgentTool<TParams>;
39
+ /**
40
+ * Internal tools for PageAgent.
41
+ * Note: Using any to allow different parameter types for each tool
42
+ */
43
+ export declare const tools: Map<string, PageAgentTool<any>>;
@@ -0,0 +1,317 @@
1
+ import type { LLMConfig } from "../../llms/src/index.js";
2
+ import type { PageAgentCore } from "./PageAgentCore.js";
3
+ import type { PageAgentTool } from "./tools/index.js";
4
+ /** Supported UI languages */
5
+ export type SupportedLanguage = 'en-US' | 'pt-BR';
6
+ export interface AgentConfig extends LLMConfig {
7
+ language?: SupportedLanguage;
8
+ /** Enable experimental per-task contextual observations. Default false for reversible rollout. */
9
+ experimentalContextualDecision?: boolean;
10
+ /** Account/tenant scope for previous user context. Return null to disable cross-task reuse. */
11
+ contextualAccountScope?: (url: string) => string | null;
12
+ /** Opt in to semantic selection of same-account history with the configured model. */
13
+ contextualHistorySelection?: 'model';
14
+ /** Opt in to a separate model review for flagged or declared sensitive actions. */
15
+ contextualDecisionReview?: 'model';
16
+ /** Opt in to review clicks in structurally grouped contexts; may defer legitimate actions. */
17
+ contextualReviewGroupedClicks?: boolean;
18
+ /** Opt in to model review when a DOM click may hit an interactive descendant. */
19
+ contextualReviewDomHits?: boolean;
20
+ /** Opt in to reporting success as unverified when an explicitly expected text is absent. Requires contextual mode. */
21
+ contextualRequireExpectedText?: boolean;
22
+ /** Opt in to reporting completion as unverified after the last action reported a failure. Requires contextual mode. */
23
+ contextualGuardReportedFailure?: boolean;
24
+ /** Opt in to sessionStorage recovery. New tabs with an opener can inherit a copy. Requires contextualAccountScope. */
25
+ contextualRecovery?: {
26
+ /** Retention from the last saved update. Default 5000 ms, maximum 24 hours. */
27
+ ttlMs?: number;
28
+ /** Session storage key. Use a distinct key for each integration. */
29
+ storageKey?: string;
30
+ };
31
+ /**
32
+ * Maximum number of steps the agent can take per task.
33
+ * @default 40
34
+ */
35
+ maxSteps?: number;
36
+ /**
37
+ * Custom tools to extend PageAgent capabilities
38
+ * @experimental
39
+ * @note You can also override or remove internal tools by using the same name.
40
+ * @see PageAgentTool
41
+ *
42
+ * @example
43
+ * // override internal tool
44
+ * import { z } from 'zod/v4'
45
+ * import { tool } from '@nostop/page'
46
+ * const customTools = {
47
+ * ask_user: tool({
48
+ * description:
49
+ * 'Ask the user or parent model a question and wait for their answer. Use this if you need more information or clarification.',
50
+ * inputSchema: z.object({
51
+ * question: z.string(),
52
+ * }),
53
+ * execute: async function (this: PageAgent, input) {
54
+ * const answer = await do_some_thing(input.question)
55
+ * return "✅ Received user answer: " + answer
56
+ * },
57
+ * })
58
+ * }
59
+ *
60
+ * @example
61
+ * // remove internal tool
62
+ * const customTools = {
63
+ * ask_user: null // never ask user questions
64
+ * }
65
+ */
66
+ customTools?: Record<string, PageAgentTool | null>;
67
+ /**
68
+ * Instructions to guide the agent's behavior
69
+ */
70
+ instructions?: {
71
+ /**
72
+ * Global system-level instructions, applied to all tasks
73
+ */
74
+ system?: string;
75
+ /**
76
+ * Dynamic page-level instructions callback
77
+ * Called before each step to get instructions for the current page
78
+ * @param url - Current page URL (window.location.href)
79
+ * @returns Instructions string, or undefined/null to skip
80
+ */
81
+ getPageInstructions?: (url: string) => string | undefined | null;
82
+ };
83
+ /**
84
+ * Lifecycle hooks for task execution.
85
+ * @experimental API may change in future versions.
86
+ *
87
+ * All hooks receive the agent instance as first parameter.
88
+ */
89
+ /**
90
+ * Called before each step execution.
91
+ * @experimental
92
+ * @param agent - The PageAgentCore instance
93
+ * @param stepCount - Current step number (0-indexed)
94
+ */
95
+ onBeforeStep?: (agent: PageAgentCore, stepCount: number) => Promise<void> | void;
96
+ /**
97
+ * Called after each step execution.
98
+ * @experimental
99
+ * @param agent - The PageAgentCore instance
100
+ * @param history - Current history of events
101
+ */
102
+ onAfterStep?: (agent: PageAgentCore, history: HistoricalEvent[]) => Promise<void> | void;
103
+ /**
104
+ * Called before task execution starts.
105
+ * @experimental
106
+ * @param agent - The PageAgentCore instance
107
+ */
108
+ onBeforeTask?: (agent: PageAgentCore) => Promise<void> | void;
109
+ /**
110
+ * Called after task execution completes (success or failure).
111
+ * @experimental
112
+ * @param agent - The PageAgentCore instance
113
+ * @param result - The execution result
114
+ */
115
+ onAfterTask?: (agent: PageAgentCore, result: ExecutionResult) => Promise<void> | void;
116
+ /**
117
+ * Called when the agent is disposed.
118
+ * @experimental
119
+ * @note This hook can block the disposal process if it's async.
120
+ * @param agent - The PageAgentCore instance
121
+ * @param reason - Optional reason for disposal
122
+ */
123
+ onDispose?: (agent: PageAgentCore, reason?: string) => void;
124
+ /**
125
+ * @experimental
126
+ * The script execution tool (`execute_javascript`) runs generated JavaScript code on the page. It is enabled
127
+ * by default; set `false` to remove it.
128
+ * Text and voice requests through the agent require explicit user confirmation before execution,
129
+ * including scripts intended to be read-only. Scripts still have page privileges after approval.
130
+ * @note Can cause unpredictable side effects.
131
+ * @note May bypass some safe guards and data-masking mechanisms.
132
+ * @default true
133
+ */
134
+ experimentalScriptExecutionTool?: boolean;
135
+ /**
136
+ * @experimental
137
+ * Fetch /llms.txt from current site origin and include as context.
138
+ * Only fetched once per origin per task.
139
+ * @default false
140
+ */
141
+ experimentalLlmsTxt?: boolean;
142
+ /**
143
+ * Transform page content before sending to LLM.
144
+ * Called after DOM extraction and simplification, before LLM invocation.
145
+ * Use cases: inspect extraction results, modify page info, mask sensitive data.
146
+ *
147
+ * @param content - Simplified page content that will be sent to LLM
148
+ * @returns Transformed content
149
+ *
150
+ * @example
151
+ * // Mask phone numbers
152
+ * transformPageContent: async (content) => {
153
+ * return content.replace(/1[3-9]\d{9}/g, '***********')
154
+ * }
155
+ */
156
+ transformPageContent?: (content: string) => Promise<string> | string;
157
+ /**
158
+ * Text for the system prompt. It is added after the built-in system prompt, which is kept whole.
159
+ * It replaces the built-in prompt only when `overrideSystemPrompt` is `true`.
160
+ */
161
+ customSystemPrompt?: string;
162
+ /**
163
+ * REVERSIBLE (2026-11-23, system prompt override).
164
+ * Let `customSystemPrompt` replace the built-in system prompt instead of being added to it.
165
+ * @experimental Use with caution - the built-in rules are lost, and an incomplete prompt may break agent behavior.
166
+ * @default false
167
+ */
168
+ overrideSystemPrompt?: boolean;
169
+ /**
170
+ * Delay between steps in seconds.
171
+ * @default 0.4
172
+ */
173
+ stepDelay?: number;
174
+ }
175
+ /**
176
+ * Agent reflection state - the reflection-before-action model
177
+ *
178
+ * Every tool call must first reflect on:
179
+ * - evaluation_previous_goal: How well did the previous action achieve its goal?
180
+ * - memory: Key information to remember for future steps
181
+ * - next_goal: What should be accomplished in the next action?
182
+ */
183
+ export interface AgentReflection {
184
+ evaluation_previous_goal: string;
185
+ memory: string;
186
+ next_goal: string;
187
+ }
188
+ /**
189
+ * MacroTool input structure
190
+ *
191
+ * This is the core abstraction that enforces the "reflection-before-action" mental model.
192
+ * Before executing any action, the LLM must output its reasoning state.
193
+ */
194
+ export interface MacroToolInput extends Partial<AgentReflection> {
195
+ action: Record<string, any>;
196
+ /** Optional model proposal; referenced observations are not independently verified. */
197
+ decision?: {
198
+ purpose?: string;
199
+ evidence?: string[];
200
+ alternatives?: string[];
201
+ uncertainty?: string;
202
+ requestReview?: boolean;
203
+ expectedText?: string;
204
+ references?: {
205
+ snapshot: number;
206
+ index: number;
207
+ quote?: string;
208
+ }[];
209
+ };
210
+ }
211
+ /**
212
+ * MacroTool output structure
213
+ */
214
+ export interface MacroToolResult {
215
+ input: MacroToolInput;
216
+ output: string;
217
+ completionDeferred?: boolean;
218
+ /** The same click kept being requested after the executor had already blocked it. */
219
+ repeatedActionStalled?: boolean;
220
+ reviewActionStalled?: boolean;
221
+ }
222
+ /**
223
+ * A single agent step with reflection and action
224
+ */
225
+ export interface AgentStepEvent {
226
+ type: 'step';
227
+ stepIndex: number;
228
+ reflection: Partial<AgentReflection>;
229
+ action: {
230
+ name: string;
231
+ input: any;
232
+ output: string;
233
+ };
234
+ usage: {
235
+ promptTokens: number;
236
+ completionTokens: number;
237
+ totalTokens: number;
238
+ cachedTokens?: number;
239
+ reasoningTokens?: number;
240
+ };
241
+ /** Raw LLM response for debugging */
242
+ rawResponse?: unknown;
243
+ /** Raw LLM request for debugging */
244
+ rawRequest?: unknown;
245
+ }
246
+ /**
247
+ * Persistent observation event (stays in memory)
248
+ */
249
+ export interface ObservationEvent {
250
+ type: 'observation';
251
+ content: string;
252
+ }
253
+ /**
254
+ * User takeover event
255
+ */
256
+ export interface UserTakeoverEvent {
257
+ type: 'user_takeover';
258
+ }
259
+ /**
260
+ * Retry event - LLM call is being retried
261
+ */
262
+ export interface RetryEvent {
263
+ type: 'retry';
264
+ message: string;
265
+ attempt: number;
266
+ maxAttempts: number;
267
+ }
268
+ /**
269
+ * Error event - fatal error from LLM or execution
270
+ */
271
+ export interface AgentErrorEvent {
272
+ type: 'error';
273
+ message: string;
274
+ rawResponse?: unknown;
275
+ }
276
+ /**
277
+ * Union type for all history events
278
+ */
279
+ export type HistoricalEvent = AgentStepEvent | ObservationEvent | UserTakeoverEvent | RetryEvent | AgentErrorEvent;
280
+ /**
281
+ * Agent lifecycle status.
282
+ */
283
+ export type AgentStatus = 'idle' | 'running' | 'completed' | 'error' | 'stopped';
284
+ /**
285
+ * Agent activity - transient state for immediate UI feedback.
286
+ *
287
+ * Unlike historical events (which are persisted), activities are ephemeral
288
+ * and represent "what the agent is doing right now". UI components should
289
+ * listen to 'activity' events to show real-time feedback.
290
+ *
291
+ * Note: There is no 'idle' activity - absence of activity events means idle.
292
+ */
293
+ export type AgentActivity = {
294
+ type: 'thinking';
295
+ } | {
296
+ type: 'executing';
297
+ tool: string;
298
+ input: unknown;
299
+ } | {
300
+ type: 'executed';
301
+ tool: string;
302
+ input: unknown;
303
+ output: string;
304
+ duration: number;
305
+ } | {
306
+ type: 'retrying';
307
+ attempt: number;
308
+ maxAttempts: number;
309
+ } | {
310
+ type: 'error';
311
+ message: string;
312
+ };
313
+ export interface ExecutionResult {
314
+ success: boolean;
315
+ data: string;
316
+ history: HistoricalEvent[];
317
+ }
@@ -0,0 +1,14 @@
1
+ import type { PageAgentTool } from "../tools/index.js";
2
+ /**
3
+ * Normalize LLM response and fix common format issues.
4
+ *
5
+ * Handles:
6
+ * - No tool_calls but JSON in message.content (fallback)
7
+ * - Model returns action name as tool call instead of AgentOutput
8
+ * - Arguments wrapped as double JSON string
9
+ * - Nested function call format
10
+ * - Missing action field (fallback to wait)
11
+ * - Primitive action input for single-field tools (e.g. `{"click_element_by_index": 2}`)
12
+ * - etc.
13
+ */
14
+ export declare function normalizeResponse(response: any, tools?: Map<string, PageAgentTool>): any;
@@ -0,0 +1,26 @@
1
+ export * from "./autoFixer.js";
2
+ /**
3
+ * Wait for `seconds`. If a `signal` is provided, the wait is cancellable:
4
+ * aborting rejects with the signal's reason (an `AbortError`).
5
+ */
6
+ export declare function waitFor(seconds: number, signal?: AbortSignal): Promise<void>;
7
+ export declare function truncate(text: string, maxLength: number): string;
8
+ export declare function randomID(existingIDs?: string[]): string;
9
+ /**
10
+ * Generate a random ID.
11
+ * @note Unique within this window.
12
+ */
13
+ export declare function uid(): string;
14
+ /** Fetch /llms.txt for a URL's origin. Cached per origin, `null` = tried and not found. */
15
+ export declare function fetchLlmsTxt(url: string): Promise<string | null>;
16
+ /**
17
+ * Simple assertion function that throws an error if the condition is falsy
18
+ * @param condition - The condition to assert
19
+ * @param message - Optional error message
20
+ * @throws Error if condition is falsy
21
+ */
22
+ export declare function assert(condition: unknown, message?: string, silent?: boolean): asserts condition;
23
+ /**
24
+ * Suppress errors from a function.
25
+ */
26
+ export declare function suppress<T>(fn: () => T | Promise<T>): Promise<Awaited<T> | undefined>;
@@ -0,0 +1,10 @@
1
+ import type { InvokeOptions, InvokeResult, LLMClient, Message, ResolvedLLMConfig, Tool } from "./types.js";
2
+ /**
3
+ * Client for OpenAI compatible APIs
4
+ */
5
+ export declare class OpenAIClient implements LLMClient {
6
+ config: ResolvedLLMConfig;
7
+ private fetch;
8
+ constructor(config: ResolvedLLMConfig);
9
+ invoke(messages: Message[], tools: Record<string, Tool>, abortSignal?: AbortSignal, options?: InvokeOptions): Promise<InvokeResult>;
10
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Error types and error handling for LLM invocations.
3
+ */
4
+ export declare const InvokeErrorTypes: {
5
+ readonly NETWORK_ERROR: "network_error";
6
+ readonly RATE_LIMIT: "rate_limit";
7
+ readonly SERVER_ERROR: "server_error";
8
+ readonly NO_TOOL_CALL: "no_tool_call";
9
+ readonly INVALID_TOOL_ARGS: "invalid_tool_args";
10
+ readonly TOOL_EXECUTION_ERROR: "tool_execution_error";
11
+ readonly INVALID_RESPONSE: "invalid_response";
12
+ readonly INVALID_SCHEMA: "invalid_schema";
13
+ readonly UNKNOWN: "unknown";
14
+ readonly CONFIG_ERROR: "config_error";
15
+ readonly AUTH_ERROR: "auth_error";
16
+ readonly CONTEXT_LENGTH: "context_length";
17
+ readonly CONTENT_FILTER: "content_filter";
18
+ };
19
+ type InvokeErrorType = (typeof InvokeErrorTypes)[keyof typeof InvokeErrorTypes];
20
+ export declare class InvokeError extends Error {
21
+ type: InvokeErrorType;
22
+ retryable: boolean;
23
+ statusCode?: number;
24
+ rawError?: unknown;
25
+ rawResponse?: unknown;
26
+ constructor(type: InvokeErrorType, message: string, rawError?: unknown, rawResponse?: unknown);
27
+ }
28
+ export {};