-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathamp-api.ts
More file actions
193 lines (168 loc) · 5.05 KB
/
amp-api.ts
File metadata and controls
193 lines (168 loc) · 5.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { readFile } from 'fs/promises';
import { join } from 'path';
import { homedir } from 'os';
interface AmpConfig {
url: string;
}
interface AmpAPIResponse<T = unknown> {
ok?: boolean;
result?: T;
error?: {
message?: string;
code?: string;
};
}
async function getAmpConfig(): Promise<AmpConfig> {
const configPath = join(homedir(), '.config', 'amp', 'settings.json');
try {
const content = await readFile(configPath, 'utf-8');
// Remove comments from JSON (Amp config has // comments)
const cleanJson = content.replace(/^\s*\/\/.*$/gm, '');
const config = JSON.parse(cleanJson) as Record<string, unknown>;
return {
url: (config['amp.url'] as string) || 'https://ampcode.com',
};
} catch {
return { url: 'https://ampcode.com' };
}
}
async function getAmpToken(ampUrl = 'https://ampcode.com'): Promise<string | null> {
const secretsPath = join(homedir(), '.local', 'share', 'amp', 'secrets.json');
try {
const content = await readFile(secretsPath, 'utf-8');
const secrets = JSON.parse(content) as Record<string, string>;
// Token is stored as "apiKey@{url}/"
const key = `apiKey@${ampUrl}/`;
return secrets[key] || null;
} catch {
return null;
}
}
const MAX_RETRIES = 3;
const RETRY_BASE_MS = 500;
function isRetryableError(err: unknown): boolean {
if (err instanceof Error) {
const msg = err.message;
if (
msg.includes('ECONNRESET') ||
msg.includes('ETIMEDOUT') ||
msg.includes('ECONNREFUSED') ||
msg.includes('fetch failed') ||
msg.includes('UND_ERR_SOCKET')
) {
return true;
}
const cause = (err as Error & { cause?: Error }).cause;
if (cause instanceof Error) {
return isRetryableError(cause);
}
}
return false;
}
export async function callAmpInternalAPI<T = unknown>(
method: string,
params: Record<string, unknown>,
): Promise<T> {
const config = await getAmpConfig();
const token = await getAmpToken(config.url);
if (!token) {
throw new Error('Not authenticated with Amp. Please run "amp" to log in.');
}
const url = `${config.url}/api/internal?${encodeURIComponent(method)}`;
let lastError: Error | undefined;
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
method,
params,
}),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Amp API error (${response.status}): ${text}`);
}
const result = (await response.json()) as AmpAPIResponse<T>;
if (result.ok === false) {
throw new Error(result.error?.message || result.error?.code || 'Unknown error');
}
return (result.result ?? result) as T;
} catch (err) {
lastError = err as Error;
if (attempt < MAX_RETRIES - 1 && isRetryableError(err)) {
const delay = RETRY_BASE_MS * Math.pow(2, attempt) + Math.random() * 200;
console.warn(
`Amp API call "${method}" failed (attempt ${
attempt + 1
}/${MAX_RETRIES}), retrying in ${Math.round(delay)}ms:`,
lastError.message,
);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
throw err;
}
}
// eslint-disable-next-line @typescript-eslint/only-throw-error -- TODO: wrap lastError in a proper Error
throw lastError;
}
// ── listThreads internal API ────────────────────────────────────────────
export interface AmpThreadTree {
uri: string;
displayName: string;
repository?: { url: string; ref?: string; sha?: string; type?: string };
}
export interface AmpThreadSummary {
id: string;
v: number;
title: string;
created: number;
userLastInteractedAt: number;
messageCount: number;
agentMode: string;
archived: boolean;
creatorUserID: string;
usesDtw: boolean;
env?: {
initial?: {
trees?: AmpThreadTree[];
};
};
relationships?: Array<{
type: string;
role: 'parent' | 'child';
threadID: string;
comment?: string;
}>;
summaryStats?: {
diffStats?: { added: number; changed: number; deleted: number };
messageCount: number;
};
meta: {
visibility: string;
sharedGroupIDs: string[];
};
}
interface ListThreadsResult {
threads: AmpThreadSummary[];
}
/** Maximum threads the Amp API returns in a single call. */
export const AMP_API_MAX = 500;
/**
* Fetch threads from the Amp internal API.
*
* The API's `offset` parameter is silently ignored — it always returns the
* same set of threads regardless of offset. So we make a single call with
* limit capped at 500 (the API maximum).
*/
export async function listThreads(): Promise<AmpThreadSummary[]> {
const result = await callAmpInternalAPI<ListThreadsResult>('listThreads', {
limit: AMP_API_MAX,
});
return result.threads;
}