agents 0.31.0 → 0.33.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/dist/{agent-routing-wS1TimZ_.d.ts → agent-routing-vVMA7m8Y.d.ts} +6 -6
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-Bamxxb6Y.d.ts → agent-tools-gGXXkf1z.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/agent-tools.js +0 -1
- package/dist/agent-tools.js.map +1 -1
- package/dist/{ai-sdk-hW3vntnk.d.ts → ai-sdk-CpuRsjP5.d.ts} +2 -2
- package/dist/browser/ai.js +2 -3
- package/dist/browser/ai.js.map +1 -1
- package/dist/browser/index.d.ts +29 -21
- package/dist/browser/index.js +937 -4
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/tools/ai-sdk.d.ts +5 -5
- package/dist/browser/tools/ai-sdk.js +9 -3
- package/dist/browser/tools/ai-sdk.js.map +1 -1
- package/dist/browser/tools/pi.d.ts +11 -8
- package/dist/browser/tools/pi.js +58 -11
- package/dist/browser/tools/pi.js.map +1 -1
- package/dist/browser/tools/tanstack-ai.d.ts +6 -6
- package/dist/browser/tools/tanstack-ai.js +3 -3
- package/dist/browser/tools/tanstack-ai.js.map +1 -1
- package/dist/{browser-D9RNpJuT.d.ts → browser-CI97khiJ.d.ts} +222 -94
- package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-Cxtiwfua.d.ts} +2 -2
- package/dist/browser-tool-DOqT1oSD.js +360 -0
- package/dist/browser-tool-DOqT1oSD.js.map +1 -0
- package/dist/catalog-BpOejOsE.js +239 -0
- package/dist/catalog-BpOejOsE.js.map +1 -0
- package/dist/catalog-BpiVV1OF.d.ts +173 -0
- package/dist/chat/index.d.ts +2 -2
- package/dist/chat/react.js +1 -0
- package/dist/chat/react.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +63 -62
- package/dist/{client-wn4-yqGz.d.ts → client-eSfgYvd3.d.ts} +2 -2
- package/dist/client.d.ts +1 -1
- package/dist/{cloudflare-Dzvc7V2N.js → cloudflare-CUUm_9q9.js} +26 -4
- package/dist/cloudflare-CUUm_9q9.js.map +1 -0
- package/dist/{connector-CM-uuxKM.js → connector-Dl098To-.js} +402 -3
- package/dist/connector-Dl098To-.js.map +1 -0
- package/dist/{do-oauth-client-provider-DfsUcpc3.d.ts → do-oauth-client-provider-DtNqv7oj.d.ts} +26 -2
- package/dist/{index-YSKgfgg9.d.ts → emitter-BJZtCVjQ.d.ts} +6 -140
- package/dist/emitter-DPOVcCln.js +15 -0
- package/dist/emitter-DPOVcCln.js.map +1 -0
- package/dist/experimental/channels/web/index.js +1 -1
- package/dist/experimental/webmcp.js +1 -1
- package/dist/harness/container/index.js +0 -1
- package/dist/harness/container/index.js.map +1 -1
- package/dist/harness/container/runtime/index.js +2 -2
- package/dist/harness/opencode/index.js +0 -1
- package/dist/harness/opencode/index.js.map +1 -1
- package/dist/harness/pi/index.d.ts +84 -30
- package/dist/harness/pi/index.js +120 -224
- package/dist/harness/pi/index.js.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.js +2 -2
- package/dist/{input-schema-BQykTEp_.js → input-schema-0uUu392-.js} +2 -2
- package/dist/input-schema-0uUu392-.js.map +1 -0
- package/dist/{input-schema-B0Etuo-o.js → input-schema-waggtYrH.js} +2 -2
- package/dist/input-schema-waggtYrH.js.map +1 -0
- package/dist/markdown-BZ-VLtA1.js +86 -0
- package/dist/markdown-BZ-VLtA1.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +4 -2
- package/dist/mcp/client/do-oauth-client-provider.js +15 -1
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +1 -1
- package/dist/mcp/client/x402.d.ts +8 -8
- package/dist/mcp/index.d.ts +2 -2
- package/dist/mcp/index.js +4 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/models/pi-ai/index.js +12 -15
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/observability/ai/index.js +1 -2
- package/dist/observability/ai/index.js.map +1 -1
- package/dist/observability/index.d.ts +170 -9
- package/dist/observability/index.js +386 -11
- package/dist/observability/index.js.map +1 -1
- package/dist/react.d.ts +2 -2
- package/dist/resource-B59OV2a2.js +325 -0
- package/dist/resource-B59OV2a2.js.map +1 -0
- package/dist/routing/index.d.ts +1 -1
- package/dist/script-CFDLTk5b.d.ts +91 -0
- package/dist/script-workspace-BpdAYq1R.d.ts +41 -0
- package/dist/serializable.d.ts +1 -1
- package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
- package/dist/session-CRY0bGiI.js.map +1 -0
- package/dist/skill-DRBcIBjC.d.ts +221 -0
- package/dist/skills/index.d.ts +275 -36
- package/dist/skills/index.js +265 -1534
- package/dist/skills/index.js.map +1 -1
- package/dist/skills/runner.d.ts +37 -0
- package/dist/skills/runner.js +912 -0
- package/dist/skills/runner.js.map +1 -0
- package/dist/skills/tools/ai-sdk.d.ts +36 -0
- package/dist/skills/tools/ai-sdk.js +94 -0
- package/dist/skills/tools/ai-sdk.js.map +1 -0
- package/dist/source-9RQzlEhM.d.ts +112 -0
- package/dist/{src-BGolXG_H.js → src-DoGNJ4Ud.js} +4 -5
- package/dist/src-DoGNJ4Ud.js.map +1 -0
- package/dist/sub-routing.d.ts +1 -1
- package/dist/tool-CxKsvxjm.js.map +1 -1
- package/dist/tool-DkT_DJBm.js.map +1 -1
- package/dist/{tool-helpers-BodWi4gd.js → tool-helpers-F3_Wy2YX.js} +2 -3
- package/dist/{tool-helpers-BodWi4gd.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js +10 -258
- package/dist/vite.js.map +1 -1
- package/dist/voice/index.d.ts +1 -1
- package/dist/web/fetch/tools/ai-sdk.js +1 -1
- package/dist/web/fetch/tools/pi.d.ts +4 -7
- package/dist/web/fetch/tools/pi.js +7 -6
- package/dist/web/fetch/tools/pi.js.map +1 -1
- package/dist/web/fetch/tools/tanstack-ai.js +1 -1
- package/dist/web/search/tools/ai-sdk.js +1 -1
- package/dist/web/search/tools/pi.d.ts +5 -4
- package/dist/web/search/tools/pi.js +5 -10
- package/dist/web/search/tools/pi.js.map +1 -1
- package/dist/web/search/tools/tanstack-ai.js +1 -1
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-CyoeosdO.js → websockets-C6SJtWCJ.js} +1 -2
- package/dist/{websockets-CyoeosdO.js.map → websockets-C6SJtWCJ.js.map} +1 -1
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/workflows.js +0 -1
- package/dist/workflows.js.map +1 -1
- package/docs/browse-the-web.md +36 -3
- package/docs/harnesses/pi.md +59 -33
- package/docs/mcp-client.md +23 -1
- package/docs/mcp-servers.md +2 -2
- package/docs/models-pi-ai.md +1 -1
- package/docs/observability.md +5 -3
- package/package.json +37 -22
- package/dist/browser-1eUbPvC2.js +0 -931
- package/dist/browser-1eUbPvC2.js.map +0 -1
- package/dist/browser-tool-lGnvEBLJ.js +0 -497
- package/dist/browser-tool-lGnvEBLJ.js.map +0 -1
- package/dist/cloudflare-Dzvc7V2N.js.map +0 -1
- package/dist/connector-CM-uuxKM.js.map +0 -1
- package/dist/index-iv9FTXX9.d.ts +0 -311
- package/dist/input-schema-B0Etuo-o.js.map +0 -1
- package/dist/input-schema-BQykTEp_.js.map +0 -1
- package/dist/session-7CDgVE0z.js.map +0 -1
- package/dist/skills/compile.d.ts +0 -40
- package/dist/skills/compile.js +0 -65
- package/dist/skills/compile.js.map +0 -1
- package/dist/src-BGolXG_H.js.map +0 -1
- package/skills-module.d.ts +0 -22
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as Agent } from "./agent-routing-
|
|
1
|
+
import { c as Agent } from "./agent-routing-vVMA7m8Y.js";
|
|
2
2
|
import {
|
|
3
3
|
ClientParameters,
|
|
4
4
|
Method,
|
|
@@ -445,4 +445,4 @@ export {
|
|
|
445
445
|
splitCallOptions as x,
|
|
446
446
|
isTerminalCloseEvent as y
|
|
447
447
|
};
|
|
448
|
-
//# sourceMappingURL=client-
|
|
448
|
+
//# sourceMappingURL=client-eSfgYvd3.d.ts.map
|
package/dist/client.d.ts
CHANGED
|
@@ -124,7 +124,10 @@ var ManagedSpan = class {
|
|
|
124
124
|
fail(cause) {
|
|
125
125
|
if (_classPrivateFieldGet2(_closed, this)) return;
|
|
126
126
|
if (isCancellation(cause)) setAttributes(this.span, { "cloudflare.agents.canceled": true });
|
|
127
|
-
else
|
|
127
|
+
else {
|
|
128
|
+
setAttributes(this.span, { "error.type": cause instanceof Error ? cause.name || "Error" : typeof cause });
|
|
129
|
+
setErrorStatus(this.span);
|
|
130
|
+
}
|
|
128
131
|
this.close();
|
|
129
132
|
}
|
|
130
133
|
close() {
|
|
@@ -176,6 +179,12 @@ function setAttributes(span, attributes) {
|
|
|
176
179
|
for (const [key, value] of Object.entries(attributes)) if (value !== void 0) span.setAttribute(key, value);
|
|
177
180
|
} catch {}
|
|
178
181
|
}
|
|
182
|
+
function setErrorStatus(span) {
|
|
183
|
+
if (!span.isTraced || typeof span.setStatus !== "function") return;
|
|
184
|
+
try {
|
|
185
|
+
span.setStatus({ code: "error" });
|
|
186
|
+
} catch {}
|
|
187
|
+
}
|
|
179
188
|
function isPromiseLike(value) {
|
|
180
189
|
return value !== null && value !== void 0 && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
|
|
181
190
|
}
|
|
@@ -189,6 +198,13 @@ function isCancellation(cause) {
|
|
|
189
198
|
return typeof cause === "object" && cause !== null && "name" in cause && cause.name === "AbortError";
|
|
190
199
|
}
|
|
191
200
|
//#endregion
|
|
201
|
+
//#region src/observability/tracing/native.ts
|
|
202
|
+
/** Returns `tracing` when it carries the methods the Agents SDK needs. */
|
|
203
|
+
function resolveNativeTracing(tracing) {
|
|
204
|
+
const candidate = tracing;
|
|
205
|
+
return typeof candidate?.startActiveSpan === "function" && typeof candidate.getActiveSpan === "function" ? candidate : void 0;
|
|
206
|
+
}
|
|
207
|
+
//#endregion
|
|
192
208
|
//#region src/observability/tracing/cloudflare.ts
|
|
193
209
|
const noopSpan = {
|
|
194
210
|
isTraced: false,
|
|
@@ -198,14 +214,20 @@ const noopSpan = {
|
|
|
198
214
|
const noopRuntime = { startActiveSpan(_name, run) {
|
|
199
215
|
return run(noopSpan);
|
|
200
216
|
} };
|
|
201
|
-
const
|
|
217
|
+
const workersTracing = cloudflareWorkers.tracing;
|
|
218
|
+
const runtime = resolveCloudflareSpanRuntime(workersTracing);
|
|
202
219
|
/** Selects native Cloudflare tracing or a no-op for unsupported runtimes. */
|
|
203
220
|
function resolveCloudflareSpanRuntime(runtime) {
|
|
204
221
|
const candidate = runtime;
|
|
205
222
|
return typeof candidate?.startActiveSpan === "function" ? candidate : noopRuntime;
|
|
206
223
|
}
|
|
207
224
|
const tracer = createTracer(runtime);
|
|
225
|
+
/**
|
|
226
|
+
* Workers native tracing, when the runtime can carry the OpenTelemetry bridge
|
|
227
|
+
* (`startActiveSpan` and `getActiveSpan`). `undefined` on older runtimes.
|
|
228
|
+
*/
|
|
229
|
+
const nativeTracing = resolveNativeTracing(workersTracing);
|
|
208
230
|
//#endregion
|
|
209
|
-
export {
|
|
231
|
+
export { writeSpanAttributes as i, tracer as n, withInvocationScope as r, nativeTracing as t };
|
|
210
232
|
|
|
211
|
-
//# sourceMappingURL=cloudflare-
|
|
233
|
+
//# sourceMappingURL=cloudflare-CUUm_9q9.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare-CUUm_9q9.js","names":[],"sources":["../src/observability/tracing/tracer.ts","../src/observability/tracing/native.ts","../src/observability/tracing/cloudflare.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/** Attribute values accepted by custom spans. */\nexport type TraceAttributeValue = string | number | boolean | undefined;\n\n/** Initial or finish attributes attached to a span. */\nexport type TraceAttributes = Readonly<Record<string, TraceAttributeValue>>;\n\n/** A value that may complete synchronously or through a promise-like result. */\nexport type MaybePromise<T> = T | PromiseLike<T>;\n\n/** Minimal runtime span surface used by tracers. */\nexport type SpanWriter = {\n readonly isTraced: boolean;\n setAttribute(key: string, value: TraceAttributeValue): void;\n end(): void;\n /**\n * Sets the span status. Workers added `Span.setStatus()` in the 2026-10-26\n * runtime release; older runtimes do not have it.\n */\n setStatus?(status: { readonly code: \"error\" }): unknown;\n};\n\n/** Runtime capability for starting an active span in the current async context. */\nexport type SpanRuntime = {\n startActiveSpan<T>(name: string, run: (span: SpanWriter) => T): T;\n};\n\n/** Optional automatic lifetime policy for invocation-bounded spans. */\nexport type SpanLifetime = {\n /**\n * Close the span no later than the end of the surrounding\n * {@link withInvocationScope}, so it cannot outlive the native invocation\n * that owns its tracing context. Ignored outside such a scope.\n */\n readonly boundToInvocation?: boolean;\n};\n\n/** AgentTracer seam used by integrations. */\nexport type AgentTracer = {\n /**\n * Runs `run` inside an active span whose lifetime the tracer owns: the span\n * finishes when `run` returns (or its promise resolves) and fails when `run`\n * throws or rejects. Callers do not call {@link AgentSpan.finish}/{@link AgentSpan.fail};\n * doing so early is safe but the tracer guarantees closure.\n *\n * @template T The value produced by the instrumented work.\n */\n withSpan<T>(\n name: string,\n attributes: TraceAttributes,\n run: (span: AgentSpan) => MaybePromise<T>,\n lifetime?: SpanLifetime\n ): T | Promise<T>;\n /**\n * Activates a span and returns whatever `activate` returns (typically the\n * {@link AgentSpan} handle itself). The caller owns the span lifetime and MUST call\n * {@link AgentSpan.finish} or {@link AgentSpan.fail}; an unfinished span leaks. Use this\n * for work that outlives the callback, such as streams and event-driven\n * telemetry. A throw from `activate` still fails the span before rethrowing.\n *\n * @template T The value returned to the caller, usually the span handle.\n */\n openSpan<T>(\n name: string,\n attributes: TraceAttributes,\n activate: (span: AgentSpan) => T,\n lifetime?: SpanLifetime\n ): T;\n};\n\n/** Active span handle passed to instrumented work. */\nexport type AgentSpan = {\n /**\n * Whether this invocation is actually being traced. Instrumentation can use\n * this to skip expensive capture work when nobody is listening.\n */\n readonly isTraced: boolean;\n /** Records the optional finish attributes and ends the span. Idempotent. */\n finish(attributes?: TraceAttributes): void;\n /**\n * Ends the span as not-successful. Genuine failures record `error.type`;\n * recognized cancellations (an `AbortError`) record `canceled` instead so aborts\n * are not counted as errors. The cause message is never recorded. Idempotent.\n */\n fail(cause: unknown): void;\n};\n\ntype InvocationScope = {\n /** Bounded spans still open. Emptied when the invocation ends. */\n readonly open: Set<ManagedSpan>;\n /** Whether the invocation this scope represents has already ended. */\n ended: boolean;\n};\n\nexport type InvocationScopeOptions = {\n /**\n * Open a scope even inside a live one, for work deliberately detached from\n * the handler that started it — `ctx.waitUntil` bodies, queue drains — which\n * runs on past that handler and must not be cut off with it.\n */\n readonly detached?: boolean;\n};\n\n/**\n * Spans that asked to be invocation-bounded while a scope was active. Closed\n * when that scope ends; see {@link withInvocationScope}.\n */\nconst invocationScope = new AsyncLocalStorage<InvocationScope>();\n\n/**\n * Runs `body` as one traced invocation.\n *\n * Work that escapes its native invocation cannot be traced from the context it\n * started in: the still-open span is force-closed against the invocation that\n * owned that context, which reports a negative duration or `span_not_ended`.\n * Spans opened with {@link SpanLifetime.boundToInvocation} inside this scope\n * are therefore closed before `body` settles — but not one moment earlier, so\n * everything that completes during the invocation (the normal case: a chat\n * turn is awaited by the handler that received it) still records its finish\n * attributes. A span truncated this way is marked\n * `cloudflare.agents.span.truncated` rather than passing as complete.\n */\nexport function withInvocationScope<T>(\n body: () => T,\n options?: InvocationScopeOptions\n): T {\n // Nested scopes would truncate spans at an inner boundary that is not an\n // invocation edge, so the outermost live scope owns the lifetime. A scope\n // that has already ended is not an enclosing invocation at all — it is a\n // leftover context on work that resumed later — so `body` starts a new one.\n const current = invocationScope.getStore();\n if (options?.detached !== true && current !== undefined && !current.ended) {\n return body();\n }\n\n const scope: InvocationScope = { ended: false, open: new Set() };\n const endInvocation = () => {\n scope.ended = true;\n for (const span of scope.open) {\n // Fail open: this runs on the return path of every agent handler, so a\n // span writer that throws must not take the handler's result with it,\n // nor stop the remaining spans from closing.\n try {\n span.truncate();\n } catch {\n // Nothing useful to do with a broken span writer.\n }\n }\n scope.open.clear();\n };\n\n return invocationScope.run(scope, () => {\n let result: T;\n try {\n result = body();\n } catch (cause: unknown) {\n endInvocation();\n throw cause;\n }\n\n if (isPromiseLike(result)) {\n // SAFETY: T is promise-like here, so the settled promise is still a T.\n return Promise.resolve(result).finally(endInvocation) as T;\n }\n\n endInvocation();\n return result;\n });\n}\n\n/** Creates a tracer from a runtime span capability. */\nexport function createTracer(runtime: SpanRuntime): AgentTracer {\n return new RuntimeTracer(runtime);\n}\n\nclass RuntimeTracer implements AgentTracer {\n constructor(private readonly runtime: SpanRuntime) {}\n\n withSpan<T>(\n name: string,\n attributes: TraceAttributes,\n run: (span: AgentSpan) => MaybePromise<T>,\n lifetime?: SpanLifetime\n ): T | Promise<T> {\n return this.activate(name, attributes, (span) => {\n // Ask before running: a span that opens and closes in one tick still\n // needs to know whether that tick happened after its invocation ended.\n const outOfBand =\n lifetime?.boundToInvocation === true && bindToInvocation(span);\n const result = run(span);\n if (isPromiseLike(result)) {\n if (outOfBand) {\n span.truncate();\n }\n return Promise.resolve(result)\n .catch((cause: unknown) => {\n span.fail(cause);\n throw cause;\n })\n .finally(() => {\n span.close();\n });\n }\n\n if (outOfBand) {\n span.truncate();\n }\n span.close();\n return result;\n });\n }\n\n openSpan<T>(\n name: string,\n attributes: TraceAttributes,\n activate: (span: AgentSpan) => T,\n lifetime?: SpanLifetime\n ): T {\n if (!lifetime?.boundToInvocation) {\n return this.activate(name, attributes, activate);\n }\n\n return this.activate(name, attributes, (span) => {\n const invocationEnded = bindToInvocation(span);\n try {\n return activate(span);\n } finally {\n // Truncate only once `activate` has had its turn: callers that open\n // with an empty attribute set and write the real one lazily (the AI\n // operation span does, to stay cheap for untraced calls) would\n // otherwise be closed before writing anything at all.\n if (invocationEnded) {\n span.truncate();\n }\n }\n });\n }\n\n /**\n * Shared scaffold: opens an active span, seeds its attributes, and fails the\n * span on a thrown defect before rethrowing. The `body` decides the span's\n * finishing policy (managed vs. caller-owned).\n */\n private activate<T>(\n name: string,\n attributes: TraceAttributes,\n body: (span: ManagedSpan) => T\n ): T {\n return this.runtime.startActiveSpan(name, (writer) => {\n setAttributes(writer, attributes);\n const span = new ManagedSpan(writer);\n\n try {\n return body(span);\n } catch (cause: unknown) {\n span.fail(cause);\n throw cause;\n }\n });\n }\n}\n\nclass ManagedSpan implements AgentSpan {\n #closed = false;\n\n constructor(private readonly span: SpanWriter) {}\n\n get isTraced(): boolean {\n return this.span.isTraced;\n }\n\n /** INTERNAL: see {@link writeSpanAttributes}. */\n writeAttributes(attributes: TraceAttributes): void {\n if (this.#closed) {\n return;\n }\n\n setAttributes(this.span, attributes);\n }\n\n finish(attributes: TraceAttributes = {}): void {\n if (this.#closed) {\n return;\n }\n\n setAttributes(this.span, attributes);\n this.close();\n }\n\n fail(cause: unknown): void {\n if (this.#closed) {\n return;\n }\n\n if (isCancellation(cause)) {\n // Cancellation is a control path, not a failure: OTel semconv leaves\n // status Unset and records no error.type for cancellations, so aborted\n // operations do not inflate error rates. The vendor marker is additive.\n setAttributes(this.span, { \"cloudflare.agents.canceled\": true });\n } else {\n // error.type stays the low-cardinality, queryable marker; status is span\n // state, set where the runtime supports it. No description: the cause\n // message is never recorded.\n setAttributes(this.span, {\n \"error.type\":\n cause instanceof Error ? cause.name || \"Error\" : typeof cause\n });\n setErrorStatus(this.span);\n }\n\n this.close();\n }\n\n close(): void {\n if (this.#closed) {\n return;\n }\n\n this.#closed = true;\n this.span.end();\n }\n\n /**\n * Closes a span whose work has not finished because its invocation is ending.\n * The marker distinguishes \"this span has no tokens because the turn escaped\n * its invocation\" from \"this span completed and reported none\".\n */\n truncate(): void {\n if (this.#closed) {\n return;\n }\n\n setAttributes(this.span, { \"cloudflare.agents.span.truncated\": true });\n this.close();\n }\n}\n\n/**\n * Registers a span for closure at the end of the current invocation, and\n * reports whether that invocation has already ended.\n *\n * Outside any scope the span keeps its natural lifetime: with no known\n * invocation boundary there is nothing to bound it to, and closing early would\n * discard finish attributes for no gain. Inside a scope that has already\n * ended — work resumed later while still carrying this context — the span\n * cannot outlive an invocation that is already gone, so the caller truncates\n * it as soon as it has written what it knows.\n */\nfunction bindToInvocation(span: ManagedSpan): boolean {\n const scope = invocationScope.getStore();\n if (scope === undefined) {\n return false;\n }\n\n if (scope.ended) {\n return true;\n }\n\n scope.open.add(span);\n return false;\n}\n\n/**\n * INTERNAL: writes attributes onto an open managed span. Lets instrumentation\n * defer expensive attribute computation until after the isTraced check (span\n * names must exist at open time; attributes need not). Not part of the public\n * barrel surface.\n */\nexport function writeSpanAttributes(\n span: AgentSpan,\n attributes: TraceAttributes\n): void {\n if (span instanceof ManagedSpan) {\n span.writeAttributes(attributes);\n }\n}\n\nfunction setAttributes(span: SpanWriter, attributes: TraceAttributes): void {\n if (!span.isTraced) {\n return;\n }\n\n // Fail-safe: a throwing writer must not leak the span or replace the\n // application's original error with a telemetry one.\n try {\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n span.setAttribute(key, value);\n }\n }\n } catch {\n // Drop the attributes; the span still closes.\n }\n}\n\nfunction setErrorStatus(span: SpanWriter): void {\n if (!span.isTraced || typeof span.setStatus !== \"function\") {\n return;\n }\n\n // Fail-safe, like setAttributes: telemetry must not replace the\n // application's original error.\n try {\n span.setStatus({ code: \"error\" });\n } catch {\n // The span still closes.\n }\n}\n\nfunction isPromiseLike<T>(value: MaybePromise<T>): value is PromiseLike<T> {\n return (\n value !== null &&\n value !== undefined &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\n/**\n * Recognizes caller/runtime cancellation (an `AbortError`, e.g. from an aborted\n * `AbortSignal`) so it can be classified separately from genuine failures. A\n * `DOMException` named `AbortError` is not always an `Error` instance, so this\n * probes the `name` field structurally rather than via `instanceof`.\n */\nfunction isCancellation(cause: unknown): boolean {\n return (\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n cause.name === \"AbortError\"\n );\n}\n","/**\n * The subset of Workers native tracing (`import { tracing } from\n * \"cloudflare:workers\"`) that the Agents SDK builds on. Methods added in later\n * runtime releases are optional and feature-detected per call, so an older\n * runtime degrades (no IDs, no status, no rename) instead of throwing.\n */\n\n/** A scalar attribute value accepted by native spans. */\nexport type NativeAttributeValue = string | number | boolean;\n\n/** Native span identity, matching the IDs Workers Observability exports. */\nexport type NativeSpanContext = {\n readonly traceId: string;\n readonly spanId: string;\n readonly traceFlags: number;\n};\n\n/** Native span status. */\nexport type NativeSpanStatus = {\n readonly code: \"unset\" | \"ok\" | \"error\";\n readonly message?: string;\n};\n\n/** An exception accepted by `Span.recordException`. */\nexport type NativeException =\n | string\n | {\n readonly code?: string | number;\n readonly name?: string;\n readonly message?: string;\n readonly stack?: string;\n };\n\n/** A native span. */\nexport type NativeSpan = {\n /**\n * False when observability is disabled, and after `end()`. Does not reflect\n * head sampling: an unsampled request can report `true`.\n */\n readonly isTraced: boolean;\n setAttribute(key: string, value: NativeAttributeValue): unknown;\n recordException(exception: NativeException): void;\n /** Idempotent; no effect on the invocation root span. */\n end(): void;\n /** Added in the 2026-10-26 runtime release. */\n spanContext?(): NativeSpanContext;\n /**\n * Added in the 2026-10-26 runtime release. Applies OTel's rules: `ok` is\n * final, `unset` has no effect, the message is kept only with `error`, and\n * calls after `end()` are ignored.\n */\n setStatus?(status: NativeSpanStatus): unknown;\n /** Added in the 2026-10-26 runtime release. */\n updateName?(name: string): unknown;\n};\n\n/** Native tracing: async-context span activation. */\nexport type NativeTracing = {\n /**\n * Opens a span that is the active parent while `callback` runs. The caller\n * ends it; it stays open after `callback` returns but is no longer active.\n */\n startActiveSpan<T>(name: string, callback: (span: NativeSpan) => T): T;\n /**\n * The active span: the innermost custom span, or the invocation root span.\n * `undefined` outside a request.\n */\n getActiveSpan(): NativeSpan | undefined;\n};\n\n/** Returns `tracing` when it carries the methods the Agents SDK needs. */\nexport function resolveNativeTracing(\n tracing: unknown\n): NativeTracing | undefined {\n const candidate = tracing as Partial<NativeTracing> | null | undefined;\n return typeof candidate?.startActiveSpan === \"function\" &&\n typeof candidate.getActiveSpan === \"function\"\n ? (candidate as NativeTracing)\n : undefined;\n}\n","import * as cloudflareWorkers from \"cloudflare:workers\";\nimport { createTracer } from \"./tracer\";\nimport type { SpanRuntime, SpanWriter, AgentTracer } from \"./tracer\";\nimport { resolveNativeTracing } from \"./native\";\nimport type { NativeTracing } from \"./native\";\n\nconst noopSpan: SpanWriter = {\n isTraced: false,\n setAttribute() {},\n end() {}\n};\n\nconst noopRuntime: SpanRuntime = {\n startActiveSpan(_name, run) {\n return run(noopSpan);\n }\n};\n\n// Accessed via the namespace because this loads with the main `agents` entry.\n// Runtimes can omit `tracing` or expose it without `startActiveSpan`; both\n// degrade to no-op tracing instead of breaking Agent behavior.\nconst workersTracing = (cloudflareWorkers as { tracing?: unknown }).tracing;\nconst runtime = resolveCloudflareSpanRuntime(workersTracing);\n\n/** Selects native Cloudflare tracing or a no-op for unsupported runtimes. */\nexport function resolveCloudflareSpanRuntime(runtime: unknown): SpanRuntime {\n const candidate = runtime as Partial<SpanRuntime> | null | undefined;\n return typeof candidate?.startActiveSpan === \"function\"\n ? (candidate as SpanRuntime)\n : noopRuntime;\n}\n\nexport const tracer: AgentTracer = createTracer(runtime);\n\n/**\n * Workers native tracing, when the runtime can carry the OpenTelemetry bridge\n * (`startActiveSpan` and `getActiveSpan`). `undefined` on older runtimes.\n */\nexport const nativeTracing: NativeTracing | undefined =\n resolveNativeTracing(workersTracing);\n"],"mappings":";;;;;;;;AA4GA,MAAM,kBAAkB,IAAI,kBAAmC;;;;;;;;;;;;;;AAe/D,SAAgB,oBACd,MACA,SACG;CAKH,MAAM,UAA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AAI,QAAQ;AACrB,EACF;AAKA,MAAM,iBAAkB,kBAA4C;AACpE,MAAM,UAAU,6BAA6B,cAAc;;AAG3D,SAAgB,6BAA6B,SAA+B;CAC1E,MAAM,YAAY;CAClB,OAAO,OAAO,WAAW,oBAAoB,aACxC,YACD;AACN;AAEA,MAAa,SAAsB,aAAa,OAAO;;;;;AAMvD,MAAa,gBACX,qBAAqB,cAAc"}
|
|
@@ -1,8 +1,191 @@
|
|
|
1
1
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
|
|
2
2
|
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
|
|
3
|
-
import {
|
|
3
|
+
import { c as CdpConnection, d as connectUrl, l as CdpProtocolError } from "./session-CRY0bGiI.js";
|
|
4
4
|
import { CodemodeConnector } from "@cloudflare/codemode";
|
|
5
5
|
import { Validator } from "@cfworker/json-schema";
|
|
6
|
+
//#region src/browser/browser-run.ts
|
|
7
|
+
var BrowserRenderingError = class extends Error {
|
|
8
|
+
constructor(message, status) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.name = "BrowserRenderingError";
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Whether an error means the platform session is gone: Browser Run uses 404
|
|
16
|
+
* for unknown ids and 410 after `keep_alive` expiry.
|
|
17
|
+
*/
|
|
18
|
+
function isMissingBrowserSession$1(error) {
|
|
19
|
+
return error instanceof BrowserRenderingError && (error.status === 404 || error.status === 410);
|
|
20
|
+
}
|
|
21
|
+
function browserSessionEndpoint(sessionId, options) {
|
|
22
|
+
const path = sessionId ? `/v1/devtools/browser/${sessionId}` : "/v1/devtools/browser";
|
|
23
|
+
const url = new URL(`https://localhost${path}`);
|
|
24
|
+
if (options?.keepAliveMs !== void 0) url.searchParams.set("keep_alive", String(options.keepAliveMs));
|
|
25
|
+
if (options?.includeTargets) url.searchParams.set("targets", "true");
|
|
26
|
+
if (options?.recording) url.searchParams.set("recording", "true");
|
|
27
|
+
if (options?.browser) url.searchParams.set("browser", options.browser);
|
|
28
|
+
return url.toString();
|
|
29
|
+
}
|
|
30
|
+
async function parseBrowserSessionInfo(response) {
|
|
31
|
+
const payload = await response.json();
|
|
32
|
+
const sessionId = typeof payload.sessionId === "string" ? payload.sessionId : "";
|
|
33
|
+
if (!sessionId) throw new Error("Browser Rendering response did not include a sessionId");
|
|
34
|
+
return {
|
|
35
|
+
sessionId,
|
|
36
|
+
targets: Array.isArray(payload.targets) ? payload.targets : void 0,
|
|
37
|
+
webSocketDebuggerUrl: typeof payload.webSocketDebuggerUrl === "string" ? payload.webSocketDebuggerUrl : void 0
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
async function createBrowserSession(browser, options) {
|
|
41
|
+
const response = await browser.fetch(browserSessionEndpoint(void 0, options), {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { "Content-Type": "application/json" },
|
|
44
|
+
body: JSON.stringify(options?.guardrails ? { guardrails: options.guardrails } : {})
|
|
45
|
+
});
|
|
46
|
+
if (!response.ok) throw new BrowserRenderingError(`Failed to create Browser Rendering session: ${response.status}`, response.status);
|
|
47
|
+
return parseBrowserSessionInfo(response);
|
|
48
|
+
}
|
|
49
|
+
async function listBrowserTargets(browser, sessionId) {
|
|
50
|
+
const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}/json/list`);
|
|
51
|
+
if (!response.ok) throw new BrowserRenderingError(`Failed to list Browser Rendering targets for ${sessionId}: ${response.status}`, response.status);
|
|
52
|
+
const payload = await response.json();
|
|
53
|
+
return Array.isArray(payload) ? payload : [];
|
|
54
|
+
}
|
|
55
|
+
async function deleteBrowserSession(browser, sessionId) {
|
|
56
|
+
const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}`, { method: "DELETE" });
|
|
57
|
+
if (!response.ok && response.status !== 404) throw new BrowserRenderingError(`Failed to delete Browser Rendering session ${sessionId}: ${response.status}`, response.status);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Whether a typed binding call failed because the binding doesn't have that
|
|
61
|
+
* method. Fully local dev (Miniflare) has only `fetch`: every other method
|
|
62
|
+
* still looks like a function, then throws this when called.
|
|
63
|
+
*/
|
|
64
|
+
function isUnimplementedBindingMethod(error, method) {
|
|
65
|
+
return error instanceof TypeError && error.message === `The RPC receiver does not implement the method "${method}".`;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Create a session with the binding's typed `acquire()`. Falls back to the
|
|
69
|
+
* HTTP API ({@link createBrowserSession}) when the binding doesn't have
|
|
70
|
+
* `acquire()`, as in fully local dev.
|
|
71
|
+
*/
|
|
72
|
+
async function acquireBrowserSession(browser, options = {}) {
|
|
73
|
+
const { outboundByHost, ...httpOptions } = options;
|
|
74
|
+
if (browser.acquire) try {
|
|
75
|
+
const { sessionId } = await browser.acquire({
|
|
76
|
+
keepAlive: options.keepAliveMs,
|
|
77
|
+
recording: options.recording,
|
|
78
|
+
guardrails: options.guardrails,
|
|
79
|
+
...outboundByHost ? { outboundByHost } : {}
|
|
80
|
+
});
|
|
81
|
+
return { sessionId };
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (!isUnimplementedBindingMethod(error, "acquire")) throw error;
|
|
84
|
+
}
|
|
85
|
+
if (outboundByHost) warnInternalHostsUnavailable(Object.keys(outboundByHost));
|
|
86
|
+
const { sessionId } = await createBrowserSession(browser, httpOptions);
|
|
87
|
+
return { sessionId };
|
|
88
|
+
}
|
|
89
|
+
let warnedInternalHostsUnavailable = false;
|
|
90
|
+
/** Say once per isolate that internal hostnames need a deployed Worker. */
|
|
91
|
+
function warnInternalHostsUnavailable(hosts) {
|
|
92
|
+
if (warnedInternalHostsUnavailable) return;
|
|
93
|
+
warnedInternalHostsUnavailable = true;
|
|
94
|
+
console.warn(`[agents/browser] Internal hostnames (${hosts.join(", ")}) only work once deployed: this Browser Run binding has no acquire(), as in local dev, so the browser starts without them.`);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The HTTP status in a typed binding method's error. Browser Run's binding
|
|
98
|
+
* errors carry it only in the message, e.g. `Not Found (status=404)`.
|
|
99
|
+
*/
|
|
100
|
+
function bindingErrorStatus(error) {
|
|
101
|
+
if (!(error instanceof Error)) return void 0;
|
|
102
|
+
const match = /\(status=(\d{3})[,)]/.exec(error.message);
|
|
103
|
+
return match ? Number(match[1]) : void 0;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Close a session with the binding's typed `closeSession()`. A session
|
|
107
|
+
* Browser Run no longer knows (404 or 410) counts as closed. Falls back to
|
|
108
|
+
* the HTTP API ({@link deleteBrowserSession}) when the binding doesn't have
|
|
109
|
+
* `closeSession()`, as in fully local dev.
|
|
110
|
+
*/
|
|
111
|
+
async function closeBrowserSession(browser, sessionId) {
|
|
112
|
+
if (browser.closeSession) try {
|
|
113
|
+
await browser.closeSession(sessionId);
|
|
114
|
+
return;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const status = bindingErrorStatus(error);
|
|
117
|
+
if (status === 404 || status === 410) return;
|
|
118
|
+
if (!isUnimplementedBindingMethod(error, "closeSession")) throw error;
|
|
119
|
+
}
|
|
120
|
+
await deleteBrowserSession(browser, sessionId);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Connect to a Browser Rendering session and delete it when closed.
|
|
124
|
+
*/
|
|
125
|
+
async function connectBrowser(browser, options) {
|
|
126
|
+
const normalizedOptions = typeof options === "number" ? { timeoutMs: options } : options ?? {};
|
|
127
|
+
if (normalizedOptions.browser === "kitesurf") {
|
|
128
|
+
const smuggled = normalizedOptions;
|
|
129
|
+
if (smuggled.keepAliveMs || smuggled.includeTargets || smuggled.recording) throw new Error("Kitesurf does not support keepAliveMs, includeTargets, or recording");
|
|
130
|
+
}
|
|
131
|
+
const response = await browser.fetch(browserSessionEndpoint(void 0, normalizedOptions.browser === "kitesurf" ? { browser: "kitesurf" } : {
|
|
132
|
+
keepAliveMs: normalizedOptions.keepAliveMs,
|
|
133
|
+
includeTargets: normalizedOptions.includeTargets,
|
|
134
|
+
recording: normalizedOptions.recording
|
|
135
|
+
}), { headers: { Upgrade: "websocket" } });
|
|
136
|
+
const ws = response.webSocket;
|
|
137
|
+
if (!ws) throw new Error("Browser Rendering binding did not return a WebSocket. Ensure the 'browser' binding is configured in wrangler.jsonc.");
|
|
138
|
+
if (normalizedOptions.browser === "kitesurf") {
|
|
139
|
+
ws.accept();
|
|
140
|
+
return new CdpConnection(ws, { timeoutMs: normalizedOptions.timeoutMs });
|
|
141
|
+
}
|
|
142
|
+
const sessionId = response.headers.get("cf-browser-session-id");
|
|
143
|
+
if (!sessionId) throw new Error("Browser Rendering binding did not include a session ID when opening the CDP WebSocket");
|
|
144
|
+
ws.accept();
|
|
145
|
+
return new CdpConnection(ws, {
|
|
146
|
+
timeoutMs: normalizedOptions.timeoutMs,
|
|
147
|
+
onClose: () => {
|
|
148
|
+
deleteBrowserSession(browser, sessionId).catch((error) => {
|
|
149
|
+
console.warn(`[agents/browser] Failed to delete one-shot Browser Run session ${sessionId}`, error);
|
|
150
|
+
});
|
|
151
|
+
},
|
|
152
|
+
sessionId
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Fetch a Browser Run [session recording](https://developers.cloudflare.com/browser-run/features/session-recording/)
|
|
157
|
+
* by session id, via the Browser Rendering REST API.
|
|
158
|
+
*
|
|
159
|
+
* A recording is only available **after** the session closes (explicit
|
|
160
|
+
* `closeSession()`, idle `keep_alive` expiry, or sweep) and is retained for 30
|
|
161
|
+
* days. Capture the session id while the session is alive — e.g. from
|
|
162
|
+
* `connector.liveView()`/`sessionInfo()` — then call this once it has ended.
|
|
163
|
+
*
|
|
164
|
+
* Unlike the binding-based helpers, this hits `api.cloudflare.com` directly, so
|
|
165
|
+
* it needs an account id and an API token with `Browser Rendering` read access
|
|
166
|
+
* (the Workers Browser Run binding cannot read recordings).
|
|
167
|
+
*/
|
|
168
|
+
async function getBrowserRecording(options) {
|
|
169
|
+
const { accountId, apiToken, sessionId } = options;
|
|
170
|
+
const response = await (options.fetchImpl ?? fetch)(`https://api.cloudflare.com/client/v4/accounts/${accountId}/browser-rendering/recording/${sessionId}`, { headers: { Authorization: `Bearer ${apiToken}` } });
|
|
171
|
+
if (!response.ok) throw new BrowserRenderingError(`Failed to fetch Browser Run recording for ${sessionId}: ${response.status}`, response.status);
|
|
172
|
+
const payload = await response.json();
|
|
173
|
+
return "result" in payload && payload.result ? payload.result : payload;
|
|
174
|
+
}
|
|
175
|
+
async function connectBrowserSession(browser, sessionId, options) {
|
|
176
|
+
const normalized = typeof options === "number" ? { timeoutMs: options } : options ?? {};
|
|
177
|
+
const response = await browser.fetch(browserSessionEndpoint(sessionId), { headers: { Upgrade: "websocket" } });
|
|
178
|
+
const ws = response.webSocket;
|
|
179
|
+
if (!ws) throw new BrowserRenderingError(`Browser Rendering binding did not return a WebSocket for session ${sessionId} (${response.status})`, response.status);
|
|
180
|
+
ws.accept();
|
|
181
|
+
return new CdpConnection(ws, {
|
|
182
|
+
timeoutMs: normalized.timeoutMs,
|
|
183
|
+
onClose: normalized.onClose,
|
|
184
|
+
sessionId,
|
|
185
|
+
onActivity: normalized.onActivity
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
//#endregion
|
|
6
189
|
//#region src/browser/quick-actions.ts
|
|
7
190
|
function runQuickAction(browser, action, params) {
|
|
8
191
|
return browser.quickAction(action, params);
|
|
@@ -165,6 +348,222 @@ function validateConnectorArgs(connector, name, tool) {
|
|
|
165
348
|
};
|
|
166
349
|
}
|
|
167
350
|
//#endregion
|
|
351
|
+
//#region src/browser/live-view.ts
|
|
352
|
+
/**
|
|
353
|
+
* Browser Run mints `devtoolsFrontendUrl`s (the Live View links) that are
|
|
354
|
+
* valid for ~5 minutes. We surface the window so callers can decide how long
|
|
355
|
+
* a shared link is good for before re-listing targets.
|
|
356
|
+
*/
|
|
357
|
+
const LIVE_VIEW_URL_TTL_MS = 300 * 1e3;
|
|
358
|
+
/**
|
|
359
|
+
* Rewrite the hosted Live View UI's `mode` query param (`tab` | `devtools`).
|
|
360
|
+
* The raw `devtoolsFrontendUrl` is returned unchanged when no mode is asked
|
|
361
|
+
* for or the URL can't be parsed.
|
|
362
|
+
*/
|
|
363
|
+
function applyLiveViewMode(rawUrl, mode) {
|
|
364
|
+
if (!mode) return rawUrl;
|
|
365
|
+
try {
|
|
366
|
+
const url = new URL(rawUrl);
|
|
367
|
+
url.searchParams.set("mode", mode === "devtools" ? "devtools" : "tab");
|
|
368
|
+
return url.toString();
|
|
369
|
+
} catch {
|
|
370
|
+
return rawUrl;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Project a fresh target listing into Live View links — one per tab that has
|
|
375
|
+
* a `devtoolsFrontendUrl`. Pure; the caller supplies just-listed targets.
|
|
376
|
+
*/
|
|
377
|
+
function createLiveView(sessionId, targets, mode) {
|
|
378
|
+
return {
|
|
379
|
+
sessionId,
|
|
380
|
+
targets: targets.filter((target) => target.devtoolsFrontendUrl).map((target) => ({
|
|
381
|
+
targetId: target.id,
|
|
382
|
+
url: applyLiveViewMode(target.devtoolsFrontendUrl, mode),
|
|
383
|
+
pageUrl: target.url,
|
|
384
|
+
title: target.title,
|
|
385
|
+
type: target.type
|
|
386
|
+
})),
|
|
387
|
+
expiresInMs: LIVE_VIEW_URL_TTL_MS
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
//#endregion
|
|
391
|
+
//#region src/browser/spec.ts
|
|
392
|
+
const MISSING_BROWSER_CONFIG = "Either 'browser' (Fetcher binding) or 'cdpUrl' must be provided";
|
|
393
|
+
const urlSpecCache = /* @__PURE__ */ new Map();
|
|
394
|
+
const bindingSpecCache = /* @__PURE__ */ new WeakMap();
|
|
395
|
+
const CACHE_TTL_MS = 300 * 1e3;
|
|
396
|
+
/** Qualify a same-domain `$ref` (`"FrameId"` → `"Page.FrameId"`). */
|
|
397
|
+
function qualifyRef(domain, ref) {
|
|
398
|
+
if (ref === void 0) return void 0;
|
|
399
|
+
return ref.includes(".") ? ref : `${domain}.${ref}`;
|
|
400
|
+
}
|
|
401
|
+
function normalizeItems(domain, items) {
|
|
402
|
+
if (!items) return void 0;
|
|
403
|
+
return {
|
|
404
|
+
type: items.type,
|
|
405
|
+
$ref: qualifyRef(domain, items.$ref),
|
|
406
|
+
enum: items.enum
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
function normalizeFields(domain, fields) {
|
|
410
|
+
return (fields ?? []).map((field) => ({
|
|
411
|
+
name: field.name,
|
|
412
|
+
description: field.description,
|
|
413
|
+
optional: field.optional,
|
|
414
|
+
experimental: field.experimental,
|
|
415
|
+
deprecated: field.deprecated,
|
|
416
|
+
type: field.type,
|
|
417
|
+
$ref: qualifyRef(domain, field.$ref),
|
|
418
|
+
enum: field.enum,
|
|
419
|
+
items: normalizeItems(domain, field.items)
|
|
420
|
+
}));
|
|
421
|
+
}
|
|
422
|
+
function normalizeCdpSpec(spec) {
|
|
423
|
+
return { domains: (spec.domains ?? []).map(({ domain, ...raw }) => ({
|
|
424
|
+
name: domain,
|
|
425
|
+
description: raw.description,
|
|
426
|
+
experimental: raw.experimental,
|
|
427
|
+
deprecated: raw.deprecated,
|
|
428
|
+
commands: (raw.commands ?? []).map((command) => ({
|
|
429
|
+
name: command.name,
|
|
430
|
+
method: `${domain}.${command.name}`,
|
|
431
|
+
description: command.description,
|
|
432
|
+
experimental: command.experimental,
|
|
433
|
+
deprecated: command.deprecated,
|
|
434
|
+
parameters: normalizeFields(domain, command.parameters),
|
|
435
|
+
returns: normalizeFields(domain, command.returns)
|
|
436
|
+
})),
|
|
437
|
+
events: (raw.events ?? []).map((event) => ({
|
|
438
|
+
name: event.name,
|
|
439
|
+
event: `${domain}.${event.name}`,
|
|
440
|
+
description: event.description,
|
|
441
|
+
experimental: event.experimental,
|
|
442
|
+
deprecated: event.deprecated,
|
|
443
|
+
parameters: normalizeFields(domain, event.parameters)
|
|
444
|
+
})),
|
|
445
|
+
types: (raw.types ?? []).map((type) => ({
|
|
446
|
+
id: type.id,
|
|
447
|
+
name: `${domain}.${type.id}`,
|
|
448
|
+
description: type.description,
|
|
449
|
+
experimental: type.experimental,
|
|
450
|
+
deprecated: type.deprecated,
|
|
451
|
+
type: type.type,
|
|
452
|
+
enum: type.enum,
|
|
453
|
+
properties: normalizeFields(domain, type.properties),
|
|
454
|
+
items: normalizeItems(domain, type.items)
|
|
455
|
+
}))
|
|
456
|
+
})) };
|
|
457
|
+
}
|
|
458
|
+
function getSpecCacheKey(source, headers) {
|
|
459
|
+
const headerEntries = Object.entries(headers ?? {}).sort(([a], [b]) => a.localeCompare(b));
|
|
460
|
+
return `${source}:${JSON.stringify(headerEntries)}`;
|
|
461
|
+
}
|
|
462
|
+
async function getCachedSpec(cache, key, load) {
|
|
463
|
+
const cached = cache.get(key);
|
|
464
|
+
if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) return cached.spec;
|
|
465
|
+
const spec = normalizeCdpSpec(await load());
|
|
466
|
+
cache.set(key, {
|
|
467
|
+
spec,
|
|
468
|
+
cachedAt: Date.now()
|
|
469
|
+
});
|
|
470
|
+
return spec;
|
|
471
|
+
}
|
|
472
|
+
async function fetchCdpSpecFromUrl(cdpBaseUrl, headers) {
|
|
473
|
+
const endpoint = new URL("/json/protocol", cdpBaseUrl).toString();
|
|
474
|
+
return getCachedSpec(urlSpecCache, getSpecCacheKey(endpoint, headers), async () => {
|
|
475
|
+
const response = await fetch(endpoint, { headers });
|
|
476
|
+
if (!response.ok) throw new Error(`Failed to fetch CDP spec from ${endpoint}: ${response.status}`);
|
|
477
|
+
return await response.json();
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
async function fetchCdpSpecFromSession(browser, sessionId) {
|
|
481
|
+
return getCachedSpec(bindingSpecCache, browser, async () => {
|
|
482
|
+
const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}/json/protocol`);
|
|
483
|
+
if (!response.ok) throw new Error(`Failed to fetch CDP spec from Browser Rendering: ${response.status}`);
|
|
484
|
+
return await response.json();
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
async function fetchCdpSpecFromBrowser(browser) {
|
|
488
|
+
return getCachedSpec(bindingSpecCache, browser, async () => {
|
|
489
|
+
const createResponse = await browser.fetch("https://localhost/v1/devtools/browser", { method: "POST" });
|
|
490
|
+
if (!createResponse.ok) throw new Error(`Failed to create Browser Rendering session for protocol fetch: ${createResponse.status}`);
|
|
491
|
+
const sessionId = (await createResponse.json()).sessionId;
|
|
492
|
+
if (!sessionId) throw new Error("Browser Rendering session response did not include a sessionId");
|
|
493
|
+
try {
|
|
494
|
+
const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}/json/protocol`);
|
|
495
|
+
if (!response.ok) throw new Error(`Failed to fetch CDP spec from Browser Rendering: ${response.status}`);
|
|
496
|
+
return await response.json();
|
|
497
|
+
} finally {
|
|
498
|
+
try {
|
|
499
|
+
await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}`, { method: "DELETE" });
|
|
500
|
+
} catch {}
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
/** Load the (cached) searchable CDP spec for a browser source. */
|
|
505
|
+
async function loadCdpSpec(source) {
|
|
506
|
+
if (source.cdpUrl) return fetchCdpSpecFromUrl(source.cdpUrl, source.cdpHeaders);
|
|
507
|
+
if (source.browser && source.sessionId) return fetchCdpSpecFromSession(source.browser, source.sessionId);
|
|
508
|
+
if (source.browser) return fetchCdpSpecFromBrowser(source.browser);
|
|
509
|
+
throw new Error(MISSING_BROWSER_CONFIG);
|
|
510
|
+
}
|
|
511
|
+
//#endregion
|
|
512
|
+
//#region src/browser/session-store.ts
|
|
513
|
+
var _DurableBrowserSessionStore_brand = /* @__PURE__ */ new WeakSet();
|
|
514
|
+
var DurableBrowserSessionStore = class {
|
|
515
|
+
constructor(storage) {
|
|
516
|
+
this.storage = storage;
|
|
517
|
+
_classPrivateMethodInitSpec(this, _DurableBrowserSessionStore_brand);
|
|
518
|
+
}
|
|
519
|
+
async acquireLock(key) {
|
|
520
|
+
let queues = _queues._.get(this.storage);
|
|
521
|
+
if (!queues) {
|
|
522
|
+
queues = /* @__PURE__ */ new Map();
|
|
523
|
+
_queues._.set(this.storage, queues);
|
|
524
|
+
}
|
|
525
|
+
const previous = queues.get(key) ?? Promise.resolve();
|
|
526
|
+
let releaseQueue = () => void 0;
|
|
527
|
+
const current = previous.then(() => new Promise((resolve) => {
|
|
528
|
+
releaseQueue = resolve;
|
|
529
|
+
}));
|
|
530
|
+
queues.set(key, current);
|
|
531
|
+
await previous;
|
|
532
|
+
let released = false;
|
|
533
|
+
return { release: () => {
|
|
534
|
+
if (released) return;
|
|
535
|
+
released = true;
|
|
536
|
+
if (queues.get(key) === current) queues.delete(key);
|
|
537
|
+
releaseQueue();
|
|
538
|
+
} };
|
|
539
|
+
}
|
|
540
|
+
async get(key) {
|
|
541
|
+
return this.storage.get(_assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, key));
|
|
542
|
+
}
|
|
543
|
+
async set(key, session) {
|
|
544
|
+
await this.storage.put(_assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, key), session);
|
|
545
|
+
}
|
|
546
|
+
async delete(key) {
|
|
547
|
+
await this.storage.delete(_assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, key));
|
|
548
|
+
}
|
|
549
|
+
async list(prefix) {
|
|
550
|
+
const storagePrefix = _assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, prefix);
|
|
551
|
+
const entries = await this.storage.list({ prefix: storagePrefix });
|
|
552
|
+
const result = /* @__PURE__ */ new Map();
|
|
553
|
+
for (const [storageKey, value] of entries) result.set(storageKey.slice(16), value);
|
|
554
|
+
return result;
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
function _storageKey(key) {
|
|
558
|
+
return `browser-session:${key}`;
|
|
559
|
+
}
|
|
560
|
+
var _queues = { _: /* @__PURE__ */ new WeakMap() };
|
|
561
|
+
/**
|
|
562
|
+
* Default idle window used by {@link BrowserConnector.sweep} for the shared
|
|
563
|
+
* (reuse/promoted) session entry.
|
|
564
|
+
*/
|
|
565
|
+
const DEFAULT_SWEEP_IDLE_MS = 600 * 1e3;
|
|
566
|
+
//#endregion
|
|
168
567
|
//#region src/browser/connector.ts
|
|
169
568
|
const EXEC_KEY_PREFIX = "cdp:exec:";
|
|
170
569
|
/**
|
|
@@ -1023,6 +1422,6 @@ async function _closeStoredSession(key) {
|
|
|
1023
1422
|
if (stored) await deleteBrowserSession(browser, stored.sessionId);
|
|
1024
1423
|
}
|
|
1025
1424
|
//#endregion
|
|
1026
|
-
export {
|
|
1425
|
+
export { getBrowserRecording as C, deleteBrowserSession as S, listBrowserTargets as T, acquireBrowserSession as _, loadCdpSpec as a, connectBrowserSession as b, browserExtract as c, browserPdf as d, browserScrape as f, BrowserRenderingError as g, runQuickAction as h, DurableBrowserSessionStore as i, browserLinks as l, browserSnapshot as m, DEFAULT_EXEC_SWEEP_IDLE_MS as n, createLiveView as o, browserScreenshot as p, DEFAULT_SWEEP_IDLE_MS as r, browserContent as s, BrowserConnector as t, browserMarkdown as u, closeBrowserSession as v, isMissingBrowserSession$1 as w, createBrowserSession as x, connectBrowser as y };
|
|
1027
1426
|
|
|
1028
|
-
//# sourceMappingURL=connector-
|
|
1427
|
+
//# sourceMappingURL=connector-Dl098To-.js.map
|