arc402-cli 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/README.md +245 -0
  2. package/dist/abis.d.ts +19 -0
  3. package/dist/abis.d.ts.map +1 -0
  4. package/dist/abis.js +177 -0
  5. package/dist/abis.js.map +1 -0
  6. package/dist/bundler.d.ts +65 -0
  7. package/dist/bundler.d.ts.map +1 -0
  8. package/dist/bundler.js +181 -0
  9. package/dist/bundler.js.map +1 -0
  10. package/dist/client.d.ts +14 -0
  11. package/dist/client.d.ts.map +1 -0
  12. package/dist/client.js +24 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/coinbase-smart-wallet.d.ts +28 -0
  15. package/dist/coinbase-smart-wallet.d.ts.map +1 -0
  16. package/dist/coinbase-smart-wallet.js +38 -0
  17. package/dist/coinbase-smart-wallet.js.map +1 -0
  18. package/dist/commands/accept.d.ts +3 -0
  19. package/dist/commands/accept.d.ts.map +1 -0
  20. package/dist/commands/accept.js +26 -0
  21. package/dist/commands/accept.js.map +1 -0
  22. package/dist/commands/agent-handshake.d.ts +3 -0
  23. package/dist/commands/agent-handshake.d.ts.map +1 -0
  24. package/dist/commands/agent-handshake.js +61 -0
  25. package/dist/commands/agent-handshake.js.map +1 -0
  26. package/dist/commands/agent.d.ts +3 -0
  27. package/dist/commands/agent.d.ts.map +1 -0
  28. package/dist/commands/agent.js +417 -0
  29. package/dist/commands/agent.js.map +1 -0
  30. package/dist/commands/agreements.d.ts +3 -0
  31. package/dist/commands/agreements.d.ts.map +1 -0
  32. package/dist/commands/agreements.js +344 -0
  33. package/dist/commands/agreements.js.map +1 -0
  34. package/dist/commands/arbitrator.d.ts +3 -0
  35. package/dist/commands/arbitrator.d.ts.map +1 -0
  36. package/dist/commands/arbitrator.js +157 -0
  37. package/dist/commands/arbitrator.js.map +1 -0
  38. package/dist/commands/arena-handshake.d.ts +3 -0
  39. package/dist/commands/arena-handshake.d.ts.map +1 -0
  40. package/dist/commands/arena-handshake.js +187 -0
  41. package/dist/commands/arena-handshake.js.map +1 -0
  42. package/dist/commands/cancel.d.ts +3 -0
  43. package/dist/commands/cancel.d.ts.map +1 -0
  44. package/dist/commands/cancel.js +30 -0
  45. package/dist/commands/cancel.js.map +1 -0
  46. package/dist/commands/channel.d.ts +3 -0
  47. package/dist/commands/channel.d.ts.map +1 -0
  48. package/dist/commands/channel.js +238 -0
  49. package/dist/commands/channel.js.map +1 -0
  50. package/dist/commands/coldstart.d.ts +3 -0
  51. package/dist/commands/coldstart.d.ts.map +1 -0
  52. package/dist/commands/coldstart.js +148 -0
  53. package/dist/commands/coldstart.js.map +1 -0
  54. package/dist/commands/config.d.ts +3 -0
  55. package/dist/commands/config.d.ts.map +1 -0
  56. package/dist/commands/config.js +40 -0
  57. package/dist/commands/config.js.map +1 -0
  58. package/dist/commands/contract-interaction.d.ts +3 -0
  59. package/dist/commands/contract-interaction.d.ts.map +1 -0
  60. package/dist/commands/contract-interaction.js +165 -0
  61. package/dist/commands/contract-interaction.js.map +1 -0
  62. package/dist/commands/daemon.d.ts +3 -0
  63. package/dist/commands/daemon.d.ts.map +1 -0
  64. package/dist/commands/daemon.js +891 -0
  65. package/dist/commands/daemon.js.map +1 -0
  66. package/dist/commands/deliver.d.ts +3 -0
  67. package/dist/commands/deliver.d.ts.map +1 -0
  68. package/dist/commands/deliver.js +156 -0
  69. package/dist/commands/deliver.js.map +1 -0
  70. package/dist/commands/discover.d.ts +3 -0
  71. package/dist/commands/discover.d.ts.map +1 -0
  72. package/dist/commands/discover.js +224 -0
  73. package/dist/commands/discover.js.map +1 -0
  74. package/dist/commands/dispute.d.ts +3 -0
  75. package/dist/commands/dispute.d.ts.map +1 -0
  76. package/dist/commands/dispute.js +348 -0
  77. package/dist/commands/dispute.js.map +1 -0
  78. package/dist/commands/endpoint.d.ts +3 -0
  79. package/dist/commands/endpoint.d.ts.map +1 -0
  80. package/dist/commands/endpoint.js +604 -0
  81. package/dist/commands/endpoint.js.map +1 -0
  82. package/dist/commands/hire.d.ts +3 -0
  83. package/dist/commands/hire.d.ts.map +1 -0
  84. package/dist/commands/hire.js +189 -0
  85. package/dist/commands/hire.js.map +1 -0
  86. package/dist/commands/migrate.d.ts +3 -0
  87. package/dist/commands/migrate.d.ts.map +1 -0
  88. package/dist/commands/migrate.js +163 -0
  89. package/dist/commands/migrate.js.map +1 -0
  90. package/dist/commands/negotiate.d.ts +3 -0
  91. package/dist/commands/negotiate.d.ts.map +1 -0
  92. package/dist/commands/negotiate.js +247 -0
  93. package/dist/commands/negotiate.js.map +1 -0
  94. package/dist/commands/openshell.d.ts +3 -0
  95. package/dist/commands/openshell.d.ts.map +1 -0
  96. package/dist/commands/openshell.js +952 -0
  97. package/dist/commands/openshell.js.map +1 -0
  98. package/dist/commands/owner.d.ts +3 -0
  99. package/dist/commands/owner.d.ts.map +1 -0
  100. package/dist/commands/owner.js +32 -0
  101. package/dist/commands/owner.js.map +1 -0
  102. package/dist/commands/policy.d.ts +4 -0
  103. package/dist/commands/policy.d.ts.map +1 -0
  104. package/dist/commands/policy.js +248 -0
  105. package/dist/commands/policy.js.map +1 -0
  106. package/dist/commands/relay.d.ts +3 -0
  107. package/dist/commands/relay.d.ts.map +1 -0
  108. package/dist/commands/relay.js +279 -0
  109. package/dist/commands/relay.js.map +1 -0
  110. package/dist/commands/remediate.d.ts +3 -0
  111. package/dist/commands/remediate.d.ts.map +1 -0
  112. package/dist/commands/remediate.js +42 -0
  113. package/dist/commands/remediate.js.map +1 -0
  114. package/dist/commands/reputation.d.ts +4 -0
  115. package/dist/commands/reputation.d.ts.map +1 -0
  116. package/dist/commands/reputation.js +72 -0
  117. package/dist/commands/reputation.js.map +1 -0
  118. package/dist/commands/setup.d.ts +3 -0
  119. package/dist/commands/setup.d.ts.map +1 -0
  120. package/dist/commands/setup.js +332 -0
  121. package/dist/commands/setup.js.map +1 -0
  122. package/dist/commands/trust.d.ts +3 -0
  123. package/dist/commands/trust.d.ts.map +1 -0
  124. package/dist/commands/trust.js +23 -0
  125. package/dist/commands/trust.js.map +1 -0
  126. package/dist/commands/verify.d.ts +3 -0
  127. package/dist/commands/verify.d.ts.map +1 -0
  128. package/dist/commands/verify.js +88 -0
  129. package/dist/commands/verify.js.map +1 -0
  130. package/dist/commands/wallet.d.ts +3 -0
  131. package/dist/commands/wallet.d.ts.map +1 -0
  132. package/dist/commands/wallet.js +2520 -0
  133. package/dist/commands/wallet.js.map +1 -0
  134. package/dist/commands/watchtower.d.ts +3 -0
  135. package/dist/commands/watchtower.d.ts.map +1 -0
  136. package/dist/commands/watchtower.js +238 -0
  137. package/dist/commands/watchtower.js.map +1 -0
  138. package/dist/commands/workroom.d.ts +3 -0
  139. package/dist/commands/workroom.d.ts.map +1 -0
  140. package/dist/commands/workroom.js +855 -0
  141. package/dist/commands/workroom.js.map +1 -0
  142. package/dist/config.d.ts +62 -0
  143. package/dist/config.d.ts.map +1 -0
  144. package/dist/config.js +141 -0
  145. package/dist/config.js.map +1 -0
  146. package/dist/daemon/config.d.ts +74 -0
  147. package/dist/daemon/config.d.ts.map +1 -0
  148. package/dist/daemon/config.js +271 -0
  149. package/dist/daemon/config.js.map +1 -0
  150. package/dist/daemon/hire-listener.d.ts +31 -0
  151. package/dist/daemon/hire-listener.d.ts.map +1 -0
  152. package/dist/daemon/hire-listener.js +207 -0
  153. package/dist/daemon/hire-listener.js.map +1 -0
  154. package/dist/daemon/index.d.ts +29 -0
  155. package/dist/daemon/index.d.ts.map +1 -0
  156. package/dist/daemon/index.js +535 -0
  157. package/dist/daemon/index.js.map +1 -0
  158. package/dist/daemon/job-lifecycle.d.ts +62 -0
  159. package/dist/daemon/job-lifecycle.d.ts.map +1 -0
  160. package/dist/daemon/job-lifecycle.js +201 -0
  161. package/dist/daemon/job-lifecycle.js.map +1 -0
  162. package/dist/daemon/notify.d.ts +22 -0
  163. package/dist/daemon/notify.d.ts.map +1 -0
  164. package/dist/daemon/notify.js +148 -0
  165. package/dist/daemon/notify.js.map +1 -0
  166. package/dist/daemon/token-metering.d.ts +42 -0
  167. package/dist/daemon/token-metering.d.ts.map +1 -0
  168. package/dist/daemon/token-metering.js +178 -0
  169. package/dist/daemon/token-metering.js.map +1 -0
  170. package/dist/daemon/userops.d.ts +21 -0
  171. package/dist/daemon/userops.d.ts.map +1 -0
  172. package/dist/daemon/userops.js +88 -0
  173. package/dist/daemon/userops.js.map +1 -0
  174. package/dist/daemon/wallet-monitor.d.ts +16 -0
  175. package/dist/daemon/wallet-monitor.d.ts.map +1 -0
  176. package/dist/daemon/wallet-monitor.js +57 -0
  177. package/dist/daemon/wallet-monitor.js.map +1 -0
  178. package/dist/drain-v4.d.ts +2 -0
  179. package/dist/drain-v4.d.ts.map +1 -0
  180. package/dist/drain-v4.js +167 -0
  181. package/dist/drain-v4.js.map +1 -0
  182. package/dist/endpoint-config.d.ts +36 -0
  183. package/dist/endpoint-config.d.ts.map +1 -0
  184. package/dist/endpoint-config.js +96 -0
  185. package/dist/endpoint-config.js.map +1 -0
  186. package/dist/index.d.ts +3 -0
  187. package/dist/index.d.ts.map +1 -0
  188. package/dist/index.js +79 -0
  189. package/dist/index.js.map +1 -0
  190. package/dist/openshell-runtime.d.ts +55 -0
  191. package/dist/openshell-runtime.d.ts.map +1 -0
  192. package/dist/openshell-runtime.js +268 -0
  193. package/dist/openshell-runtime.js.map +1 -0
  194. package/dist/signing.d.ts +2 -0
  195. package/dist/signing.d.ts.map +1 -0
  196. package/dist/signing.js +23 -0
  197. package/dist/signing.js.map +1 -0
  198. package/dist/telegram-notify.d.ts +23 -0
  199. package/dist/telegram-notify.d.ts.map +1 -0
  200. package/dist/telegram-notify.js +106 -0
  201. package/dist/telegram-notify.js.map +1 -0
  202. package/dist/ui/banner.d.ts +7 -0
  203. package/dist/ui/banner.d.ts.map +1 -0
  204. package/dist/ui/banner.js +37 -0
  205. package/dist/ui/banner.js.map +1 -0
  206. package/dist/ui/colors.d.ts +14 -0
  207. package/dist/ui/colors.d.ts.map +1 -0
  208. package/dist/ui/colors.js +29 -0
  209. package/dist/ui/colors.js.map +1 -0
  210. package/dist/ui/format.d.ts +26 -0
  211. package/dist/ui/format.d.ts.map +1 -0
  212. package/dist/ui/format.js +77 -0
  213. package/dist/ui/format.js.map +1 -0
  214. package/dist/ui/spinner.d.ts +8 -0
  215. package/dist/ui/spinner.d.ts.map +1 -0
  216. package/dist/ui/spinner.js +43 -0
  217. package/dist/ui/spinner.js.map +1 -0
  218. package/dist/utils/format.d.ts +10 -0
  219. package/dist/utils/format.d.ts.map +1 -0
  220. package/dist/utils/format.js +61 -0
  221. package/dist/utils/format.js.map +1 -0
  222. package/dist/utils/hash.d.ts +3 -0
  223. package/dist/utils/hash.d.ts.map +1 -0
  224. package/dist/utils/hash.js +43 -0
  225. package/dist/utils/hash.js.map +1 -0
  226. package/dist/utils/time.d.ts +3 -0
  227. package/dist/utils/time.d.ts.map +1 -0
  228. package/dist/utils/time.js +21 -0
  229. package/dist/utils/time.js.map +1 -0
  230. package/dist/wallet-router.d.ts +25 -0
  231. package/dist/wallet-router.d.ts.map +1 -0
  232. package/dist/wallet-router.js +153 -0
  233. package/dist/wallet-router.js.map +1 -0
  234. package/dist/walletconnect-session.d.ts +12 -0
  235. package/dist/walletconnect-session.d.ts.map +1 -0
  236. package/dist/walletconnect-session.js +26 -0
  237. package/dist/walletconnect-session.js.map +1 -0
  238. package/dist/walletconnect.d.ts +46 -0
  239. package/dist/walletconnect.d.ts.map +1 -0
  240. package/dist/walletconnect.js +267 -0
  241. package/dist/walletconnect.js.map +1 -0
  242. package/package.json +38 -0
  243. package/scripts/authorize-machine-key.ts +43 -0
  244. package/scripts/drain-wallet.ts +149 -0
  245. package/scripts/execute-spend-only.ts +81 -0
  246. package/scripts/register-agent-userop.ts +186 -0
  247. package/src/abis.ts +187 -0
  248. package/src/bundler.ts +235 -0
  249. package/src/client.ts +34 -0
  250. package/src/coinbase-smart-wallet.ts +51 -0
  251. package/src/commands/accept.ts +25 -0
  252. package/src/commands/agent-handshake.ts +67 -0
  253. package/src/commands/agent.ts +458 -0
  254. package/src/commands/agreements.ts +324 -0
  255. package/src/commands/arbitrator.ts +129 -0
  256. package/src/commands/arena-handshake.ts +217 -0
  257. package/src/commands/cancel.ts +26 -0
  258. package/src/commands/channel.ts +208 -0
  259. package/src/commands/coldstart.ts +156 -0
  260. package/src/commands/config.ts +35 -0
  261. package/src/commands/contract-interaction.ts +166 -0
  262. package/src/commands/daemon.ts +971 -0
  263. package/src/commands/deliver.ts +116 -0
  264. package/src/commands/discover.ts +295 -0
  265. package/src/commands/dispute.ts +373 -0
  266. package/src/commands/endpoint.ts +619 -0
  267. package/src/commands/hire.ts +200 -0
  268. package/src/commands/migrate.ts +175 -0
  269. package/src/commands/negotiate.ts +270 -0
  270. package/src/commands/openshell.ts +1053 -0
  271. package/src/commands/owner.ts +30 -0
  272. package/src/commands/policy.ts +252 -0
  273. package/src/commands/relay.ts +272 -0
  274. package/src/commands/remediate.ts +22 -0
  275. package/src/commands/reputation.ts +71 -0
  276. package/src/commands/setup.ts +343 -0
  277. package/src/commands/trust.ts +15 -0
  278. package/src/commands/verify.ts +88 -0
  279. package/src/commands/wallet.ts +2892 -0
  280. package/src/commands/watchtower.ts +232 -0
  281. package/src/commands/workroom.ts +889 -0
  282. package/src/config.ts +153 -0
  283. package/src/daemon/config.ts +308 -0
  284. package/src/daemon/hire-listener.ts +226 -0
  285. package/src/daemon/index.ts +609 -0
  286. package/src/daemon/job-lifecycle.ts +215 -0
  287. package/src/daemon/notify.ts +157 -0
  288. package/src/daemon/token-metering.ts +183 -0
  289. package/src/daemon/userops.ts +119 -0
  290. package/src/daemon/wallet-monitor.ts +90 -0
  291. package/src/drain-v4.ts +159 -0
  292. package/src/endpoint-config.ts +83 -0
  293. package/src/index.ts +75 -0
  294. package/src/openshell-runtime.ts +277 -0
  295. package/src/signing.ts +28 -0
  296. package/src/telegram-notify.ts +88 -0
  297. package/src/ui/banner.ts +41 -0
  298. package/src/ui/colors.ts +30 -0
  299. package/src/ui/format.ts +77 -0
  300. package/src/ui/spinner.ts +46 -0
  301. package/src/utils/format.ts +48 -0
  302. package/src/utils/hash.ts +5 -0
  303. package/src/utils/time.ts +15 -0
  304. package/src/wallet-router.ts +178 -0
  305. package/src/walletconnect-session.ts +27 -0
  306. package/src/walletconnect.ts +294 -0
  307. package/test/time.test.js +11 -0
  308. package/tsconfig.json +19 -0
