@cmdoss/agent-pass-plugin 0.0.0-stage → 0.1.0-dev.5.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.
Files changed (68) hide show
  1. package/README.md +131 -2
  2. package/dist/agentpass.js +199 -0
  3. package/dist/cli.js +37 -0
  4. package/dist/domain.js +103 -0
  5. package/dist/engine.js +260 -0
  6. package/dist/http.js +170 -0
  7. package/dist/mcp.js +259 -0
  8. package/dist/onboarding.js +258 -0
  9. package/dist/public/catalog.js +35 -0
  10. package/dist/public/http.js +89 -0
  11. package/dist/public-server.js +11 -0
  12. package/dist/runtime/config.js +16 -0
  13. package/dist/runtime/installation.js +107 -0
  14. package/dist/runtime/lock.js +38 -0
  15. package/dist/runtime/paths.js +56 -0
  16. package/dist/runtime/setup.js +155 -0
  17. package/dist/sdk-ui.js +48 -0
  18. package/dist/server.js +107 -0
  19. package/dist/shared/constants.js +9 -0
  20. package/dist/store.js +84 -0
  21. package/dist/testnet/adapter.js +275 -0
  22. package/dist/testnet/authorization.js +620 -0
  23. package/dist/testnet/chain/codec.js +68 -0
  24. package/dist/testnet/chain/inspection.js +54 -0
  25. package/dist/testnet/chain/policy.js +78 -0
  26. package/dist/testnet/chain/prepared.js +150 -0
  27. package/dist/testnet/chain/receipt.js +49 -0
  28. package/dist/testnet/chain/sdk.js +34 -0
  29. package/dist/testnet/chain/types.js +1 -0
  30. package/dist/testnet/engine.js +395 -0
  31. package/dist/testnet/http.js +139 -0
  32. package/dist/testnet/model.js +49 -0
  33. package/dist/testnet/policy.js +44 -0
  34. package/dist/testnet/read-model.js +217 -0
  35. package/dist/testnet/repository.js +62 -0
  36. package/dist/testnet/runner.js +306 -0
  37. package/dist/testnet/types.js +1 -0
  38. package/dist/workflows.js +379 -0
  39. package/docs/agent-pass-integration.md +75 -0
  40. package/docs/architecture.md +93 -0
  41. package/docs/npm-release.md +83 -0
  42. package/npm-shrinkwrap.json +5376 -0
  43. package/package.json +72 -4
  44. package/public/assets/agent-pass-plugin-client.js +16 -0
  45. package/public/assets/agent-pass-plugin-sdk.js +1 -0
  46. package/public/assets/sui-payment-rails.avif +0 -0
  47. package/public/assets/sui-payments-hero.json +1 -0
  48. package/public/fonts/TWKEverett-Medium.woff2 +0 -0
  49. package/public/fonts/TWKEverett-Regular.woff2 +0 -0
  50. package/public/fonts/TWKEverettMono-Medium.woff2 +0 -0
  51. package/public/fonts/TWKEverettMono-Regular.woff2 +0 -0
  52. package/public/index.html +81 -0
  53. package/public/styles/base.css +117 -0
  54. package/public/styles/catalog.css +279 -0
  55. package/public/styles/controls.css +118 -0
  56. package/public/styles/dialog.css +257 -0
  57. package/public/styles/home.css +82 -0
  58. package/public/styles/layout.css +45 -0
  59. package/public/styles/plans.css +271 -0
  60. package/public/styles/responsive.css +643 -0
  61. package/public/styles/review.css +150 -0
  62. package/public/styles/sdk-wallet.css +125 -0
  63. package/public/styles/sdk.css +441 -0
  64. package/public/styles/shell.css +348 -0
  65. package/public/styles/tokens.css +75 -0
  66. package/public/styles.css +11 -0
  67. package/scripts/setup.mjs +10 -0
  68. package/skills/agent-pass-plugin-trading/SKILL.md +60 -0
