Repository navigation
Expand file tree
/
Copy pathcustom-amp-agent.ts
More file actions
179 lines (157 loc) · 6.63 KB
/
Copy pathcustom-amp-agent.ts
File metadata and controls
179 lines (157 loc) · 6.63 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
import { Agent, Box } from "@upstash/box";
// Amp custom agent harness (ampcode.com)
//
// Runs the Amp CLI in execute mode and translates its Claude Code-compatible
// stream JSON into box-sse-v1 events. Box sessions map to Amp threads.
// MCP servers are passed with --mcp-config; prompt files are inlined (text)
// or saved under /workspace/home/.box-attachments (images, PDFs).
//
// Needs AMP_API_KEY: an access token from ampcode.com/settings (Security),
// starts with sgamp_. The model is an Amp mode: low, medium, high, or ultra.
//
// Cost is reported as 0: Amp's stream JSON has token counts but no price. Amp
// bills in credits; `amp threads usage <thread-id>` shows a thread's cost.
const agentSource = String.raw`
import { spawn } from "child_process";
import { randomUUID } from "crypto";
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
import { basename } from "path";
import { createInterface } from "readline";
const WORK_DIR = "/workspace/home";
const ATTACHMENTS_DIR = WORK_DIR + "/.box-attachments";
const MCP_CONFIG_PATH = WORK_DIR + "/.box-internal/mcp-config.json";
const args = process.argv.slice(2);
const readArg = (name) => {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : undefined;
};
const mode = readArg("--model");
const session = readArg("--session");
const emit = (event, data) => process.stdout.write("event: " + event + "\ndata: " + JSON.stringify(data) + "\n\n");
const TEXT_TYPES = ["application/json", "application/javascript", "application/typescript",
"application/xml", "application/yaml", "application/toml", "application/sql"];
const isText = (mime) => mime.startsWith("text/") || TEXT_TYPES.includes(mime.split(";")[0]);
// Text files are inlined; other files (images, PDFs) are saved so Amp can read them by path.
function buildPrompt(base) {
const filesPath = process.env.PROMPT_FILES_PATH;
if (!filesPath) return base;
const files = JSON.parse(readFileSync(filesPath, "utf-8"));
try { unlinkSync(filesPath); } catch {}
const fence = String.fromCharCode(96, 96, 96);
let prompt = base;
files.forEach((f, i) => {
const name = basename(f.filename || "file-" + i);
const data = Buffer.from(f.data, "base64");
if (isText(f.media_type)) {
prompt += "\n\nAttached file: " + name + "\n" + fence + "\n" + data.toString("utf-8") + "\n" + fence;
} else {
const dir = ATTACHMENTS_DIR + "/" + randomUUID();
mkdirSync(dir, { recursive: true });
writeFileSync(dir + "/" + name, data);
prompt += "\n\nAttached file: " + dir + "/" + name;
}
});
return prompt;
}
function mcpConfig() {
let servers;
try { servers = JSON.parse(readFileSync(MCP_CONFIG_PATH, "utf-8")); } catch { return []; }
const config = {};
for (const s of servers) {
config[s.name] = s.source === "npm"
? { command: "npx", args: ["-y", s.package_or_url, ...(s.args ?? [])], env: s.headers ?? {} }
: { url: s.package_or_url, headers: s.headers ?? {} };
}
return servers.length ? ["--mcp-config", JSON.stringify(config)] : [];
}
if (process.env.JSON_SCHEMA) console.error("[amp] Warning: JSON_SCHEMA is not supported by the Amp harness");
if (process.env.AGENT_OPTIONS) console.error("[amp] Warning: AGENT_OPTIONS are not supported by the Amp harness");
const ampArgs = [
...(session ? ["threads", "continue", session] : ["--no-archive-after-execute"]),
"--dangerously-allow-all",
"--stream-json",
...mcpConfig(),
...(mode && mode !== "custom" ? ["-m", mode] : []),
"-x", buildPrompt(readArg("-p") ?? ""),
];
const amp = spawn("amp", ampArgs, { cwd: WORK_DIR, stdio: ["ignore", "pipe", "pipe"] });
let stderr = "";
amp.stderr.on("data", (d) => { stderr = (stderr + d).slice(-4000); });
let threadId = session ?? "";
let output = "";
let inputTokens = 0, outputTokens = 0, cachedInputTokens = 0;
let finished = false;
for await (const line of createInterface({ input: amp.stdout })) {
let event;
try { event = JSON.parse(line); } catch { continue; }
if (event.session_id) threadId = event.session_id;
if (event.type === "assistant") {
const usage = event.message?.usage ?? {};
inputTokens += (usage.input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
cachedInputTokens += usage.cache_read_input_tokens ?? 0;
outputTokens += usage.output_tokens ?? 0;
for (const part of event.message?.content ?? []) {
if (part.type === "text") emit("text", { text: part.text });
if (part.type === "tool_use") emit("tool", { name: part.name, toolCallId: part.id, input: part.input ?? {} });
}
} else if (event.type === "user") {
for (const part of event.message?.content ?? []) {
if (part.type !== "tool_result") continue;
const content = typeof part.content === "string" ? part.content : JSON.stringify(part.content);
emit("tool_result", { toolCallId: part.tool_use_id, output: content, is_error: part.is_error ?? false });
}
} else if (event.type === "result") {
finished = true;
const meta = { input_tokens: inputTokens, output_tokens: outputTokens, cached_input_tokens: cachedInputTokens, total_cost_usd: 0, session_id: threadId };
if (event.is_error) emit("error", { error: event.error ?? event.result ?? "Amp run failed", ...meta });
else emit("done", { output: event.result ?? output, ...meta });
}
}
const code = await new Promise((resolve) => amp.on("close", resolve));
if (!finished) {
emit("error", { error: "amp exited with code " + code + ": " + stderr.trim().split("\n").slice(-5).join("\n"), session_id: threadId });
process.exit(1);
}
`;
const box = await Box.create({
apiKey: process.env.UPSTASH_BOX_API_KEY!,
baseUrl: process.env.UPSTASH_BOX_BASE_URL,
runtime: "node",
agent: {
harness: Agent.Custom,
model: "medium",
customHarness: {
command: "node",
args: ["/workspace/home/custom-amp-agent.mjs"],
protocol: "box-sse-v1",
},
},
env: {
AMP_API_KEY: process.env.AMP_API_KEY!,
},
});
console.log(`Created box: ${box.id}`);
try {
console.log("Installing Amp...");
await box.exec.command("sudo -n npm install -g @sourcegraph/amp");
await box.files.write({
path: "custom-amp-agent.mjs",
content: agentSource,
});
console.log("\n=== Turn 1 ===");
const run1 = await box.agent.run({
prompt: "Create a file called hello.txt with the content 'Hello from Amp!'",
});
console.log(run1.result);
console.log("\n=== Turn 2 (follow-up) ===");
const stream = await box.agent.stream({
prompt: "Now read back the file you just created.",
});
for await (const chunk of stream) {
if (chunk.type === "text-delta") process.stdout.write(chunk.text);
}
console.log();
} finally {
await box.delete();
console.log("\nBox deleted.");
}