@curl.md/amp 0.0.0 → 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 weth, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @curl.md/amp
2
+
3
+ Amp plugin for `curl.md`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm dlx @curl.md/amp install
9
+ ```
10
+
11
+ ## License
12
+
13
+ [MIT](https://github.com/wevm/curl.md/blob/main/LICENSE)
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import process from 'node:process';
7
+ import { fileURLToPath } from 'node:url';
8
+ if (isMain())
9
+ await main();
10
+ export async function installAmpPlugin(options = {}) {
11
+ const env = options.env || process.env;
12
+ const platform = options.platform || process.platform;
13
+ const packageJson = options.packageJson || (await readPackageJson());
14
+ const ampConfigDir = options.ampConfigDir || getAmpConfigDir(env, platform);
15
+ const packageSpec = `${packageJson.name}@${packageJson.version}`;
16
+ await ensurePackageJson(ampConfigDir);
17
+ installPackage(ampConfigDir, packageSpec, options.spawnSync || spawnSync, env);
18
+ const shimPath = await writePluginShim(ampConfigDir);
19
+ return { ampConfigDir, packageSpec, shimPath };
20
+ }
21
+ export function getAmpConfigDir(env = process.env, platform = process.platform) {
22
+ if (env.AMP_CONFIG_DIR)
23
+ return env.AMP_CONFIG_DIR;
24
+ if (platform === 'win32') {
25
+ const appData = env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
26
+ return path.join(appData, 'amp');
27
+ }
28
+ const configHome = env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
29
+ return path.join(configHome, 'amp');
30
+ }
31
+ async function main() {
32
+ const command = process.argv[2];
33
+ if (command && command !== 'install') {
34
+ console.error('Usage: pnpm dlx @curl.md/amp install');
35
+ process.exitCode = 1;
36
+ return;
37
+ }
38
+ try {
39
+ const result = await installAmpPlugin();
40
+ console.log(`Installed ${result.packageSpec}`);
41
+ console.log(`Amp config: ${result.ampConfigDir}`);
42
+ console.log(`Plugin shim: ${result.shimPath}`);
43
+ console.log('Next: run `amp`. If auth is needed, set `CURLMD_API_KEY` or run `curl.md auth login`.');
44
+ }
45
+ catch (error) {
46
+ console.error(error instanceof Error ? error.message : String(error));
47
+ process.exitCode = 1;
48
+ }
49
+ }
50
+ async function ensurePackageJson(ampConfigDir) {
51
+ await fs.mkdir(ampConfigDir, { recursive: true });
52
+ const packageJsonPath = path.join(ampConfigDir, 'package.json');
53
+ try {
54
+ await fs.access(packageJsonPath);
55
+ }
56
+ catch {
57
+ await fs.writeFile(packageJsonPath, `${JSON.stringify({ name: 'amp-plugins', private: true }, undefined, 2)}\n`, 'utf8');
58
+ }
59
+ }
60
+ function installPackage(ampConfigDir, packageSpec, spawn, env) {
61
+ const result = spawn('pnpm', ['add', '--save-exact', packageSpec], {
62
+ cwd: ampConfigDir,
63
+ env,
64
+ stdio: 'inherit',
65
+ });
66
+ if (result.error)
67
+ throw result.error;
68
+ if (result.status === 0)
69
+ return;
70
+ throw new Error(`Failed to install ${packageSpec} into ${ampConfigDir}.`);
71
+ }
72
+ async function readPackageJson() {
73
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
74
+ const packageJsonPath = path.join(currentDir, path.basename(currentDir) === 'dist' ? '..' : '.', 'package.json');
75
+ return JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
76
+ }
77
+ async function writePluginShim(ampConfigDir) {
78
+ const pluginsDir = path.join(ampConfigDir, 'plugins');
79
+ const shimPath = path.join(pluginsDir, 'curlmd.ts');
80
+ await fs.mkdir(pluginsDir, { recursive: true });
81
+ await fs.writeFile(shimPath, [
82
+ '// @i-know-the-amp-plugin-api-is-wip-and-very-experimental-right-now',
83
+ "import plugin from '@curl.md/amp'",
84
+ '',
85
+ 'export default plugin',
86
+ '',
87
+ ].join('\n'), 'utf8');
88
+ return shimPath;
89
+ }
90
+ function isMain() {
91
+ if (!process.argv[1])
92
+ return false;
93
+ return path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
94
+ }
package/package.json CHANGED
@@ -1,5 +1,39 @@
1
1
  {
2
- "name": "@curl.md/amp",
3
- "version": "0.0.0",
4
- "license": "MIT"
5
- }
2
+ "name": "@curl.md/amp",
3
+ "version": "0.0.1",
4
+ "description": "curl.md plugin for Amp",
5
+ "bin": {
6
+ "curlmd-amp": "./dist/install.js"
7
+ },
8
+ "contributors": [
9
+ "awkweb.eth <t@wevm.dev>",
10
+ "jxom.eth <j@wevm.dev>"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/wevm/curl.md.git",
16
+ "directory": "plugins/amp"
17
+ },
18
+ "funding": "https://github.com/sponsors/wevm",
19
+ "keywords": [
20
+ "curl.md",
21
+ "amp",
22
+ "markdown"
23
+ ],
24
+ "exports": {
25
+ ".": {
26
+ "types": "./plugin.ts",
27
+ "default": "./plugin.ts"
28
+ }
29
+ },
30
+ "files": [
31
+ "README.md",
32
+ "dist",
33
+ "plugin.ts"
34
+ ],
35
+ "type": "module",
36
+ "dependencies": {
37
+ "curl.md": "0.0.15"
38
+ }
39
+ }
package/plugin.ts ADDED
@@ -0,0 +1,224 @@
1
+ // @i-know-the-amp-plugin-api-is-wip-and-very-experimental-right-now
2
+ import type { PluginAPI } from '@ampcode/plugin'
3
+ import { createClient, defaultBaseUrl } from 'curl.md'
4
+ import { Auth, Session } from 'curl.md/internal'
5
+
6
+ export default function (amp: PluginAPI) {
7
+ const baseUrl = process.env.CURLMD_BASE_URL || defaultBaseUrl
8
+ const apiKey = process.env.CURLMD_API_KEY
9
+ const resolver = Auth.createResolver(baseUrl, apiKey)
10
+
11
+ amp.on('tool.call', async (event, ctx) => {
12
+ if (event.tool !== 'read_web_page') return { action: 'allow' }
13
+ ctx.logger.log(`curl.md intercepting read_web_page: ${String(event.input.url)}`)
14
+
15
+ try {
16
+ const result = await fetchPage({
17
+ fresh: event.input.fresh as boolean | undefined,
18
+ keywords: event.input.keywords as string[] | undefined,
19
+ mode: event.input.mode as 'rush' | 'smart' | undefined,
20
+ objective: event.input.objective as string | undefined,
21
+ url: event.input.url as string,
22
+ })
23
+ return { action: 'synthesize', result: { output: result.markdown } }
24
+ } catch (error) {
25
+ return {
26
+ action: 'reject-and-continue',
27
+ message: error instanceof Error ? error.message : String(error),
28
+ }
29
+ }
30
+ })
31
+
32
+ amp.registerTool({
33
+ name: 'md_fetch',
34
+ description:
35
+ 'Read the contents of a web page at a given URL via curl.md and return markdown optimized for coding agents. Fallback for read_web_page interception.',
36
+ inputSchema: {
37
+ type: 'object',
38
+ properties: {
39
+ url: {
40
+ type: 'string',
41
+ description:
42
+ 'HTTP(S) URL or bare domain to fetch via curl.md. Prefer the canonical docs or article URL you want summarized.',
43
+ },
44
+ objective: {
45
+ type: 'string',
46
+ description:
47
+ 'Specific question or goal to answer from the page. Prefer concrete objectives like "compare pricing tiers" or "find auth header requirements".',
48
+ },
49
+ keywords: {
50
+ type: 'array',
51
+ items: { type: 'string' },
52
+ description:
53
+ 'Keywords to pre-filter sections by. Prefer 2-5 distinct terms when only part of a long page matters.',
54
+ },
55
+ mode: {
56
+ type: 'string',
57
+ enum: ['rush', 'smart'],
58
+ description:
59
+ 'rush: lower-latency, best when you already know the section. smart: higher-quality narrowing for long or noisy pages.',
60
+ },
61
+ fresh: {
62
+ type: 'boolean',
63
+ description:
64
+ 'Bypass curl.md cache when freshness matters, such as changelogs, release notes, or recently updated docs.',
65
+ },
66
+ },
67
+ required: ['url'],
68
+ },
69
+ async execute(input) {
70
+ return fetchPage({
71
+ fresh: input.fresh as boolean | undefined,
72
+ keywords: input.keywords as string[] | undefined,
73
+ mode: input.mode as 'rush' | 'smart' | undefined,
74
+ objective: input.objective as string | undefined,
75
+ url: input.url as string,
76
+ })
77
+ },
78
+ })
79
+
80
+ async function fetchPage(input: {
81
+ fresh?: boolean
82
+ keywords?: string[]
83
+ mode?: 'rush' | 'smart'
84
+ objective?: string
85
+ url: string
86
+ }) {
87
+ const url = (() => {
88
+ const url = new URL(input.url.includes('://') ? input.url : `https://${input.url}`)
89
+ if (!/^https?:$/.test(url.protocol)) throw new Error('URL must use http or https')
90
+ return url.toString()
91
+ })()
92
+
93
+ let authHeaders = await resolver()
94
+ let authType: 'anon' | 'api_key' | 'session' = (() => {
95
+ if (apiKey) return 'api_key'
96
+ if (authHeaders) return 'session'
97
+ return 'anon'
98
+ })()
99
+
100
+ const fetchParams = {
101
+ fresh: input.fresh,
102
+ keywords: input.keywords,
103
+ mode: input.mode,
104
+ objective: input.objective,
105
+ }
106
+
107
+ const client = createClient(baseUrl, {
108
+ headers: apiKey ? createHeaders(null) : createHeaders(authHeaders),
109
+ })
110
+ let res = await client.fetch(url, { ...fetchParams, token: apiKey })
111
+
112
+ if (res.status === 401 && authType === 'session') {
113
+ authHeaders = await resolver()
114
+ if (!authHeaders) authType = 'anon'
115
+ const retryClient = createClient(baseUrl, {
116
+ headers: apiKey ? createHeaders(null) : createHeaders(authHeaders),
117
+ })
118
+ res = await retryClient.fetch(url, { ...fetchParams, token: apiKey })
119
+ }
120
+
121
+ if (res.status === 400) {
122
+ const json = await res.json()
123
+ const errorMessage = (() => {
124
+ if (
125
+ typeof json !== 'object' ||
126
+ json === null ||
127
+ !('issues' in json) ||
128
+ !Array.isArray(json.issues)
129
+ )
130
+ return json.message
131
+
132
+ return json.issues
133
+ .map((issue: { path: string; message: string }) => `${issue.path}: ${issue.message}`)
134
+ .join('\n')
135
+ })()
136
+ throw new Error(errorMessage)
137
+ }
138
+
139
+ if (res.status === 401) {
140
+ if (authType === 'api_key')
141
+ throw new Error('curl.md authentication failed. Fix CURLMD_API_KEY.')
142
+ if (authType === 'session')
143
+ throw new Error('curl.md authentication failed. Run `curl.md auth login` again.')
144
+ throw new Error(
145
+ 'curl.md authentication required. Set CURLMD_API_KEY or run `curl.md auth login`.',
146
+ )
147
+ }
148
+
149
+ if (res.status === 403) {
150
+ const json = await res.json()
151
+ Session.write({ organization_id: undefined }, baseUrl)
152
+ if (authType === 'api_key') throw new Error(`${json.message}. Check CURLMD_API_KEY access.`)
153
+ throw new Error(`${json.message}. Set CURLMD_API_KEY or run \`curl.md auth login\`.`)
154
+ }
155
+
156
+ if (res.status === 429) {
157
+ const json = await res.json()
158
+ const retryAfter = res.headers.get('retry-after')
159
+ const message = retryAfter ? `${json.message}. Try again in ${retryAfter}s` : json.message
160
+
161
+ if (authType === 'anon')
162
+ throw new Error(
163
+ `${message}. Set CURLMD_API_KEY or run \`curl.md auth login\` for higher limits.`,
164
+ )
165
+
166
+ throw new Error(`${message}. Add credits with \`curl.md credits add\` if needed.`)
167
+ }
168
+
169
+ if (!res.ok) {
170
+ const json = await res
171
+ .clone()
172
+ .json()
173
+ .catch(() => undefined)
174
+ const error = parseApiError(json)
175
+ if (error) throw new Error(formatApiError(error))
176
+
177
+ const text = await res.text()
178
+ throw new Error(text || `curl.md request failed with status ${res.status}`)
179
+ }
180
+
181
+ const json = await res.json()
182
+ return {
183
+ auth: authType,
184
+ cache: res.headers.get('x-cache') || undefined,
185
+ credits_remaining: parseNumberHeader(res.headers.get('x-credits-remaining')),
186
+ fresh: input.fresh || undefined,
187
+ keywords: input.keywords,
188
+ markdown: json.content,
189
+ mode: input.mode,
190
+ objective: input.objective,
191
+ request_id: res.headers.get('x-request-id') || undefined,
192
+ tokens_count: parseNumberHeader(res.headers.get('x-tokens-count')),
193
+ tokens_saved: parseNumberHeader(res.headers.get('x-tokens-saved')),
194
+ url,
195
+ }
196
+ }
197
+ }
198
+
199
+ function createHeaders(auth: Auth.Headers | null) {
200
+ const headers: Record<string, string> = { accept: 'application/json' }
201
+ if (auth?.authorization) headers.authorization = auth.authorization
202
+ if (auth?.organization_id) headers['x-organization-id'] = auth.organization_id
203
+ return headers
204
+ }
205
+
206
+ function parseApiError(json: unknown) {
207
+ if (typeof json !== 'object' || json === null) return undefined
208
+ if (!('message' in json) || typeof json.message !== 'string') return undefined
209
+ return {
210
+ code:
211
+ 'code' in json && typeof json.code === 'string' ? json.code.toUpperCase() : 'REQUEST_FAILED',
212
+ message: json.message,
213
+ }
214
+ }
215
+
216
+ function formatApiError(error: { code: string; message: string }) {
217
+ return `(${error.code}) ${error.message}`
218
+ }
219
+
220
+ function parseNumberHeader(value: string | null) {
221
+ if (!value) return undefined
222
+ const number = Number(value)
223
+ return Number.isFinite(number) ? number : undefined
224
+ }