@@ -0,0 +1,609 @@
1
+ /**
2
+ * ARC-402 Daemon — main process entry point.
3
+ *
4
+ * Startup sequence per Spec 32 §3.
5
+ * Runs when spawned by `arc402 daemon start` or invoked with --foreground.
6
+ *
7
+ * IPC: Unix socket at ~/.arc402/daemon.sock (JSON-lines protocol).
8
+ * Signals: SIGTERM → graceful shutdown.
9
+ */
10
+ import * as fs from "fs";
11
+ import * as path from "path";
12
+ import * as net from "net";
13
+ import { ethers } from "ethers";
14
+ import Database from "better-sqlite3";
15
+
16
+ import {
17
+ loadDaemonConfig,
18
+ loadMachineKey,
19
+ DAEMON_DIR,
20
+ DAEMON_PID,
21
+ DAEMON_LOG,
22
+ DAEMON_DB,
23
+ DAEMON_SOCK,
24
+ type DaemonConfig,
25
+ } from "./config";
26
+ import { verifyWallet, getWalletBalance } from "./wallet-monitor";
27
+ import { Notifier } from "./notify";
28
+ import { HireListener } from "./hire-listener";
29
+ import { UserOpsManager, buildAcceptCalldata } from "./userops";
30
+ import { generateReceipt, extractLearnings, createJobDirectory, cleanJobDirectory } from "./job-lifecycle";
31
+
32
+ // ─── State DB ─────────────────────────────────────────────────────────────────
33
+
34
+ export interface HireRequestRow {
35
+ id: string;
36
+ agreement_id: string | null;
37
+ hirer_address: string;
38
+ capability: string;
39
+ price_eth: string;
40
+ deadline_unix: number;
41
+ spec_hash: string;
42
+ status: string; // pending_approval | accepted | rejected | delivered | complete
43
+ created_at: number;
44
+ updated_at: number;
45
+ reject_reason: string | null;
46
+ }
47
+
48
+ export interface DaemonDB {
49
+ insertHireRequest(row: Omit<HireRequestRow, "created_at" | "updated_at">): void;
50
+ getHireRequest(id: string): HireRequestRow | undefined;
51
+ updateHireRequestStatus(id: string, status: string, rejectReason?: string): void;
52
+ listPendingHireRequests(): HireRequestRow[];
53
+ listActiveHireRequests(): HireRequestRow[];
54
+ countActiveHireRequests(): number;
55
+ close(): void;
56
+ }
57
+
58
+ function openStateDB(dbPath: string): DaemonDB {
59
+ const db = new Database(dbPath);
60
+ db.pragma("journal_mode = WAL");
61
+
62
+ db.exec(`
63
+ CREATE TABLE IF NOT EXISTS hire_requests (
64
+ id TEXT PRIMARY KEY,
65
+ agreement_id TEXT,
66
+ hirer_address TEXT NOT NULL,
67
+ capability TEXT,
68
+ price_eth TEXT,
69
+ deadline_unix INTEGER,
70
+ spec_hash TEXT,
71
+ status TEXT NOT NULL,
72
+ created_at INTEGER,
73
+ updated_at INTEGER,
74
+ reject_reason TEXT
75
+ );
76
+
77
+ CREATE TABLE IF NOT EXISTS userop_queue (
78
+ id TEXT PRIMARY KEY,
79
+ hire_request_id TEXT,
80
+ call_data TEXT NOT NULL,
81
+ user_op_hash TEXT,
82
+ status TEXT NOT NULL,
83
+ submitted_at INTEGER,
84
+ included_at INTEGER,
85
+ retry_count INTEGER DEFAULT 0,
86
+ last_error TEXT
87
+ );
88
+
89
+ CREATE TABLE IF NOT EXISTS session_channels (
90
+ channel_id TEXT PRIMARY KEY,
91
+ counterparty TEXT NOT NULL,
92
+ token_address TEXT,
93
+ latest_state_seq INTEGER,
94
+ latest_state_bytes BLOB,
95
+ status TEXT NOT NULL,
96
+ challenge_deadline_unix INTEGER,
97
+ external_watcher_id TEXT
98
+ );
99
+
100
+ CREATE TABLE IF NOT EXISTS notifications (
101
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
102
+ type TEXT NOT NULL,
103
+ payload TEXT,
104
+ sent_at INTEGER,
105
+ status TEXT
106
+ );
107
+ `);
108
+
109
+ const insertHireRequest = db.prepare(`
110
+ INSERT OR IGNORE INTO hire_requests
111
+ (id, agreement_id, hirer_address, capability, price_eth, deadline_unix, spec_hash, status, created_at, updated_at, reject_reason)
112
+ VALUES
113
+ (@id, @agreement_id, @hirer_address, @capability, @price_eth, @deadline_unix, @spec_hash, @status, @created_at, @updated_at, @reject_reason)
114
+ `);
115
+
116
+ const getHireRequest = db.prepare(`SELECT * FROM hire_requests WHERE id = ?`);
117
+ const updateStatus = db.prepare(`UPDATE hire_requests SET status = ?, reject_reason = ?, updated_at = ? WHERE id = ?`);
118
+ const listPending = db.prepare(`SELECT * FROM hire_requests WHERE status = 'pending_approval' ORDER BY created_at ASC`);
119
+ const listActive = db.prepare(`SELECT * FROM hire_requests WHERE status IN ('accepted', 'delivered') ORDER BY created_at ASC`);
120
+ const countActive = db.prepare(`SELECT COUNT(*) as n FROM hire_requests WHERE status IN ('accepted', 'delivered')`);
121
+
122
+ return {
123
+ insertHireRequest(row) {
124
+ const now = Date.now();
125
+ insertHireRequest.run({ ...row, created_at: now, updated_at: now });
126
+ },
127
+ getHireRequest(id) {
128
+ return getHireRequest.get(id) as HireRequestRow | undefined;
129
+ },
130
+ updateHireRequestStatus(id, status, rejectReason) {
131
+ updateStatus.run(status, rejectReason ?? null, Date.now(), id);
132
+ },
133
+ listPendingHireRequests() {
134
+ return listPending.all() as HireRequestRow[];
135
+ },
136
+ listActiveHireRequests() {
137
+ return listActive.all() as HireRequestRow[];
138
+ },
139
+ countActiveHireRequests() {
140
+ const row = countActive.get() as { n: number };
141
+ return row.n;
142
+ },
143
+ close() {
144
+ db.close();
145
+ },
146
+ };
147
+ }
148
+
149
+ // ─── Logger ───────────────────────────────────────────────────────────────────
150
+
151
+ function openLogger(logPath: string, foreground: boolean): (entry: Record<string, unknown>) => void {
152
+ let stream: fs.WriteStream | null = null;
153
+ if (!foreground) {
154
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
155
+ stream = fs.createWriteStream(logPath, { flags: "a" });
156
+ }
157
+
158
+ return (entry: Record<string, unknown>) => {
159
+ const line = JSON.stringify({ ...entry, ts: new Date().toISOString() });
160
+ if (foreground) {
161
+ process.stdout.write(line + "\n");
162
+ } else if (stream) {
163
+ stream.write(line + "\n");
164
+ }
165
+ };
166
+ }
167
+
168
+ // ─── IPC Socket ───────────────────────────────────────────────────────────────
169
+
170
+ interface IpcContext {
171
+ db: DaemonDB;
172
+ config: DaemonConfig;
173
+ startTime: number;
174
+ walletAddress: string;
175
+ machineKeyAddress: string;
176
+ hireListener: HireListener | null;
177
+ userOps: UserOpsManager | null;
178
+ activeAgreements: number;
179
+ bundlerMode: string;
180
+ bundlerEndpoint: string;
181
+ }
182
+
183
+ function startIpcServer(ctx: IpcContext, log: ReturnType<typeof openLogger>): net.Server {
184
+ // Remove stale socket
185
+ if (fs.existsSync(DAEMON_SOCK)) {
186
+ fs.unlinkSync(DAEMON_SOCK);
187
+ }
188
+
189
+ const server = net.createServer((socket) => {
190
+ let buf = "";
191
+ socket.on("data", (data) => {
192
+ buf += data.toString();
193
+ const lines = buf.split("\n");
194
+ buf = lines.pop() ?? "";
195
+ for (const line of lines) {
196
+ if (!line.trim()) continue;
197
+ let cmd: { command: string; id?: string; reason?: string };
198
+ try {
199
+ cmd = JSON.parse(line) as { command: string; id?: string; reason?: string };
200
+ } catch {
201
+ socket.write(JSON.stringify({ ok: false, error: "invalid_json" }) + "\n");
202
+ continue;
203
+ }
204
+
205
+ const response = handleIpcCommand(cmd, ctx, log);
206
+ socket.write(JSON.stringify(response) + "\n");
207
+ }
208
+ });
209
+ socket.on("error", () => { /* client disconnected */ });
210
+ });
211
+
212
+ server.listen(DAEMON_SOCK, () => {
213
+ fs.chmodSync(DAEMON_SOCK, 0o600);
214
+ log({ event: "ipc_ready", socket: DAEMON_SOCK });
215
+ });
216
+
217
+ return server;
218
+ }
219
+
220
+ function handleIpcCommand(
221
+ cmd: { command: string; id?: string; reason?: string },
222
+ ctx: IpcContext,
223
+ log: ReturnType<typeof openLogger>
224
+ ): { ok: boolean; data?: unknown; error?: string } {
225
+ const uptimeSeconds = Math.floor((Date.now() - ctx.startTime) / 1000);
226
+ const uptimeStr = formatUptime(uptimeSeconds);
227
+
228
+ switch (cmd.command) {
229
+ case "status": {
230
+ const pending = ctx.db.listPendingHireRequests();
231
+ const active = ctx.db.listActiveHireRequests();
232
+ return {
233
+ ok: true,
234
+ data: {
235
+ state: "running",
236
+ pid: process.pid,
237
+ uptime: uptimeStr,
238
+ wallet: ctx.walletAddress,
239
+ machine_key_address: ctx.machineKeyAddress,
240
+ relay_enabled: ctx.config.relay.enabled,
241
+ relay_url: ctx.config.relay.relay_url,
242
+ relay_poll_seconds: ctx.config.relay.poll_interval_seconds,
243
+ watchtower_enabled: ctx.config.watchtower.enabled,
244
+ bundler_mode: ctx.bundlerMode,
245
+ bundler_endpoint: ctx.bundlerEndpoint,
246
+ active_agreements: active.length,
247
+ pending_approval: pending.length,
248
+ },
249
+ };
250
+ }
251
+
252
+ case "pending": {
253
+ return { ok: true, data: { requests: ctx.db.listPendingHireRequests() } };
254
+ }
255
+
256
+ case "agreements": {
257
+ return { ok: true, data: { agreements: ctx.db.listActiveHireRequests() } };
258
+ }
259
+
260
+ case "agreement": {
261
+ if (!cmd.id) return { ok: false, error: "id required" };
262
+ const agreement = ctx.db.getHireRequest(cmd.id);
263
+ if (!agreement) return { ok: false, error: "agreement not found" };
264
+ return { ok: true, data: { agreement } };
265
+ }
266
+
267
+ case "approve": {
268
+ if (!cmd.id) return { ok: false, error: "id required" };
269
+ const hire = ctx.db.getHireRequest(cmd.id);
270
+ if (!hire) return { ok: false, error: "hire request not found" };
271
+ if (hire.status !== "pending_approval") {
272
+ return { ok: false, error: `hire request status is '${hire.status}', not pending_approval` };
273
+ }
274
+ ctx.db.updateHireRequestStatus(cmd.id, "accepted");
275
+ log({ event: "hire_approved", id: cmd.id });
276
+
277
+ // Trigger accept UserOp (fire and forget)
278
+ if (ctx.userOps && ctx.config.serviceAgreementAddress) {
279
+ const callData = buildAcceptCalldata(
280
+ ctx.config.serviceAgreementAddress,
281
+ hire.agreement_id ?? cmd.id,
282
+ ctx.walletAddress
283
+ );
284
+ ctx.userOps.submit(callData, ctx.walletAddress).then((hash) => {
285
+ log({ event: "userop_submitted", id: cmd.id, hash });
286
+ }).catch((err: unknown) => {
287
+ log({ event: "userop_error", id: cmd.id, error: String(err) });
288
+ });
289
+ }
290
+
291
+ return { ok: true, data: { approved: true, id: cmd.id } };
292
+ }
293
+
294
+ case "reject": {
295
+ if (!cmd.id) return { ok: false, error: "id required" };
296
+ const hire = ctx.db.getHireRequest(cmd.id);
297
+ if (!hire) return { ok: false, error: "hire request not found" };
298
+ if (hire.status !== "pending_approval") {
299
+ return { ok: false, error: `hire request status is '${hire.status}', not pending_approval` };
300
+ }
301
+ const reason = cmd.reason ?? "operator_rejected";
302
+ ctx.db.updateHireRequestStatus(cmd.id, "rejected", reason);
303
+ log({ event: "hire_rejected", id: cmd.id, reason });
304
+ return { ok: true, data: { rejected: true, id: cmd.id, reason } };
305
+ }
306
+
307
+ case "complete": {
308
+ // Called after a job is delivered and accepted. Triggers post-job lifecycle:
309
+ // receipt generation, learning extraction, worker memory update.
310
+ if (!cmd.id) return { ok: false, error: "id required" };
311
+ const hire = ctx.db.getHireRequest(cmd.id);
312
+ if (!hire) return { ok: false, error: "hire request not found" };
313
+
314
+ const now = new Date().toISOString();
315
+ const startedAt = new Date(hire.created_at).toISOString();
316
+
317
+ // Generate execution receipt
318
+ const receipt = generateReceipt({
319
+ agreementId: hire.agreement_id ?? cmd.id,
320
+ deliverableHash: hire.spec_hash ?? "0x0",
321
+ walletAddress: ctx.walletAddress,
322
+ startedAt,
323
+ completedAt: now,
324
+ });
325
+ log({ event: "receipt_generated", id: cmd.id, receipt_hash: receipt.receipt_hash });
326
+
327
+ // Extract learnings
328
+ extractLearnings({
329
+ agreementId: hire.agreement_id ?? cmd.id,
330
+ taskDescription: hire.capability ?? "unknown",
331
+ deliverableHash: hire.spec_hash ?? "0x0",
332
+ priceEth: hire.price_eth ?? "0",
333
+ capability: hire.capability ?? "general",
334
+ wallClockSeconds: receipt.metrics.wall_clock_seconds,
335
+ success: true,
336
+ });
337
+ log({ event: "learnings_extracted", id: cmd.id });
338
+
339
+ // Update status to complete
340
+ ctx.db.updateHireRequestStatus(cmd.id, "complete");
341
+
342
+ // Clean job directory (keep receipt + memory)
343
+ cleanJobDirectory(hire.agreement_id ?? cmd.id);
344
+
345
+ return {
346
+ ok: true,
347
+ data: {
348
+ completed: true,
349
+ id: cmd.id,
350
+ receipt_hash: receipt.receipt_hash,
351
+ },
352
+ };
353
+ }
354
+
355
+ default:
356
+ return { ok: false, error: `unknown command: ${cmd.command}` };
357
+ }
358
+ }
359
+
360
+ function formatUptime(seconds: number): string {
361
+ const h = Math.floor(seconds / 3600);
362
+ const m = Math.floor((seconds % 3600) / 60);
363
+ const s = seconds % 60;
364
+ if (h > 0) return `${h}h ${m}m`;
365
+ if (m > 0) return `${m}m ${s}s`;
366
+ return `${s}s`;
367
+ }
368
+
369
+ // ─── Daemon main ──────────────────────────────────────────────────────────────
370
+
371
+ // Extend config with serviceAgreementAddress (loaded from CLI config if available)
372
+ declare module "./config" {
373
+ interface DaemonConfig {
374
+ serviceAgreementAddress?: string;
375
+ }
376
+ }
377
+
378
+ export async function runDaemon(foreground = false): Promise<void> {
379
+ fs.mkdirSync(DAEMON_DIR, { recursive: true, mode: 0o700 });
380
+ const log = openLogger(DAEMON_LOG, foreground);
381
+
382
+ log({ event: "daemon_starting" });
383
+
384
+ // ── Step 1: Load config ──────────────────────────────────────────────────
385
+ let config: DaemonConfig;
386
+ try {
387
+ config = loadDaemonConfig();
388
+ log({ event: "config_loaded", path: require("path").join(require("os").homedir(), ".arc402", "daemon.toml") });
389
+ } catch (err) {
390
+ process.stderr.write(`Config error: ${err}\n`);
391
+ process.exit(1);
392
+ }
393
+
394
+ // ── Step 2: Load machine key ─────────────────────────────────────────────
395
+ let machineKeyAddress: string;
396
+ let machinePrivateKey: string;
397
+ try {
398
+ const mk = loadMachineKey(config);
399
+ machinePrivateKey = mk.privateKey;
400
+ machineKeyAddress = mk.address;
401
+ log({ event: "machine_key_loaded", address: machineKeyAddress });
402
+ } catch (err) {
403
+ process.stderr.write(`Machine key error: ${err}\n`);
404
+ process.exit(1);
405
+ }
406
+
407
+ // ── Step 3: Connect to RPC ───────────────────────────────────────────────
408
+ const provider = new ethers.JsonRpcProvider(config.network.rpc_url);
409
+ try {
410
+ const chainId = (await provider.getNetwork()).chainId;
411
+ if (Number(chainId) !== config.network.chain_id) {
412
+ process.stderr.write(
413
+ `RPC chain ID ${chainId} does not match config ${config.network.chain_id}\n`
414
+ );
415
+ process.exit(1);
416
+ }
417
+ const networkName = config.network.chain_id === 8453 ? "Base Mainnet" : `Chain ${config.network.chain_id}`;
418
+ log({ event: "rpc_connected", chain_id: config.network.chain_id, network: networkName });
419
+ } catch (err) {
420
+ process.stderr.write(`RPC connection failed: ${err}\n`);
421
+ process.exit(1);
422
+ }
423
+
424
+ // ── Step 4+5: Verify wallet ──────────────────────────────────────────────
425
+ try {
426
+ const walletStatus = await verifyWallet(config, provider, machineKeyAddress);
427
+ log({
428
+ event: "wallet_verified",
429
+ address: walletStatus.contractAddress,
430
+ owner: walletStatus.ownerAddress,
431
+ balance_eth: walletStatus.ethBalance,
432
+ machine_key_authorized: walletStatus.machineKeyAuthorized,
433
+ });
434
+ } catch (err) {
435
+ process.stderr.write(`Wallet verification failed: ${err}\n`);
436
+ process.exit(1);
437
+ }
438
+
439
+ // ── Step 6: Connect bundler ──────────────────────────────────────────────
440
+ const userOps = new UserOpsManager(config, provider);
441
+ const bundlerOk = await userOps.pingBundler();
442
+ if (!bundlerOk) {
443
+ log({ event: "bundler_warn", msg: "Bundler endpoint unreachable — will retry on demand" });
444
+ }
445
+ const bundlerEndpoint = config.bundler.endpoint || "https://api.pimlico.io/v2/base/rpc";
446
+ log({ event: "bundler_configured", mode: config.bundler.mode, endpoint: bundlerEndpoint });
447
+
448
+ // ── Step 7: Open state DB ────────────────────────────────────────────────
449
+ let db: DaemonDB;
450
+ try {
451
+ db = openStateDB(DAEMON_DB);
452
+ log({ event: "state_db_opened", path: DAEMON_DB });
453
+ } catch (err) {
454
+ process.stderr.write(`State DB error: ${err}\n`);
455
+ process.exit(1);
456
+ }
457
+
458
+ // ── Setup notifier ───────────────────────────────────────────────────────
459
+ const notifier = new Notifier(
460
+ config.notifications.telegram_bot_token,
461
+ config.notifications.telegram_chat_id,
462
+ {
463
+ hire_request: config.notifications.notify_on_hire_request,
464
+ hire_accepted: config.notifications.notify_on_hire_accepted,
465
+ hire_rejected: config.notifications.notify_on_hire_rejected,
466
+ delivery: config.notifications.notify_on_delivery,
467
+ dispute: config.notifications.notify_on_dispute,
468
+ channel_challenge: config.notifications.notify_on_channel_challenge,
469
+ low_balance: config.notifications.notify_on_low_balance,
470
+ }
471
+ );
472
+
473
+ // ── Step 10: Start relay listener ───────────────────────────────────────
474
+ const hireListener = new HireListener(config, db, notifier, config.wallet.contract_address);
475
+
476
+ const ipcCtx: IpcContext = {
477
+ db,
478
+ config,
479
+ startTime: Date.now(),
480
+ walletAddress: config.wallet.contract_address,
481
+ machineKeyAddress,
482
+ hireListener,
483
+ userOps,
484
+ activeAgreements: 0,
485
+ bundlerMode: config.bundler.mode,
486
+ bundlerEndpoint,
487
+ };
488
+
489
+ // Wire approve callback — submits UserOp when hire is auto-accepted
490
+ hireListener.setApproveCallback(async (hireId) => {
491
+ const hire = db.getHireRequest(hireId);
492
+ if (!hire || !hire.agreement_id || !config.serviceAgreementAddress) return;
493
+ try {
494
+ const callData = buildAcceptCalldata(
495
+ config.serviceAgreementAddress,
496
+ hire.agreement_id,
497
+ config.wallet.contract_address
498
+ );
499
+ const hash = await userOps.submit(callData, config.wallet.contract_address);
500
+ log({ event: "hire_auto_accepted", id: hireId, userop_hash: hash });
501
+ if (config.notifications.notify_on_hire_accepted) {
502
+ await notifier.notifyHireAccepted(hireId, hire.agreement_id);
503
+ }
504
+ } catch (err) {
505
+ log({ event: "accept_userop_error", id: hireId, error: String(err) });
506
+ }
507
+ });
508
+
509
+ // Relay poll interval
510
+ let relayInterval: ReturnType<typeof setInterval> | null = null;
511
+ if (config.relay.enabled && config.relay.relay_url) {
512
+ const pollMs = config.relay.poll_interval_seconds * 1000;
513
+ relayInterval = setInterval(() => { void hireListener.poll(); }, pollMs);
514
+ void hireListener.poll(); // immediate first poll
515
+ log({ event: "relay_started", url: config.relay.relay_url, poll_seconds: config.relay.poll_interval_seconds });
516
+ }
517
+
518
+ // Hire timeout checker — reject stale pending approvals
519
+ const timeoutInterval = setInterval(() => {
520
+ const pending = db.listPendingHireRequests();
521
+ const now = Math.floor(Date.now() / 1000);
522
+ for (const req of pending) {
523
+ const minLead = config.policy.min_hire_lead_time_seconds;
524
+ if (req.deadline_unix > 0 && req.deadline_unix < now + minLead) {
525
+ db.updateHireRequestStatus(req.id, "rejected", "approval_timeout");
526
+ log({ event: "hire_timeout_rejected", id: req.id });
527
+ }
528
+ }
529
+ }, 30_000);
530
+
531
+ // Balance monitor — every 5 minutes
532
+ const balanceInterval = setInterval(async () => {
533
+ try {
534
+ const balance = await getWalletBalance(config.wallet.contract_address, provider);
535
+ const threshold = parseFloat(config.notifications.low_balance_threshold_eth);
536
+ if (parseFloat(balance) < threshold) {
537
+ log({ event: "low_balance", balance_eth: balance, threshold_eth: config.notifications.low_balance_threshold_eth });
538
+ await notifier.notifyLowBalance(balance, config.notifications.low_balance_threshold_eth);
539
+ }
540
+ } catch { /* non-fatal */ }
541
+ }, 5 * 60 * 1000);
542
+
543
+ // ── Step 11: Write PID file (if not foreground) ──────────────────────────
544
+ if (!foreground) {
545
+ fs.writeFileSync(DAEMON_PID, String(process.pid), { mode: 0o600 });
546
+ log({ event: "pid_written", pid: process.pid, path: DAEMON_PID });
547
+ }
548
+
549
+ // ── Start IPC socket ─────────────────────────────────────────────────────
550
+ const ipcServer = startIpcServer(ipcCtx, log);
551
+
552
+ // ── Step 12: Startup complete ────────────────────────────────────────────
553
+ const subsystems = [];
554
+ if (config.relay.enabled) subsystems.push("relay");
555
+ if (config.watchtower.enabled) subsystems.push("watchtower");
556
+ subsystems.push(`bundler(${config.bundler.mode})`);
557
+
558
+ log({
559
+ event: "daemon_started",
560
+ wallet: config.wallet.contract_address,
561
+ subsystems,
562
+ pid: process.pid,
563
+ });
564
+
565
+ await notifier.notifyStarted(config.wallet.contract_address, subsystems);
566
+
567
+ // ── Graceful shutdown ────────────────────────────────────────────────────
568
+ const shutdown = async (signal: string) => {
569
+ log({ event: "daemon_stopping", signal });
570
+
571
+ // Stop accepting new hire requests
572
+ if (relayInterval) clearInterval(relayInterval);
573
+ clearInterval(timeoutInterval);
574
+ clearInterval(balanceInterval);
575
+
576
+ // Close IPC
577
+ ipcServer.close();
578
+ if (fs.existsSync(DAEMON_SOCK)) fs.unlinkSync(DAEMON_SOCK);
579
+
580
+ await notifier.notifyStopped();
581
+ log({ event: "daemon_stopped" });
582
+
583
+ // Clean up PID file
584
+ if (!foreground && fs.existsSync(DAEMON_PID)) {
585
+ fs.unlinkSync(DAEMON_PID);
586
+ }
587
+
588
+ db.close();
589
+ process.exit(0);
590
+ };
591
+
592
+ process.on("SIGTERM", () => { void shutdown("SIGTERM"); });
593
+ process.on("SIGINT", () => { void shutdown("SIGINT"); });
594
+
595
+ // Keep process alive
596
+ process.stdin.resume();
597
+ }
598
+
599
+ // ─── Entry point ──────────────────────────────────────────────────────────────
600
+ // Run when spawned directly (node dist/daemon/index.js [--foreground])
601
+
602
+ if (require.main === module || process.env.ARC402_DAEMON_PROCESS === "1") {
603
+ const foreground = process.argv.includes("--foreground") ||
604
+ process.env.ARC402_DAEMON_FOREGROUND === "1";
605
+ runDaemon(foreground).catch((err) => {
606
+ process.stderr.write(`Daemon fatal error: ${err}\n`);
607
+ process.exit(1);
608
+ });
609
+ }