@herbertgao/pi-extensions 2026.11.17 → 2026.11.19
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 +25 -0
- package/README.md +3 -3
- package/THIRD_PARTY_NOTICES.md +2 -23
- package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
- package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
- package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/index.ts +7 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/agent-badge.ts +244 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +10 -3
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +18 -0
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
- package/node_modules/@herbertgao/pi-inline-skill-commands/README.md +18 -0
- package/node_modules/@herbertgao/pi-inline-skill-commands/package.json +1 -1
- package/node_modules/@herbertgao/pi-inline-skill-commands/src/index.ts +80 -0
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +320 -102
- package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -30
- package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
- package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
- package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
- package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +27 -13
- package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
- package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
- package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +217 -41
- package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
- package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -93
- package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
- package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
- package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
- package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
- package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
- package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
- package/node_modules/pi-commandcode-provider/README.md +3 -2
- package/node_modules/pi-commandcode-provider/index.ts +120 -13
- package/node_modules/pi-commandcode-provider/package.json +4 -3
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
- package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
- package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
- package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
- package/package.json +12 -15
- package/node_modules/pi-antigravity/README.md +0 -298
- package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
- package/node_modules/pi-antigravity/package.json +0 -87
- package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
- package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
- package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
- package/node_modules/pi-antigravity/src/client/client.ts +0 -602
- package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
- package/node_modules/pi-antigravity/src/client/index.ts +0 -2
- package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
- package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
- package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
- package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
- package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
- package/node_modules/pi-antigravity/src/image/image.ts +0 -427
- package/node_modules/pi-antigravity/src/image/index.ts +0 -1
- package/node_modules/pi-antigravity/src/image/native.ts +0 -69
- package/node_modules/pi-antigravity/src/index.ts +0 -547
- package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
- package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
- package/node_modules/pi-antigravity/src/models/index.ts +0 -3
- package/node_modules/pi-antigravity/src/models/models.ts +0 -647
- package/node_modules/pi-antigravity/src/search/index.ts +0 -1
- package/node_modules/pi-antigravity/src/search/search.ts +0 -967
- package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
- package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
- package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
- package/node_modules/pi-antigravity/src/types/index.ts +0 -2
- package/node_modules/pi-antigravity/src/types/types.ts +0 -329
- package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
- package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
- package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
- package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
- package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
- package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
- package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
- package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
- package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
- package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
- package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
- package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
- package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
- package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
- package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
- package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
- package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
- package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
- package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
- package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
- package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
- package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
- package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
- package/node_modules/pi-antigravity/tsconfig.json +0 -21
|
@@ -1,957 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Read a public page through Google's Antigravity fetch service.
|
|
3
|
-
*
|
|
4
|
-
* This integration uses the Google-only retrieval path observed in the official `agy`
|
|
5
|
-
* CLI. The crawl runs on Google's side using the account's OAuth token:
|
|
6
|
-
*
|
|
7
|
-
* 1. `v1internal:rewriteUri` resolves a redirect chain and reports the final URI.
|
|
8
|
-
* 2. `v1internal:fetchFromTrawlerCache` answers from Google's crawl cache, and a
|
|
9
|
-
* 404 there means "not cached" rather than "no such page".
|
|
10
|
-
* 3. The same RPC with `liveFetch: true` retries missing or inadequate copies.
|
|
11
|
-
*
|
|
12
|
-
* The response is crawled source, usually HTML. Inspection preserves metadata and
|
|
13
|
-
* recovery links before Markdown cleanup; output is capped before reaching a model.
|
|
14
|
-
* No local HTTP client or JavaScript renderer contacts the target site. The official
|
|
15
|
-
* CLI's direct-download fallback is not implemented here.
|
|
16
|
-
*/
|
|
17
|
-
import {
|
|
18
|
-
antigravityHeaders,
|
|
19
|
-
endpointCandidates,
|
|
20
|
-
jsonOrTextError,
|
|
21
|
-
parseApiKey,
|
|
22
|
-
} from "../client/client.js";
|
|
23
|
-
import { checkPublicUrl } from "../utils/address.js";
|
|
24
|
-
import { antigravityFetch } from "../utils/http.js";
|
|
25
|
-
import { boundaryForward, capText, cleanText, elideMiddle, repairText } from "../utils/text.js";
|
|
26
|
-
import { redactSecrets, safeError } from "../utils/security.js";
|
|
27
|
-
import { antigravityEnv, isRecord } from "../utils/util.js";
|
|
28
|
-
import { DocumentLimitError } from "./document.js";
|
|
29
|
-
import { looksLikeHtml } from "./markdown.js";
|
|
30
|
-
|
|
31
|
-
import { inspectPage, inspectUnconverted, type PageInspection } from "./inspect.js";
|
|
32
|
-
import { mediaKind } from "./media.js";
|
|
33
|
-
import { representationFor } from "./representation.js";
|
|
34
|
-
import { siteRepresentation } from "./sites.js";
|
|
35
|
-
import { DEFAULT_WEB_FETCH_MAX_CHARS, WEB_FETCH_TIMEOUT_MS, MAX_RESPONSE_BYTES } from "./limits.js";
|
|
36
|
-
import { formatWebFetchHeader } from "./header.js";
|
|
37
|
-
import { FENCE_LINE, unclosedFence } from "./fences.js";
|
|
38
|
-
import {
|
|
39
|
-
runWithDiagnostics,
|
|
40
|
-
setLastEndpoint,
|
|
41
|
-
setLastStatus,
|
|
42
|
-
setLastError,
|
|
43
|
-
setLastLatencyMs,
|
|
44
|
-
setLastFetchTrace,
|
|
45
|
-
} from "../diagnostics/index.js";
|
|
46
|
-
|
|
47
|
-
const REWRITE_URI_PATH = "/v1internal:rewriteUri";
|
|
48
|
-
const TRAWLER_FETCH_PATH = "/v1internal:fetchFromTrawlerCache";
|
|
49
|
-
|
|
50
|
-
export { DEFAULT_WEB_FETCH_MAX_CHARS, WEB_FETCH_TIMEOUT_MS } from "./limits.js";
|
|
51
|
-
export { formatWebFetchHeader } from "./header.js";
|
|
52
|
-
|
|
53
|
-
type WebFetchSource = "cache" | "live";
|
|
54
|
-
|
|
55
|
-
type WebFetchOptions = {
|
|
56
|
-
apiKey?: string;
|
|
57
|
-
/** Page to read. */
|
|
58
|
-
url: string;
|
|
59
|
-
/** Return the crawled source instead of Markdown. */
|
|
60
|
-
raw?: boolean;
|
|
61
|
-
/** Character budget for the returned content. */
|
|
62
|
-
maxChars?: number;
|
|
63
|
-
/** Testable network deadline; defaults to ten seconds. */
|
|
64
|
-
timeoutMs?: number;
|
|
65
|
-
signal?: AbortSignal;
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
export type WebFetchResult = {
|
|
69
|
-
/** URL as requested. */
|
|
70
|
-
requestedUrl: string;
|
|
71
|
-
/** Whether the raw requested and resolved URLs differed before display redaction. */
|
|
72
|
-
redirected?: boolean;
|
|
73
|
-
/** URL the fetch service finally read, after any redirect. */
|
|
74
|
-
resolvedUrl: string;
|
|
75
|
-
/** Converted page content; each consumer owns its complete output budget. */
|
|
76
|
-
content: string;
|
|
77
|
-
title?: string;
|
|
78
|
-
description?: string;
|
|
79
|
-
/** Date the page states it was last modified, when it states one. */
|
|
80
|
-
updated?: string;
|
|
81
|
-
/** Whether the crawl cache answered, or the page was fetched live. */
|
|
82
|
-
source: WebFetchSource;
|
|
83
|
-
/** Size of the crawler response before conversion and truncation. */
|
|
84
|
-
bytes: number;
|
|
85
|
-
/** Whether the returned content was capped at the character budget. */
|
|
86
|
-
truncated: boolean;
|
|
87
|
-
/** True if incomplete, false if complete, or null when the source is ambiguous. */
|
|
88
|
-
partial: boolean | null;
|
|
89
|
-
/** Assessment of the extracted content, independent of source completeness. */
|
|
90
|
-
assessment?: PageInspection["assessment"];
|
|
91
|
-
author?: string;
|
|
92
|
-
notes?: string[];
|
|
93
|
-
published?: string;
|
|
94
|
-
language?: string;
|
|
95
|
-
/** Actual fetched representation, when different from the article URL. */
|
|
96
|
-
representationUrl?: string;
|
|
97
|
-
attempts?: Array<{
|
|
98
|
-
url: string;
|
|
99
|
-
source: WebFetchSource;
|
|
100
|
-
outcome: string;
|
|
101
|
-
endpoint?: string;
|
|
102
|
-
stage?: string;
|
|
103
|
-
}>;
|
|
104
|
-
/** Character budget used for this result, including header and footer space. */
|
|
105
|
-
maxChars?: number;
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Validate a target URL, returning its normalized form.
|
|
110
|
-
*
|
|
111
|
-
* The fetch runs on Google's machines, so a private address is not a request-forgery
|
|
112
|
-
* risk here, but it can never be reached from there: rejecting it locally turns a
|
|
113
|
-
* confusing remote failure into a clear message. URLs with embedded credentials are
|
|
114
|
-
* refused because they would be sent to a third party. Sensitive query values are still
|
|
115
|
-
* sent with the request, but are redacted from displayed output and errors.
|
|
116
|
-
*/
|
|
117
|
-
export function validateFetchTarget(raw: string): string {
|
|
118
|
-
const checked = checkPublicUrl(raw);
|
|
119
|
-
if (checked.ok) return checked.url;
|
|
120
|
-
const messages = {
|
|
121
|
-
missing: "A URL is required.",
|
|
122
|
-
invalid: "Not a valid public HTTP(S) URL.",
|
|
123
|
-
scheme: "Only http and https URLs can be read.",
|
|
124
|
-
credentials: "URLs with embedded credentials are not supported.",
|
|
125
|
-
local: "That URL is a private or local address, which the fetch service cannot reach.",
|
|
126
|
-
"too-long": "The URL exceeds the 2,048-character limit.",
|
|
127
|
-
};
|
|
128
|
-
throw Object.assign(new Error(messages[checked.reason]), {
|
|
129
|
-
unsafeTarget: checked.reason !== "invalid",
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const PDF_GUIDANCE =
|
|
134
|
-
"This tool does not support PDF content. Do not retry this URL with read_url_content. " +
|
|
135
|
-
"If permitted, use an available download tool or terminal to download it directly, then read the local file with a PDF reader. " +
|
|
136
|
-
"Downloading alone does not extract its text.";
|
|
137
|
-
|
|
138
|
-
function pdfError(url?: string): Error {
|
|
139
|
-
return Object.assign(
|
|
140
|
-
new Error(`${url ? `Unsupported representation ${redactSecrets(url)}: ` : ""}${PDF_GUIDANCE}`),
|
|
141
|
-
{ fatal: true, status: 415 },
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** A small leading text window for signature detection, not PDF parsing. */
|
|
146
|
-
const PDF_HEADER_WINDOW = 1_024;
|
|
147
|
-
|
|
148
|
-
function isPdfContentType(contentType?: string): boolean {
|
|
149
|
-
return mediaKind(contentType) === "pdf";
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** PDF detection is not limited to a URL suffix; inspect the returned representation too. */
|
|
153
|
-
function isPdfContent(content: string, contentType?: string): boolean {
|
|
154
|
-
if (isPdfContentType(contentType)) return true;
|
|
155
|
-
// A PDF signature must begin a line, followed by a version. Prose mentioning
|
|
156
|
-
// "%PDF-1.7" is not a binary document.
|
|
157
|
-
return /(?:^|[\r\n])%PDF-\d\.\d(?:[\r\n]|$)/.test(content.slice(0, PDF_HEADER_WINDOW));
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** Reject known PDF URLs with guidance for the calling agent. */
|
|
161
|
-
function rejectPdfUrl(url: string): void {
|
|
162
|
-
if (/\.pdf$/i.test(new URL(url).pathname)) throw pdfError(url);
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** Request body for the redirect resolver. */
|
|
166
|
-
function buildRewriteUriRequest(originalUri: string): Record<string, unknown> {
|
|
167
|
-
return { originalUri };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** Request body for the crawl cache, and for the live fetch when the cache misses. */
|
|
171
|
-
function buildTrawlerFetchRequest(url: string, live = false): Record<string, unknown> {
|
|
172
|
-
return live ? { url, liveFetch: true } : { url };
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** Some Cloud Code Assist methods answer with a `response` wrapper; accept both shapes. */
|
|
176
|
-
function unwrapResponse(data: unknown): unknown {
|
|
177
|
-
if (isRecord(data) && isRecord(data.response)) return data.response;
|
|
178
|
-
return data;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function firstNonEmptyText(...values: unknown[]): string | undefined {
|
|
182
|
-
for (const value of values) if (typeof value === "string" && value.trim()) return value;
|
|
183
|
-
return undefined;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/** Final URI from a rewrite response, when the request was redirected. */
|
|
187
|
-
function parseRedirectUri(data: unknown): string | undefined {
|
|
188
|
-
const body = unwrapResponse(data);
|
|
189
|
-
if (!isRecord(body)) return undefined;
|
|
190
|
-
const value = firstNonEmptyText(body.redirectUri, body.redirect_uri, body.rewrittenUri);
|
|
191
|
-
return value?.trim();
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/** Page content from a trawler response. */
|
|
195
|
-
function parseTrawlerContent(data: unknown): string | undefined {
|
|
196
|
-
const body = unwrapResponse(data);
|
|
197
|
-
if (!isRecord(body)) return undefined;
|
|
198
|
-
const content = firstNonEmptyText(body.content, body.markdownContent);
|
|
199
|
-
return content === undefined ? undefined : repairText(content);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/** Explicit media type from a trawler response, when the service reports one. */
|
|
203
|
-
function parseTrawlerContentType(data: unknown): string | undefined {
|
|
204
|
-
const body = unwrapResponse(data);
|
|
205
|
-
if (!isRecord(body)) return undefined;
|
|
206
|
-
return firstNonEmptyText(body.contentType, body.content_type, body.mimeType, body.mime_type)
|
|
207
|
-
?.split(";")[0]
|
|
208
|
-
.trim()
|
|
209
|
-
.toLowerCase();
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/** Character budget, from the caller or `ANTIGRAVITY_WEB_FETCH_MAX_CHARS`. */
|
|
213
|
-
export function resolveMaxChars(explicit?: number): number {
|
|
214
|
-
if (typeof explicit === "number" && Number.isSafeInteger(Math.floor(explicit)) && explicit >= 1) {
|
|
215
|
-
return Math.floor(explicit);
|
|
216
|
-
}
|
|
217
|
-
const configured = Number(antigravityEnv("WEB_FETCH_MAX_CHARS"));
|
|
218
|
-
return Number.isSafeInteger(Math.floor(configured)) && configured >= 1
|
|
219
|
-
? Math.floor(configured)
|
|
220
|
-
: DEFAULT_WEB_FETCH_MAX_CHARS;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
type JsonPost = {
|
|
224
|
-
status: number;
|
|
225
|
-
data: unknown;
|
|
226
|
-
text: string;
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
/** Error for a response the tool refuses to read; retrying cannot make it smaller. */
|
|
230
|
-
function tooLargeError(): Error {
|
|
231
|
-
return Object.assign(new Error("The fetch response was too large to read safely."), {
|
|
232
|
-
fatal: true,
|
|
233
|
-
status: 413,
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** Read a response without allowing an unbounded body into the parser. */
|
|
238
|
-
async function readResponseText(response: Response): Promise<string> {
|
|
239
|
-
const declared = Number(response.headers?.get?.("content-length"));
|
|
240
|
-
if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
|
|
241
|
-
await response.body?.cancel().catch(() => undefined);
|
|
242
|
-
throw tooLargeError();
|
|
243
|
-
}
|
|
244
|
-
const body = response.body;
|
|
245
|
-
const reader = body && typeof body.getReader === "function" ? body.getReader() : undefined;
|
|
246
|
-
if (!reader) {
|
|
247
|
-
// A response without a readable stream has to be buffered; keep one copy of it.
|
|
248
|
-
if (typeof response.arrayBuffer === "function") {
|
|
249
|
-
const buffer = await response.arrayBuffer();
|
|
250
|
-
if (buffer.byteLength > MAX_RESPONSE_BYTES) throw tooLargeError();
|
|
251
|
-
return new TextDecoder().decode(buffer);
|
|
252
|
-
}
|
|
253
|
-
const text = await response.text();
|
|
254
|
-
if (new TextEncoder().encode(text).byteLength > MAX_RESPONSE_BYTES) throw tooLargeError();
|
|
255
|
-
return text;
|
|
256
|
-
}
|
|
257
|
-
const chunks: Uint8Array[] = [];
|
|
258
|
-
let total = 0;
|
|
259
|
-
try {
|
|
260
|
-
for (;;) {
|
|
261
|
-
const { done, value } = await reader.read();
|
|
262
|
-
if (done) break;
|
|
263
|
-
if (!value) continue;
|
|
264
|
-
total += value.byteLength;
|
|
265
|
-
if (total > MAX_RESPONSE_BYTES) {
|
|
266
|
-
await reader.cancel().catch(() => undefined);
|
|
267
|
-
throw tooLargeError();
|
|
268
|
-
}
|
|
269
|
-
chunks.push(value);
|
|
270
|
-
}
|
|
271
|
-
} finally {
|
|
272
|
-
reader.releaseLock();
|
|
273
|
-
}
|
|
274
|
-
const merged = new Uint8Array(total);
|
|
275
|
-
let offset = 0;
|
|
276
|
-
for (const chunk of chunks) {
|
|
277
|
-
merged.set(chunk, offset);
|
|
278
|
-
offset += chunk.byteLength;
|
|
279
|
-
}
|
|
280
|
-
return new TextDecoder().decode(merged);
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
async function postJson(
|
|
284
|
-
endpoint: string,
|
|
285
|
-
path: string,
|
|
286
|
-
headers: Record<string, string>,
|
|
287
|
-
body: Record<string, unknown>,
|
|
288
|
-
signal?: AbortSignal,
|
|
289
|
-
): Promise<JsonPost> {
|
|
290
|
-
setLastEndpoint(endpoint);
|
|
291
|
-
const response = await antigravityFetch(`${endpoint}${path}`, {
|
|
292
|
-
method: "POST",
|
|
293
|
-
headers,
|
|
294
|
-
body: JSON.stringify(body),
|
|
295
|
-
signal,
|
|
296
|
-
});
|
|
297
|
-
setLastStatus(response.status);
|
|
298
|
-
const text = await readResponseText(response);
|
|
299
|
-
let data: unknown;
|
|
300
|
-
try {
|
|
301
|
-
data = text ? JSON.parse(text) : undefined;
|
|
302
|
-
} catch {
|
|
303
|
-
data = undefined;
|
|
304
|
-
}
|
|
305
|
-
return { status: response.status, data, text };
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
type RetrievalStage = "cache" | "live" | "representation";
|
|
309
|
-
/** A cache miss is not a page failure; all other stages share the same status policy. */
|
|
310
|
-
export function statusAction(
|
|
311
|
-
stage: RetrievalStage,
|
|
312
|
-
status: number,
|
|
313
|
-
): "content" | "missing" | "recover" | "stop" {
|
|
314
|
-
if (status === 200) return "content";
|
|
315
|
-
if (status === 401 || status === 403) return "stop";
|
|
316
|
-
if (stage === "cache" && (status < 400 || status === 404 || status === 410)) return "missing";
|
|
317
|
-
return status === 429 || status >= 500 ? "recover" : "stop";
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
/** Error carrying a stage-independent retry/refusal decision. */
|
|
321
|
-
function fetchError(text: string, status: number, stage: RetrievalStage): Error {
|
|
322
|
-
const detail = capText(repairText(redactSecrets(jsonOrTextError(text))), 400) || `HTTP ${status}`;
|
|
323
|
-
const message =
|
|
324
|
-
stage === "cache"
|
|
325
|
-
? `The crawl cache could not answer (HTTP ${status}: ${detail}).`
|
|
326
|
-
: `The live fetch failed (HTTP ${status}: ${detail}). Try again later, or open the page in a browser.`;
|
|
327
|
-
return Object.assign(new Error(message), {
|
|
328
|
-
fatal: statusAction(stage, status) === "stop",
|
|
329
|
-
status,
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
/** Whether a validation failure names a private or local destination. */
|
|
334
|
-
function isUnsafeTarget(error: unknown): boolean {
|
|
335
|
-
return error instanceof Error && (error as { unsafeTarget?: boolean }).unsafeTarget === true;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
/** Resolve best-effort, but reject any unsafe destination the service reports. */
|
|
339
|
-
async function resolveRedirect(
|
|
340
|
-
endpoint: string,
|
|
341
|
-
url: string,
|
|
342
|
-
headers: Record<string, string>,
|
|
343
|
-
signal?: AbortSignal,
|
|
344
|
-
strict = false,
|
|
345
|
-
request = postJson,
|
|
346
|
-
): Promise<string | undefined> {
|
|
347
|
-
let redirect: string | undefined;
|
|
348
|
-
try {
|
|
349
|
-
const response = await request(
|
|
350
|
-
endpoint,
|
|
351
|
-
REWRITE_URI_PATH,
|
|
352
|
-
headers,
|
|
353
|
-
buildRewriteUriRequest(url),
|
|
354
|
-
signal,
|
|
355
|
-
);
|
|
356
|
-
if (response.status !== 200) {
|
|
357
|
-
if (strict) throw new Error(`Alternate redirect resolver failed (HTTP ${response.status}).`);
|
|
358
|
-
return undefined;
|
|
359
|
-
}
|
|
360
|
-
redirect = parseRedirectUri(response.data);
|
|
361
|
-
} catch (error) {
|
|
362
|
-
// Original-page resolution is best-effort. Alternate recovery must fail closed.
|
|
363
|
-
if (strict) throw error;
|
|
364
|
-
}
|
|
365
|
-
if (!redirect || redirect === url) return undefined;
|
|
366
|
-
let absolute: string;
|
|
367
|
-
try {
|
|
368
|
-
absolute = new URL(redirect, url).toString();
|
|
369
|
-
} catch (error) {
|
|
370
|
-
// A malformed destination says nothing about the requested page; keep reading it.
|
|
371
|
-
if (strict) throw error;
|
|
372
|
-
return undefined;
|
|
373
|
-
}
|
|
374
|
-
if (absolute === url) return undefined;
|
|
375
|
-
try {
|
|
376
|
-
return validateFetchTarget(absolute);
|
|
377
|
-
} catch (error) {
|
|
378
|
-
// An unsafe destination the service reports fails closed. A malformed or
|
|
379
|
-
// unsupported target only costs the redirect, so the read continues.
|
|
380
|
-
if (strict || isUnsafeTarget(error))
|
|
381
|
-
throw new Error(`The service reported an unsafe redirect: ${safeError(error)}`, {
|
|
382
|
-
cause: error,
|
|
383
|
-
});
|
|
384
|
-
return undefined;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
/** Close a code fence the character cap cut through, so the note is not read as code. */
|
|
389
|
-
function keepFencesClosed(markdown: string): string {
|
|
390
|
-
const fence = unclosedFence(markdown);
|
|
391
|
-
return fence ? `${markdown}\n${fence.prefix}${fence.marker.repeat(fence.length)}` : markdown;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function splitsSurrogate(text: string, index: number): boolean {
|
|
395
|
-
return (
|
|
396
|
-
index > 0 &&
|
|
397
|
-
index < text.length &&
|
|
398
|
-
/[\uD800-\uDBFF]/.test(text[index - 1]) &&
|
|
399
|
-
/[\uDC00-\uDFFF]/.test(text[index])
|
|
400
|
-
);
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
/** Move a character boundary off a surrogate pair and outside a fence delimiter line. */
|
|
404
|
-
function safeTruncate(text: string, end: number, start = 0): number {
|
|
405
|
-
let next = Math.min(text.length, Math.max(start, end));
|
|
406
|
-
next = boundaryForward(text, next);
|
|
407
|
-
if (next <= start || next >= text.length) return next;
|
|
408
|
-
const lineStart = text.lastIndexOf("\n", next - 1) + 1;
|
|
409
|
-
const lineEndRaw = text.indexOf("\n", next);
|
|
410
|
-
const lineEnd = lineEndRaw < 0 ? text.length : lineEndRaw;
|
|
411
|
-
if (next > lineStart && next < lineEnd && FENCE_LINE.test(text.slice(lineStart, lineEnd))) {
|
|
412
|
-
if (lineStart > start) return lineStart;
|
|
413
|
-
// A delimiter line longer than the whole range cannot be skipped without
|
|
414
|
-
// losing the range, so the budget bound wins and the fence is closed later.
|
|
415
|
-
return Math.min(lineEnd < text.length ? lineEnd + 1 : text.length, next);
|
|
416
|
-
}
|
|
417
|
-
return next;
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
/** Format the rendered page, extract metadata, and apply the character budget. */
|
|
421
|
-
function toResult(params: {
|
|
422
|
-
requestedUrl: string;
|
|
423
|
-
resolvedUrl: string;
|
|
424
|
-
content: string;
|
|
425
|
-
rendered: string;
|
|
426
|
-
source: WebFetchSource;
|
|
427
|
-
maxChars: number;
|
|
428
|
-
inspection: PageInspection;
|
|
429
|
-
representationUrl?: string;
|
|
430
|
-
attempts: NonNullable<WebFetchResult["attempts"]>;
|
|
431
|
-
}): WebFetchResult {
|
|
432
|
-
const { requestedUrl, resolvedUrl, content, source, maxChars, inspection } = params;
|
|
433
|
-
// Redact caller/service URLs wherever the page echoes them, before the page is shown or saved.
|
|
434
|
-
let rendered = repairText(params.rendered);
|
|
435
|
-
for (const url of [requestedUrl, resolvedUrl, params.representationUrl]) {
|
|
436
|
-
if (url) rendered = rendered.replaceAll(url, redactSecrets(url));
|
|
437
|
-
}
|
|
438
|
-
const metadata = inspection.metadata;
|
|
439
|
-
const completeness = inspection.completeness;
|
|
440
|
-
const partial = completeness === "complete" ? false : completeness === "incomplete" ? true : null;
|
|
441
|
-
const provisional: WebFetchResult = {
|
|
442
|
-
requestedUrl: redactSecrets(requestedUrl),
|
|
443
|
-
resolvedUrl: redactSecrets(resolvedUrl),
|
|
444
|
-
redirected: requestedUrl !== resolvedUrl,
|
|
445
|
-
content: rendered,
|
|
446
|
-
title: metadata.title,
|
|
447
|
-
description: metadata.description,
|
|
448
|
-
updated: metadata.updated,
|
|
449
|
-
source,
|
|
450
|
-
bytes: 0,
|
|
451
|
-
truncated: false,
|
|
452
|
-
partial,
|
|
453
|
-
assessment: inspection.assessment,
|
|
454
|
-
notes: inspection.notes,
|
|
455
|
-
author: metadata.author,
|
|
456
|
-
published: metadata.published,
|
|
457
|
-
language: metadata.language,
|
|
458
|
-
representationUrl: params.representationUrl
|
|
459
|
-
? redactSecrets(params.representationUrl)
|
|
460
|
-
: undefined,
|
|
461
|
-
attempts: params.attempts,
|
|
462
|
-
maxChars,
|
|
463
|
-
};
|
|
464
|
-
return {
|
|
465
|
-
...provisional,
|
|
466
|
-
bytes: new TextEncoder().encode(content).byteLength,
|
|
467
|
-
truncated: rendered.length + formatWebFetchHeader(provisional).length > maxChars,
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
/** Inspect a page; raw mode keeps a source beyond the conversion limits as it is. */
|
|
472
|
-
function inspectSource(
|
|
473
|
-
content: string,
|
|
474
|
-
url: string,
|
|
475
|
-
contentType: string | undefined,
|
|
476
|
-
raw: boolean | undefined,
|
|
477
|
-
): PageInspection {
|
|
478
|
-
try {
|
|
479
|
-
return inspectPage(content, url, contentType);
|
|
480
|
-
} catch (error) {
|
|
481
|
-
if (raw && error instanceof DocumentLimitError)
|
|
482
|
-
return inspectUnconverted(content, error.message);
|
|
483
|
-
throw error;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
function recordFailure(
|
|
488
|
-
attempt: NonNullable<WebFetchResult["attempts"]>[number],
|
|
489
|
-
error: unknown,
|
|
490
|
-
retained: boolean,
|
|
491
|
-
timedOut: boolean,
|
|
492
|
-
): void {
|
|
493
|
-
const status = error instanceof Error ? (error as { status?: number }).status : undefined;
|
|
494
|
-
if (timedOut) attempt.outcome = "overall deadline exceeded";
|
|
495
|
-
else if (status === 415) attempt.outcome = "unsupported PDF content";
|
|
496
|
-
else if (status === 413) attempt.outcome = "response too large to read safely";
|
|
497
|
-
else if (status !== undefined) attempt.outcome = `HTTP ${status}`;
|
|
498
|
-
else if (attempt.outcome === "HTTP 200")
|
|
499
|
-
attempt.outcome = `content inspection failed: ${cleanText(safeError(error), 120) ?? "unknown error"}`;
|
|
500
|
-
if (retained) attempt.outcome += "; retained usable copy";
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
type Candidate = {
|
|
504
|
-
content: string;
|
|
505
|
-
inspection: PageInspection;
|
|
506
|
-
resolvedUrl: string;
|
|
507
|
-
representationUrl?: string;
|
|
508
|
-
source: WebFetchSource;
|
|
509
|
-
};
|
|
510
|
-
|
|
511
|
-
/** Prefer readable article evidence, then a closed source, then additional content. */
|
|
512
|
-
function candidateRank(candidate: Candidate): number {
|
|
513
|
-
const page = candidate.inspection;
|
|
514
|
-
return (
|
|
515
|
-
(page.assessment === "readable"
|
|
516
|
-
? 4_000_000
|
|
517
|
-
: page.assessment === "suspected-shell"
|
|
518
|
-
? 1_000_000
|
|
519
|
-
: 0) +
|
|
520
|
-
(page.completeness === "complete"
|
|
521
|
-
? 2_000_000
|
|
522
|
-
: page.completeness === "unknown"
|
|
523
|
-
? 1_000_000
|
|
524
|
-
: 0) +
|
|
525
|
-
Math.min(page.rendered.length, 999_999)
|
|
526
|
-
);
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
/** A readable fragment is usable; only positive signs of a problem trigger recovery. */
|
|
530
|
-
function needsRecovery(candidate: Candidate): boolean {
|
|
531
|
-
return (
|
|
532
|
-
candidate.inspection.assessment !== "readable" ||
|
|
533
|
-
candidate.inspection.completeness === "incomplete" ||
|
|
534
|
-
// Google cuts these sites' ordinary pages; only a verified copy is complete.
|
|
535
|
-
(candidate.inspection.completeness !== "complete" &&
|
|
536
|
-
!candidate.representationUrl &&
|
|
537
|
-
siteRepresentation(candidate.resolvedUrl) !== undefined)
|
|
538
|
-
);
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
/**
|
|
542
|
-
* Read through Google only: inspect cache, recover live when inadequate, and try
|
|
543
|
-
* one advertised same-origin article representation. Keep the best usable copy
|
|
544
|
-
* if recovery fails; never splice different versions of an article together.
|
|
545
|
-
*/
|
|
546
|
-
class WebFetchError extends Error {
|
|
547
|
-
readonly attempts: NonNullable<WebFetchResult["attempts"]>;
|
|
548
|
-
constructor(url: string, detail: string, attempts: WebFetchResult["attempts"] = []) {
|
|
549
|
-
const trail = formatAttemptTrail(attempts);
|
|
550
|
-
super(
|
|
551
|
-
repairText(
|
|
552
|
-
redactSecrets(`Could not read ${url}: ${detail}${trail ? ` (Attempts: ${trail})` : ""}`),
|
|
553
|
-
),
|
|
554
|
-
);
|
|
555
|
-
this.name = "WebFetchError";
|
|
556
|
-
this.attempts = attempts;
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
function formatAttemptTrail(attempts: WebFetchResult["attempts"]): string {
|
|
561
|
-
return (attempts ?? [])
|
|
562
|
-
.map(
|
|
563
|
-
(attempt) =>
|
|
564
|
-
`${attempt.stage ?? attempt.source}@${attempt.endpoint ?? "Google"} ${elideMiddle(attempt.url, 256)}: ${attempt.outcome}`,
|
|
565
|
-
)
|
|
566
|
-
.join(" → ");
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
export async function executeAntigravityWebFetch(
|
|
570
|
-
options: WebFetchOptions,
|
|
571
|
-
): Promise<WebFetchResult> {
|
|
572
|
-
return runWithDiagnostics(async () => {
|
|
573
|
-
const started = performance.now();
|
|
574
|
-
try {
|
|
575
|
-
const result = await fetchPage(options);
|
|
576
|
-
setLastFetchTrace(formatAttemptTrail(result.attempts));
|
|
577
|
-
if (result.assessment !== "readable" || result.partial !== false)
|
|
578
|
-
setLastError(
|
|
579
|
-
`Degraded fetch: assessment=${result.assessment ?? "unknown"}; partial=${result.partial}; ${result.attempts?.map((attempt) => `${attempt.stage ?? attempt.source}: ${attempt.outcome}`).join(" → ") ?? ""}`,
|
|
580
|
-
);
|
|
581
|
-
return result;
|
|
582
|
-
} catch (error) {
|
|
583
|
-
const checked = checkPublicUrl(options.url);
|
|
584
|
-
const safe =
|
|
585
|
-
error instanceof WebFetchError
|
|
586
|
-
? error
|
|
587
|
-
: new WebFetchError(
|
|
588
|
-
checked.ok ? redactSecrets(checked.url) : "the supplied URL",
|
|
589
|
-
safeError(error),
|
|
590
|
-
);
|
|
591
|
-
setLastError(safe.message);
|
|
592
|
-
setLastFetchTrace(formatAttemptTrail(safe.attempts));
|
|
593
|
-
|
|
594
|
-
throw safe;
|
|
595
|
-
} finally {
|
|
596
|
-
setLastLatencyMs(Math.round(performance.now() - started));
|
|
597
|
-
}
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
async function fetchPage(options: WebFetchOptions): Promise<WebFetchResult> {
|
|
602
|
-
const requestedUrl = validateFetchTarget(options.url);
|
|
603
|
-
rejectPdfUrl(requestedUrl);
|
|
604
|
-
const deadline = AbortSignal.timeout(options.timeoutMs ?? WEB_FETCH_TIMEOUT_MS);
|
|
605
|
-
const signal = options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
|
|
606
|
-
const creds = parseApiKey(options.apiKey);
|
|
607
|
-
const headers = antigravityHeaders(creds.token);
|
|
608
|
-
const maxChars = resolveMaxChars(options.maxChars);
|
|
609
|
-
const attempts: NonNullable<WebFetchResult["attempts"]> = [];
|
|
610
|
-
let best: Candidate | undefined;
|
|
611
|
-
let lastError = "no endpoint available";
|
|
612
|
-
// Google's copy, kept when it is beyond the conversion limits so the caller can save it.
|
|
613
|
-
let unconvertedCopy: string | undefined;
|
|
614
|
-
let lastContent: string | undefined;
|
|
615
|
-
let requests = 0;
|
|
616
|
-
let endpointAnswered: boolean;
|
|
617
|
-
let alternateTried = false;
|
|
618
|
-
const endpoints = endpointCandidates();
|
|
619
|
-
const unavailable = new Set<string>();
|
|
620
|
-
const requested = new Set<string>();
|
|
621
|
-
const request: typeof postJson = async (_endpoint, path, requestHeaders, body, requestSignal) => {
|
|
622
|
-
let attempt = attempts.at(-1);
|
|
623
|
-
if (path === REWRITE_URI_PATH) {
|
|
624
|
-
attempt = {
|
|
625
|
-
url: cleanText(redactSecrets(String(body.originalUri ?? "")), 2_048)!,
|
|
626
|
-
source: "cache",
|
|
627
|
-
stage: "redirect",
|
|
628
|
-
outcome: "transport failed",
|
|
629
|
-
};
|
|
630
|
-
attempts.push(attempt);
|
|
631
|
-
}
|
|
632
|
-
for (const endpoint of endpoints) {
|
|
633
|
-
if (unavailable.has(endpoint)) continue;
|
|
634
|
-
const key = JSON.stringify([endpoint, path, body]);
|
|
635
|
-
if (requested.has(key)) continue;
|
|
636
|
-
if (requests >= 10)
|
|
637
|
-
throw Object.assign(
|
|
638
|
-
new Error("The bounded fetch request budget was exhausted. Open the page in a browser."),
|
|
639
|
-
{ fatal: true },
|
|
640
|
-
);
|
|
641
|
-
requested.add(key);
|
|
642
|
-
requests += 1;
|
|
643
|
-
if (attempt) attempt.endpoint = endpoint;
|
|
644
|
-
try {
|
|
645
|
-
const response = await postJson(endpoint, path, requestHeaders, body, requestSignal);
|
|
646
|
-
if (attempt) attempt.outcome = `HTTP ${response.status}`;
|
|
647
|
-
if (path === TRAWLER_FETCH_PATH) endpointAnswered = true;
|
|
648
|
-
return response;
|
|
649
|
-
} catch (error) {
|
|
650
|
-
if (
|
|
651
|
-
requestSignal?.aborted ||
|
|
652
|
-
(error instanceof Error && (error as { fatal?: boolean }).fatal)
|
|
653
|
-
)
|
|
654
|
-
throw error;
|
|
655
|
-
unavailable.add(endpoint);
|
|
656
|
-
if (attempt) {
|
|
657
|
-
// Preserve this failed endpoint, then keep the caller's live record at the
|
|
658
|
-
// end so later inspection updates the endpoint that actually answered.
|
|
659
|
-
const failed = { ...attempt, outcome: "transport failed" };
|
|
660
|
-
attempts.splice(attempts.length - 1, 0, failed);
|
|
661
|
-
}
|
|
662
|
-
lastError = capText(repairText(safeError(error)), 400);
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
if (attempt) attempts.pop(); // No physical request corresponds to the pending record.
|
|
666
|
-
throw Object.assign(new Error(`No Google endpoint could complete this request: ${lastError}`), {
|
|
667
|
-
fatal: true,
|
|
668
|
-
});
|
|
669
|
-
};
|
|
670
|
-
const aborted = () => {
|
|
671
|
-
if (options.signal?.aborted) throw new Error("Web fetch aborted");
|
|
672
|
-
};
|
|
673
|
-
const usable = (candidate: Candidate | undefined): boolean =>
|
|
674
|
-
Boolean(
|
|
675
|
-
candidate &&
|
|
676
|
-
(candidate.inspection.rendered.trim() || (options.raw && candidate.content.trim())),
|
|
677
|
-
);
|
|
678
|
-
const retain = (candidate: Candidate) => {
|
|
679
|
-
if (!best || candidateRank(candidate) > candidateRank(best)) best = candidate;
|
|
680
|
-
};
|
|
681
|
-
const result = (candidate: Candidate) =>
|
|
682
|
-
toResult({
|
|
683
|
-
requestedUrl,
|
|
684
|
-
resolvedUrl: candidate.resolvedUrl,
|
|
685
|
-
content: candidate.content,
|
|
686
|
-
rendered: options.raw ? candidate.content : candidate.inspection.rendered,
|
|
687
|
-
source: candidate.source,
|
|
688
|
-
maxChars,
|
|
689
|
-
inspection: candidate.inspection,
|
|
690
|
-
representationUrl: candidate.representationUrl,
|
|
691
|
-
attempts,
|
|
692
|
-
});
|
|
693
|
-
|
|
694
|
-
// Per-request dispatch owns endpoint failover; never repeat the whole retrieval flow.
|
|
695
|
-
for (const endpoint of endpoints.slice(0, 1)) {
|
|
696
|
-
endpointAnswered = false;
|
|
697
|
-
aborted();
|
|
698
|
-
if (deadline.aborted) break;
|
|
699
|
-
const resolvedUrl =
|
|
700
|
-
(await resolveRedirect(endpoint, requestedUrl, headers, signal, false, request)) ??
|
|
701
|
-
requestedUrl;
|
|
702
|
-
aborted();
|
|
703
|
-
rejectPdfUrl(resolvedUrl);
|
|
704
|
-
let page: Candidate | undefined;
|
|
705
|
-
let alternatePage: Candidate | undefined;
|
|
706
|
-
for (const source of ["cache", "live"] as const) {
|
|
707
|
-
aborted();
|
|
708
|
-
if (deadline.aborted) break;
|
|
709
|
-
const attempt = {
|
|
710
|
-
url: cleanText(redactSecrets(resolvedUrl), 2_048)!,
|
|
711
|
-
endpoint,
|
|
712
|
-
stage: source,
|
|
713
|
-
source,
|
|
714
|
-
outcome: "transport failed",
|
|
715
|
-
};
|
|
716
|
-
attempts.push(attempt);
|
|
717
|
-
try {
|
|
718
|
-
const response = await request(
|
|
719
|
-
endpoint,
|
|
720
|
-
TRAWLER_FETCH_PATH,
|
|
721
|
-
headers,
|
|
722
|
-
buildTrawlerFetchRequest(resolvedUrl, source === "live"),
|
|
723
|
-
signal,
|
|
724
|
-
);
|
|
725
|
-
aborted();
|
|
726
|
-
attempt.outcome = `HTTP ${response.status}`;
|
|
727
|
-
if (response.status !== 200) {
|
|
728
|
-
// The cache saying "not here" leaves the live fetch to try.
|
|
729
|
-
if (statusAction(source, response.status) === "missing") continue;
|
|
730
|
-
throw fetchError(response.text, response.status, source);
|
|
731
|
-
}
|
|
732
|
-
const contentType = parseTrawlerContentType(response.data);
|
|
733
|
-
if (isPdfContentType(contentType)) throw pdfError();
|
|
734
|
-
const content = parseTrawlerContent(response.data);
|
|
735
|
-
lastContent = content;
|
|
736
|
-
if (content === undefined) {
|
|
737
|
-
attempt.outcome = "empty response";
|
|
738
|
-
lastError = /error|message/i.test(response.text)
|
|
739
|
-
? capText(redactSecrets(jsonOrTextError(response.text)), 400)
|
|
740
|
-
: "Google returned no readable article content.";
|
|
741
|
-
continue;
|
|
742
|
-
}
|
|
743
|
-
if (isPdfContent(content, contentType)) throw pdfError();
|
|
744
|
-
const candidate: Candidate = {
|
|
745
|
-
content,
|
|
746
|
-
resolvedUrl,
|
|
747
|
-
source,
|
|
748
|
-
inspection: inspectSource(content, resolvedUrl, contentType, options.raw),
|
|
749
|
-
};
|
|
750
|
-
attempt.outcome = `${candidate.inspection.assessment}; source ${candidate.inspection.completeness}`;
|
|
751
|
-
retain(candidate);
|
|
752
|
-
if (
|
|
753
|
-
candidate.inspection.alternates.length &&
|
|
754
|
-
(!alternatePage || candidateRank(candidate) > candidateRank(alternatePage))
|
|
755
|
-
)
|
|
756
|
-
alternatePage = candidate;
|
|
757
|
-
if (!page || candidateRank(candidate) > candidateRank(page)) page = candidate;
|
|
758
|
-
if (!needsRecovery(candidate)) return result(candidate);
|
|
759
|
-
} catch (error) {
|
|
760
|
-
aborted();
|
|
761
|
-
recordFailure(attempt, error, source !== "cache" && usable(best), deadline.aborted);
|
|
762
|
-
if (
|
|
763
|
-
error instanceof Error &&
|
|
764
|
-
(error as { fatal?: boolean }).fatal &&
|
|
765
|
-
(source === "cache" || !usable(best))
|
|
766
|
-
)
|
|
767
|
-
throw new WebFetchError(requestedUrl, safeError(error), attempts);
|
|
768
|
-
lastError = capText(repairText(safeError(error)), 400);
|
|
769
|
-
const unconvertible = error instanceof DocumentLimitError;
|
|
770
|
-
if (unconvertible && lastContent) {
|
|
771
|
-
unconvertedCopy = repairText(lastContent);
|
|
772
|
-
for (const url of [requestedUrl, resolvedUrl])
|
|
773
|
-
unconvertedCopy = unconvertedCopy.replaceAll(url, redactSecrets(url));
|
|
774
|
-
}
|
|
775
|
-
if (!endpointAnswered || unconvertible) break;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
// Raw mode means the requested page source, not a substituted representation.
|
|
779
|
-
const discovery = alternatePage ?? page;
|
|
780
|
-
const representation = options.raw
|
|
781
|
-
? undefined
|
|
782
|
-
: representationFor(resolvedUrl, discovery?.inspection.alternates[0]);
|
|
783
|
-
if (representation && !deadline.aborted && !alternateTried) {
|
|
784
|
-
alternateTried = true;
|
|
785
|
-
aborted();
|
|
786
|
-
let representationAttempt: NonNullable<WebFetchResult["attempts"]>[number] | undefined;
|
|
787
|
-
try {
|
|
788
|
-
const url = validateFetchTarget(representation.url);
|
|
789
|
-
rejectPdfUrl(url);
|
|
790
|
-
const redirected = representation.resolve
|
|
791
|
-
? await resolveRedirect(endpoint, url, headers, signal, true, request)
|
|
792
|
-
: undefined;
|
|
793
|
-
aborted();
|
|
794
|
-
if (deadline.aborted) break;
|
|
795
|
-
if (redirected && new URL(redirected).origin !== new URL(url).origin) {
|
|
796
|
-
attempts.push({
|
|
797
|
-
url: cleanText(redactSecrets(url), 2_048)!,
|
|
798
|
-
source: "live",
|
|
799
|
-
endpoint,
|
|
800
|
-
stage: "representation",
|
|
801
|
-
outcome: "cross-origin redirect rejected",
|
|
802
|
-
});
|
|
803
|
-
} else {
|
|
804
|
-
const representationUrl = redirected ?? url;
|
|
805
|
-
representationAttempt = {
|
|
806
|
-
url: cleanText(redactSecrets(representationUrl), 2_048)!,
|
|
807
|
-
endpoint,
|
|
808
|
-
stage: "representation",
|
|
809
|
-
source: "live",
|
|
810
|
-
outcome: "transport failed",
|
|
811
|
-
};
|
|
812
|
-
attempts.push(representationAttempt);
|
|
813
|
-
rejectPdfUrl(representationUrl);
|
|
814
|
-
const response = await request(
|
|
815
|
-
endpoint,
|
|
816
|
-
TRAWLER_FETCH_PATH,
|
|
817
|
-
headers,
|
|
818
|
-
buildTrawlerFetchRequest(representationUrl, true),
|
|
819
|
-
signal,
|
|
820
|
-
);
|
|
821
|
-
aborted();
|
|
822
|
-
representationAttempt.outcome = `HTTP ${response.status}`;
|
|
823
|
-
if (response.status === 200) {
|
|
824
|
-
const content = parseTrawlerContent(response.data);
|
|
825
|
-
const reportedType = parseTrawlerContentType(response.data);
|
|
826
|
-
if (content !== undefined && isPdfContent(content, reportedType)) throw pdfError();
|
|
827
|
-
const document =
|
|
828
|
-
content === undefined
|
|
829
|
-
? undefined
|
|
830
|
-
: representation.read(content, reportedType, resolvedUrl);
|
|
831
|
-
if (document?.body.trim()) {
|
|
832
|
-
const articleUrl = document.articleUrl ?? resolvedUrl;
|
|
833
|
-
const inspection = inspectPage(document.body, articleUrl, document.contentType);
|
|
834
|
-
if (document.completeness) inspection.completeness = document.completeness;
|
|
835
|
-
if (document.notes) inspection.notes = document.notes;
|
|
836
|
-
const defined = (metadata: object | undefined) =>
|
|
837
|
-
Object.fromEntries(
|
|
838
|
-
Object.entries(metadata ?? {}).filter(([, value]) => value !== undefined),
|
|
839
|
-
);
|
|
840
|
-
inspection.metadata = {
|
|
841
|
-
...discovery?.inspection.metadata,
|
|
842
|
-
...defined(document.metadata),
|
|
843
|
-
...defined(inspection.metadata),
|
|
844
|
-
};
|
|
845
|
-
const alternateLanguage =
|
|
846
|
-
inspection.metadata.language ?? document.language ?? representation.language;
|
|
847
|
-
const pageLanguage = discovery?.inspection.metadata.language;
|
|
848
|
-
if (alternateLanguage) inspection.metadata.language = alternateLanguage;
|
|
849
|
-
// The alternate was chosen by base language, so the note compares the same.
|
|
850
|
-
const sameLanguage =
|
|
851
|
-
alternateLanguage?.split("-")[0].toLowerCase() ===
|
|
852
|
-
pageLanguage?.split("-")[0].toLowerCase();
|
|
853
|
-
representationAttempt.outcome =
|
|
854
|
-
alternateLanguage && pageLanguage && !sameLanguage
|
|
855
|
-
? `${inspection.assessment}; alternate language ${alternateLanguage}`
|
|
856
|
-
: inspection.assessment;
|
|
857
|
-
const candidate: Candidate = {
|
|
858
|
-
content: content!,
|
|
859
|
-
resolvedUrl: articleUrl,
|
|
860
|
-
representationUrl,
|
|
861
|
-
source: "live",
|
|
862
|
-
inspection,
|
|
863
|
-
};
|
|
864
|
-
retain(candidate);
|
|
865
|
-
if (!needsRecovery(candidate)) return result(candidate);
|
|
866
|
-
} else {
|
|
867
|
-
representationAttempt.outcome = "no supported article body";
|
|
868
|
-
if (/error|message/i.test(content ?? ""))
|
|
869
|
-
lastError = capText(redactSecrets(jsonOrTextError(content!)), 400);
|
|
870
|
-
}
|
|
871
|
-
} else {
|
|
872
|
-
lastError = capText(
|
|
873
|
-
safeError(fetchError(response.text, response.status, "representation")),
|
|
874
|
-
400,
|
|
875
|
-
);
|
|
876
|
-
representationAttempt.outcome = `HTTP ${response.status}${usable(best) ? "; retained usable copy" : ""}`;
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
|
-
} catch (error) {
|
|
880
|
-
aborted();
|
|
881
|
-
if (representationAttempt)
|
|
882
|
-
recordFailure(representationAttempt, error, usable(best), deadline.aborted);
|
|
883
|
-
if (error instanceof Error && (error as { fatal?: boolean }).fatal && !usable(best))
|
|
884
|
-
throw new WebFetchError(requestedUrl, safeError(error), attempts);
|
|
885
|
-
lastError = capText(repairText(safeError(error)), 400);
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
// A useful partial result beats an error; recovery is bounded to this endpoint.
|
|
889
|
-
if (best && usable(best)) return result(best);
|
|
890
|
-
if (endpointAnswered) break;
|
|
891
|
-
}
|
|
892
|
-
aborted();
|
|
893
|
-
if (best && usable(best)) return result(best);
|
|
894
|
-
if (best && best.inspection.completeness !== "complete" && looksLikeHtml(best.content))
|
|
895
|
-
return result(best);
|
|
896
|
-
if (best)
|
|
897
|
-
lastError =
|
|
898
|
-
best.inspection.assessment === "suspected-shell"
|
|
899
|
-
? "This appears to be a JavaScript-rendered page; this tool cannot render it. Open it in a browser."
|
|
900
|
-
: "Google returned no readable article content. The response may be truncated, blocked, or a page shell; try another representation or open it in a browser.";
|
|
901
|
-
if (deadline.aborted)
|
|
902
|
-
lastError =
|
|
903
|
-
"The web fetch exceeded its overall 10-second deadline. Try again later or open the page in a browser.";
|
|
904
|
-
throw Object.assign(new WebFetchError(requestedUrl, lastError, attempts), { unconvertedCopy });
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
/**
|
|
908
|
-
* Render a result as the block a model or the user reads.
|
|
909
|
-
*
|
|
910
|
-
* The requested URL is only printed when it differs from the source, so a redirect is
|
|
911
|
-
* visible without repeating the same URL twice on ordinary pages, and an incomplete
|
|
912
|
-
* crawler copy is called out rather than passed off as the whole page.
|
|
913
|
-
*/
|
|
914
|
-
export function formatWebFetchResult(result: WebFetchResult, footer = ""): string {
|
|
915
|
-
const prefix = formatWebFetchHeader(result);
|
|
916
|
-
const maxChars = result.maxChars ?? DEFAULT_WEB_FETCH_MAX_CHARS;
|
|
917
|
-
const available = maxChars - prefix.length - footer.length;
|
|
918
|
-
if (available < 1)
|
|
919
|
-
throw new Error(
|
|
920
|
-
"The character budget is too small for page provenance. Open the page in a browser or ask the user to increase ANTIGRAVITY_WEB_FETCH_MAX_CHARS.",
|
|
921
|
-
);
|
|
922
|
-
if (result.content.length <= available) return prefix + result.content + footer;
|
|
923
|
-
|
|
924
|
-
// A saved-page footer already says where the rest is.
|
|
925
|
-
const note = footer ? "\n\n…" : `\n\n… [output truncated at ${maxChars} characters]`;
|
|
926
|
-
let end = Math.max(0, available - note.length);
|
|
927
|
-
for (;;) {
|
|
928
|
-
if (splitsSurrogate(result.content, end)) end -= 1;
|
|
929
|
-
const boundary = safeTruncate(result.content, end);
|
|
930
|
-
// A delimiter line larger than the budget cannot be included in this output.
|
|
931
|
-
end = boundary > end ? result.content.lastIndexOf("\n", end - 1) + 1 : boundary;
|
|
932
|
-
const body = keepFencesClosed(result.content.slice(0, end)) + note;
|
|
933
|
-
if (body.length <= available) return prefix + body + footer;
|
|
934
|
-
if (end === 0) return prefix + note.slice(0, available) + footer;
|
|
935
|
-
end = Math.max(0, end - (body.length - available));
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
type FetchCommandArgs = {
|
|
940
|
-
url: string;
|
|
941
|
-
raw: boolean;
|
|
942
|
-
};
|
|
943
|
-
|
|
944
|
-
/** Parse `/antigravity.fetch [--raw] <url>`. */
|
|
945
|
-
export function parseFetchCommandArgs(args: string): FetchCommandArgs {
|
|
946
|
-
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
947
|
-
const rest: string[] = [];
|
|
948
|
-
let raw = false;
|
|
949
|
-
for (const token of tokens) {
|
|
950
|
-
if (token === "--raw") {
|
|
951
|
-
raw = true;
|
|
952
|
-
continue;
|
|
953
|
-
}
|
|
954
|
-
rest.push(token);
|
|
955
|
-
}
|
|
956
|
-
return { url: rest.join(" "), raw };
|
|
957
|
-
}
|