package/dist/mcp.js ADDED
@@ -0,0 +1,259 @@
1
+ import { DEFAULT_APP_PORT, SERVICE_ID } from "./shared/constants.js";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { randomUUID } from "node:crypto";
5
+ import { z } from "zod";
6
+ const base = new URL(process.env.AGENT_PASS_PLUGIN_LOCAL_URL ??
7
+ `http://127.0.0.1:${DEFAULT_APP_PORT}`);
8
+ if (base.protocol !== "http:" ||
9
+ base.hostname !== "127.0.0.1" ||
10
+ base.username ||
11
+ base.password ||
12
+ base.pathname !== "/" ||
13
+ base.search ||
14
+ base.hash) {
15
+ throw new Error("MCP connects only to the local loopback runtime, without URL credentials.");
16
+ }
17
+ const QuoteDataSchema = z.object({ data: z.unknown() });
18
+ const readOnly = {
19
+ readOnlyHint: true,
20
+ destructiveHint: false,
21
+ idempotentHint: true,
22
+ openWorldHint: false,
23
+ };
24
+ const propose = {
25
+ readOnlyHint: false,
26
+ destructiveHint: false,
27
+ idempotentHint: true,
28
+ openWorldHint: false,
29
+ };
30
+ const mutate = {
31
+ readOnlyHint: false,
32
+ destructiveHint: false,
33
+ idempotentHint: false,
34
+ openWorldHint: false,
35
+ };
36
+ async function api(path, body) {
37
+ try {
38
+ const headers = {};
39
+ if (body !== undefined) {
40
+ const session = await fetch(new URL("/api/session", base), {
41
+ signal: AbortSignal.timeout(5000),
42
+ });
43
+ if (!session.ok)
44
+ throw new Error("Cannot connect to the local session.");
45
+ const value = (await session.json());
46
+ if (!value.token)
47
+ throw new Error("Local session did not return its transport credential.");
48
+ headers["x-local-token"] = value.token;
49
+ headers["content-type"] = "application/json";
50
+ }
51
+ const response = await fetch(new URL(path, base), {
52
+ method: body === undefined ? "GET" : "POST",
53
+ headers,
54
+ body: body === undefined ? undefined : JSON.stringify(body),
55
+ signal: AbortSignal.timeout(30000),
56
+ });
57
+ const value = await response.json();
58
+ return {
59
+ content: [
60
+ { type: "text", text: JSON.stringify(value, null, 2) },
61
+ ],
62
+ structuredContent: { data: value },
63
+ isError: !response.ok,
64
+ };
65
+ }
66
+ catch (error) {
67
+ const value = {
68
+ error: `Local runtime unavailable. Start npm run dev in Agent Pass Plugin first. ${error.message}`,
69
+ };
70
+ return {
71
+ isError: true,
72
+ content: [{ type: "text", text: JSON.stringify(value) }],
73
+ structuredContent: { data: value },
74
+ };
75
+ }
76
+ }
77
+ const server = new McpServer({ name: SERVICE_ID, version: "0.1.0" }, {
78
+ instructions: "Inspect marketplace_status for the mode. For Testnet setup/onboarding, call onboard before reporting readiness: it automatically opens the local wallet connection page when no fresh browser wallet connection exists. Poll onboarding_status until onboardingComplete is true. A browser launch, installed MCP, cached address or successful quote is not completed onboarding. If browser opening fails, report that failure and the returned manual URL. Wallet connection is separate from Agent Pass authorization and explicit Start; never sign, authorize or start on the owner's behalf.",
79
+ });
80
+ let onboardingRequestId = randomUUID();
81
+ let onboardingId;
82
+ server.registerTool("onboard", {
83
+ description: "Complete Testnet wallet onboarding. Automatically open the local Agent Pass Plugin connection page if a fresh connected browser wallet is missing; return pending until the user actually connects. Call this during setup rather than merely telling the user to open a URL. Repeated calls reuse this client session; retryBrowser explicitly retries a failed/dismissed launch. No wallet selection, signature, Pass authorization or trading is performed.",
84
+ inputSchema: { retryBrowser: z.boolean().optional() },
85
+ outputSchema: QuoteDataSchema,
86
+ annotations: mutate,
87
+ }, async ({ retryBrowser }) => {
88
+ const clientName = server.server.getClientVersion()?.name;
89
+ let result = await api("/api/onboarding", {
90
+ requestId: onboardingRequestId,
91
+ retryBrowser: retryBrowser ?? false,
92
+ openBrowser: true,
93
+ clientName,
94
+ });
95
+ let data = result.structuredContent.data;
96
+ if (!result.isError && data.status === "expired") {
97
+ onboardingRequestId = randomUUID();
98
+ result = await api("/api/onboarding", {
99
+ requestId: onboardingRequestId,
100
+ openBrowser: true,
101
+ clientName,
102
+ });
103
+ data = result.structuredContent.data;
104
+ }
105
+ if (!result.isError && typeof data.id === "string")
106
+ onboardingId = data.id;
107
+ return result;
108
+ });
109
+ server.registerTool("onboarding_status", {
110
+ description: "Read this MCP session's wallet onboarding progress after onboard. Report complete only when onboardingComplete is true and the browser wallet presence is current. This never opens a browser or grants trading permission. A pending/rejected/disconnected/expired connection is not success.",
111
+ inputSchema: {},
112
+ outputSchema: QuoteDataSchema,
113
+ annotations: readOnly,
114
+ }, () => {
115
+ if (onboardingId)
116
+ return api(`/api/onboarding/${encodeURIComponent(onboardingId)}`);
117
+ const data = {
118
+ status: "not_started",
119
+ onboardingComplete: false,
120
+ authorizationGranted: false,
121
+ tradingStarted: false,
122
+ nextAction: "Call onboard to open the local wallet connection page.",
123
+ };
124
+ return {
125
+ content: [{ type: "text", text: JSON.stringify(data) }],
126
+ structuredContent: { data },
127
+ };
128
+ });
129
+ server.registerTool("testnet_capabilities", {
130
+ description: "Read the explicit Sui Testnet deployment, demo coins, supported pools and gas defaults before proposing a plan. No authorization or transaction.",
131
+ inputSchema: {},
132
+ outputSchema: QuoteDataSchema,
133
+ annotations: readOnly,
134
+ }, () => api("/api/testnet/capabilities"));
135
+ server.registerTool("create_testnet_plan", {
136
+ description: "Create a Sui Testnet Agent Pass draft using the owner's explicit address, direction, decimal input/budget/daily cap, owner-selected demo USDC per SUI price bound, whole-day term, venue and gas caps. This creates no pass or transaction. Request authorization separately, show exact official rules, wait for the owner signature, then Start only with explicit intent. Never invent the price bound. No mainnet.",
137
+ inputSchema: {
138
+ expectedOwner: z.string().regex(/^0x[0-9a-fA-F]{64}$/),
139
+ botId: z.enum(["steady-dca", "price-watch"]),
140
+ direction: z.enum(["usdc_to_sui", "sui_to_usdc"]),
141
+ amountIn: z.string(),
142
+ budgetIn: z.string(),
143
+ dailyLimitIn: z.string(),
144
+ limitPrice: z.string(),
145
+ intervalSeconds: z.number().int().min(5).max(86400),
146
+ durationDays: z.number().int().min(1).max(7),
147
+ slippageBps: z.number().int().min(1).max(500),
148
+ venue: z.enum(["cetus", "deepbook"]),
149
+ gasSui: z.string(),
150
+ gasCapSui: z.string(),
151
+ gasDailySui: z.string(),
152
+ },
153
+ outputSchema: QuoteDataSchema,
154
+ annotations: mutate,
155
+ }, (args) => api("/api/plans", { ...args, mode: "testnet", network: "testnet" }));
156
+ server.registerTool("marketplace_status", {
157
+ description: "Read the runtime mode, wallet, plans, heartbeat and catalog. For Testnet setup call onboard next to automatically open the wallet connection page when needed; this status read does not complete onboarding. Testnet data is separate from simulated Paper data; inspect mode before acting.",
158
+ inputSchema: {},
159
+ outputSchema: QuoteDataSchema,
160
+ annotations: readOnly,
161
+ }, () => api("/api/status"));
162
+ server.registerTool("agent_pass_readiness", {
163
+ description: "Read-only official SDK/testnet quote readiness. Does not create a key, sign, fund or trade.",
164
+ inputSchema: {},
165
+ outputSchema: QuoteDataSchema,
166
+ annotations: { ...readOnly, openWorldHint: true },
167
+ }, () => api("/api/integration"));
168
+ server.registerTool("list_strategies", {
169
+ description: "Search the versioned strategy catalog by name or rules. Inspect runtime mode and performance provenance. Missing historical performance is null; Testnet is not a live-money return record.",
170
+ inputSchema: { query: z.string().max(100).optional() },
171
+ outputSchema: QuoteDataSchema,
172
+ annotations: readOnly,
173
+ }, ({ query }) => api(`/api/strategies${query ? `?query=${encodeURIComponent(query)}` : ""}`));
174
+ server.registerTool("get_strategy", {
175
+ description: "Read a strategy's author, version, rules, skill instructions and mode-labeled performance availability.",
176
+ inputSchema: { strategyId: z.enum(["steady-dca", "price-watch"]) },
177
+ outputSchema: QuoteDataSchema,
178
+ annotations: readOnly,
179
+ }, ({ strategyId }) => api(`/api/strategies/${strategyId}`));
180
+ server.registerTool("account_status", {
181
+ description: "Read account status. Testnet uses fresh browser wallet presence, not a persisted address hint. If disconnected call onboard to automatically open the connection page, then poll onboarding_status. Wallet connection grants no trading authorization; only a verified owner-signed Pass permits execution. Paper balances are simulated.",
182
+ inputSchema: {},
183
+ outputSchema: QuoteDataSchema,
184
+ annotations: readOnly,
185
+ }, () => api("/api/account"));
186
+ server.registerTool("create_account", {
187
+ description: "Paper-only: initiate local simulated account creation/reconnection; return the user review URL. Testnet rejects this tool: the owner connects a Sui wallet and signs a separate official Pass proposal. Reuse requestId only for exact retries.",
188
+ inputSchema: { requestId: z.string().uuid() },
189
+ outputSchema: QuoteDataSchema,
190
+ annotations: propose,
191
+ }, (args) => api("/api/account/requests", args));
192
+ server.registerTool("request_funding", {
193
+ description: "Paper-only: request a virtual USDC credit with browser confirmation. Testnet rejects virtual credits and returns official funding guidance; never claim a deposit or sign for the owner. Reuse the UUID requestId only for identical retries.",
194
+ inputSchema: {
195
+ amountUsdc: z.number().finite().min(0.01).max(10000),
196
+ requestId: z.string().uuid(),
197
+ },
198
+ outputSchema: QuoteDataSchema,
199
+ annotations: propose,
200
+ }, (args) => api("/api/funding/requests", args));
201
+ server.registerTool("request_plan_authorization", {
202
+ description: "Request authorization for the exact plan fingerprint. Testnet returns an official Agent Pass wallet review URL and exact rules/warnings; only the owner signs. Poll get_review_request for verified chain authorization, never self-confirm. Paper mode uses explicitly simulated local confirmation. Start remains separate. Reuse requestId only for the same plan.",
203
+ inputSchema: { planId: z.string().uuid(), requestId: z.string().uuid() },
204
+ outputSchema: QuoteDataSchema,
205
+ annotations: propose,
206
+ }, ({ planId, requestId }) => api(`/api/plans/${planId}/authorization`, { requestId }));
207
+ server.registerTool("get_review_request", {
208
+ description: "Poll a review. Testnet confirmation requires matching owner/network/plan/policy verified from the official session and chain; browser closure is not proof. Paper reviews expire after 15 minutes. Never confirm/sign for the owner.",
209
+ inputSchema: { reviewId: z.string().uuid() },
210
+ outputSchema: QuoteDataSchema,
211
+ annotations: readOnly,
212
+ }, ({ reviewId }) => api(`/api/requests/${reviewId}`));
213
+ server.registerTool("create_plan", {
214
+ description: "Create a PAPER draft from approved strategy parameters. Then request_plan_authorization to obtain a web review URL. No approval or start is implied; this draft creation is not idempotent.",
215
+ inputSchema: {
216
+ botId: z.enum(["steady-dca", "price-watch"]),
217
+ amountUsdc: z.number(),
218
+ budgetUsdc: z.number(),
219
+ intervalSeconds: z.number().optional(),
220
+ targetPrice: z.number().optional(),
221
+ slippageBps: z.number().optional(),
222
+ durationHours: z.number().optional(),
223
+ dailyLimitUsdc: z.number().optional(),
224
+ },
225
+ outputSchema: QuoteDataSchema,
226
+ annotations: mutate,
227
+ }, (args) => api("/api/plans", args));
228
+ server.registerTool("review_plan", {
229
+ description: "Read a plan's exact parameters, fingerprint and history. Browser authorization remains a separate review request.",
230
+ inputSchema: { planId: z.string().uuid() },
231
+ outputSchema: QuoteDataSchema,
232
+ annotations: readOnly,
233
+ }, ({ planId }) => api(`/api/plans/${planId}`));
234
+ server.registerTool("list_plans", {
235
+ description: "Read plans, portfolio, mode, valuation provenance, PnL availability and independent runner state. Testnet proceeds without cost basis are not profit.",
236
+ inputSchema: {},
237
+ outputSchema: QuoteDataSchema,
238
+ annotations: readOnly,
239
+ }, () => api("/api/portfolio"));
240
+ server.registerTool("list_transactions", {
241
+ description: "Read execution records, optionally filtered to a plan. Testnet records contain actual confirmed digests, fills and net gas when verified. Pending or incomplete receipts are not fills. Paper identifiers and fills are simulated.",
242
+ inputSchema: { planId: z.string().uuid().optional() },
243
+ outputSchema: QuoteDataSchema,
244
+ annotations: readOnly,
245
+ }, ({ planId }) => api(`/api/transactions${planId ? `?planId=${encodeURIComponent(planId)}` : ""}`));
246
+ for (const action of ["start", "pause", "resume", "stop", "revoke"]) {
247
+ server.registerTool(`${action}_plan`, {
248
+ description: `${action} a plan in the runtime mode. Testnet Start/resume requires matching verified onchain authorization and explicit user intent. Pause/Stop block new submissions; submitted digests still reconcile. Testnet Revoke stops local submissions and returns the official owner wallet review URL; only report onchain revoked after fresh confirmation. Paper revoke is simulation. Holdings are not sold.`,
249
+ inputSchema: { planId: z.string().uuid() },
250
+ outputSchema: QuoteDataSchema,
251
+ annotations: {
252
+ ...mutate,
253
+ destructiveHint: ["stop", "revoke"].includes(action),
254
+ idempotentHint: action === "revoke",
255
+ },
256
+ }, ({ planId }) => api(`/api/plans/${planId}/${action}`, {}));
257
+ }
258
+ // Intentionally no confirm/approve tool: only a direct user action on the review page confirms.
259
+ await server.connect(new StdioServerTransport());
@@ -0,0 +1,258 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ export const ONBOARDING_TTL_MS = 15 * 60 * 1000;
4
+ export const WALLET_PRESENCE_TTL_MS = 45 * 1000;
5
+ const MAX_ENTRIES = 64;
6
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ const ADDRESS = /^0x[0-9a-f]{64}$/i;
8
+ const OPEN_ERROR = "The browser could not be opened. Open the local URL manually to connect your wallet.";
9
+ function localBase(value) {
10
+ const url = new URL(value);
11
+ if (url.protocol !== "http:" ||
12
+ url.hostname !== "127.0.0.1" ||
13
+ !url.port ||
14
+ url.username ||
15
+ url.password ||
16
+ url.pathname !== "/" ||
17
+ url.search ||
18
+ url.hash)
19
+ throw new Error("Onboarding requires an HTTP loopback runtime URL with an explicit port.");
20
+ return url;
21
+ }
22
+ /** Launch only a generated local challenge URL. The operating system never receives shell code. */
23
+ export async function openOnboardingBrowser(value) {
24
+ const url = new URL(value);
25
+ if (!/^#connect\/[0-9a-f-]{36}$/i.test(url.hash) ||
26
+ !UUID.test(url.hash.slice("#connect/".length)))
27
+ throw new Error("Invalid local onboarding URL.");
28
+ const base = new URL(url);
29
+ base.hash = "";
30
+ localBase(base.toString());
31
+ const [command, args] = process.platform === "darwin"
32
+ ? ["open", [url.toString()]]
33
+ : process.platform === "win32"
34
+ ? [
35
+ "rundll32",
36
+ ["url.dll,FileProtocolHandler", url.toString()],
37
+ ]
38
+ : process.platform === "linux"
39
+ ? ["xdg-open", [url.toString()]]
40
+ : (() => {
41
+ throw new Error("Automatic browser opening is unavailable on this platform.");
42
+ })();
43
+ await new Promise((resolve, reject) => {
44
+ execFile(command, [...args], { shell: false, timeout: 8000, windowsHide: true, maxBuffer: 4096 }, (error) => (error ? reject(new Error(OPEN_ERROR)) : resolve()));
45
+ });
46
+ }
47
+ /** Browser identity is transient observation, never a Pass authorization or a trading instruction. */
48
+ export class Onboarding {
49
+ base;
50
+ now;
51
+ openBrowser;
52
+ challenges = new Map();
53
+ byRequest = new Map();
54
+ presence = new Map();
55
+ constructor(options) {
56
+ this.base = localBase(options.baseUrl);
57
+ this.now = options.now ?? Date.now;
58
+ this.openBrowser = options.openBrowser ?? openOnboardingBrowser;
59
+ }
60
+ url(id) {
61
+ return `${this.base.origin}/#connect/${id}`;
62
+ }
63
+ get(id) {
64
+ if (!UUID.test(id))
65
+ throw new Error("Invalid onboarding id.");
66
+ const entry = this.challenges.get(id);
67
+ if (!entry)
68
+ throw new Error("Onboarding request not found. Begin a new connection request.");
69
+ return entry;
70
+ }
71
+ freshPresence() {
72
+ const now = this.now();
73
+ for (const [id, value] of this.presence)
74
+ if (now - value.observedAt >= WALLET_PRESENCE_TTL_MS)
75
+ this.presence.delete(id);
76
+ return [...this.presence.values()];
77
+ }
78
+ uniqueConnection() {
79
+ const fresh = this.freshPresence();
80
+ if (new Set(fresh.map((value) => value.address)).size !== 1)
81
+ return undefined;
82
+ return fresh.sort((a, b) => b.observedAt - a.observedAt)[0];
83
+ }
84
+ currentConnection() {
85
+ const connection = this.uniqueConnection();
86
+ return {
87
+ connected: Boolean(connection),
88
+ address: connection?.address ?? null,
89
+ };
90
+ }
91
+ refresh(entry) {
92
+ if (this.now() >= Date.parse(entry.expiresAt)) {
93
+ entry.status = "expired";
94
+ entry.address = null;
95
+ delete entry.browserId;
96
+ delete entry.error;
97
+ }
98
+ else if (entry.status === "connected") {
99
+ this.freshPresence();
100
+ const current = entry.browserId
101
+ ? this.presence.get(entry.browserId)
102
+ : undefined;
103
+ if (!current || current.address !== entry.address) {
104
+ entry.status = "awaiting_wallet";
105
+ entry.address = null;
106
+ entry.needsOpen = true;
107
+ delete entry.browserId;
108
+ delete entry.error;
109
+ }
110
+ }
111
+ }
112
+ dto(entry) {
113
+ this.refresh(entry);
114
+ return {
115
+ id: entry.id,
116
+ requestId: entry.requestId,
117
+ status: entry.status,
118
+ url: this.url(entry.id),
119
+ browserOpened: entry.browserOpened,
120
+ address: entry.address,
121
+ ...(entry.clientName ? { clientName: entry.clientName } : {}),
122
+ onboardingComplete: entry.status === "connected",
123
+ authorizationGranted: false,
124
+ tradingStarted: false,
125
+ createdAt: entry.createdAt,
126
+ expiresAt: entry.expiresAt,
127
+ ...(entry.error ? { error: entry.error } : {}),
128
+ };
129
+ }
130
+ bind(entry, connection) {
131
+ entry.browserId = connection.browserId;
132
+ entry.address = connection.address;
133
+ entry.status = "connected";
134
+ delete entry.needsOpen;
135
+ delete entry.error;
136
+ }
137
+ makeRoom() {
138
+ if (this.challenges.size < MAX_ENTRIES)
139
+ return;
140
+ for (const [id, entry] of this.challenges) {
141
+ this.refresh(entry);
142
+ if (entry.status === "expired" && !entry.opening) {
143
+ this.challenges.delete(id);
144
+ this.byRequest.delete(entry.requestId);
145
+ if (this.challenges.size < MAX_ENTRIES)
146
+ return;
147
+ }
148
+ }
149
+ throw new Error("Too many active onboarding requests. Reuse the existing request or wait for expiry.");
150
+ }
151
+ async begin(requestId, retryBrowser = false, openBrowser = true, clientName) {
152
+ if (!UUID.test(requestId))
153
+ throw new Error("Onboarding requestId must be a UUID.");
154
+ const existingId = this.byRequest.get(requestId);
155
+ let entry = existingId ? this.get(existingId) : undefined;
156
+ const created = !entry;
157
+ if (!entry) {
158
+ this.makeRoom();
159
+ const now = this.now();
160
+ entry = {
161
+ id: randomUUID(),
162
+ requestId,
163
+ status: "awaiting_wallet",
164
+ browserOpened: false,
165
+ address: null,
166
+ createdAt: new Date(now).toISOString(),
167
+ expiresAt: new Date(now + ONBOARDING_TTL_MS).toISOString(),
168
+ };
169
+ this.challenges.set(entry.id, entry);
170
+ this.byRequest.set(requestId, entry.id);
171
+ }
172
+ if (clientName)
173
+ entry.clientName = clientName.trim().slice(0, 100);
174
+ this.refresh(entry);
175
+ if (entry.status === "expired")
176
+ return this.dto(entry);
177
+ if (entry.status !== "connected") {
178
+ const connection = this.uniqueConnection();
179
+ if (connection)
180
+ this.bind(entry, connection);
181
+ }
182
+ if (entry.status === "connected")
183
+ return this.dto(entry);
184
+ if (entry.opening) {
185
+ await entry.opening;
186
+ return this.dto(entry);
187
+ }
188
+ if (!openBrowser)
189
+ return this.dto(entry);
190
+ if (!created && !retryBrowser && !entry.needsOpen)
191
+ return this.dto(entry);
192
+ const target = entry;
193
+ delete target.needsOpen;
194
+ target.opening = Promise.resolve()
195
+ .then(() => this.openBrowser(this.url(target.id)))
196
+ .then(() => {
197
+ target.browserOpened = true;
198
+ if (target.status === "browser_open_failed")
199
+ target.status = "awaiting_wallet";
200
+ delete target.error;
201
+ }, () => {
202
+ if (target.status !== "connected" && target.status !== "expired") {
203
+ target.status = "browser_open_failed";
204
+ target.error = OPEN_ERROR;
205
+ }
206
+ })
207
+ .finally(() => {
208
+ delete target.opening;
209
+ });
210
+ await target.opening;
211
+ return this.dto(target);
212
+ }
213
+ status(id) {
214
+ return this.dto(this.get(id));
215
+ }
216
+ observe(browserId, value) {
217
+ if (typeof browserId !== "string" ||
218
+ !browserId.trim() ||
219
+ browserId.length > 128)
220
+ throw new Error("Invalid browser identity.");
221
+ if (value !== null && (typeof value !== "string" || !ADDRESS.test(value)))
222
+ throw new Error("Invalid wallet address.");
223
+ this.freshPresence();
224
+ if (value === null)
225
+ this.presence.delete(browserId);
226
+ else {
227
+ if (!this.presence.has(browserId) && this.presence.size >= MAX_ENTRIES)
228
+ throw new Error("Too many active browser connections.");
229
+ this.presence.set(browserId, {
230
+ browserId,
231
+ address: value.toLowerCase(),
232
+ observedAt: this.now(),
233
+ });
234
+ }
235
+ for (const entry of this.challenges.values())
236
+ this.refresh(entry);
237
+ }
238
+ complete(id, browserId, address) {
239
+ const entry = this.get(id);
240
+ this.refresh(entry);
241
+ if (address === null) {
242
+ this.observe(browserId, null);
243
+ return this.dto(entry);
244
+ }
245
+ if (entry.status === "expired")
246
+ return this.dto(entry);
247
+ if (typeof address !== "string" || !ADDRESS.test(address))
248
+ throw new Error("A connected wallet address is required.");
249
+ this.observe(browserId, address);
250
+ this.bind(entry, this.presence.get(browserId));
251
+ return this.dto(entry);
252
+ }
253
+ disconnectAll() {
254
+ this.presence.clear();
255
+ for (const entry of this.challenges.values())
256
+ this.refresh(entry);
257
+ }
258
+ }
@@ -0,0 +1,35 @@
1
+ import { catalog } from "../domain.js";
2
+ import { PRODUCT_NAME, STRATEGY_VERSION } from "../shared/constants.js";
3
+ /** Public strategy definitions; local receipt counts may be supplied explicitly. */
4
+ export function testnetCatalog(query = "", sampleSize = (_id) => 0) {
5
+ return catalog
6
+ .filter((bot) => `${bot.name} ${bot.description} ${PRODUCT_NAME}`
7
+ .toLowerCase()
8
+ .includes(query.toLowerCase()))
9
+ .map((bot) => ({
10
+ ...bot,
11
+ version: STRATEGY_VERSION,
12
+ mode: "testnet",
13
+ author: PRODUCT_NAME,
14
+ performance: {
15
+ status: "insufficient_history",
16
+ pnl30dUsdc: null,
17
+ roi30d: null,
18
+ sampleSize: sampleSize(bot.id),
19
+ },
20
+ }));
21
+ }
22
+ export function testnetStrategy(id, sampleSize) {
23
+ const bot = testnetCatalog("", sampleSize).find((entry) => entry.id === id);
24
+ if (!bot)
25
+ throw new Error("Strategy not found");
26
+ return {
27
+ ...bot,
28
+ rules: [
29
+ "Only the selected testnet pool, direction and owner-reviewed caps may be used.",
30
+ "DCA executes once per due interval; Price Watch at most once per chain UTC day. Missed opportunities are not replayed.",
31
+ "Pause/stop prevents new submissions; submitted digests still reconcile. Onchain revoke requires the owner signature.",
32
+ ],
33
+ skillMarkdown: `# ${bot.name}\n\nVersion: ${STRATEGY_VERSION}\nNetwork: Sui Testnet\nAssets: test SUI / demo USDC\n\n${bot.description}\n\nOwner-selected price limit, exact decimal input/budget/daily cap, whole-day term, route and gas limits bind the pass. Authorization never starts the independent local loop. Actual receipts and gas are reconciled by digest. Sale proceeds without acquisition cost basis are not presented as profit.`,
34
+ };
35
+ }
@@ -0,0 +1,89 @@
1
+ import fastifyStatic from "@fastify/static";
2
+ import Fastify from "fastify";
3
+ import { fileURLToPath } from "node:url";
4
+ import { z, ZodError } from "zod";
5
+ import { PRODUCT_NAME, SERVICE_ID } from "../shared/constants.js";
6
+ import { packageMetadata } from "../runtime/paths.js";
7
+ import { testnetCatalog, testnetStrategy } from "./catalog.js";
8
+ export function publicSetup() {
9
+ return {
10
+ prompt: `Set up Agent Pass Plugin locally from the public npm package @cmdoss/agent-pass-plugin@${packageMetadata().version}. Use Node 22.13+ and npm. Identify whether this is Claude Code or Codex and run PORT=4317 AGENT_PASS_PLUGIN_MODE=testnet npx --yes @cmdoss/agent-pass-plugin@${packageMetadata().version} setup --client claude (or codex) --register --start. Read the installed README.md and trading skill at skillPath in the setup output. Do not clone the private GitHub repository or build inside the installed package. Verify the agent-pass-plugin MCP tools, then marketplace_status and onboard; poll onboarding_status until the wallet is actually connected. Keep all keys, signing, plan data and the runner on my machine. Use Sui Testnet demo assets. Help me choose a strategy and collect its explicit amounts, price, budget, duration and gas limits. Owner authorization and Start are separate user actions. Do not authorize, sign or Start on my behalf, and never request a private key.`,
11
+ promptPreview: "Set up Agent Pass Plugin on your machine and connect its MCP.",
12
+ };
13
+ }
14
+ /** Hosted catalog only. This module never opens a store, signer or runner. */
15
+ export async function buildPublicServer() {
16
+ const app = Fastify({ logger: false, bodyLimit: 16384 });
17
+ app.addHook("onRequest", async (req, reply) => {
18
+ if (!["GET", "HEAD"].includes(req.method))
19
+ return reply.header("Allow", "GET, HEAD").code(405).send({
20
+ error: "Trading and wallet operations run in your local app.",
21
+ });
22
+ });
23
+ app.addHook("onSend", async (_req, reply) => {
24
+ reply
25
+ .header("X-Content-Type-Options", "nosniff")
26
+ .header("Referrer-Policy", "no-referrer")
27
+ .header("Cache-Control", "no-store")
28
+ .header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
29
+ });
30
+ app.setErrorHandler((error, _req, reply) => {
31
+ reply.code(error instanceof ZodError ? 400 : 404).send({
32
+ error: error instanceof ZodError
33
+ ? "Invalid catalog query."
34
+ : "Resource not found.",
35
+ });
36
+ });
37
+ const wallet = {
38
+ usdc: null,
39
+ sui: null,
40
+ gasSui: null,
41
+ asOf: null,
42
+ source: null,
43
+ };
44
+ const status = () => ({
45
+ mode: "testnet",
46
+ deployment: "public",
47
+ network: "testnet",
48
+ owner: null,
49
+ catalog: testnetCatalog(),
50
+ plans: [],
51
+ wallet,
52
+ market: { price: null, asOf: null, source: null },
53
+ runner: null,
54
+ totalValueUsdc: null,
55
+ totalPnlUsdc: null,
56
+ });
57
+ app.get("/api/health", async () => ({
58
+ product: SERVICE_ID,
59
+ deployment: "public",
60
+ status: "ok",
61
+ executionEnabled: false,
62
+ }));
63
+ app.get("/api/status", async () => status());
64
+ app.get("/api/account", async () => ({
65
+ mode: "testnet",
66
+ connected: false,
67
+ account: null,
68
+ authorizedOwner: null,
69
+ authorizationGranted: false,
70
+ wallet,
71
+ }));
72
+ app.get("/api/portfolio", async () => status());
73
+ app.get("/api/setup", async () => publicSetup());
74
+ app.get("/api/strategies", async (req) => testnetCatalog(z
75
+ .object({ query: z.string().max(100).optional() })
76
+ .strict()
77
+ .parse(req.query).query));
78
+ app.get("/api/strategies/:id", async (req) => testnetStrategy(z
79
+ .enum(["steady-dca", "price-watch"])
80
+ .parse(req.params.id)));
81
+ await app.register(fastifyStatic, {
82
+ root: fileURLToPath(new URL("../../public/", import.meta.url)),
83
+ index: "index.html",
84
+ });
85
+ for (const route of ["/directory", "/leaderboard", "/plans", "/review/:id"])
86
+ app.get(route, async (_req, reply) => reply.sendFile("index.html"));
87
+ app.log.info(`${PRODUCT_NAME} public catalog configured`);
88
+ return app;
89
+ }
@@ -0,0 +1,11 @@
1
+ import { buildPublicServer } from "./public/http.js";
2
+ const port = Number(process.env.PORT ?? 3000);
3
+ if (!Number.isInteger(port) || port < 1024 || port > 65535)
4
+ throw new Error("PORT must be an integer between 1024 and 65535.");
5
+ const app = await buildPublicServer();
6
+ for (const signal of ["SIGINT", "SIGTERM"])
7
+ process.once(signal, () => {
8
+ void app.close();
9
+ });
10
+ await app.listen({ host: "0.0.0.0", port });
11
+ console.log(`Agent Pass Plugin public catalog listening on port ${port}. Trading remains local.`);
@@ -0,0 +1,16 @@
1
+ import { DEFAULT_APP_PORT } from "../shared/constants.js";
2
+ import { dataDirectory } from "./paths.js";
3
+ export function readRuntimeConfig(env = process.env, cwd = process.cwd()) {
4
+ const port = Number(env.PORT ?? DEFAULT_APP_PORT);
5
+ if (!Number.isInteger(port) || port < 1024 || port > 65535)
6
+ throw new Error("PORT must be an integer between 1024 and 65535.");
7
+ const mode = env.AGENT_PASS_PLUGIN_MODE ?? "testnet";
8
+ if (mode !== "paper" && mode !== "testnet")
9
+ throw new Error("AGENT_PASS_PLUGIN_MODE must be testnet or paper. Mainnet execution is unavailable.");
10
+ return {
11
+ port,
12
+ mode,
13
+ directory: dataDirectory(env, cwd),
14
+ origin: `http://127.0.0.1:${port}`,
15
+ };
16
+ }