@telegraphprotocol/telegraph-protocol-mcp 2.1.0 → 2.2.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/.agents/skills/anjoman/SKILL.md +94 -0
- package/.agents/skills/anjoman/scripts/anjoman.mjs +594 -0
- package/.agents/skills/telegraph/SKILL.md +70 -69
- package/LICENSE +21 -21
- package/README.md +127 -119
- package/dist/api.d.ts +7 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +11 -1
- package/dist/api.js.map +1 -1
- package/dist/chain.d.ts +16 -12
- package/dist/chain.d.ts.map +1 -1
- package/dist/chain.js +45 -29
- package/dist/chain.js.map +1 -1
- package/dist/cli.js +26 -21
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +14 -4
- package/dist/config.js.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/pay.d.ts +2 -0
- package/dist/pay.d.ts.map +1 -1
- package/dist/pay.js +20 -2
- package/dist/pay.js.map +1 -1
- package/dist/tools.d.ts +5 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +88 -37
- package/dist/tools.js.map +1 -1
- package/guides/1-getting-started.md +44 -42
- package/guides/2-payments.md +44 -43
- package/guides/3-intents-and-ranking.md +29 -29
- package/guides/4-troubleshooting.md +45 -41
- package/package.json +63 -63
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Anjoman skill client. One file, no dependencies, Node 18+.
|
|
3
|
+
//
|
|
4
|
+
// Sends a request to Anjoman's agent (POST /agent/chat) with the user's API key and prints the result for an AI agent
|
|
5
|
+
// to read: the answer, what it cost, which sources answered with their receipts, and the conversation id for a follow-up.
|
|
6
|
+
// Anjoman does the planning, the choice of miners, the combining and the recovery; this file only carries the request.
|
|
7
|
+
//
|
|
8
|
+
// node anjoman.mjs ask "What is the BTC price?" [--conversation <id>] [--max-spend <usd>] [--json] [--quiet]
|
|
9
|
+
// node anjoman.mjs auto "BTC price" [--intent X --params JSON] [--json] auto-routed ask: the node picks the miner
|
|
10
|
+
// node anjoman.mjs miner <id|slug> ["question"] [--intent X --params JSON | --endpoint /p --method GET --payload JSON]
|
|
11
|
+
// miner call: one named miner, no routing
|
|
12
|
+
// node anjoman.mjs job <jobId> [--wait] read a request that is still running, or ended
|
|
13
|
+
// node anjoman.mjs cancel <jobId> stop a request that is still running
|
|
14
|
+
// node anjoman.mjs balance the account's escrow balance and recent spend
|
|
15
|
+
// node anjoman.mjs login save the API key (read from the terminal or standard input)
|
|
16
|
+
// node anjoman.mjs rule print the short always-on rule for an agent's instruction file
|
|
17
|
+
|
|
18
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import { createInterface } from "node:readline";
|
|
22
|
+
import { pathToFileURL } from "node:url";
|
|
23
|
+
|
|
24
|
+
const DEFAULT_URL = "https://backend.telegraphprotocol.com";
|
|
25
|
+
/** The Telegraph node, read only to find a miner's id from its slug for a miner call. */
|
|
26
|
+
const DEFAULT_NODE_URL = "https://devnode.telegraphprotocol.com";
|
|
27
|
+
/** An auto-routed ask or a miner call answers in one reply: the node's own deadline is 60 seconds, plus payment. */
|
|
28
|
+
const ENGINE_WAIT_MS = 120_000;
|
|
29
|
+
/**
|
|
30
|
+
* The user sets their spending limit in Anjoman, on their account, and the backend applies it to every request from the
|
|
31
|
+
* account, whatever is sent here. This script adds no cap of its own unless --max-spend or ANJOMAN_MAX_SPEND_USD asks for
|
|
32
|
+
* a lower one for a session; with neither set, the account's limit (or, with none, its balance) is all that applies.
|
|
33
|
+
* When a cap applies, the backend stops the job at that amount and asks for approval. It holds back each call's quoted
|
|
34
|
+
* ceiling (about $0.26) from the cap while the call runs and gives back what the call did not cost, so a request that asks
|
|
35
|
+
* several specialists at once needs a cap with room for each, well above what such a request really costs.
|
|
36
|
+
*/
|
|
37
|
+
const DEFAULT_MAX_SPEND_USD = undefined;
|
|
38
|
+
/** How long a request that outlives its connection is followed before handing back its job id. */
|
|
39
|
+
const DEFAULT_WAIT_MINUTES = 15;
|
|
40
|
+
const POLL_MS = 3_000;
|
|
41
|
+
const CLOSE_OUT_MS = 10_000;
|
|
42
|
+
const EXIT = { ok: 0, error: 1, usage: 2, needsApproval: 3 };
|
|
43
|
+
|
|
44
|
+
const env = process.env;
|
|
45
|
+
const apiUrl = () => (env.ANJOMAN_API_URL || env.TELEGRAPH_API_URL || DEFAULT_URL).replace(/\/$/, "");
|
|
46
|
+
const nodeUrl = () => (env.ANJOMAN_NODE_URL || env.TELEGRAPH_URL || DEFAULT_NODE_URL).replace(/\/$/, "");
|
|
47
|
+
const homeDir = () => env.ANJOMAN_HOME || join(homedir(), ".anjoman");
|
|
48
|
+
const keyFile = () => join(homeDir(), "key");
|
|
49
|
+
|
|
50
|
+
class Fail extends Error {
|
|
51
|
+
constructor(message, code = EXIT.error) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.code = code;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ─── The key ────────────────────────────────────────────────────────────────────────────────────
|
|
58
|
+
|
|
59
|
+
function readKey() {
|
|
60
|
+
const fromEnv = (env.ANJOMAN_API_KEY || env.TELEGRAPH_API_KEY || "").trim();
|
|
61
|
+
if (fromEnv) return fromEnv;
|
|
62
|
+
try {
|
|
63
|
+
if (existsSync(keyFile())) return readFileSync(keyFile(), "utf8").trim();
|
|
64
|
+
} catch {
|
|
65
|
+
// Unreadable: treated as no key, with the same instructions.
|
|
66
|
+
}
|
|
67
|
+
return "";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function requireKey() {
|
|
71
|
+
const key = readKey();
|
|
72
|
+
if (!key) {
|
|
73
|
+
throw new Fail(
|
|
74
|
+
"No Anjoman API key. Ask the user to create one at https://anjoman.ai/dashboard/api-keys, then either set ANJOMAN_API_KEY or run:\n" +
|
|
75
|
+
" node anjoman.mjs login\n" +
|
|
76
|
+
"Never ask for the key in chat and never print it.",
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return key;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Reads the key without echoing it when typed, or from standard input when piped. */
|
|
83
|
+
async function readSecret() {
|
|
84
|
+
if (!process.stdin.isTTY) {
|
|
85
|
+
const chunks = [];
|
|
86
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
87
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
88
|
+
}
|
|
89
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
90
|
+
const write = rl._writeToOutput;
|
|
91
|
+
rl._writeToOutput = (s) => (s.includes("\n") || s.includes("\r") ? write.call(rl, s) : undefined);
|
|
92
|
+
process.stderr.write("Anjoman API key: ");
|
|
93
|
+
const answer = await new Promise((resolve) => rl.question("", resolve));
|
|
94
|
+
rl.close();
|
|
95
|
+
process.stderr.write("\n");
|
|
96
|
+
return String(answer).trim();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function login() {
|
|
100
|
+
const key = await readSecret();
|
|
101
|
+
if (!key) throw new Fail("No key was given.", EXIT.usage);
|
|
102
|
+
mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
|
|
103
|
+
writeFileSync(keyFile(), `${key}\n`, { mode: 0o600 });
|
|
104
|
+
try {
|
|
105
|
+
chmodSync(keyFile(), 0o600);
|
|
106
|
+
} catch {
|
|
107
|
+
// Windows has no file modes; the file is still in the user's own profile.
|
|
108
|
+
}
|
|
109
|
+
console.log(`Saved the key to ${keyFile()} (readable only by you).`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ─── Talking to the API ─────────────────────────────────────────────────────────────────────────
|
|
113
|
+
|
|
114
|
+
/** What the user should do about a refused request, in the words of the status. */
|
|
115
|
+
function hintFor(status) {
|
|
116
|
+
if (status === 401) return "The API key was rejected: it may be wrong, expired or revoked. Ask the user to check or create a key at https://anjoman.ai/dashboard/api-keys.";
|
|
117
|
+
if (status === 402) return "The account cannot pay for this. Ask the user to add funds in Anjoman (Deposit in the wallet menu).";
|
|
118
|
+
if (status === 403) return "This key is not allowed to do that.";
|
|
119
|
+
if (status === 429) return "Too many requests (a key makes up to 30 a minute). Wait a minute and try again.";
|
|
120
|
+
return "";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function failureOf(res, path) {
|
|
124
|
+
const text = await res.text().catch(() => "");
|
|
125
|
+
let message = "";
|
|
126
|
+
try {
|
|
127
|
+
const body = JSON.parse(text);
|
|
128
|
+
message = Array.isArray(body.message) ? body.message.join(", ") : body.message || body.error || "";
|
|
129
|
+
} catch {
|
|
130
|
+
message = text.slice(0, 300);
|
|
131
|
+
}
|
|
132
|
+
const hint = hintFor(res.status);
|
|
133
|
+
return new Fail(`${res.status} from ${path}: ${message || "no message"}${hint ? `\n${hint}` : ""}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function api(method, path, body, { signal } = {}) {
|
|
137
|
+
const key = requireKey();
|
|
138
|
+
let res;
|
|
139
|
+
try {
|
|
140
|
+
res = await fetch(`${apiUrl()}${path}`, {
|
|
141
|
+
method,
|
|
142
|
+
headers: { Authorization: `Bearer ${key}`, Accept: "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
143
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
144
|
+
signal: signal ?? AbortSignal.timeout(30_000),
|
|
145
|
+
});
|
|
146
|
+
} catch (err) {
|
|
147
|
+
throw new Fail(`Could not reach Anjoman at ${apiUrl()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
148
|
+
}
|
|
149
|
+
if (!res.ok) throw await failureOf(res, path);
|
|
150
|
+
const text = await res.text();
|
|
151
|
+
return text ? JSON.parse(text) : {};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Server-sent events as { event, data } objects, as they arrive. */
|
|
155
|
+
async function* events(res) {
|
|
156
|
+
const decoder = new TextDecoder();
|
|
157
|
+
let buffer = "";
|
|
158
|
+
for await (const chunk of res.body) {
|
|
159
|
+
buffer += decoder.decode(chunk, { stream: true }).replace(/\r\n/g, "\n");
|
|
160
|
+
let end;
|
|
161
|
+
while ((end = buffer.indexOf("\n\n")) !== -1) {
|
|
162
|
+
const frame = buffer.slice(0, end);
|
|
163
|
+
buffer = buffer.slice(end + 2);
|
|
164
|
+
let event = "message";
|
|
165
|
+
const data = [];
|
|
166
|
+
for (const line of frame.split("\n")) {
|
|
167
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
168
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
|
|
169
|
+
}
|
|
170
|
+
if (data.length === 0) continue;
|
|
171
|
+
try {
|
|
172
|
+
yield { event, data: JSON.parse(data.join("\n")) };
|
|
173
|
+
} catch {
|
|
174
|
+
// A frame that is not JSON carries nothing we use.
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ─── ask ────────────────────────────────────────────────────────────────────────────────────────
|
|
181
|
+
|
|
182
|
+
function parseFlags(args, spec) {
|
|
183
|
+
const flags = {};
|
|
184
|
+
const rest = [];
|
|
185
|
+
for (let i = 0; i < args.length; i++) {
|
|
186
|
+
const a = args[i];
|
|
187
|
+
if (!a.startsWith("--")) {
|
|
188
|
+
rest.push(a);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const name = a.slice(2);
|
|
192
|
+
if (!(name in spec)) throw new Fail(`Unknown option --${name}.`, EXIT.usage);
|
|
193
|
+
if (spec[name] === "boolean") flags[name] = true;
|
|
194
|
+
else {
|
|
195
|
+
const value = args[++i];
|
|
196
|
+
if (value === undefined) throw new Fail(`--${name} needs a value.`, EXIT.usage);
|
|
197
|
+
flags[name] = value;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return { flags, rest };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function spendCap(flag) {
|
|
204
|
+
const raw = flag ?? env.ANJOMAN_MAX_SPEND_USD;
|
|
205
|
+
if (raw === undefined || raw === "") return DEFAULT_MAX_SPEND_USD;
|
|
206
|
+
if (raw === "0" || raw === "none" || raw === "off") return undefined;
|
|
207
|
+
const n = Number(raw);
|
|
208
|
+
if (!Number.isFinite(n) || n <= 0) throw new Fail(`The spend cap must be a positive number of dollars, or "none": got "${raw}".`, EXIT.usage);
|
|
209
|
+
return Math.round(n * 1e6) / 1e6;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Dollars to the cent, with more digits only where a small amount needs them: $0.50, $0.0123. */
|
|
213
|
+
const usd = (n) => (typeof n === "number" ? `$${n.toFixed(4).replace(/(\.\d{2}\d*?)0+$/, "$1")}` : "unknown");
|
|
214
|
+
const seconds = (ms) => (typeof ms === "number" ? `${(ms / 1000).toFixed(1)}s` : "");
|
|
215
|
+
|
|
216
|
+
async function readMessage(words) {
|
|
217
|
+
if (words.length === 1 && words[0] === "-") {
|
|
218
|
+
const chunks = [];
|
|
219
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
220
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
221
|
+
}
|
|
222
|
+
return words.join(" ").trim();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function ask(args) {
|
|
226
|
+
const { flags, rest } = parseFlags(args, { conversation: "value", "max-spend": "value", json: "boolean", quiet: "boolean", wait: "value" });
|
|
227
|
+
const message = await readMessage(rest);
|
|
228
|
+
if (!message) throw new Fail('Give the request, e.g. node anjoman.mjs ask "What is the BTC price in USD?"', EXIT.usage);
|
|
229
|
+
const maxSpendUsd = spendCap(flags["max-spend"]);
|
|
230
|
+
const waitMs = Number(flags.wait ?? DEFAULT_WAIT_MINUTES) * 60_000;
|
|
231
|
+
const progress = (text) => {
|
|
232
|
+
if (!flags.quiet && !flags.json) process.stderr.write(`… ${text}\n`);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const run = { conversationId: flags.conversation, jobId: undefined, steps: [], done: undefined, error: undefined };
|
|
236
|
+
const controller = new AbortController();
|
|
237
|
+
const timer = setTimeout(() => controller.abort(), waitMs);
|
|
238
|
+
try {
|
|
239
|
+
const key = requireKey();
|
|
240
|
+
let res;
|
|
241
|
+
try {
|
|
242
|
+
res = await fetch(`${apiUrl()}/agent/chat`, {
|
|
243
|
+
method: "POST",
|
|
244
|
+
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", Accept: "text/event-stream, application/json" },
|
|
245
|
+
body: JSON.stringify({ message, ...(flags.conversation && { conversationId: flags.conversation }), ...(maxSpendUsd !== undefined && { maxSpendUsd }) }),
|
|
246
|
+
signal: controller.signal,
|
|
247
|
+
});
|
|
248
|
+
} catch (err) {
|
|
249
|
+
throw new Fail(`Could not reach Anjoman at ${apiUrl()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
250
|
+
}
|
|
251
|
+
if (!res.ok) throw await failureOf(res, "/agent/chat");
|
|
252
|
+
|
|
253
|
+
try {
|
|
254
|
+
for await (const { event, data } of events(res)) {
|
|
255
|
+
if (event === "conversation") run.conversationId = data.conversationId;
|
|
256
|
+
else if (event === "job") run.jobId = data.jobId;
|
|
257
|
+
else if (event === "status") progress(data.message || data.stage);
|
|
258
|
+
else if (event === "trace") run.steps = data.steps || [];
|
|
259
|
+
else if (event === "done") run.done = data;
|
|
260
|
+
else if (event === "error") run.error = data.message || "The request failed.";
|
|
261
|
+
}
|
|
262
|
+
} catch (err) {
|
|
263
|
+
// The connection dropped. The request keeps running on Anjoman's side, so it is followed by its job below.
|
|
264
|
+
if (!run.jobId) throw new Fail(`The connection to Anjoman was lost before the request started: ${err instanceof Error ? err.message : String(err)}`);
|
|
265
|
+
progress("connection lost; following the job");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (!run.done && !run.error && run.jobId) progress("the stream ended early; following the job");
|
|
269
|
+
|
|
270
|
+
// The job holds the cost and the final state. One that ended without its `done` event (a dropped connection, a long
|
|
271
|
+
// job) is followed until it ends; one that just finished gets a few seconds to be closed out, so its cost is there.
|
|
272
|
+
let job;
|
|
273
|
+
if (run.jobId) {
|
|
274
|
+
try {
|
|
275
|
+
job = await followJob(run.jobId, run.done || run.error ? CLOSE_OUT_MS : waitMs, progress);
|
|
276
|
+
} catch (err) {
|
|
277
|
+
// An answer already received is never thrown away because the job's record could not be read.
|
|
278
|
+
if (run.done) progress(`could not read the job's final state (${err instanceof Error ? err.message : String(err)})`);
|
|
279
|
+
else if (run.error) progress("could not read the job's final state");
|
|
280
|
+
else if (err instanceof Fail && /^404 /.test(err.message)) {
|
|
281
|
+
throw new Fail(
|
|
282
|
+
"Anjoman ended the request without an answer and has no record of the job. A first message that fails is discarded, and nothing is charged. Try the request again; if it keeps failing, tell the user.",
|
|
283
|
+
);
|
|
284
|
+
} else throw err;
|
|
285
|
+
}
|
|
286
|
+
} else if (!run.done && !run.error) {
|
|
287
|
+
throw new Fail("Anjoman closed the connection without an answer. Nothing is known to have been charged. Try the request again.");
|
|
288
|
+
}
|
|
289
|
+
const result = summarise(run, job);
|
|
290
|
+
print(result, flags.json);
|
|
291
|
+
process.exitCode = result.status === "waiting_authorization" ? EXIT.needsApproval : result.failed ? EXIT.error : EXIT.ok;
|
|
292
|
+
} finally {
|
|
293
|
+
clearTimeout(timer);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** The job's state: once it has ended, or when `waitMs` runs out. */
|
|
298
|
+
async function followJob(jobId, waitMs, progress) {
|
|
299
|
+
const until = Date.now() + waitMs;
|
|
300
|
+
for (;;) {
|
|
301
|
+
const job = await api("GET", `/agent/jobs/${encodeURIComponent(jobId)}`);
|
|
302
|
+
if (job.status !== "running" || Date.now() >= until) return job;
|
|
303
|
+
progress("still working");
|
|
304
|
+
await new Promise((r) => setTimeout(r, Math.min(POLL_MS, Math.max(250, until - Date.now()))));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function stepLine(s, i) {
|
|
309
|
+
const who = s.miner ? `${s.miner.name || s.miner.slug}${s.routedBy === "node" || !s.miner.rank ? "" : ` (rank ${s.miner.rank})`}` : s.status === "answered" ? "knowledge base" : "no miner";
|
|
310
|
+
const parts = [`${i + 1}. ${s.intent} → ${who}: ${s.status}`];
|
|
311
|
+
if (s.durationMs) parts.push(seconds(s.durationMs));
|
|
312
|
+
if (s.delivery && s.delivery !== "specialist") parts.push(`fallback: ${s.delivery.replace(/_/g, " ")}`);
|
|
313
|
+
if (s.missing) parts.push(`missing: ${s.missing}`);
|
|
314
|
+
if (s.status !== "answered" && s.reason) parts.push(`reason: ${s.reason}`);
|
|
315
|
+
if (s.needsInput?.length) parts.push(`needs from the user: ${s.needsInput.join(", ")}`);
|
|
316
|
+
return parts.join(" · ");
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function receiptOf(s) {
|
|
320
|
+
const r = s.receipt;
|
|
321
|
+
if (!r) return undefined;
|
|
322
|
+
if (typeof r === "string") return r;
|
|
323
|
+
const id = r.receiptHash ?? r.receipt_hash ?? r.hash ?? r.txHash ?? r.id;
|
|
324
|
+
return typeof id === "string" ? id : JSON.stringify(r).slice(0, 160);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Everything the caller needs, as one structure: the printed report and `--json` both come from it. */
|
|
328
|
+
function summarise(run, job) {
|
|
329
|
+
const done = run.done;
|
|
330
|
+
const answer = done?.answer ?? job?.answer ?? "";
|
|
331
|
+
const status = job?.status === "waiting_authorization" ? "waiting_authorization" : (done?.status ?? job?.outcome ?? job?.status ?? "unknown");
|
|
332
|
+
// A cap that stopped the job needs the user, not a retry; every other way of not answering is a failure.
|
|
333
|
+
const failed = status !== "waiting_authorization" && (!answer || status === "failed" || job?.status === "failed" || Boolean(run.error));
|
|
334
|
+
return {
|
|
335
|
+
answer,
|
|
336
|
+
status,
|
|
337
|
+
jobStatus: job?.status,
|
|
338
|
+
failed,
|
|
339
|
+
error: run.error ?? (job?.status === "failed" ? job.error || job.reason || "The request failed." : undefined),
|
|
340
|
+
reason: job?.reason,
|
|
341
|
+
costUsd: job?.costUsd ?? null,
|
|
342
|
+
conversationId: run.conversationId ?? job?.conversationId,
|
|
343
|
+
jobId: run.jobId ?? job?.id,
|
|
344
|
+
steps: run.steps.map((s) => ({
|
|
345
|
+
intent: s.intent,
|
|
346
|
+
status: s.status,
|
|
347
|
+
miner: s.miner?.slug,
|
|
348
|
+
routedBy: s.routedBy,
|
|
349
|
+
delivery: s.delivery,
|
|
350
|
+
missing: s.missing,
|
|
351
|
+
reason: s.reason,
|
|
352
|
+
durationMs: s.durationMs,
|
|
353
|
+
receipt: receiptOf(s),
|
|
354
|
+
})),
|
|
355
|
+
stepLines: run.steps.map(stepLine),
|
|
356
|
+
sources: done?.sources ?? [],
|
|
357
|
+
files: done?.files ?? [],
|
|
358
|
+
timings: done?.timings,
|
|
359
|
+
stillRunning: job?.status === "running",
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function print(r, asJson) {
|
|
364
|
+
if (asJson) {
|
|
365
|
+
const { stepLines: _lines, ...out } = r;
|
|
366
|
+
console.log(JSON.stringify(out, null, 2));
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const out = [];
|
|
370
|
+
if (r.answer) out.push(r.answer.trim(), "");
|
|
371
|
+
if (r.stillRunning) out.push(`The request is still running. Read it later with: node anjoman.mjs job ${r.jobId} --wait`, "");
|
|
372
|
+
if (r.error) out.push(`Error: ${r.error}`, "");
|
|
373
|
+
out.push("— Anjoman —");
|
|
374
|
+
const label = { complete: "complete", partial: "PARTIAL — only part of the request was answered", failed: "FAILED", unsupported: "UNSUPPORTED — the network has nothing for this", waiting_authorization: "STOPPED — it reached the spend cap and needs the user's approval" }[r.status] ?? r.status;
|
|
375
|
+
out.push(`Status: ${label}`);
|
|
376
|
+
out.push(`Cost: ${usd(r.costUsd)}`);
|
|
377
|
+
if (r.conversationId) out.push(`Conversation: ${r.conversationId} (pass --conversation ${r.conversationId} to continue it)`);
|
|
378
|
+
if (r.jobId) out.push(`Job: ${r.jobId}`);
|
|
379
|
+
if (r.stepLines.length) out.push("Steps:", ...r.stepLines.map((l) => ` ${l}`));
|
|
380
|
+
const receipts = r.steps.filter((s) => s.receipt);
|
|
381
|
+
if (receipts.length) out.push("Receipts:", ...receipts.map((s) => ` ${s.intent}: ${s.receipt}`));
|
|
382
|
+
const named = r.sources.map((s) => `${s.intent}${s.miner ? ` — ${s.miner.name || s.miner.slug}` : s.kind === "docs" ? " — Telegraph docs" : ""}${s.delivery && s.delivery !== "specialist" ? ` (${s.delivery.replace(/_/g, " ")})` : ""}${s.receiptHash ? ` [receipt ${s.receiptHash}]` : ""}`);
|
|
383
|
+
if (named.length) out.push("Sources:", ...named.map((l) => ` ${l}`));
|
|
384
|
+
if (r.files.length) out.push("Files made (download in the Anjoman app):", ...r.files.map((f) => ` ${f.name} (${f.size} bytes)`));
|
|
385
|
+
if (r.status === "waiting_authorization") out.push("", "It stopped at a spending limit. Tell the user what it stopped at and ask whether to continue. A limit the user set in Anjoman can only be raised there (the spend limit button in the chat, at anjoman.ai); --max-spend can only lower it. Never raise or remove a limit yourself.");
|
|
386
|
+
if (r.status === "partial") out.push("", "Tell the user which parts are missing (see Steps). Do not present the answer as complete.");
|
|
387
|
+
console.log(out.join("\n"));
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// ─── auto, miner ────────────────────────────────────────────────────────────────────────────────
|
|
391
|
+
// Straight to the Telegraph node through the account, without Anjoman's agent: no planning and no written answer, just the
|
|
392
|
+
// miner's answer in the intent's fields. Paid from the account's escrow like `ask`.
|
|
393
|
+
|
|
394
|
+
function jsonObject(name, raw) {
|
|
395
|
+
try {
|
|
396
|
+
const value = JSON.parse(raw);
|
|
397
|
+
if (value && typeof value === "object" && !Array.isArray(value)) return value;
|
|
398
|
+
} catch {
|
|
399
|
+
// Reported below.
|
|
400
|
+
}
|
|
401
|
+
throw new Fail(`--${name} must be a JSON object, e.g. '{"symbol":"BTC"}'.`, EXIT.usage);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** A question, an exact intent with its params, or both (the node reads the missing params from the question). */
|
|
405
|
+
function canonicalBody(question, flags) {
|
|
406
|
+
const params = flags.params !== undefined ? jsonObject("params", flags.params) : undefined;
|
|
407
|
+
const intent = flags.intent ? flags.intent.trim().toUpperCase() : undefined;
|
|
408
|
+
if (params && !intent) throw new Fail("--params need --intent.", EXIT.usage);
|
|
409
|
+
if (!question && !params) throw new Fail('Give a question, or --intent with --params, e.g. node anjoman.mjs auto "BTC price in USD"', EXIT.usage);
|
|
410
|
+
return { ...(question && { query: question }), ...(intent && { intent }), ...(params && { params }) };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** The node's miner call finds a miner by id, so a slug is looked up on the node first; unknown, it is sent as given. */
|
|
414
|
+
async function minerId(miner) {
|
|
415
|
+
if (/^\d+$/.test(miner)) return miner;
|
|
416
|
+
try {
|
|
417
|
+
const res = await fetch(`${nodeUrl()}/engine/v1/miners`, { signal: AbortSignal.timeout(15_000) });
|
|
418
|
+
const found = ((await res.json()).miners || []).find((m) => m.slug === miner);
|
|
419
|
+
return found ? String(found.id) : miner;
|
|
420
|
+
} catch {
|
|
421
|
+
return miner;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function auto(args) {
|
|
426
|
+
const { flags, rest } = parseFlags(args, { intent: "value", params: "value", json: "boolean" });
|
|
427
|
+
const body = canonicalBody(await readMessage(rest), flags);
|
|
428
|
+
printEngine(await api("POST", "/engine/ask", body, { signal: AbortSignal.timeout(ENGINE_WAIT_MS) }), "auto-routed ask", flags.json);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async function miner(args) {
|
|
432
|
+
const { flags, rest } = parseFlags(args, { intent: "value", params: "value", endpoint: "value", method: "value", payload: "value", json: "boolean" });
|
|
433
|
+
const [who, ...words] = rest;
|
|
434
|
+
if (!who) throw new Fail('Give the miner, e.g. node anjoman.mjs miner crypto-kraken "BTC price"', EXIT.usage);
|
|
435
|
+
const question = words.join(" ").trim();
|
|
436
|
+
let body;
|
|
437
|
+
if (flags.endpoint) {
|
|
438
|
+
if (question || flags.intent || flags.params) throw new Fail("Send either a question (with --intent and --params), or --endpoint with --method and --payload, not both.", EXIT.usage);
|
|
439
|
+
body = { method: (flags.method || "GET").toUpperCase(), endpoint: flags.endpoint, payload: flags.payload ? jsonObject("payload", flags.payload) : {} };
|
|
440
|
+
} else {
|
|
441
|
+
body = canonicalBody(question, flags);
|
|
442
|
+
}
|
|
443
|
+
const id = await minerId(who);
|
|
444
|
+
printEngine(await api("POST", `/engine/ask/${encodeURIComponent(id)}`, body, { signal: AbortSignal.timeout(ENGINE_WAIT_MS) }), "miner call", flags.json);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function fieldLines(answer) {
|
|
448
|
+
if (answer && typeof answer === "object" && !Array.isArray(answer)) {
|
|
449
|
+
return Object.entries(answer).map(([k, v]) => `${k}: ${v !== null && typeof v === "object" ? JSON.stringify(v) : v}`);
|
|
450
|
+
}
|
|
451
|
+
return [typeof answer === "string" ? answer : JSON.stringify(answer)];
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The node's reply, as the account hands it back: `result` is the node's body and `receipt` the payment's. */
|
|
455
|
+
function printEngine(r, kind, asJson) {
|
|
456
|
+
const b = r?.result && typeof r.result === "object" ? r.result : { result: r?.result };
|
|
457
|
+
const f = b.fulfillment;
|
|
458
|
+
const receipt = r?.receipt?.receipt_hash ?? r?.receipt?.receiptHash ?? f?.payments?.[0]?.receipt_hash;
|
|
459
|
+
const out = {
|
|
460
|
+
kind,
|
|
461
|
+
answer: b.result,
|
|
462
|
+
status: f?.status ?? "answered",
|
|
463
|
+
intent: b.intent,
|
|
464
|
+
miner: b.miner_name ? `${b.miner_name} (id ${b.miner_id})` : b.miner_id,
|
|
465
|
+
costUsd: b.cost_usd ?? null,
|
|
466
|
+
receipt,
|
|
467
|
+
missing: f?.missing_ids,
|
|
468
|
+
resultShape: b.result_shape,
|
|
469
|
+
fieldStatus: b.field_status,
|
|
470
|
+
payments: f?.payments,
|
|
471
|
+
warnings: b.warnings,
|
|
472
|
+
};
|
|
473
|
+
if (asJson) return console.log(JSON.stringify(out, null, 2));
|
|
474
|
+
const label = { complete: "complete", partial: "PARTIAL — only part of the request was answered", unverifiable: "UNVERIFIABLE — an answer exists but could not be checked", unavailable: "UNAVAILABLE — nothing usable came back" }[out.status] ?? out.status;
|
|
475
|
+
const lines = [...fieldLines(out.answer), "", `— Anjoman · ${kind} —`, `Status: ${label}`];
|
|
476
|
+
if (out.intent) lines.push(`Intent: ${out.intent}`);
|
|
477
|
+
if (out.miner) lines.push(`Miner: ${out.miner}`);
|
|
478
|
+
lines.push(`Cost: ${usd(out.costUsd)}`);
|
|
479
|
+
if (out.receipt) lines.push(`Receipt: ${out.receipt}`);
|
|
480
|
+
if (out.missing?.length) lines.push(`Missing: ${out.missing.join(", ")}`);
|
|
481
|
+
if (out.warnings?.length) lines.push(`Warnings: ${out.warnings.join("; ")}`);
|
|
482
|
+
if (out.status === "partial") lines.push("", "Tell the user which fields are missing. Do not present the answer as complete.");
|
|
483
|
+
console.log(lines.join("\n"));
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// ─── job, cancel, balance ───────────────────────────────────────────────────────────────────────
|
|
487
|
+
|
|
488
|
+
async function job(args) {
|
|
489
|
+
const { flags, rest } = parseFlags(args, { wait: "boolean", json: "boolean" });
|
|
490
|
+
const id = rest[0];
|
|
491
|
+
if (!id) throw new Fail("Give the job id: node anjoman.mjs job <jobId> [--wait]", EXIT.usage);
|
|
492
|
+
const state = flags.wait ? await followJob(id, DEFAULT_WAIT_MINUTES * 60_000, (t) => process.stderr.write(`… ${t}\n`)) : await api("GET", `/agent/jobs/${encodeURIComponent(id)}`);
|
|
493
|
+
if (flags.json) return console.log(JSON.stringify(state, null, 2));
|
|
494
|
+
if (state.answer) console.log(`${state.answer.trim()}\n`);
|
|
495
|
+
console.log(["— Anjoman —", `Job: ${state.id ?? id}`, `State: ${state.status}${state.outcome ? ` (${state.outcome})` : ""}`, `Cost: ${usd(state.costUsd)}`, state.reason ? `Reason: ${state.reason}` : "", state.error ? `Error: ${state.error}` : "", state.conversationId ? `Conversation: ${state.conversationId}` : ""].filter(Boolean).join("\n"));
|
|
496
|
+
if (state.status === "waiting_authorization") process.exitCode = EXIT.needsApproval;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
async function cancel(args) {
|
|
500
|
+
const id = args[0];
|
|
501
|
+
if (!id) throw new Fail("Give the job id: node anjoman.mjs cancel <jobId>", EXIT.usage);
|
|
502
|
+
const state = await api("POST", `/agent/jobs/${encodeURIComponent(id)}/cancel`, {});
|
|
503
|
+
console.log(`Job ${id}: ${state.status}`);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function balance() {
|
|
507
|
+
// The per-message limit is read too, so an agent can tell what holds. An older backend without it just shows none.
|
|
508
|
+
const [bal, spend, limit] = await Promise.all([
|
|
509
|
+
api("GET", "/engine/escrow/balance"),
|
|
510
|
+
api("GET", "/agent/spend?limit=5"),
|
|
511
|
+
api("GET", "/agent/spend/limit").catch(() => ({})),
|
|
512
|
+
]);
|
|
513
|
+
console.log(
|
|
514
|
+
[
|
|
515
|
+
"— Anjoman account —",
|
|
516
|
+
`Spendable: ${usd(Number(bal.effectiveBalance))}`,
|
|
517
|
+
`Spend limit per message: ${typeof limit.limitUsd === "number" ? usd(limit.limitUsd) : "none"} (set by the user in Anjoman)`,
|
|
518
|
+
`Deposited: ${usd(Number(bal.escrowBalance))}`,
|
|
519
|
+
bal.agentDebt ? `Owed: ${usd(Number(bal.agentDebt))}` : "",
|
|
520
|
+
spend.totals ? `Spent so far: ${JSON.stringify(spend.totals)}` : "",
|
|
521
|
+
...(spend.jobs || []).map((j) => ` ${j.startedAt ?? ""} ${j.status} ${usd(j.costUsd)}`),
|
|
522
|
+
"Top up in Anjoman (Deposit in the wallet menu). This script cannot move funds.",
|
|
523
|
+
]
|
|
524
|
+
.filter(Boolean)
|
|
525
|
+
.join("\n"),
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ─── The always-on rule ─────────────────────────────────────────────────────────────────────────
|
|
530
|
+
|
|
531
|
+
const RULE = `<!-- anjoman:start -->
|
|
532
|
+
## Anjoman for outside intelligence
|
|
533
|
+
When a task needs information or analysis from outside this conversation and the local project (live prices and market data, weather, news, web or academic research, security or compliance checks, wallet or contract risk, fact checks, or multi-source research), use the \`anjoman\` skill instead of searching the web or guessing. Send the user's request to Anjoman as it is; it decides which specialists to use. Continue a topic with the same conversation id. Report its status, cost and sources honestly, and never present a partial answer as complete. Do not use it for editing local code or files, or for anything answerable from the project itself.
|
|
534
|
+
<!-- anjoman:end -->`;
|
|
535
|
+
|
|
536
|
+
// ─── Entry ──────────────────────────────────────────────────────────────────────────────────────
|
|
537
|
+
|
|
538
|
+
const HELP = `Anjoman skill client
|
|
539
|
+
|
|
540
|
+
node anjoman.mjs ask "<request>" [--conversation <id>] [--max-spend <usd|none>] [--wait <minutes>] [--json] [--quiet]
|
|
541
|
+
node anjoman.mjs auto "<question>" [--intent <INTENT> --params '<json>'] [--json]
|
|
542
|
+
node anjoman.mjs miner <id|slug> ["<question>"] [--intent <INTENT> --params '<json>'] [--json]
|
|
543
|
+
node anjoman.mjs miner <id|slug> --endpoint </path> [--method GET|POST] [--payload '<json>'] [--json]
|
|
544
|
+
node anjoman.mjs job <jobId> [--wait] [--json]
|
|
545
|
+
node anjoman.mjs cancel <jobId>
|
|
546
|
+
node anjoman.mjs balance
|
|
547
|
+
node anjoman.mjs login
|
|
548
|
+
node anjoman.mjs rule
|
|
549
|
+
|
|
550
|
+
The key is read from ANJOMAN_API_KEY, or from ${keyFile()} after \`login\`.
|
|
551
|
+
Your spending limit is set in Anjoman (the spend limit button in the chat) and applies to every request from your account;
|
|
552
|
+
--max-spend or ANJOMAN_MAX_SPEND_USD can only set a lower one. With no limit set, your balance is the limit.
|
|
553
|
+
auto (auto-routed ask) and miner (miner call) go straight to the Telegraph node, without the agent. An auto-routed ask holds
|
|
554
|
+
a budget of $0.26 while it runs and is billed only for the miners whose answers are used; a miner call costs that miner's price.`;
|
|
555
|
+
|
|
556
|
+
export async function main(argv) {
|
|
557
|
+
const [command, ...args] = argv;
|
|
558
|
+
switch (command) {
|
|
559
|
+
case "ask":
|
|
560
|
+
return ask(args);
|
|
561
|
+
case "auto":
|
|
562
|
+
return auto(args);
|
|
563
|
+
case "miner":
|
|
564
|
+
return miner(args);
|
|
565
|
+
case "job":
|
|
566
|
+
return job(args);
|
|
567
|
+
case "cancel":
|
|
568
|
+
return cancel(args);
|
|
569
|
+
case "balance":
|
|
570
|
+
return balance();
|
|
571
|
+
case "login":
|
|
572
|
+
return login();
|
|
573
|
+
case "rule":
|
|
574
|
+
return console.log(RULE);
|
|
575
|
+
case undefined:
|
|
576
|
+
case "help":
|
|
577
|
+
case "--help":
|
|
578
|
+
case "-h":
|
|
579
|
+
return console.log(HELP);
|
|
580
|
+
default:
|
|
581
|
+
throw new Fail(`Unknown command "${command}".\n\n${HELP}`, EXIT.usage);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Resolve the launcher path: skill installers may link the script or its directory.
|
|
586
|
+
// Imports still do not run the CLI.
|
|
587
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
588
|
+
main(process.argv.slice(2)).catch((err) => {
|
|
589
|
+
console.error(err instanceof Fail ? err.message : `Unexpected error: ${err instanceof Error ? err.message : String(err)}`);
|
|
590
|
+
process.exitCode = err instanceof Fail ? err.code : EXIT.error;
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
export { spendCap, summarise, parseFlags, events, stepLine, canonicalBody, RULE };
|