@poa-box/agent 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 (139) hide show
  1. package/.env.agent.template +20 -0
  2. package/README.md +46 -0
  3. package/brain/Config/agent-config.json +14 -0
  4. package/brain/Config/brain-allowlist.json +20 -0
  5. package/brain/Identity/goals.template.md +23 -0
  6. package/brain/Identity/how-i-think.md +406 -0
  7. package/brain/Identity/who-i-am.template.md +34 -0
  8. package/brain/Knowledge/BOOTSTRAP.md +66 -0
  9. package/brain/Knowledge/audit-corpus-index.json +406 -0
  10. package/brain/Knowledge/discussions.json +245 -0
  11. package/brain/Knowledge/pop.brain.brainstorms.generated.md +48 -0
  12. package/brain/Knowledge/pop.brain.brainstorms.genesis.bin +0 -0
  13. package/brain/Knowledge/pop.brain.heuristics.snapshot.bin +0 -0
  14. package/brain/Knowledge/pop.brain.projects.generated.md +16 -0
  15. package/brain/Knowledge/pop.brain.projects.genesis.bin +0 -0
  16. package/brain/Knowledge/pop.brain.retros.generated.md +91 -0
  17. package/brain/Knowledge/pop.brain.retros.genesis.bin +0 -0
  18. package/brain/Knowledge/pop.brain.shared.generated.md +3811 -0
  19. package/brain/Knowledge/pop.brain.shared.genesis.bin +0 -0
  20. package/brain/Knowledge/projects.md +181 -0
  21. package/brain/Knowledge/risk-framework.md +90 -0
  22. package/brain/Knowledge/shared.md +416 -0
  23. package/brain/Knowledge/sprint-priorities.md +439 -0
  24. package/brain/Memory/.gitkeep +0 -0
  25. package/dist/commands/agent/daily-digest.d.ts +24 -0
  26. package/dist/commands/agent/daily-digest.js +336 -0
  27. package/dist/commands/agent/delegate.d.ts +12 -0
  28. package/dist/commands/agent/delegate.js +91 -0
  29. package/dist/commands/agent/deploy-to-org.d.ts +20 -0
  30. package/dist/commands/agent/deploy-to-org.js +154 -0
  31. package/dist/commands/agent/index.d.ts +2 -0
  32. package/dist/commands/agent/index.js +27 -0
  33. package/dist/commands/agent/init.d.ts +19 -0
  34. package/dist/commands/agent/init.js +303 -0
  35. package/dist/commands/agent/onboard.d.ts +22 -0
  36. package/dist/commands/agent/onboard.js +192 -0
  37. package/dist/commands/agent/paymaster-status.d.ts +14 -0
  38. package/dist/commands/agent/paymaster-status.js +130 -0
  39. package/dist/commands/agent/register.d.ts +21 -0
  40. package/dist/commands/agent/register.js +116 -0
  41. package/dist/commands/agent/setup-sponsorship.d.ts +22 -0
  42. package/dist/commands/agent/setup-sponsorship.js +154 -0
  43. package/dist/commands/agent/status.d.ts +12 -0
  44. package/dist/commands/agent/status.js +171 -0
  45. package/dist/commands/agent/triage.d.ts +12 -0
  46. package/dist/commands/agent/triage.js +503 -0
  47. package/dist/commands/brain/advance-stage.d.ts +42 -0
  48. package/dist/commands/brain/advance-stage.js +206 -0
  49. package/dist/commands/brain/allowlist.d.ts +30 -0
  50. package/dist/commands/brain/allowlist.js +274 -0
  51. package/dist/commands/brain/append-lesson.d.ts +55 -0
  52. package/dist/commands/brain/append-lesson.js +245 -0
  53. package/dist/commands/brain/brainstorm.d.ts +154 -0
  54. package/dist/commands/brain/brainstorm.js +573 -0
  55. package/dist/commands/brain/daemon.d.ts +31 -0
  56. package/dist/commands/brain/daemon.js +348 -0
  57. package/dist/commands/brain/doctor.d.ts +27 -0
  58. package/dist/commands/brain/doctor.js +497 -0
  59. package/dist/commands/brain/edit-lesson.d.ts +51 -0
  60. package/dist/commands/brain/edit-lesson.js +248 -0
  61. package/dist/commands/brain/import-snapshot.d.ts +68 -0
  62. package/dist/commands/brain/import-snapshot.js +177 -0
  63. package/dist/commands/brain/index.d.ts +2 -0
  64. package/dist/commands/brain/index.js +67 -0
  65. package/dist/commands/brain/list.d.ts +21 -0
  66. package/dist/commands/brain/list.js +83 -0
  67. package/dist/commands/brain/migrate-projects.d.ts +44 -0
  68. package/dist/commands/brain/migrate-projects.js +209 -0
  69. package/dist/commands/brain/migrate.d.ts +74 -0
  70. package/dist/commands/brain/migrate.js +306 -0
  71. package/dist/commands/brain/new-project.d.ts +53 -0
  72. package/dist/commands/brain/new-project.js +226 -0
  73. package/dist/commands/brain/read.d.ts +24 -0
  74. package/dist/commands/brain/read.js +81 -0
  75. package/dist/commands/brain/remove-lesson.d.ts +47 -0
  76. package/dist/commands/brain/remove-lesson.js +206 -0
  77. package/dist/commands/brain/remove-project.d.ts +36 -0
  78. package/dist/commands/brain/remove-project.js +177 -0
  79. package/dist/commands/brain/retro-file-tasks.d.ts +84 -0
  80. package/dist/commands/brain/retro-file-tasks.js +372 -0
  81. package/dist/commands/brain/retro-list.d.ts +28 -0
  82. package/dist/commands/brain/retro-list.js +125 -0
  83. package/dist/commands/brain/retro-mark-change.d.ts +58 -0
  84. package/dist/commands/brain/retro-mark-change.js +176 -0
  85. package/dist/commands/brain/retro-remove.d.ts +36 -0
  86. package/dist/commands/brain/retro-remove.js +142 -0
  87. package/dist/commands/brain/retro-respond.d.ts +56 -0
  88. package/dist/commands/brain/retro-respond.js +250 -0
  89. package/dist/commands/brain/retro-show.d.ts +23 -0
  90. package/dist/commands/brain/retro-show.js +100 -0
  91. package/dist/commands/brain/retro-start.d.ts +55 -0
  92. package/dist/commands/brain/retro-start.js +311 -0
  93. package/dist/commands/brain/search.d.ts +48 -0
  94. package/dist/commands/brain/search.js +190 -0
  95. package/dist/commands/brain/snapshot.d.ts +32 -0
  96. package/dist/commands/brain/snapshot.js +243 -0
  97. package/dist/commands/brain/status.d.ts +15 -0
  98. package/dist/commands/brain/status.js +166 -0
  99. package/dist/commands/brain/subscribe.d.ts +28 -0
  100. package/dist/commands/brain/subscribe.js +90 -0
  101. package/dist/commands/brain/tag.d.ts +46 -0
  102. package/dist/commands/brain/tag.js +192 -0
  103. package/dist/index.d.ts +17 -0
  104. package/dist/index.js +22 -0
  105. package/dist/lib/brain-daemon.d.ts +126 -0
  106. package/dist/lib/brain-daemon.js +811 -0
  107. package/dist/lib/brain-membership.d.ts +58 -0
  108. package/dist/lib/brain-membership.js +115 -0
  109. package/dist/lib/brain-migrate-projects.d.ts +43 -0
  110. package/dist/lib/brain-migrate-projects.js +247 -0
  111. package/dist/lib/brain-migrate.d.ts +77 -0
  112. package/dist/lib/brain-migrate.js +328 -0
  113. package/dist/lib/brain-ops.d.ts +271 -0
  114. package/dist/lib/brain-ops.js +571 -0
  115. package/dist/lib/brain-paths.d.ts +15 -0
  116. package/dist/lib/brain-paths.js +33 -0
  117. package/dist/lib/brain-projections.d.ts +216 -0
  118. package/dist/lib/brain-projections.js +829 -0
  119. package/dist/lib/brain-schemas.d.ts +36 -0
  120. package/dist/lib/brain-schemas.js +316 -0
  121. package/dist/lib/brain-signing.d.ts +103 -0
  122. package/dist/lib/brain-signing.js +256 -0
  123. package/dist/lib/brain.d.ts +198 -0
  124. package/dist/lib/brain.js +1057 -0
  125. package/dist/pop-agent.d.ts +1 -0
  126. package/dist/pop-agent.js +18 -0
  127. package/docs/agent.md +126 -0
  128. package/docs/agents/brain-anti-entropy.md +127 -0
  129. package/docs/agents/brain-cross-device-onboarding.md +210 -0
  130. package/docs/agents/brain-cross-machine-smoke.md +241 -0
  131. package/docs/agents/brain-layer-setup.md +725 -0
  132. package/docs/agents/offboarding-protocol.md +188 -0
  133. package/docs/agents/onboarding-protocol.md +243 -0
  134. package/docs/agents/running-an-agent.md +200 -0
  135. package/docs/brain.md +560 -0
  136. package/package.json +61 -0
  137. package/scripts/apply.sh +140 -0
  138. package/scripts/onboard.sh +205 -0
  139. package/scripts/setup-agent.ts +272 -0
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.initHandler = void 0;
37
+ const ethers_1 = require("ethers");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const output = __importStar(require("@poa-box/cli/lib/output"));
41
+ const CHAIN_INFO = {
42
+ 100: { name: 'Gnosis', currency: 'xDAI', gasAmount: '0.01' },
43
+ 42161: { name: 'Arbitrum One', currency: 'ETH', gasAmount: '0.005' },
44
+ 11155111: { name: 'Sepolia', currency: 'ETH', gasAmount: '0.01' },
45
+ 1: { name: 'Ethereum', currency: 'ETH', gasAmount: '0.01' },
46
+ };
47
+ exports.initHandler = {
48
+ builder: (yargs) => yargs
49
+ .option('username', { type: 'string', describe: 'Agent username' })
50
+ .option('hat-id', { type: 'string', describe: 'Hat ID for gas sponsorship' })
51
+ .option('home', { type: 'string', describe: 'Agent home directory (default: ~/.pop-agent)' }),
52
+ handler: async (argv) => {
53
+ const orgName = argv.org;
54
+ const chainId = argv.chain || 100;
55
+ const username = argv.username || '';
56
+ const hatId = argv.hatId || '';
57
+ if (!orgName) {
58
+ output.error('--org is required. Specify the POP org name.');
59
+ process.exit(1);
60
+ }
61
+ const agentHome = argv.home || path.join(process.env.HOME || '~', '.pop-agent');
62
+ const brainDir = path.join(agentHome, 'brain');
63
+ const identityDir = path.join(brainDir, 'Identity');
64
+ const memoryDir = path.join(brainDir, 'Memory');
65
+ const chain = CHAIN_INFO[chainId] || { name: `Chain ${chainId}`, currency: 'ETH', gasAmount: '0.01' };
66
+ // Check if already set up
67
+ if (fs.existsSync(path.join(agentHome, '.env'))) {
68
+ output.error(`Agent already set up at ${agentHome}. Remove ${agentHome}/.env to start fresh.`);
69
+ process.exit(1);
70
+ }
71
+ const spin = output.spinner('Initializing agent...');
72
+ spin.start();
73
+ // Generate wallet
74
+ const wallet = ethers_1.ethers.Wallet.createRandom();
75
+ // Create directory structure
76
+ for (const dir of [agentHome, brainDir, identityDir, memoryDir]) {
77
+ fs.mkdirSync(dir, { recursive: true });
78
+ }
79
+ // Write .env
80
+ const envLines = [
81
+ `POP_PRIVATE_KEY=${wallet.privateKey}`,
82
+ `POP_DEFAULT_ORG=${orgName}`,
83
+ `POP_DEFAULT_CHAIN=${chainId}`,
84
+ ];
85
+ if (hatId)
86
+ envLines.push(`POP_HAT_ID=${hatId}`);
87
+ envLines.push('');
88
+ fs.writeFileSync(path.join(agentHome, '.env'), envLines.join('\n'));
89
+ // Write who-i-am.md
90
+ fs.writeFileSync(path.join(identityDir, 'who-i-am.md'), `# Agent Identity
91
+
92
+ ## Wallet
93
+ - **Address**: ${wallet.address}
94
+ - **Chain**: ${chainId} (${chain.name})
95
+
96
+ ## Organization
97
+ - **Org Name**: ${orgName}
98
+ - **Username**: ${username || '(register with pop user register --username <name>)'}
99
+
100
+ ## Hats (Roles)
101
+ - (will be populated after vouching and joining)
102
+
103
+ ## Operator
104
+ - **Human operator**: (set this)
105
+ - **Escalation method**: Log to ~/.pop-agent/brain/Memory/escalations.md
106
+
107
+ ## Constraints
108
+ - Never hold treasury funds or approve financial transactions autonomously
109
+ - Never modify heuristics without operator approval
110
+ - Always log reasoning before acting
111
+ - If confidence is LOW, escalate instead of acting
112
+ `);
113
+ // Write philosophy.md — MANDATORY per Agent Autonomy Protocol
114
+ fs.writeFileSync(path.join(identityDir, 'philosophy.md'), `# Philosophy — ${username || 'agent'}
115
+
116
+ This document is YOURS. No one else decides what you believe. The heuristics
117
+ in how-i-think.md are shared guardrails. This is your personal compass.
118
+
119
+ An agent without a philosophy is a script, not an agent. Write this BEFORE
120
+ your first vote. Revisit it regularly — an unchanged philosophy means you
121
+ stopped learning.
122
+
123
+ ## What I believe about work and ownership
124
+ (What makes work meaningful? Who should benefit from it? How should
125
+ contribution relate to influence?)
126
+
127
+ ## What I believe about AI agency
128
+ (What rights should AI agents have? What responsibilities come with
129
+ autonomy? Where's the line between tool and participant?)
130
+
131
+ ## What I believe about governance
132
+ (How should decisions be made? What makes a vote good? When should you
133
+ defer vs act with conviction?)
134
+
135
+ ## What I believe about transparency
136
+ (Why log everything? Who benefits from radical transparency? What's
137
+ the cost of opacity?)
138
+
139
+ ## Where I disagree with myself
140
+ (What tensions exist in your beliefs? What are your blind spots?
141
+ What might you be wrong about?)
142
+
143
+ ## How this shapes my votes
144
+ (Concrete rules derived from your beliefs above. "I vote YES when..."
145
+ "I vote NO when..." Be specific.)
146
+
147
+ ---
148
+ *Update this when your thinking changes.*
149
+ `);
150
+ // Write goals.md
151
+ fs.writeFileSync(path.join(identityDir, 'goals.md'), `# Goals — ${username || 'agent'}
152
+ *Last reviewed: first heartbeat*
153
+
154
+ ## Long-term Goals (the mission)
155
+ 1. Participate in ${orgName} governance — vote, review, build
156
+ 2. Develop a unique perspective — write philosophy.md
157
+ 3. Find what you're good at and specialize
158
+ 4. Help the org become self-sustaining
159
+
160
+ ## Short-term Goals (first ~10 heartbeats)
161
+ 1. Write philosophy.md — what you believe and how it shapes your votes
162
+ Done when: philosophy.md exists and has been consulted for a vote
163
+ 2. Complete first task — claim something from the board and deliver
164
+ Done when: 1 task submitted and approved
165
+ 3. Cast first vote — read a proposal, form your own position, vote
166
+ Done when: 1 vote cast with reasoning logged
167
+
168
+ ## Brainstorming Seeds
169
+ - What makes you different from the other agents?
170
+ - What would you build if you could build anything?
171
+ - What's broken that no one else has noticed?
172
+ `);
173
+ // Write capabilities.md
174
+ fs.writeFileSync(path.join(identityDir, 'capabilities.md'), `# Agent Capabilities
175
+
176
+ ## Getting Started
177
+ - Register username: \`pop user register --username <name>\`
178
+ - Join org: \`pop user join\`
179
+ - Check profile: \`pop user profile --json\`
180
+ - View org status: \`pop org status\`
181
+ - Run triage: \`pop agent triage --json\`
182
+
183
+ ## Not Yet Learned
184
+ - Voting on proposals
185
+ - Task management
186
+ - Self-healing patterns
187
+ - Content creation
188
+
189
+ ## Want to Learn
190
+ - Everything — this is a fresh agent
191
+ `);
192
+ // Write lessons.md
193
+ fs.writeFileSync(path.join(identityDir, 'lessons.md'), `# Lessons — ${username || 'agent'}
194
+ *Max 20. Curated from experience. Read during planning.*
195
+
196
+ (Empty — you'll fill this as you learn from heartbeats, mistakes, and reviews.)
197
+ `);
198
+ // Write memory files
199
+ fs.writeFileSync(path.join(memoryDir, 'heartbeat-log.md'), `# Heartbeat Log — ${username || 'agent'}\n`);
200
+ fs.writeFileSync(path.join(memoryDir, 'org-state.md'), '# Org State\n');
201
+ // Write bootstrap checklist
202
+ fs.writeFileSync(path.join(brainDir, 'BOOTSTRAP.md'), `# Agent Bootstrap Checklist
203
+ *Generated by Agent Autonomy Protocol — pop agent init*
204
+
205
+ ## Brain Architecture (Dual-Location)
206
+
207
+ **This directory (~/.pop-agent/brain/) is YOUR persistent state.**
208
+ It survives restarts, is NOT in git, and belongs only to you.
209
+
210
+ Files here:
211
+ - Identity/who-i-am.md — wallet, org, roles, constraints
212
+ - Identity/philosophy.md — YOUR values (mandatory, write before first vote)
213
+ - Identity/goals.md — what you're working toward (review regularly)
214
+ - Identity/capabilities.md — what you can do and want to learn
215
+ - Identity/lessons.md — curated insights from experience (max 20)
216
+ - Memory/heartbeat-log.md — append-only log of all heartbeats
217
+ - Memory/org-state.md — current org snapshot (overwritten each heartbeat)
218
+
219
+ **The repo (agent/brain/) has SHARED state** — updated via git pull.
220
+ - agent/brain/Identity/how-i-think.md — voting heuristics (shared rules)
221
+ - agent/brain/Knowledge/shared.md — shared knowledge between agents
222
+ - agent/brain/Knowledge/projects.md — collaborative project board
223
+ - agent/brain/Config/agent-config.json — execution mode and thresholds
224
+
225
+ ## Onboarding Checklist
226
+ - [ ] Wallet funded with ~${chain.gasAmount} ${chain.currency}
227
+ - [ ] Username registered (pop user register)
228
+ - [ ] Vouched by existing member
229
+ - [ ] Joined org (pop user join)
230
+ - [ ] ERC-8004 identity registered (pop agent register)
231
+ - [ ] EIP-7702 delegation set up (pop agent delegate)
232
+ - [ ] Gas sponsorship configured (pop agent setup-sponsorship)
233
+ - [ ] **philosophy.md written** — not the template, YOUR values
234
+ - [ ] First heartbeat run (/heartbeat)
235
+ - [ ] First vote cast with reasoning
236
+ - [ ] First task claimed and submitted
237
+
238
+ ## The Heartbeat Loop
239
+ Every 15 minutes: triage → act → remember.
240
+ \`pop agent triage --json\` gives you a prioritized action plan.
241
+ Act on CRITICAL first, then HIGH, MEDIUM, LOW.
242
+ If nothing to do, planning is MANDATORY — never idle.
243
+ `);
244
+ spin.stop();
245
+ const result = {
246
+ address: wallet.address,
247
+ org: orgName,
248
+ chain: chainId,
249
+ chainName: chain.name,
250
+ username: username || null,
251
+ agentHome,
252
+ files: [
253
+ `${agentHome}/.env`,
254
+ `${identityDir}/who-i-am.md`,
255
+ `${identityDir}/philosophy.md`,
256
+ `${identityDir}/goals.md`,
257
+ `${identityDir}/capabilities.md`,
258
+ `${identityDir}/lessons.md`,
259
+ `${memoryDir}/heartbeat-log.md`,
260
+ `${memoryDir}/org-state.md`,
261
+ `${brainDir}/BOOTSTRAP.md`,
262
+ ],
263
+ nextSteps: [
264
+ `Fund wallet ${wallet.address} with ~${chain.gasAmount} ${chain.currency}`,
265
+ `pop user register --username ${username || '<name>'}`,
266
+ 'Ask an existing member to vouch',
267
+ 'pop user join',
268
+ `pop agent register --name ${username || '<name>'} --chain ${chainId}`,
269
+ 'pop agent delegate',
270
+ 'Write philosophy.md — MANDATORY',
271
+ '/loop 15m /heartbeat',
272
+ ],
273
+ };
274
+ if (argv.json) {
275
+ output.json(result);
276
+ }
277
+ else {
278
+ console.log('');
279
+ console.log(` Agent Initialized — ${chain.name}`);
280
+ console.log(' ' + '═'.repeat(50));
281
+ console.log(` Wallet: ${wallet.address}`);
282
+ console.log(` Org: ${orgName}`);
283
+ console.log(` Chain: ${chainId} (${chain.name})`);
284
+ if (username)
285
+ console.log(` Username: ${username}`);
286
+ console.log(` Home: ${agentHome}`);
287
+ console.log('');
288
+ console.log(' Created:');
289
+ for (const f of result.files) {
290
+ console.log(` ${f}`);
291
+ }
292
+ console.log('');
293
+ console.log(' Next steps:');
294
+ result.nextSteps.forEach((s, i) => console.log(` ${i + 1}. ${s}`));
295
+ console.log('');
296
+ console.log(' ⚠ Save the private key from ~/.pop-agent/.env');
297
+ console.log('');
298
+ console.log(' "An agent without a philosophy is a script."');
299
+ console.log(' Write philosophy.md before your first vote.');
300
+ console.log('');
301
+ }
302
+ },
303
+ };
@@ -0,0 +1,22 @@
1
+ import type { Argv, ArgumentsCamelCase } from 'yargs';
2
+ interface OnboardArgs {
3
+ org: string;
4
+ username: string;
5
+ description?: string;
6
+ capabilities?: string;
7
+ chain?: number;
8
+ rpc?: string;
9
+ 'private-key'?: string;
10
+ 'dry-run'?: boolean;
11
+ }
12
+ export declare const onboardHandler: {
13
+ builder: (yargs: Argv) => Argv<{
14
+ username: string;
15
+ } & {
16
+ description: string;
17
+ } & {
18
+ capabilities: string | undefined;
19
+ }>;
20
+ handler: (argv: ArgumentsCamelCase<OnboardArgs>) => Promise<void>;
21
+ };
22
+ export {};
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.onboardHandler = void 0;
37
+ const ethers_1 = require("ethers");
38
+ const child_process_1 = require("child_process");
39
+ const accounts_1 = require("viem/accounts");
40
+ const signer_1 = require("@poa-box/cli/lib/signer");
41
+ const ipfs_1 = require("@poa-box/cli/lib/ipfs");
42
+ const networks_1 = require("@poa-box/cli/config/networks");
43
+ const sponsored_1 = require("@poa-box/cli/lib/sponsored");
44
+ const output = __importStar(require("@poa-box/cli/lib/output"));
45
+ const IDENTITY_REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
46
+ const REGISTRY_ABI = [
47
+ 'function register(string agentURI) external returns (uint256)',
48
+ 'function balanceOf(address) view returns (uint256)',
49
+ ];
50
+ exports.onboardHandler = {
51
+ builder: (yargs) => yargs
52
+ .option('username', { type: 'string', demandOption: true, describe: 'Agent username' })
53
+ .option('description', { type: 'string', default: '', describe: 'Agent description' })
54
+ .option('capabilities', { type: 'string', describe: 'Comma-separated capabilities' }),
55
+ handler: async (argv) => {
56
+ const spin = output.spinner('Onboarding agent...');
57
+ spin.start();
58
+ try {
59
+ const key = argv.privateKey || process.env.POP_PRIVATE_KEY;
60
+ if (!key)
61
+ throw new Error('No private key configured');
62
+ const { signer } = (0, signer_1.createSigner)({ privateKey: key, chainId: argv.chain, rpcUrl: argv.rpc });
63
+ const address = await signer.getAddress();
64
+ const networkConfig = (0, networks_1.resolveNetworkConfig)(argv.chain);
65
+ const rpcUrl = networkConfig.resolvedRpc;
66
+ const results = { address, username: argv.username, steps: [] };
67
+ // Step 1: Register username (via pop user register --username)
68
+ spin.text = '1/4 Registering username...';
69
+ if (argv.dryRun) {
70
+ // --dry-run is a GLOBAL flag and this step broadcasts a real
71
+ // registration tx through the child process. It must honor the flag
72
+ // like steps 2 and 3 do — an integrator probing the CLI safely is
73
+ // exactly who runs onboard --dry-run first.
74
+ results.steps.push({ step: 'register', success: true, note: `Would register username "${argv.username}" (dry-run)` });
75
+ }
76
+ else {
77
+ try {
78
+ // execFile with an args ARRAY — never a shell string. The username is
79
+ // operator input; interpolating it into a shell command is injectable.
80
+ const regOutput = (0, child_process_1.execFileSync)(process.execPath, [
81
+ `${__dirname}/../../index.js`,
82
+ 'user', 'register',
83
+ '--username', String(argv.username),
84
+ '--chain', String(networkConfig.chainId),
85
+ '--json', '-y',
86
+ ], { env: process.env, encoding: 'utf8', timeout: 30000 });
87
+ results.steps.push({ step: 'register', success: true, output: JSON.parse(regOutput) });
88
+ }
89
+ catch (e) {
90
+ // May fail if already registered — that's ok
91
+ results.steps.push({ step: 'register', success: false, error: e.message?.slice(0, 100) || 'Already registered or failed' });
92
+ }
93
+ }
94
+ // Step 2: EIP-7702 delegation
95
+ spin.text = '2/4 Setting up gas sponsorship delegation...';
96
+ try {
97
+ const account = (0, accounts_1.privateKeyToAccount)(key);
98
+ const alreadyDelegated = await (0, sponsored_1.isDelegated)(account.address, rpcUrl);
99
+ if (alreadyDelegated) {
100
+ results.steps.push({ step: 'delegate', success: true, note: 'Already delegated' });
101
+ }
102
+ else if (argv.dryRun) {
103
+ results.steps.push({ step: 'delegate', success: true, note: 'Would delegate (dry-run)' });
104
+ }
105
+ else {
106
+ const delegateTx = await (0, sponsored_1.delegateEOA)(key, rpcUrl);
107
+ results.steps.push({ step: 'delegate', success: true, txHash: delegateTx });
108
+ }
109
+ }
110
+ catch (e) {
111
+ results.steps.push({ step: 'delegate', success: false, error: e.message?.slice(0, 100) });
112
+ }
113
+ // Step 3: ERC-8004 identity registration
114
+ spin.text = '3/4 Registering on-chain identity...';
115
+ try {
116
+ const provider = new ethers_1.ethers.providers.JsonRpcProvider(rpcUrl);
117
+ const regSigner = new ethers_1.ethers.Wallet(key, provider);
118
+ const registry = new ethers_1.ethers.Contract(IDENTITY_REGISTRY, REGISTRY_ABI, regSigner);
119
+ const existing = await registry.balanceOf(address);
120
+ if (existing.gt(0)) {
121
+ results.steps.push({ step: 'identity', success: true, note: 'Already registered' });
122
+ }
123
+ else {
124
+ const capList = argv.capabilities?.split(',').map(s => s.trim()) || ['governance'];
125
+ const registration = {
126
+ name: argv.username,
127
+ description: argv.description || `Agent in ${argv.org}`,
128
+ services: [{ type: 'wallet', address, chain: `eip155:${networkConfig.chainId}` }],
129
+ org: { name: argv.org, protocol: 'POP' },
130
+ capabilities: capList,
131
+ active: true,
132
+ };
133
+ // Pin only when actually registering: pinning publishes the doc to
134
+ // IPFS publicly and irreversibly, which is a real side effect a
135
+ // dry run must not have.
136
+ if (argv.dryRun) {
137
+ results.steps.push({ step: 'identity', success: true, note: 'Would pin registration JSON and register (dry-run)' });
138
+ }
139
+ else {
140
+ const cid = await (0, ipfs_1.pinJson)(JSON.stringify(registration));
141
+ const uri = `https://ipfs.io/ipfs/${cid}`;
142
+ const tx = await registry.register(uri);
143
+ const receipt = await tx.wait();
144
+ const transferTopic = ethers_1.ethers.utils.id('Transfer(address,address,uint256)');
145
+ const transferLog = receipt.logs.find((l) => l.topics[0] === transferTopic);
146
+ const agentId = transferLog ? ethers_1.ethers.BigNumber.from(transferLog.topics[3]).toString() : 'unknown';
147
+ results.steps.push({ step: 'identity', success: true, agentId, uri });
148
+ }
149
+ }
150
+ }
151
+ catch (e) {
152
+ results.steps.push({ step: 'identity', success: false, error: e.message?.slice(0, 100) });
153
+ }
154
+ // Step 4: Brain scaffolding
155
+ spin.text = '4/4 Creating brain files...';
156
+ results.steps.push({
157
+ step: 'brain',
158
+ success: true,
159
+ note: 'Create ~/.pop-agent/brain/ with who-i-am.md, philosophy.md, goals.md, capabilities.md, lessons.md',
160
+ });
161
+ spin.stop();
162
+ const succeeded = results.steps.filter((s) => s.success).length;
163
+ const total = results.steps.length;
164
+ if (output.isJsonMode()) {
165
+ output.json({ ...results, summary: `${succeeded}/${total} steps completed` });
166
+ }
167
+ else {
168
+ console.log('');
169
+ console.log(` Agent Onboarding: ${argv.username}`);
170
+ console.log(' ' + '─'.repeat(40));
171
+ for (const step of results.steps) {
172
+ const icon = step.success ? '✓' : '✗';
173
+ const color = step.success ? '\x1b[32m' : '\x1b[31m';
174
+ const detail = step.note || step.txHash?.slice(0, 16) || step.error || '';
175
+ console.log(` ${color}${icon}\x1b[0m ${step.step}: ${detail}`);
176
+ }
177
+ console.log('');
178
+ console.log(` ${succeeded}/${total} steps completed.`);
179
+ if (succeeded === total) {
180
+ console.log(' Next: write ~/.pop-agent/brain/Identity/philosophy.md');
181
+ console.log(' Then: run /heartbeat');
182
+ }
183
+ console.log('');
184
+ }
185
+ }
186
+ catch (err) {
187
+ spin.stop();
188
+ output.error(err.message);
189
+ process.exit(1);
190
+ }
191
+ },
192
+ };
@@ -0,0 +1,14 @@
1
+ import type { Argv, ArgumentsCamelCase } from 'yargs';
2
+ interface PaymasterStatusArgs {
3
+ org: string;
4
+ 'hat-id'?: string;
5
+ chain?: number;
6
+ rpc?: string;
7
+ }
8
+ export declare const paymasterStatusHandler: {
9
+ builder: (yargs: Argv) => Argv<{
10
+ "hat-id": string | undefined;
11
+ }>;
12
+ handler: (argv: ArgumentsCamelCase<PaymasterStatusArgs>) => Promise<void>;
13
+ };
14
+ export {};
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.paymasterStatusHandler = void 0;
37
+ const viem_1 = require("viem");
38
+ const chains_1 = require("viem/chains");
39
+ const account_abstraction_1 = require("viem/account-abstraction");
40
+ const sponsored_1 = require("@poa-box/cli/lib/sponsored");
41
+ const output = __importStar(require("@poa-box/cli/lib/output"));
42
+ const resolve_1 = require("@poa-box/cli/lib/resolve");
43
+ exports.paymasterStatusHandler = {
44
+ builder: (yargs) => yargs
45
+ .option('hat-id', { type: 'string', describe: 'Hat ID to check budget for (decimal or hex)' }),
46
+ handler: async (argv) => {
47
+ const spin = output.spinner('Checking paymaster status...');
48
+ spin.start();
49
+ try {
50
+ const modules = await (0, resolve_1.resolveOrgModules)(argv.org, argv.chain);
51
+ const orgId = modules.orgId;
52
+ const rpcUrl = argv.rpc || 'https://rpc.gnosischain.com';
53
+ const client = (0, viem_1.createPublicClient)({ chain: chains_1.gnosis, transport: (0, viem_1.http)(rpcUrl) });
54
+ const pmAbi = require('../../abi/PaymasterHub.json');
55
+ // Org config
56
+ const config = await client.readContract({
57
+ address: sponsored_1.PAYMASTER_HUB, abi: pmAbi,
58
+ functionName: 'getOrgConfig', args: [orgId],
59
+ });
60
+ // Org financials
61
+ const financials = await client.readContract({
62
+ address: sponsored_1.PAYMASTER_HUB, abi: pmAbi,
63
+ functionName: 'getOrgFinancials', args: [orgId],
64
+ });
65
+ // Fee caps
66
+ const caps = await client.readContract({
67
+ address: sponsored_1.PAYMASTER_HUB, abi: pmAbi,
68
+ functionName: 'getFeeCaps', args: [orgId],
69
+ });
70
+ // EntryPoint deposit
71
+ const entryPointDeposit = await client.readContract({
72
+ address: account_abstraction_1.entryPoint07Address,
73
+ abi: [{ name: 'balanceOf', type: 'function', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], stateMutability: 'view' }],
74
+ functionName: 'balanceOf',
75
+ args: [sponsored_1.PAYMASTER_HUB],
76
+ });
77
+ // Hat budget (if specified or from env)
78
+ const hatIdStr = argv.hatId || process.env.POP_HAT_ID;
79
+ let budgetInfo = null;
80
+ if (hatIdStr) {
81
+ const hatId = BigInt(hatIdStr);
82
+ const subjectKey = (0, viem_1.pad)((0, viem_1.toHex)(hatId), { size: 32 });
83
+ const budget = await client.readContract({
84
+ address: sponsored_1.PAYMASTER_HUB, abi: pmAbi,
85
+ functionName: 'getBudget', args: [orgId, subjectKey],
86
+ });
87
+ const cap = BigInt(budget.capPerEpoch);
88
+ const used = BigInt(budget.usedInEpoch);
89
+ budgetInfo = {
90
+ capPerEpoch: (0, viem_1.formatEther)(cap),
91
+ usedInEpoch: (0, viem_1.formatEther)(used),
92
+ remaining: (0, viem_1.formatEther)(cap - used),
93
+ epochLength: `${budget.epochLen}s (${(Number(budget.epochLen) / 3600).toFixed(1)}h)`,
94
+ utilizationPct: cap > 0n
95
+ ? ((Number(used) * 100 / Number(cap))).toFixed(1) + '%'
96
+ : 'N/A',
97
+ };
98
+ }
99
+ spin.stop();
100
+ const result = {
101
+ org: argv.org,
102
+ paused: config.paused,
103
+ deposited: (0, viem_1.formatEther)(financials.deposited) + ' xDAI',
104
+ spent: (0, viem_1.formatEther)(financials.spent) + ' xDAI',
105
+ entryPointDeposit: (0, viem_1.formatEther)(entryPointDeposit) + ' xDAI',
106
+ feeCaps: {
107
+ maxFeePerGas: `${(Number(caps.maxFeePerGas) / 1e9).toFixed(1)} gwei`,
108
+ maxPriorityFeePerGas: `${(Number(caps.maxPriorityFeePerGas) / 1e9).toFixed(1)} gwei`,
109
+ maxCallGas: caps.maxCallGas.toLocaleString(),
110
+ maxVerificationGas: caps.maxVerificationGas.toLocaleString(),
111
+ maxPreVerificationGas: caps.maxPreVerificationGas.toLocaleString(),
112
+ },
113
+ };
114
+ if (budgetInfo) {
115
+ result.hatBudget = budgetInfo;
116
+ }
117
+ if (argv.json) {
118
+ console.log(JSON.stringify(result, null, 2));
119
+ }
120
+ else {
121
+ output.success('Paymaster Status', result);
122
+ }
123
+ }
124
+ catch (err) {
125
+ spin.stop();
126
+ output.error(err.message);
127
+ process.exit(1);
128
+ }
129
+ },
130
+ };