@mantle-agent/cli 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # @mantle-agent/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `mantle-agent`: connect any AI agent (Claude Code, Codex, Grok Bot, OpenClaw, …) to a Mantle Agent Account. The
4
+ same tools are available as CLI commands (`--json`, stable error codes) and as an MCP server.
5
+
6
+ ```bash
7
+ npm install -g @mantle-agent/cli
8
+ mantle-agent connect --api https://agent-api.example --name my-agent --host claude-code
9
+ # open the printed link, compare the fingerprint, approve and authorize limits on the confirmation page
10
+ ```
11
+
12
+ | Command | MCP tool | |
13
+ |---|---|---|
14
+ | `guide` | — | Usage and safety rules for agents. Agents should read this first. |
15
+ | `connect --api <url> [--no-wait] [limits]` | — | Link this agent to an account and propose limits; the owner claims and confirms in one visit |
16
+ | `install-skill [--host\|--dir]` | — | Copy the skill into Claude Code / Codex skills directories |
17
+ | `status` | `status` | Balance, remaining limits, credentials, recent trades |
18
+ | `quote buy <token> <amount>` | `quote` | Price a trade |
19
+ | `trade buy\|sell <token> <amount> [--request-id]` | `trade` | Quote + execute, waits for confirmation |
20
+ | `trade-status <intentId>` | `trade_status` | |
21
+ | `runtime` / `pause` | `runtime_status` / `pause` | Scheduled runs |
22
+ | `stop` | `stop` | Emergency stop (revokes this agent's credentials; returns the owner's revoke link) |
23
+ | `authorize [limits]` | `request_authorize` | Ask the owner to authorize trading |
24
+ | `renew --days <n>` / `revoke` | `request_renew` / `request_revoke` | Ask the owner to extend / revoke |
25
+ | `withdraw <MNT\|token> <amount\|all> --to <addr>` | `request_withdraw` | Ask the owner to withdraw (address from the owner) |
26
+ | `auto-run [...] \| --off` / `resume` | `request_auto_run` / `request_resume` | Ask the owner to change scheduled runs |
27
+ | `request-status [id]` | `request_status` | What the owner did with a request |
28
+ | `run --host <h> -- <cmd…>` | — | One scheduled run under a lease (for cron) |
29
+ | `schedule --host <h>` | — | Prints a cron entry (does not install it) |
30
+ | `mcp` | — | MCP server on stdio |
31
+
32
+ Amounts are whole units with 18 decimals (`--wei` for raw integers). State lives in `~/.mantle-agent`
33
+ (`--home` / `MANTLE_AGENT_HOME`); the agent key and credentials are written `0600` and never printed.
34
+
35
+ Everything the owner decides is asked for **in the chat**: the agent runs one of the request commands and relays the
36
+ link and summary; the owner confirms on the page with a passkey (nothing to fill in there). `limits` are
37
+ `--per-trade 2 --period 10 --period-hours 24 --total 20 --days 7 --slippage 2` (MNT, %; these are the defaults).
38
+
39
+ **Hosts with skills** (Claude Code, Codex): `mantle-agent install-skill` (or `--host claude-code|codex`, `--dir <skills
40
+ dir>`), then just say *"connect my Mantle agent account, API is <API_URL>"*. The agent runs `connect --no-wait`, shows
41
+ you the link, code and fingerprint, and picks up the approval on its next `status`.
42
+
43
+ **Other hosts that can run commands** (Grok Bot, OpenClaw, …) need one instruction: *"Use the `mantle-agent` command
44
+ for my Mantle Agent Account; run `mantle-agent guide` first and follow it."*
45
+
46
+ **MCP hosts**: `claude mcp add mantle-agent -- mantle-agent mcp`, or in a JSON config:
47
+
48
+ ```json
49
+ { "mcpServers": { "mantle-agent": { "command": "mantle-agent", "args": ["mcp"] } } }
50
+ ```
51
+
52
+ The skill (`skill/mantle-agent/SKILL.md`) is the same text `mantle-agent guide` prints.
package/dist/api.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { CredentialKind, Credentials } from "./store.js";
2
+ /** A failure with the API's stable error code (or a local one), surfaced as-is by CLI and MCP. */
3
+ export declare class CliError extends Error {
4
+ readonly code: string;
5
+ readonly details?: unknown | undefined;
6
+ constructor(code: string, message: string, details?: unknown | undefined);
7
+ }
8
+ /** Thin client over the Agent API. Each call picks the narrowest credential that can make it. */
9
+ export declare class AgentApi {
10
+ readonly baseUrl: string;
11
+ private readonly credentials;
12
+ private readonly fetchImpl;
13
+ constructor(baseUrl: string, credentials: Credentials | null, fetchImpl?: typeof fetch);
14
+ request<T>(method: "GET" | "POST", path: string, opts?: {
15
+ auth?: CredentialKind;
16
+ body?: unknown;
17
+ headers?: Record<string, string>;
18
+ }): Promise<{
19
+ status: number;
20
+ body: T;
21
+ }>;
22
+ }
package/dist/api.js ADDED
@@ -0,0 +1,48 @@
1
+ /** A failure with the API's stable error code (or a local one), surfaced as-is by CLI and MCP. */
2
+ export class CliError extends Error {
3
+ code;
4
+ details;
5
+ constructor(code, message, details) {
6
+ super(message);
7
+ this.code = code;
8
+ this.details = details;
9
+ }
10
+ }
11
+ /** Thin client over the Agent API. Each call picks the narrowest credential that can make it. */
12
+ export class AgentApi {
13
+ baseUrl;
14
+ credentials;
15
+ fetchImpl;
16
+ constructor(baseUrl, credentials, fetchImpl = fetch) {
17
+ this.baseUrl = baseUrl;
18
+ this.credentials = credentials;
19
+ this.fetchImpl = fetchImpl;
20
+ }
21
+ async request(method, path, opts = {}) {
22
+ const headers = { ...opts.headers };
23
+ if (opts.body !== undefined)
24
+ headers["content-type"] = "application/json";
25
+ if (opts.auth) {
26
+ const credential = this.credentials?.[opts.auth];
27
+ if (!credential)
28
+ throw new CliError("NOT_CONNECTED", "no credentials; run `mantle-agent connect` first");
29
+ headers["authorization"] = `Bearer ${credential.token}`;
30
+ }
31
+ let res;
32
+ try {
33
+ res = await this.fetchImpl(`${this.baseUrl}${path}`, {
34
+ method,
35
+ headers,
36
+ ...(opts.body === undefined ? {} : { body: JSON.stringify(opts.body) }),
37
+ });
38
+ }
39
+ catch (err) {
40
+ throw new CliError("API_UNREACHABLE", `cannot reach ${this.baseUrl}`, { reason: String(err) });
41
+ }
42
+ const body = (await res.json().catch(() => ({})));
43
+ if (res.status >= 400)
44
+ throw new CliError(body.code ?? `HTTP_${res.status}`, body.message ?? res.statusText, body.details);
45
+ return { status: res.status, body };
46
+ }
47
+ }
48
+ //# sourceMappingURL=api.js.map
@@ -0,0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IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;aACxE,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,gBAAgB,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACjG,CAAC;QACD,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAA+D,CAAC;QAChH,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG;YAAE,MAAM,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,QAAQ,GAAG,CAAC,MAAM,EAAE,EAAE,IAAI,CAAC,OAAO,IAAI,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAC3H,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;IACtC,CAAC;CACF"}
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli.js";
3
+ process.exitCode = await main(process.argv.slice(2));
4
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAEhC,OAAO,CAAC,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export type Io = {
2
+ out(line: string): void;
3
+ err(line: string): void;
4
+ };
5
+ /** Runs one CLI invocation; returns the exit code (0 ok, 1 failed, 2 usage). */
6
+ export declare function main(argv: string[], io?: Io, fetchImpl?: typeof fetch): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,277 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { parseArgs } from "node:util";
4
+ import { z } from "zod";
5
+ import { AgentClient, ClientError as CliError } from "@mantle-agent/client";
6
+ import { connect, finishPendingClaim } from "./connect.js";
7
+ import { serveStdio } from "./mcp.js";
8
+ import { runScheduled, schedule } from "./run.js";
9
+ import { installSkill, SKILL_FILE } from "./skill.js";
10
+ import { Store } from "./store.js";
11
+ import { limitsFrom, limitsInput, pauseTool, requestAuthorizeTool, requestAutoRunTool, requestRenewTool, requestResumeTool, requestRevokeTool, requestStatusTool, requestWithdrawTool, quoteTool, runtimeStatusTool, statusTool, stopTool, tradeStatusTool, tradeTool, } from "./tools.js";
12
+ const stdio = { out: (l) => process.stdout.write(`${l}\n`), err: (l) => process.stderr.write(`${l}\n`) };
13
+ const USAGE = `mantle-agent — connect an AI agent to a Mantle Agent Account
14
+
15
+ Agents: run \`mantle-agent guide\` first — it explains every command and the rules you must follow.
16
+
17
+ Usage:
18
+ mantle-agent guide how to use this tool and the safety rules (read this first)
19
+ mantle-agent connect --api <url> [--name <agent name>] [--host <claude-code|codex|...>] [--no-wait] [--force]
20
+ [limits] [--no-authorize]
21
+ --no-wait: print the link for the owner and return; run again to check
22
+ proposes the limits (defaults below) so the owner claims and authorizes in one visit
23
+ mantle-agent install-skill [--host <claude-code|codex>] [--dir <skills dir>]
24
+ mantle-agent status
25
+ mantle-agent quote <buy|sell> <token> <amount> [--wei]
26
+ mantle-agent trade <buy|sell> <token> <amount> [--wei] [--request-id <id>] [--no-wait]
27
+ mantle-agent trade-status <intentId>
28
+ mantle-agent stop
29
+ mantle-agent runtime auto-run status (schedule, budgets, current run)
30
+ mantle-agent pause pause auto-run (only the owner can resume)
31
+
32
+ Ask the owner (prints a link + summary; the owner confirms with a passkey):
33
+ mantle-agent authorize [limits]
34
+ mantle-agent renew [--days 7]
35
+ mantle-agent revoke
36
+ mantle-agent withdraw <MNT|token> <amount|all> --to <owner's address>
37
+ mantle-agent auto-run [--every <hours>] [--max-trades-per-run 2] [--max-trades-per-day 10]
38
+ [--max-spend-per-day 5] [--max-llm-usd-per-day 5] | --off
39
+ mantle-agent resume resume auto-run
40
+ mantle-agent request-status [requestId]
41
+ limits: [--per-trade 2] [--period 10] [--period-hours 24] [--total 20] [--days 7] [--slippage 2] (MNT, %)
42
+
43
+ mantle-agent run --host <h> -- <agent command…> one scheduled run under a lease (for cron)
44
+ mantle-agent schedule --host <claude-code|codex|…> print a cron entry for scheduled runs
45
+ mantle-agent mcp start the MCP server on stdio (same tools)
46
+
47
+ Global flags: --json (machine-readable output), --home <dir> (default ~/.mantle-agent)
48
+ Amounts are whole units (MNT for buys, tokens for sells) unless --wei is given.`;
49
+ const COMMANDS = new Set(["guide", "connect", "status", "quote", "trade", "trade-status", "stop", "runtime", "pause", "run", "schedule", "mcp", "install-skill",
50
+ "authorize", "renew", "revoke", "withdraw", "auto-run", "resume", "request-status"]);
51
+ /** Runs one CLI invocation; returns the exit code (0 ok, 1 failed, 2 usage). */
52
+ export async function main(argv, io = stdio, fetchImpl = fetch) {
53
+ // Everything after `--` is the host command for `run`.
54
+ const split = argv.indexOf("--");
55
+ const hostCommand = split >= 0 ? argv.slice(split + 1) : [];
56
+ if (split >= 0)
57
+ argv = argv.slice(0, split);
58
+ let parsed;
59
+ try {
60
+ parsed = parseArgs({
61
+ args: argv,
62
+ allowPositionals: true,
63
+ options: {
64
+ json: { type: "boolean", default: false },
65
+ home: { type: "string" },
66
+ api: { type: "string" },
67
+ name: { type: "string" },
68
+ host: { type: "string" },
69
+ dir: { type: "string" },
70
+ wei: { type: "boolean", default: false },
71
+ "request-id": { type: "string" },
72
+ "no-wait": { type: "boolean", default: false },
73
+ force: { type: "boolean", default: false },
74
+ "no-authorize": { type: "boolean", default: false },
75
+ "per-trade": { type: "string" },
76
+ period: { type: "string" },
77
+ "period-hours": { type: "string" },
78
+ total: { type: "string" },
79
+ days: { type: "string" },
80
+ slippage: { type: "string" },
81
+ to: { type: "string" },
82
+ every: { type: "string" },
83
+ "max-trades-per-run": { type: "string" },
84
+ "max-trades-per-day": { type: "string" },
85
+ "max-spend-per-day": { type: "string" },
86
+ "max-llm-usd-per-day": { type: "string" },
87
+ off: { type: "boolean", default: false },
88
+ help: { type: "boolean", short: "h", default: false },
89
+ },
90
+ });
91
+ }
92
+ catch (err) {
93
+ io.err(String(err.message));
94
+ io.err(USAGE);
95
+ return 2;
96
+ }
97
+ const { values: flags, positionals } = parsed;
98
+ const [command, ...args] = positionals;
99
+ if (!command || flags.help) {
100
+ io.out(USAGE);
101
+ return command ? 0 : 2;
102
+ }
103
+ if (!COMMANDS.has(command)) {
104
+ io.err(`unknown command: ${command}`);
105
+ io.err(USAGE);
106
+ return 2;
107
+ }
108
+ if (command === "guide") {
109
+ io.out(readFileSync(SKILL_FILE, "utf8"));
110
+ return 0;
111
+ }
112
+ const store = new Store(flags.home);
113
+ const emit = (value, human) => io.out(flags.json ? JSON.stringify(value) : (human ?? JSON.stringify(value, null, 2)));
114
+ const num = (v) => (v === undefined ? undefined : Number(v));
115
+ const limitFlags = {
116
+ ...(flags["per-trade"] ? { perTrade: flags["per-trade"] } : {}),
117
+ ...(flags.period ? { period: flags.period } : {}),
118
+ ...(flags["period-hours"] ? { periodHours: num(flags["period-hours"]) } : {}),
119
+ ...(flags.total ? { total: flags.total } : {}),
120
+ ...(flags.days ? { days: num(flags.days) } : {}),
121
+ ...(flags.slippage ? { slippagePercent: num(flags.slippage) } : {}),
122
+ };
123
+ try {
124
+ if (command === "connect") {
125
+ const apiUrl = flags.api ?? process.env["MANTLE_AGENT_API"] ?? store.pendingClaim()?.apiUrl ?? store.config()?.apiUrl;
126
+ if (!apiUrl)
127
+ throw new CliError("INVALID_REQUEST", "--api <url> is required the first time");
128
+ const existing = store.config();
129
+ if (existing?.agentId && store.credentials() && !flags.force) {
130
+ // One identity per home: connecting again would replace this agent's credentials.
131
+ throw new CliError("ALREADY_CONNECTED", `already connected as "${existing.name}" (${existing.agentId}); use --force to replace it, or --home <dir> / MANTLE_AGENT_HOME for a second agent`, { agentId: existing.agentId, name: existing.name, home: store.dir });
132
+ }
133
+ const wait = !flags["no-wait"];
134
+ const result = await connect(store, {
135
+ apiUrl,
136
+ name: flags.name ?? "agent",
137
+ host: flags.host ?? hostname(),
138
+ wait,
139
+ fetchImpl,
140
+ ...(flags["no-authorize"] ? {} : { authorize: limitsFrom(validate(limitsInput, limitFlags)) }),
141
+ onClaim: (claim) => {
142
+ // With --no-wait the single result line below carries the claim; don't print it twice.
143
+ if (wait || !flags.json) {
144
+ emit({ event: "claim", ...claim }, `Open ${claim.claimUrl}\nConfirm code ${claim.userCode} and check the key fingerprint ${claim.fingerprint}.` +
145
+ (claim.proposal ? `\nThen confirm these limits:\n ${claim.proposal.join("\n ")}` : "") +
146
+ (wait ? "\nWaiting for approval…" : ""));
147
+ }
148
+ },
149
+ });
150
+ if (result.status === "connected") {
151
+ emit({ event: "connected", agentId: result.agentId, fingerprint: result.fingerprint }, `Connected as agent ${result.agentId}. Credentials saved to ${store.dir}.`);
152
+ }
153
+ else {
154
+ const { claimUrl, userCode, fingerprint, expiresAt, proposal } = result.claim;
155
+ emit({ event: "awaiting_owner_approval", claimUrl, userCode, fingerprint, expiresAt, proposedLimits: proposal }, `Waiting for the owner. Run \`mantle-agent connect\` or \`mantle-agent status\` again after they approve.`);
156
+ }
157
+ return 0;
158
+ }
159
+ if (command === "install-skill") {
160
+ const result = installSkill({ ...(flags.host ? { host: flags.host } : {}), ...(flags.dir ? { dir: flags.dir } : {}) });
161
+ emit(result, result.installed.length ? `Installed:\n${result.installed.join("\n")}` : "No host found; use --host or --dir.");
162
+ return 0;
163
+ }
164
+ if (command === "schedule") {
165
+ const result = schedule(store, { host: flags.host ?? "claude-code", cli: "mantle-agent" });
166
+ emit(result, `${result.note}\n\n${result.cron}\n\nPrompt for each run: ${result.promptFile}`);
167
+ return 0;
168
+ }
169
+ // Pick up an approval that happened since `connect --no-wait`. Still pending: explain how to finish, unless an
170
+ // earlier connection exists (reconnecting), which keeps working meanwhile.
171
+ if (store.pendingClaim()) {
172
+ await finishPendingClaim(store, fetchImpl).catch((err) => {
173
+ if (!store.config())
174
+ throw err;
175
+ });
176
+ }
177
+ const config = store.config();
178
+ if (!config)
179
+ throw new CliError("NOT_CONNECTED", "not connected yet; run `mantle-agent connect --api <url> --no-wait`");
180
+ const lease = process.env["MANTLE_AGENT_LEASE"];
181
+ const ctx = {
182
+ client: new AgentClient(config.apiUrl, store.credentials(), { fetch: fetchImpl, ...(lease ? { leaseId: lease } : {}) }),
183
+ };
184
+ if (command === "run") {
185
+ if (hostCommand.length === 0)
186
+ throw new CliError("INVALID_REQUEST", "usage: mantle-agent run --host <h> -- <agent command…>");
187
+ return await runScheduled(ctx.client, {
188
+ host: flags.host ?? config.host ?? hostname(),
189
+ command: hostCommand,
190
+ emit: (event) => emit(event),
191
+ });
192
+ }
193
+ if (command === "mcp") {
194
+ await serveStdio(ctx);
195
+ return 0;
196
+ }
197
+ const unit = flags.wei ? "wei" : undefined;
198
+ const trade = () => {
199
+ const [side, token, amount] = args;
200
+ return { side: side, token: token, amount: amount, ...(unit ? { unit } : {}) };
201
+ };
202
+ let result;
203
+ switch (command) {
204
+ case "status":
205
+ result = await statusTool.run(ctx, {});
206
+ break;
207
+ case "quote":
208
+ result = await quoteTool.run(ctx, validate(quoteTool.input, trade()));
209
+ break;
210
+ case "trade":
211
+ result = await tradeTool.run(ctx, validate(tradeTool.input, {
212
+ ...trade(),
213
+ ...(flags["request-id"] ? { requestId: flags["request-id"] } : {}),
214
+ wait: !flags["no-wait"],
215
+ }));
216
+ break;
217
+ case "trade-status":
218
+ result = await tradeStatusTool.run(ctx, validate(tradeStatusTool.input, { intentId: args[0] }));
219
+ break;
220
+ case "stop":
221
+ result = await stopTool.run(ctx, {});
222
+ break;
223
+ case "runtime":
224
+ result = await runtimeStatusTool.run(ctx, {});
225
+ break;
226
+ case "pause":
227
+ result = await pauseTool.run(ctx, {});
228
+ break;
229
+ case "authorize":
230
+ result = await requestAuthorizeTool.run(ctx, validate(requestAuthorizeTool.input, limitFlags));
231
+ break;
232
+ case "renew":
233
+ result = await requestRenewTool.run(ctx, validate(requestRenewTool.input, { days: num(flags.days) ?? 7 }));
234
+ break;
235
+ case "revoke":
236
+ result = await requestRevokeTool.run(ctx, {});
237
+ break;
238
+ case "withdraw":
239
+ result = await requestWithdrawTool.run(ctx, validate(requestWithdrawTool.input, { asset: args[0], amount: args[1], to: flags.to }));
240
+ break;
241
+ case "auto-run":
242
+ result = await requestAutoRunTool.run(ctx, validate(requestAutoRunTool.input, {
243
+ enabled: !flags.off,
244
+ ...(flags.every ? { everyHours: num(flags.every) } : {}),
245
+ ...(flags["max-trades-per-run"] ? { maxTradesPerRun: num(flags["max-trades-per-run"]) } : {}),
246
+ ...(flags["max-trades-per-day"] ? { maxTradesPerDay: num(flags["max-trades-per-day"]) } : {}),
247
+ ...(flags["max-spend-per-day"] ? { maxSpendPerDay: flags["max-spend-per-day"] } : {}),
248
+ ...(flags["max-llm-usd-per-day"] ? { maxLlmUsdPerDay: num(flags["max-llm-usd-per-day"]) } : {}),
249
+ }));
250
+ break;
251
+ case "resume":
252
+ result = await requestResumeTool.run(ctx, {});
253
+ break;
254
+ case "request-status":
255
+ result = await requestStatusTool.run(ctx, validate(requestStatusTool.input, args[0] ? { requestId: args[0] } : {}));
256
+ break;
257
+ }
258
+ emit(result);
259
+ return 0;
260
+ }
261
+ catch (err) {
262
+ const e = err instanceof CliError ? err : new CliError("INTERNAL", String(err));
263
+ if (flags.json)
264
+ io.out(JSON.stringify({ error: { code: e.code, message: e.message, details: e.details } }));
265
+ else
266
+ io.err(`error ${e.code}: ${e.message}`);
267
+ return 1;
268
+ }
269
+ }
270
+ function validate(shape, input) {
271
+ const parsed = z.object(shape).safeParse(input);
272
+ if (!parsed.success) {
273
+ throw new CliError("INVALID_REQUEST", parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));
274
+ }
275
+ return parsed.data;
276
+ }
277
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,WAAW,IAAI,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EACL,UAAU,EACV,WAAW,EACX,SAAS,EACT,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,mBAAmB,EACnB,SAAS,EACT,iBAAiB,EACjB,UAAU,EACV,QAAQ,EACR,eAAe,EACf,SAAS,GAEV,MAAM,YAAY,CAAC;AAGpB,MAAM,KAAK,GAAO,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,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CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;;YACvG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7C,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAA0B,KAAQ,EAAE,KAAc;IACjE,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACxH,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC"}
@@ -0,0 +1,31 @@
1
+ import { type Claim, type Fetch, type SessionLimits } from "@mantle-agent/client";
2
+ import type { PendingClaim, Store } from "./store.js";
3
+ export type ClaimInfo = Claim;
4
+ export type ConnectResult = {
5
+ status: "connected";
6
+ agentId: string;
7
+ fingerprint: string;
8
+ } | {
9
+ status: "pending";
10
+ claim: PendingClaim;
11
+ };
12
+ /**
13
+ * `mantle-agent connect`: the SDK's claim flow with the agent key kept in the local store. The fingerprint the
14
+ * owner sees is computed here from the local key; a server reporting a different one is refused.
15
+ *
16
+ * With `wait: false` it returns as soon as the owner has the link, so an agent can hand it over and end its turn;
17
+ * running it again (or `status`) reuses the same claim until it is approved or expires.
18
+ */
19
+ export declare function connect(store: Store, params: {
20
+ apiUrl: string;
21
+ name: string;
22
+ host: string;
23
+ wait: boolean;
24
+ /** Limits to propose with the claim; the owner confirms them right after claiming. */
25
+ authorize?: SessionLimits;
26
+ onClaim: (claim: ClaimInfo) => void | Promise<void>;
27
+ pollMs?: number;
28
+ fetchImpl?: Fetch;
29
+ }): Promise<ConnectResult>;
30
+ /** For commands run before the owner approved: finish a pending claim if it was approved since, else explain. */
31
+ export declare function finishPendingClaim(store: Store, fetchImpl?: Fetch): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { ClientError, exchangeClaim, startClaim } from "@mantle-agent/client";
2
+ /**
3
+ * `mantle-agent connect`: the SDK's claim flow with the agent key kept in the local store. The fingerprint the
4
+ * owner sees is computed here from the local key; a server reporting a different one is refused.
5
+ *
6
+ * With `wait: false` it returns as soon as the owner has the link, so an agent can hand it over and end its turn;
7
+ * running it again (or `status`) reuses the same claim until it is approved or expires.
8
+ */
9
+ export async function connect(store, params) {
10
+ const key = store.agentKey();
11
+ const fetchOpt = params.fetchImpl ? { fetch: params.fetchImpl } : {};
12
+ const proposalKey = params.authorize ? JSON.stringify(params.authorize, (_k, v) => (typeof v === "bigint" ? v.toString() : v)) : null;
13
+ let claim = store.pendingClaim();
14
+ // A new claim when the proposed limits changed (the owner asked for different numbers), not only on expiry.
15
+ const reusable = claim && claim.apiUrl === params.apiUrl && Date.parse(claim.expiresAt) > Date.now() && (claim.proposalKey ?? null) === proposalKey;
16
+ if (!claim || !reusable) {
17
+ const started = await startClaim({
18
+ baseUrl: params.apiUrl,
19
+ agentName: params.name,
20
+ host: params.host,
21
+ key,
22
+ ...(params.authorize ? { authorize: params.authorize } : {}),
23
+ ...fetchOpt,
24
+ });
25
+ if (started.fingerprint !== key.fingerprint) {
26
+ throw new ClientError("FINGERPRINT_MISMATCH", "server reported a different key fingerprint; do not approve this claim");
27
+ }
28
+ claim = { ...started, apiUrl: params.apiUrl, name: params.name, host: params.host, proposalKey };
29
+ store.savePendingClaim(claim);
30
+ }
31
+ await params.onClaim(claim);
32
+ return checkClaim(store, claim, { wait: params.wait, ...(params.pollMs !== undefined ? { pollMs: params.pollMs } : {}), ...fetchOpt });
33
+ }
34
+ /** Exchanges a started claim for credentials once the owner approved it (once, or polling with `wait`). */
35
+ async function checkClaim(store, claim, opts) {
36
+ const key = store.agentKey();
37
+ for (;;) {
38
+ let result;
39
+ try {
40
+ result = await exchangeClaim({ baseUrl: claim.apiUrl, claimId: claim.claimId, key, ...(opts.fetch ? { fetch: opts.fetch } : {}) });
41
+ }
42
+ catch (err) {
43
+ if (err instanceof ClientError && (err.code === "CLAIM_EXPIRED" || err.code === "CLAIM_USED" || err.code === "NOT_FOUND")) {
44
+ store.savePendingClaim(null);
45
+ }
46
+ throw err;
47
+ }
48
+ if (result.status === "exchanged") {
49
+ store.saveCredentials(result.credentials);
50
+ store.saveConfig({ apiUrl: claim.apiUrl, agentId: result.agentId, name: claim.name, host: claim.host });
51
+ store.savePendingClaim(null);
52
+ return { status: "connected", agentId: result.agentId, fingerprint: key.fingerprint };
53
+ }
54
+ if (!opts.wait)
55
+ return { status: "pending", claim };
56
+ await new Promise((r) => setTimeout(r, opts.pollMs ?? 2_000));
57
+ }
58
+ }
59
+ /** For commands run before the owner approved: finish a pending claim if it was approved since, else explain. */
60
+ export async function finishPendingClaim(store, fetchImpl) {
61
+ const pending = store.pendingClaim();
62
+ if (!pending)
63
+ throw new ClientError("NOT_CONNECTED", "not connected yet; run `mantle-agent connect --api <url> --no-wait`");
64
+ const result = await checkClaim(store, pending, { wait: false, ...(fetchImpl ? { fetch: fetchImpl } : {}) });
65
+ if (result.status === "pending") {
66
+ const { claimUrl, userCode, fingerprint, expiresAt } = result.claim;
67
+ throw new ClientError("AWAITING_OWNER_APPROVAL", `the owner has not approved yet: open ${claimUrl}, confirm code ${userCode} and fingerprint ${fingerprint}`, { claimUrl, userCode, fingerprint, expiresAt });
68
+ }
69
+ }
70
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conn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IACrC,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,WAAW,CAAC,eAAe,EAAE,qEAAqE,CAAC,CAAC;IAC5H,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IAC7G,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAChC,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC;QACpE,MAAM,IAAI,WAAW,CACnB,yBAAyB,EACzB,wCAAwC,QAAQ,kBAAkB,QAAQ,oBAAoB,WAAW,EAAE,EAC3G,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,CAC/C,CAAC;IACJ,CAAC;AACH,CAAC"}
@@ -0,0 +1,7 @@
1
+ export { AgentClient, ClientError } from "@mantle-agent/client";
2
+ export { main, type Io } from "./cli.js";
3
+ export { connect, type ClaimInfo } from "./connect.js";
4
+ export { createMcpServer, serveStdio } from "./mcp.js";
5
+ export { runScheduled, schedule } from "./run.js";
6
+ export { Store, fingerprintOf, type Config, type Credentials } from "./store.js";
7
+ export { tools, type Tool, type ToolContext } from "./tools.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { AgentClient, ClientError } from "@mantle-agent/client";
2
+ export { main } from "./cli.js";
3
+ export { connect } from "./connect.js";
4
+ export { createMcpServer, serveStdio } from "./mcp.js";
5
+ export { runScheduled, schedule } from "./run.js";
6
+ export { Store, fingerprintOf } from "./store.js";
7
+ export { tools } from "./tools.js";
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,IAAI,EAAW,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,OAAO,EAAkB,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,aAAa,EAAiC,MAAM,YAAY,CAAC;AACjF,OAAO,EAAE,KAAK,EAA+B,MAAM,YAAY,CAAC"}
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { type ToolContext } from "./tools.js";
3
+ /**
4
+ * Same tools as the CLI, as MCP tools. Errors come back as tool results with the API's stable code, so the
5
+ * model can react to e.g. PER_TRADE_CAP_EXCEEDED instead of retrying blindly.
6
+ */
7
+ export declare function createMcpServer(ctx: ToolContext): McpServer;
8
+ export declare function serveStdio(ctx: ToolContext): Promise<void>;
package/dist/mcp.js ADDED
@@ -0,0 +1,32 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { ClientError as CliError } from "@mantle-agent/client";
4
+ import { tools } from "./tools.js";
5
+ const VERSION = "0.1.0";
6
+ /**
7
+ * Same tools as the CLI, as MCP tools. Errors come back as tool results with the API's stable code, so the
8
+ * model can react to e.g. PER_TRADE_CAP_EXCEEDED instead of retrying blindly.
9
+ */
10
+ export function createMcpServer(ctx) {
11
+ const server = new McpServer({ name: "mantle-agent", version: VERSION });
12
+ for (const tool of tools) {
13
+ server.registerTool(tool.name, { title: tool.title, description: tool.description, inputSchema: tool.input }, async (input) => {
14
+ try {
15
+ const result = await tool.run(ctx, input ?? {});
16
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
17
+ }
18
+ catch (err) {
19
+ const e = err instanceof CliError ? err : new CliError("INTERNAL", String(err));
20
+ return {
21
+ isError: true,
22
+ content: [{ type: "text", text: JSON.stringify({ code: e.code, message: e.message, details: e.details }) }],
23
+ };
24
+ }
25
+ });
26
+ }
27
+ return server;
28
+ }
29
+ export async function serveStdio(ctx) {
30
+ await createMcpServer(ctx).connect(new StdioServerTransport());
31
+ }
32
+ //# sourceMappingURL=mcp.js.map