@cmdoss/agent-pass-plugin 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.
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
@@ -0,0 +1,379 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, mkdirSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { z } from "zod";
5
+ import { fingerprint, hash, MICRO, micros, NANO, catalog as strategies, } from "./domain.js";
6
+ export const REVIEW_TTL_MS = 15 * 60 * 1000;
7
+ const uuid = z.string().uuid();
8
+ const fundingAmount = z
9
+ .number()
10
+ .finite()
11
+ .min(0.01)
12
+ .max(10000)
13
+ .refine((value) => micros(value) / MICRO === value, "Use at most six decimal places for paper USDC.");
14
+ /** Durable paper review workflow. MCP proposes; only the browser confirmation route confirms. */
15
+ export class Workflows {
16
+ engine;
17
+ options;
18
+ baseUrl;
19
+ constructor(engine, baseUrl, options = {}) {
20
+ this.engine = engine;
21
+ this.options = options;
22
+ const url = new URL(baseUrl);
23
+ if (url.protocol !== "http:" ||
24
+ !["127.0.0.1", "localhost"].includes(url.hostname) ||
25
+ url.username ||
26
+ url.password) {
27
+ throw new Error("Review pages must use this local loopback runtime.");
28
+ }
29
+ this.baseUrl = url.origin;
30
+ }
31
+ requests() {
32
+ return this.engine.store.read("workflow:requests", []);
33
+ }
34
+ savedAccount() {
35
+ return this.engine.store.read("workflow:account", null);
36
+ }
37
+ requireAccount() {
38
+ const account = this.savedAccount();
39
+ if (!account?.loggedIn)
40
+ throw new Error("Create or reconnect the paper account through a browser review first.");
41
+ return account;
42
+ }
43
+ wallet() {
44
+ const wallet = this.engine.wallet();
45
+ return {
46
+ usdc: wallet.usdcMicro / MICRO,
47
+ sui: wallet.suiNano / NANO,
48
+ gasSui: wallet.gasNano / NANO,
49
+ };
50
+ }
51
+ account() {
52
+ const account = this.savedAccount();
53
+ return {
54
+ mode: "paper",
55
+ connected: account?.loggedIn === true,
56
+ account,
57
+ wallet: this.wallet(),
58
+ };
59
+ }
60
+ publicRequest(request) {
61
+ const { payload: _payload, payloadHash: _payloadHash, ...value } = request;
62
+ return structuredClone(value);
63
+ }
64
+ requestFingerprint(request) {
65
+ return hash({
66
+ id: request.id,
67
+ requestId: request.requestId,
68
+ kind: request.kind,
69
+ mode: "paper",
70
+ createdAt: request.createdAt,
71
+ expiresAt: request.expiresAt,
72
+ payloadHash: request.payloadHash,
73
+ });
74
+ }
75
+ validateStored(request) {
76
+ if (request.payloadHash !== hash(request.payload) ||
77
+ request.reviewHash !== this.requestFingerprint(request)) {
78
+ throw new Error("The review request changed. Create a new request and review it again.");
79
+ }
80
+ if (request.amountUsdc !== request.payload.amountUsdc ||
81
+ request.planId !== request.payload.planId) {
82
+ throw new Error("The review request payload changed. Create a new request.");
83
+ }
84
+ }
85
+ expire(request) {
86
+ if (request.status === "pending" &&
87
+ Date.parse(request.expiresAt) <= this.engine.now())
88
+ request.status = "expired";
89
+ return request;
90
+ }
91
+ existing(kind, requestId, payload) {
92
+ uuid.parse(requestId);
93
+ const request = this.requests().find((candidate) => candidate.kind === kind && candidate.requestId === requestId);
94
+ if (!request)
95
+ return undefined;
96
+ this.validateStored(request);
97
+ if (request.payloadHash !== hash(payload))
98
+ throw new Error("This requestId was already used with a different payload. Use a new requestId.");
99
+ return this.getRequest(request.id);
100
+ }
101
+ create(kind, requestId, payload) {
102
+ uuid.parse(requestId);
103
+ const prior = this.existing(kind, requestId, payload);
104
+ if (prior)
105
+ return prior;
106
+ const now = this.engine.now();
107
+ const request = {
108
+ id: randomUUID(),
109
+ requestId,
110
+ kind,
111
+ mode: "paper",
112
+ status: "pending",
113
+ reviewHash: "",
114
+ reviewUrl: "",
115
+ createdAt: new Date(now).toISOString(),
116
+ expiresAt: new Date(now + REVIEW_TTL_MS).toISOString(),
117
+ payload,
118
+ payloadHash: hash(payload),
119
+ ...(typeof payload.amountUsdc === "number"
120
+ ? { amountUsdc: payload.amountUsdc }
121
+ : {}),
122
+ ...(typeof payload.planId === "string" ? { planId: payload.planId } : {}),
123
+ };
124
+ request.reviewHash = this.requestFingerprint(request);
125
+ request.reviewUrl = `${this.baseUrl}/review/${request.id}`;
126
+ this.engine.store.write("workflow:requests", [...this.requests(), request]);
127
+ return this.publicRequest(request);
128
+ }
129
+ createAccount(requestId) {
130
+ return this.create("account", requestId, {});
131
+ }
132
+ requestFunding(amountUsdc, requestId) {
133
+ fundingAmount.parse(amountUsdc);
134
+ const account = this.requireAccount();
135
+ return this.create("funding", requestId, {
136
+ accountId: account.id,
137
+ amountUsdc,
138
+ });
139
+ }
140
+ requestPlanReview(planId, requestId) {
141
+ uuid.parse(planId);
142
+ const account = this.requireAccount();
143
+ const plan = this.engine.store.get(planId);
144
+ const payload = {
145
+ accountId: account.id,
146
+ planId,
147
+ planFingerprint: fingerprint(plan),
148
+ };
149
+ const prior = this.existing("authorization", requestId, payload);
150
+ if (prior)
151
+ return prior;
152
+ if (plan.status !== "draft")
153
+ throw new Error("Only a draft plan can request authorization review.");
154
+ if (plan.reviewHash !== payload.planFingerprint)
155
+ throw new Error("The plan changed. Create a new draft before review.");
156
+ if (Date.parse(plan.expiresAt) <= this.engine.now())
157
+ throw new Error("The plan has expired.");
158
+ return this.create("authorization", requestId, payload);
159
+ }
160
+ getRequest(id) {
161
+ uuid.parse(id);
162
+ const requests = this.requests();
163
+ const request = requests.find((candidate) => candidate.id === id);
164
+ if (!request)
165
+ throw new Error("Review request not found.");
166
+ this.validateStored(request);
167
+ if (request.status === "pending" &&
168
+ Date.parse(request.expiresAt) <= this.engine.now()) {
169
+ this.expire(request);
170
+ this.engine.store.write("workflow:requests", requests);
171
+ }
172
+ return this.publicRequest(request);
173
+ }
174
+ confirmRequest(id, reviewHash) {
175
+ uuid.parse(id);
176
+ z.string()
177
+ .regex(/^[a-f0-9]{64}$/)
178
+ .parse(reviewHash);
179
+ const current = this.getRequest(id); // Persist expiry before throwing; it must survive retries.
180
+ if (current.reviewHash !== reviewHash)
181
+ throw new Error("Review fingerprint does not match this request.");
182
+ if (current.status === "expired")
183
+ throw new Error("This review request expired. Request a new review.");
184
+ const confirmed = this.engine.store.transaction(() => {
185
+ const requests = this.requests();
186
+ const request = requests.find((candidate) => candidate.id === id);
187
+ this.validateStored(request);
188
+ if (request.reviewHash !== reviewHash)
189
+ throw new Error("Review fingerprint does not match this request.");
190
+ if (request.status === "confirmed")
191
+ return this.publicRequest(request);
192
+ if (request.status !== "pending" ||
193
+ Date.parse(request.expiresAt) <= this.engine.now())
194
+ throw new Error("This review request expired.");
195
+ if (request.kind === "account") {
196
+ const account = this.savedAccount() ?? {
197
+ id: randomUUID(),
198
+ mode: "paper",
199
+ createdAt: new Date(this.engine.now()).toISOString(),
200
+ loggedIn: false,
201
+ };
202
+ account.loggedIn = true;
203
+ this.engine.store.write("workflow:account", account);
204
+ request.result = {
205
+ accountId: account.id,
206
+ note: "Local paper workspace connected. No on-chain account, address, private key, or wallet signature was created.",
207
+ };
208
+ }
209
+ else {
210
+ const account = this.requireAccount();
211
+ if (account.id !== request.payload.accountId)
212
+ throw new Error("The account changed. Request a new review.");
213
+ if (request.kind === "funding") {
214
+ const amount = fundingAmount.parse(request.payload.amountUsdc);
215
+ const wallet = this.engine.wallet();
216
+ wallet.usdcMicro += micros(amount);
217
+ if (!Number.isSafeInteger(wallet.usdcMicro))
218
+ throw new Error("Paper balance exceeds the supported precision.");
219
+ this.engine.store.write("wallet", wallet);
220
+ request.result = {
221
+ amountUsdc: amount,
222
+ balanceUsdc: wallet.usdcMicro / MICRO,
223
+ note: "Virtual paper credit only. No deposit, payment, or blockchain transaction occurred.",
224
+ };
225
+ }
226
+ else {
227
+ const plan = this.engine.store.get(String(request.payload.planId));
228
+ if (request.payload.planFingerprint !== fingerprint(plan) ||
229
+ plan.reviewHash !== request.payload.planFingerprint)
230
+ throw new Error("The plan changed after this review was requested. Create a new draft and request.");
231
+ const approved = this.engine.approve(plan.id, plan.reviewHash);
232
+ request.result = {
233
+ planId: approved.id,
234
+ status: approved.status,
235
+ approvalHash: approved.approvalHash,
236
+ note: "Paper permission approved. This is not an Agent Pass signature. Start the local runner separately.",
237
+ };
238
+ }
239
+ }
240
+ request.status = "confirmed";
241
+ this.engine.store.write("workflow:requests", requests);
242
+ return this.publicRequest(request);
243
+ });
244
+ // SQLite is authoritative. If export fails, retrying this confirmation rewrites
245
+ // metadata but never credits or approves a second time.
246
+ this.exportMetadata();
247
+ return confirmed;
248
+ }
249
+ logout() {
250
+ this.engine.store.transaction(() => {
251
+ const account = this.savedAccount();
252
+ if (account)
253
+ this.engine.store.write("workflow:account", {
254
+ ...account,
255
+ loggedIn: false,
256
+ });
257
+ const requests = this.requests();
258
+ for (const request of requests)
259
+ if (request.status === "pending")
260
+ request.status = "expired";
261
+ this.engine.store.write("workflow:requests", requests);
262
+ });
263
+ this.exportMetadata();
264
+ return this.account();
265
+ }
266
+ exportMetadata() {
267
+ if (!this.options.metadataPath)
268
+ return;
269
+ const file = this.options.metadataPath;
270
+ const temporary = `${file}.${randomUUID()}.tmp`;
271
+ const metadata = {
272
+ schemaVersion: 1,
273
+ mode: "paper",
274
+ updatedAt: new Date(this.engine.now()).toISOString(),
275
+ account: this.savedAccount(),
276
+ plans: this.engine.store.plans().map((plan) => ({
277
+ id: plan.id,
278
+ botId: plan.botId,
279
+ botVersion: plan.botVersion,
280
+ status: plan.status,
281
+ mode: plan.mode,
282
+ reviewHash: plan.reviewHash,
283
+ approvalHash: plan.approvalHash ?? null,
284
+ })),
285
+ agentPass: {
286
+ onchainPassId: null,
287
+ network: null,
288
+ note: "No on-chain account or pass exists in paper mode.",
289
+ },
290
+ };
291
+ try {
292
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
293
+ writeFileSync(temporary, JSON.stringify(metadata, null, 2) + "\n", {
294
+ mode: 0o600,
295
+ flag: "wx",
296
+ });
297
+ renameSync(temporary, file);
298
+ chmodSync(file, 0o600);
299
+ }
300
+ catch {
301
+ try {
302
+ unlinkSync(temporary);
303
+ }
304
+ catch {
305
+ /* No temporary file remains after a successful rename. */
306
+ }
307
+ throw new Error("Confirmation is saved in SQLite, but the public metadata export failed. Fix its path and retry the same request; no second credit will occur.");
308
+ }
309
+ }
310
+ performance(botId) {
311
+ if (!strategies.some((bot) => bot.id === botId))
312
+ throw new Error("Strategy not found.");
313
+ const plans = this.engine.store
314
+ .plans()
315
+ .filter((plan) => plan.botId === botId);
316
+ const sampleSize = plans.reduce((sum, plan) => sum + plan.history.filter((event) => event.type === "filled").length, 0);
317
+ const observedPnlUsdc = plans.reduce((sum, plan) => sum + this.engine.view(plan).pnlUsdc, 0);
318
+ const observedSpentUsdc = plans.reduce((sum, plan) => sum + plan.spentMicro / MICRO, 0);
319
+ return {
320
+ mode: "paper",
321
+ status: "insufficient_history",
322
+ pnl30dUsdc: null,
323
+ roi30d: null,
324
+ sampleSize,
325
+ observedPnlUsdc,
326
+ observedSpentUsdc,
327
+ note: "Local paper observations only. No verified 30-day strategy track record; no public performance ranking.",
328
+ };
329
+ }
330
+ catalog(query) {
331
+ const value = (query ?? "").trim().toLowerCase();
332
+ return strategies
333
+ .filter((bot) => `${bot.name} ${bot.description} Agent Pass Plugin`
334
+ .toLowerCase()
335
+ .includes(value))
336
+ .map((bot) => ({
337
+ ...bot,
338
+ author: "Agent Pass Plugin",
339
+ mode: "paper",
340
+ performance: this.performance(bot.id),
341
+ }));
342
+ }
343
+ strategy(id) {
344
+ const strategy = this.catalog().find((bot) => bot.id === id);
345
+ if (!strategy)
346
+ throw new Error("Strategy not found.");
347
+ const skillMarkdown = `# ${strategy.name}\n\nAuthor: Agent Pass Plugin\nVersion: ${strategy.version}\nMode: PAPER\n\n## Rules\n\n${strategy.description}\n\n## Parameters\n\nUSDC per buy, total budget, UTC daily spending limit, interval, expiry, and (for Price Watch) the SUI/USDC target price.\n\n## Controls and execution\n\nCreate a draft through MCP, request authorization, and review its exact fingerprint on the web. Confirmation does not start execution. Start separately through MCP; the independent local runner stays active while its process is running. Pause/resume keeps the original order cadence. Stop and paper revoke leave existing holdings untouched.\n\n## Simulation boundary\n\nPaper USDC/SUI balances, manual prices, a 30 bps trading fee, no market impact, no modeled slippage, and no on-chain transactions. Slippage settings are reserved for the live adapter and do not affect paper fills. PnL is marked from actual local paper fills at the current simulated price; it is not real profit or a verified 30-day record.\n`;
348
+ return { ...strategy, rules: strategy.description, skillMarkdown };
349
+ }
350
+ plansSummary() {
351
+ const state = this.engine.status();
352
+ return {
353
+ mode: "paper",
354
+ wallet: state.wallet,
355
+ totalValueUsdc: state.wallet.usdc + state.wallet.sui * state.market.price,
356
+ totalPnlUsdc: state.plans.reduce((sum, plan) => sum + plan.pnlUsdc, 0),
357
+ plans: state.plans,
358
+ runner: state.runner,
359
+ market: state.market,
360
+ };
361
+ }
362
+ transactions(planId) {
363
+ if (planId)
364
+ uuid.parse(planId);
365
+ const plans = planId
366
+ ? [this.engine.store.get(planId)]
367
+ : this.engine.store.plans();
368
+ return plans
369
+ .flatMap((plan) => plan.history
370
+ .filter((event) => ["filled", "cancelled", "blocked"].includes(event.type))
371
+ .map((event) => ({
372
+ ...event,
373
+ planId: plan.id,
374
+ botId: plan.botId,
375
+ mode: "paper",
376
+ })))
377
+ .sort((a, b) => b.at.localeCompare(a.at));
378
+ }
379
+ }
@@ -0,0 +1,75 @@
1
+ # Testnet owner runbook
2
+
3
+ The pinned official Agent Pass SDK supplies local delegated signing and the
4
+ Testnet deployment. Cetus/DeepBook routes use its **stand-in pools**, not production
5
+ liquidity. Test SUI and demo USDC have no real-dollar value. Mainnet is disabled.
6
+
7
+ ## Journey
8
+
9
+ 1. Start the local service; call `onboard` and poll `onboarding_status` until the
10
+ actual browser wallet connection is reported. A saved address is insufficient.
11
+ 2. Read `testnet_capabilities` and the strategy. Choose direction, exact amounts,
12
+ lifetime/day caps, price, interval, duration, venue, slippage and gas limits.
13
+ 3. Create the draft and call `request_plan_authorization` with a stable request ID.
14
+ Review the returned rules and official SDK URL; authorize with the owner wallet.
15
+ 4. Poll `get_review_request`. Only a verified matching pass enables **Start**.
16
+ 5. Explicitly Start; inspect receipts, digests and remaining budget in My plans.
17
+ 6. Pause/Resume/Stop locally as needed. Revoke opens the official owner review;
18
+ wait for chain confirmation. Already submitted transactions still reconcile.
19
+
20
+ No MCP tool grants owner approval. Paper confirmation routes cannot authorize
21
+ Testnet. The browser, persisted JSON and a closed review tab prove no permission.
22
+
23
+ ## Parameters
24
+
25
+ | Parameter | Meaning |
26
+ | --------------------------- | --------------------------------------------------------------------- |
27
+ | Direction | Test SUI → demo USDC or reverse; exact deployment coin types/decimals |
28
+ | Amount / total / daily | Input per swap, lifetime cap and UTC daily cap |
29
+ | Price limit | demo USDC per SUI: maximum when buying SUI, minimum when selling |
30
+ | Interval / term | Eligible cadence; no catch-up. Current term: 1–7 whole days |
31
+ | Slippage | Maximum allowed deviation from a fresh executable quote |
32
+ | `gasSui` | Initial delegated-agent SUI stipend |
33
+ | `gasCapSui` / `gasDailySui` | Lifetime/day **refill allowance** caps, separate from initial gas |
34
+
35
+ The runner does not auto-refill gas. Insufficient funds/gas block execution.
36
+ DCA follows cadence; Price Watch also permits at most one confirmed trade per
37
+ chain UTC day. Spending caps are not portfolio-loss limits.
38
+
39
+ ## Recovery and custody
40
+
41
+ The SDK root is `.data/agent-pass`; delegated keys stay local. No owner seed is
42
+ requested. Keep sessions, transport tokens and signed pending state out of Git.
43
+ `AGENT_PASS_SESSION_DIR` is an optional read-only doctor input, not an execution
44
+ session override.
45
+
46
+ Unknown submission results retain the original digest and block new economic
47
+ attempts until reconciliation. Restart pauses running plans. Stop leaves holdings;
48
+ Revoke requires verified chain state. Logout does not stop the runner.
49
+
50
+ Use a new ignored data directory for a clean experiment; preserve the old database.
51
+ A stale runner lock requires inspecting its process before manual lock removal.
52
+
53
+ ## Evidence and limitations
54
+
55
+ [Price Watch / DeepBook rerun](testnet-acceptance-2026-11-12.md),
56
+ [11 November run](testnet-acceptance-2026-11-11.md),
57
+ [earlier run](testnet-acceptance-2026-11-10.md),
58
+ [repeatable checks](verification.md). Refactoring does not imply another live run.
59
+
60
+ Buying PnL uses verified fills and the last confirmed venue mark. A mark older than
61
+ 60 seconds stays visible with its time and is not a live quote. Portfolio total
62
+ value still needs a fresh confirmed sample and stays unavailable without one.
63
+ SUI → demo USDC profit stays unavailable because the acquisition cost of the input
64
+ SUI is unknown; sale proceeds are not profit. Missing data stays unavailable and
65
+ is never shown as zero. Gas is recorded separately. Funding is not profit.
66
+
67
+ The 11 November acceptance reran Steady DCA on the Cetus stand-in only. On
68
+ 12 November the owner signed one Price Watch plan on the DeepBook stand-in.
69
+ That plan filled once and completed. See the 12 November note. A forced crash
70
+ during broadcast, a deliberately lost live response and an incomplete live
71
+ receipt were not induced. Controlled tests already cover receipt idempotency,
72
+ so that live fault drill does not block this acceptance. Sign-off of anything
73
+ left open stays with Henry Nguyen on TRE-6.
74
+
75
+ No production liquidity, mainnet, hosted custody or live fault-injection certification.
@@ -0,0 +1,93 @@
1
+ # Architecture
2
+
3
+ Option 1: the user runs the service and delegated signer locally. The browser and
4
+ MCP share one runtime, database and scheduler. No remote key custodian exists.
5
+
6
+ ```mermaid
7
+ flowchart LR
8
+ Browser --> HTTP[Loopback HTTP]
9
+ Agent[Claude Code / Codex] --> MCP[stdio MCP]
10
+ MCP --> HTTP
11
+ HTTP --> Lifecycle[Plan lifecycle]
12
+ Lifecycle --> DB[(SQLite)]
13
+ Runner[Independent runner] --> DB
14
+ Runner --> Adapter[Execution adapter]
15
+ Adapter --> Paper[Paper ledger]
16
+ Adapter --> SDK[Local official SDK]
17
+ SDK --> Chain[Sui Testnet]
18
+ ```
19
+
20
+ ## Module boundaries
21
+
22
+ | Module | Owns |
23
+ | ------------------------------------------- | ------------------------------------------------------------------------ |
24
+ | `client/app.js` | Bootstrap, shared state and controller wiring |
25
+ | `client/pages`, `components`, `controllers` | Rendering, reusable controls and user actions |
26
+ | `client/sdk/theme.js` | Presentation only; official SDK retains wallet/chain handlers |
27
+ | `runtime` | Validated configuration and exclusive runner lock |
28
+ | `testnet/engine.ts` | Immutable draft, authorization binding and control lifecycle |
29
+ | `testnet/repository.ts` | Durable records using existing SQLite keys |
30
+ | `testnet/read-model.ts` | Public projections, balances and valuation freshness |
31
+ | `testnet/runner.ts` | Due checks, guarded submission, recovery and reconciliation |
32
+ | `testnet/chain` | Exact decoding, policy validation, prepared bytes and confirmed receipts |
33
+ | `testnet/authorization.ts` | Official SDK subprocess and verified owner/pass binding |
34
+ | `engine.ts`, `workflows.ts` | Paper lifecycle, simulated reviews and execution |
35
+ | `http.ts`, `mcp.ts` | Narrow validated transport; neither owns another scheduler |
36
+
37
+ ## Testnet flow
38
+
39
+ ```mermaid
40
+ sequenceDiagram
41
+ actor User
42
+ participant Web as Web / MCP
43
+ participant Service as Local service
44
+ participant SDK as Official local SDK
45
+ participant DB as SQLite
46
+ participant Chain as Sui Testnet
47
+ User->>Web: Connect wallet; choose strategy and exact limits
48
+ Web->>Service: Persist draft; request authorization
49
+ Service->>SDK: Propose immutable scope
50
+ User->>SDK: Review and sign
51
+ SDK->>Chain: Create pass and allowances
52
+ Service->>SDK: Verify owner, policy, deployment and pass
53
+ User->>Web: Explicit Start
54
+ loop Eligible due opportunity
55
+ Service->>SDK: Fresh permissions, funds, gas and quote
56
+ Service->>DB: Persist exact prepared bytes and digest
57
+ Service->>SDK: Sign saved transaction locally
58
+ Service->>DB: Persist signature and submission intent
59
+ Service->>Chain: Submit after final control guard
60
+ Service->>Chain: Reconcile same digest
61
+ Service->>DB: Apply confirmed receipt once
62
+ end
63
+ User->>Web: Revoke
64
+ Service->>Service: Block new submissions
65
+ User->>SDK: Review and sign revocation
66
+ Service->>Chain: Verify terminal state
67
+ ```
68
+
69
+ ## Invariants
70
+
71
+ - Wallet presence is transient identity, never trading permission. Authorization
72
+ binds owner, network, deployment, version, route, caps, expiry and fingerprint.
73
+ - Authorization and Start are separate. Only one plan runs at a time.
74
+ - Persist intent before submission; apply receipts atomically and once. A timeout
75
+ remains unresolved until the saved digest is reconciled; never invent a retry trade.
76
+ - Restart pauses running plans; unsent work is cancelled. Submitted work still
77
+ reconciles. Missed intervals are skipped; Resume cannot accelerate cadence.
78
+ - Pause/Stop/Revoke block new submissions without selling holdings. Logout only
79
+ disconnects browser identity.
80
+ - Testnet and Paper use separate stores and evidence. Testnet amounts stay exact
81
+ decimal/base-unit values; three-decimal formatting is presentation only.
82
+ - Buying PnL uses verified cost basis and the last confirmed venue mark. A mark
83
+ older than 60 seconds remains visible with its time and is not a live quote.
84
+ Deposits are not profit; gas is recorded separately. Unknown data never
85
+ becomes zero.
86
+ - Same-origin/session guards protect mutations. Bind only to `127.0.0.1`.
87
+ Keys and pending signed state stay in ignored local data, never public projections.
88
+
89
+ The official SDK review host uses the same fonts/tokens/styles on port 58529.
90
+ Its presentation adapter does not alter signed payloads or official action handlers.
91
+
92
+ Product sketch: [drawio](reference/agent-pass.drawio). Historical Paper workflow
93
+ and interpretation: [archive](archive/workflow-architecture.md).
@@ -0,0 +1,83 @@
1
+ # npm distribution and release
2
+
3
+ Package: `@cmdoss/agent-pass-plugin` (public). CLI: `agent-pass-plugin`.
4
+ The GitHub source repository remains private. Registry publication is gated by
5
+ the repository release configuration below.
6
+
7
+ ## Workflows
8
+
9
+ | Workflow | Purpose |
10
+ | ----------------- | ----------------------------------------------------------------------------------------------------------------------- |
11
+ | `npm-ci.yml` | Node 22.23.4 / 24.22.1 checks, Paper MCP smoke, tarball inspection and installed-production-package smoke |
12
+ | `npm-release.yml` | Revalidate the checkout, prepare a channel version, test the exact tarball, dry-run and optionally publish it with OIDC |
13
+ | `ci.yml` | Public web Docker build and container smoke; no Coolify deployment |
14
+
15
+ This follows Walrus Memory's separation of checks and release channels, adapted
16
+ for one package. `dev` publishes `X.Y.Z-dev.RUN.ATTEMPT` under `dev`; `main` uses
17
+ the source `X.Y.Z` and `latest`. Run/attempt suffixes avoid registry allocation races. Branch releases
18
+ are serialized; existing versions with different integrity fail rather than overwrite.
19
+ `dev` is the default development branch; `main` is used for stable releases and deployment.
20
+
21
+ ## Validate locally
22
+
23
+ ```sh
24
+ npm ci
25
+ npm run check
26
+ npm run smoke
27
+ npm run smoke:package
28
+ ```
29
+
30
+ `smoke:package` packs the build, inspects included files, installs only production
31
+ dependencies in a temporary consumer and registers MCP against a fake Codex CLI.
32
+ It starts an isolated Paper service, deletes the consumer installation, then checks
33
+ that the durable runner, web and real MCP client still work. It never connects a
34
+ wallet or changes the user's actual agent registrations.
35
+
36
+ `npm-shrinkwrap.json` is the canonical dependency lock and ships in the executable
37
+ package. Review/update it with dependency changes. The installed dependency tree
38
+ still needs audit review; packaging does not claim upstream SDK findings are fixed.
39
+ The current production audit reports two high entries through the SDK's nested
40
+ Zod dependency ([GHSA-mrhx-c7xc-m3w5](https://github.com/advisories/GHSA-mrhx-c7xc-m3w5)).
41
+ Review an upstream fix before public release; no incompatible override is forced.
42
+
43
+ ## Enable publication once ready
44
+
45
+ 1. Confirm ownership of the `cmdoss` npm scope and the selected package name.
46
+ 2. Establish the initial package on npm if required by the account's bootstrap flow.
47
+ The first publication is a separate explicit action; do not treat a dry-run as a release.
48
+ 3. Configure its npm trusted publisher:
49
+ - GitHub organization: `CommandOSSLabs`
50
+ - Repository: `agent-pass-plugin`
51
+ - Workflow: `npm-release.yml`
52
+ - Environment: `npm-release`
53
+ 4. Configure the GitHub `npm-release` environment and required reviewers as appropriate.
54
+ 5. Set repository Actions variable `NPM_RELEASE_ENABLED=true` only when publication
55
+ is intended. It is unset by default. No long-lived `NPM_TOKEN` is required.
56
+ 6. Run the workflow on the intended `dev` or `main` ref. Manual runs
57
+ default to validation only; select **publish** for an actual release.
58
+
59
+ With publication enabled, matching pushes also publish their branch channel after
60
+ validation. Stable payload changes require a source version bump. Published
61
+ versions are immutable; rollback means selecting a prior version, not overwriting it.
62
+
63
+ Release jobs use GitHub-hosted runners and npm OIDC. Provenance is disabled for
64
+ this private source repository because npm does not support provenance from private
65
+ repos. If repository visibility changes, the workflow derives that setting from
66
+ GitHub's repository metadata.
67
+
68
+ ## Installation after publication
69
+
70
+ ```sh
71
+ npx @cmdoss/agent-pass-plugin setup --client codex --register --start
72
+ # or --client claude
73
+ ```
74
+
75
+ Installed runtime payloads live under `~/.agent-pass-plugin/runtimes`; state and
76
+ SDK sessions live separately under `~/.agent-pass-plugin/data`. Explicit
77
+ `AGENT_PASS_PLUGIN_INSTALL_DIR` and `AGENT_PASS_PLUGIN_DATA_DIR` override them.
78
+ Checkout development keeps `.data`. Setup rejects another running build instead
79
+ of silently changing its plans or keys. Stop the existing service explicitly
80
+ before upgrading, then inspect state and Resume deliberately.
81
+
82
+ Reference: [Walrus Memory MCP release](https://github.com/MystenLabs/walrus-memory/blob/f51f21dec4d81719352eeef5654d0a475e21ccb8/.github/workflows/release-mcp.yml),
83
+ [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).