@toon-protocol/townhouse 0.1.0-rc5 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,150 +1,48 @@
1
+ import { E as EncryptedWallet, T as TownhouseConfig, W as WalletManager, a as ComposeProfile, N as NodeType$1, B as BandwidthStats, H as HealthCheckOptions } from './manager-SsneW_Mj.js';
2
+ export { A as ApiConfig, b as ComposeLoaderError, C as ComposeLoaderOptions, c as ConnectorConfig, d as ContainerSpec, D as DerivedNodeKeys, e as DvmNodeConfig, L as LoggingConfig, M as MillNodeConfig, f as NodeKeyInfo, g as NodeKeys, h as NodesConfig, O as OrchestratorEvents, i as TownNodeConfig, j as TransportConfig, k as WalletConfig, l as WalletManagerConfig, m as WalletState, n as loadComposeTemplate, o as materializeComposeTemplate } from './manager-SsneW_Mj.js';
1
3
  import { EventEmitter } from 'node:events';
2
4
  import Docker from 'dockerode';
3
5
  import { FastifyBaseLogger, FastifyInstance } from 'fastify';
4
- import { MillHealthResponse } from '@toon-protocol/mill';
5
- export { MillHealthResponse } from '@toon-protocol/mill';
6
+ import { z } from 'zod';
6
7
 
7
8
  /**
8
- * Townhouse configuration schema TypeScript interfaces only.
9
- * Runtime validation lives in validator.ts.
9
+ * Wallet encryption/decryption for Townhouse (Story 21.4, Task 2).
10
+ *
11
+ * Uses Node.js crypto: scrypt for KDF, AES-256-GCM for authenticated encryption.
12
+ * The mnemonic is the plaintext being encrypted.
10
13
  */
11
- interface TownNodeConfig {
12
- enabled: boolean;
13
- /** Nostr relay fee in millisatoshis per event */
14
- feePerEvent?: number;
15
- /** Docker image override */
16
- image?: string;
17
- }
18
- interface ChainEndpoint {
19
- rpcUrl: string;
20
- wsUrl?: string;
21
- }
22
- interface MillChainsConfig {
23
- evm?: ChainEndpoint;
24
- solana?: ChainEndpoint;
25
- mina?: ChainEndpoint;
26
- }
27
- interface MillNodeConfig {
28
- enabled: boolean;
29
- /** Swap fee basis points (1 = 0.01%) */
30
- feeBasisPoints?: number;
31
- /** Docker image override */
32
- image?: string;
33
- /**
34
- * Chain RPC endpoints the mill should swap against (D2). The orchestrator
35
- * does not currently forward this directly into MILL_CONFIG_JSON — it
36
- * round-trips through YAML so the dashboard and future stories can read it.
37
- */
38
- chains?: MillChainsConfig;
39
- /** Enabled swap pairs, e.g. ['EVM<->SOL']. Informational; D2-introduced. */
40
- pairs?: string[];
41
- }
42
- interface DvmNodeConfig {
43
- enabled: boolean;
44
- /** DVM job fee in millisatoshis */
45
- feePerJob?: number;
46
- /** Per-kind pricing in millisatoshis (key = stringified kind number) */
47
- kindPricing?: Record<string, number>;
48
- /** Docker image override */
49
- image?: string;
50
- }
51
- interface NodesConfig {
52
- town: TownNodeConfig;
53
- mill: MillNodeConfig;
54
- dvm: DvmNodeConfig;
55
- }
56
- interface WalletConfig {
57
- /** Path to encrypted wallet file (no plaintext mnemonic in config) */
58
- encrypted_path: string;
59
- }
60
- interface ConnectorConfig {
61
- /** Docker image for the shared ILP connector */
62
- image: string;
63
- /** Admin API port */
64
- adminPort: number;
65
- }
14
+
66
15
  /**
67
- * Hidden-service publication config (Story 35.5 of the connector repo).
68
- *
69
- * When set, the connector boots `@anyone-protocol/anyone-client` in-process,
70
- * spawns the `anon` binary, publishes a v3 hidden service, and advertises
71
- * its `wss://<addr>.anyone/btp` URL to peers. The keypair lives at `dir`
72
- * inside the connector container and persists across restarts when that
73
- * path is on a mounted volume.
16
+ * Encrypt a mnemonic with a password using scrypt + AES-256-GCM.
17
+ */
18
+ declare function encryptWallet(mnemonic: string, password: string): EncryptedWallet;
19
+ /**
20
+ * Decrypt an encrypted wallet with a password.
21
+ * Throws on wrong password (GCM auth tag verification failure).
22
+ */
23
+ declare function decryptWallet(encrypted: EncryptedWallet, password: string): string;
24
+
25
+ /**
26
+ * Wallet file I/O for Townhouse (Story 21.4, Task 2.2).
74
27
  *
75
- * Operator surface (this type) is intentionally narrow; the connector's
76
- * own config has more knobs (binaryPath, configFilePath) that we omit
77
- * here until a real use case demands them.
28
+ * Persists encrypted wallet to disk with 0o600 permissions (owner-only).
29
+ * Warns if existing file has world-readable permissions.
78
30
  */
79
- interface HiddenServiceConfig$1 {
80
- /** Path inside the connector container for hs_ed25519_secret_key etc. */
81
- dir: string;
82
- /** Hidden service port peers dial <addr>.anyone:<port>. */
83
- port: number;
84
- /**
85
- * Optional override of the externalUrl the connector advertises. Default
86
- * is `"auto"` the connector reads `${dir}/hostname` at startup and
87
- * builds `wss://<hostname>.anyone/btp` itself.
88
- */
89
- externalUrl?: string;
90
- /** Optional override of the SDK's start-up readiness deadline (ms). */
91
- startupTimeoutMs?: number;
92
- /** Optional override of the SDK's shutdown deadline (ms). */
93
- stopTimeoutMs?: number;
94
- }
95
- interface TransportConfig {
96
- /** Transport mode: 'ator' for Tor-based, 'direct' for clearnet */
97
- mode: 'ator' | 'direct';
98
- /** SOCKS5 proxy address when using ator transport */
99
- socksProxy?: string;
100
- /**
101
- * Externally reachable BTP URL. Required when mode='ator' AND
102
- * hiddenService is unset (operator runs their own anon binary external
103
- * to the connector and is responsible for the URL). Ignored for
104
- * mode='direct'. When hiddenService is set and externalUrl is unset,
105
- * the generator emits the literal `"auto"` so the connector resolves
106
- * the .anyone hostname from disk at startup.
107
- */
108
- externalUrl?: string;
109
- /**
110
- * Optional inbound hidden-service publication. When set, the connector
111
- * manages its own anon binary and publishes a .anyone hidden service.
112
- */
113
- hiddenService?: HiddenServiceConfig$1;
114
- /**
115
- * Town relay hidden service. When set, the orchestrator starts a second
116
- * ator sidecar (parallel to any connector HS sidecar) that forwards
117
- * inbound HS traffic to the town container's Nostr WebSocket port (7100),
118
- * and the town container is configured to advertise the .anyone URL.
119
- * Reuses HiddenServiceConfig — same shape as connector HS config.
120
- */
121
- relayHiddenService?: HiddenServiceConfig$1;
122
- }
123
- interface ApiConfig {
124
- /** Dashboard/API port */
125
- port: number;
126
- /** Bind address */
127
- host: string;
128
- }
129
- interface LoggingConfig {
130
- level: 'debug' | 'info' | 'warn' | 'error';
131
- }
132
- interface PresetMetadata {
133
- /** Preset that produced this config (D2). */
134
- name: 'demo';
135
- /** Where the chain endpoints came from — leases.json path or 'local-fallback'. */
136
- chainEndpointSource: string;
137
- }
138
- interface TownhouseConfig {
139
- nodes: NodesConfig;
140
- wallet: WalletConfig;
141
- connector: ConnectorConfig;
142
- transport: TransportConfig;
143
- api: ApiConfig;
144
- logging: LoggingConfig;
145
- /** Present only when the config was generated by `init --preset=<name>`. */
146
- preset?: PresetMetadata;
147
- }
31
+
32
+ /**
33
+ * Save encrypted wallet to disk with restrictive permissions.
34
+ * Creates parent directory if missing.
35
+ */
36
+ declare function saveWallet(path: string, encrypted: EncryptedWallet): Promise<void>;
37
+ /**
38
+ * Load encrypted wallet from disk.
39
+ * Returns null if file does not exist.
40
+ * Warns (via returned flag) if file permissions are too open.
41
+ */
42
+ declare function loadWallet(path: string): Promise<{
43
+ wallet: EncryptedWallet;
44
+ permissionsWarning?: string;
45
+ } | null>;
148
46
 
149
47
  /**
150
48
  * Sensible default configuration. All nodes disabled by default —
@@ -185,244 +83,476 @@ declare class ConfigValidationError extends Error {
185
83
  declare function validateConfig(raw: unknown): TownhouseConfig;
186
84
 
187
85
  /**
188
- * Docker orchestration types for Townhouse (Story 21.2).
86
+ * Connector types for Townhouse (Story 21.3).
189
87
  *
190
- * STUB FILE: Created by ATDD workflow (red phase).
191
- * Implementation will be added during the green phase.
88
+ * Defines the runtime configuration shape for the standalone ILP connector,
89
+ * peer entries, and admin API response types.
192
90
  */
193
- /** Node types that can be orchestrated by Townhouse. */
194
- type NodeType$1 = 'town' | 'mill' | 'dvm';
195
- /** Specification for a container to be created by the orchestrator. */
196
- interface ContainerSpec {
197
- /** Container name (e.g., 'townhouse-town') */
198
- name: string;
199
- /** Docker image to use */
200
- image: string;
201
- /** Environment variables to pass to the container */
202
- env: Record<string, string>;
203
- /** Network to attach the container to */
204
- network: string;
205
- /** Port mappings (host:container) */
206
- ports?: Record<string, string>;
207
- }
208
- /** Events emitted by the orchestrator during operations. */
209
- interface OrchestratorEvents {
210
- /** Emitted during image pull with progress info */
211
- pullProgress: {
212
- image: string;
213
- status: string;
214
- id?: string;
215
- progress?: string;
216
- };
217
- /** Emitted when a container changes state */
218
- containerState: {
219
- name: string;
220
- state: 'creating' | 'starting' | 'running' | 'stopping' | 'stopped' | 'error';
221
- /** Additional context for error states (e.g., error message) */
222
- detail?: string;
223
- };
224
- /** Emitted during health check polling */
225
- healthCheck: {
226
- name: string;
227
- status: string;
228
- attempt: number;
229
- };
230
- /** Emitted before connector restart during peer registration update */
231
- connectorRestarting: {
232
- reason: string;
233
- };
234
- /** Emitted after connector restart and health check passes */
235
- connectorRestarted: {
236
- peers: string[];
237
- };
238
- }
239
- /** Options for health check polling. */
240
- interface HealthCheckOptions {
241
- /** Polling interval in milliseconds (default: 2000) */
242
- interval?: number;
243
- /** Timeout in milliseconds (default: 60000) */
244
- timeout?: number;
245
- }
246
- /** Network I/O stats for a container (from dockerode stats stream) */
247
- interface BandwidthStats {
248
- bytesIn: number;
249
- bytesOut: number;
250
- sampleAt: number;
251
- }
252
91
 
253
92
  /**
254
- * Wallet management types for Townhouse (Story 21.4).
255
- *
256
- * Defines interfaces for HD wallet key derivation, encryption at rest,
257
- * and node key management.
93
+ * A peer entry representing a child node connected to the connector via BTP.
94
+ * Each active node becomes a child peer of the connector.
258
95
  */
259
-
260
- /** Configuration for the WalletManager */
261
- interface WalletManagerConfig {
262
- /** Path to encrypted wallet file */
263
- encryptedPath: string;
264
- }
265
- /** Keys derived for a specific node type */
266
- interface NodeKeys {
267
- /** Nostr public key (hex-encoded, 32 bytes) */
268
- nostrPubkey: string;
269
- /** Nostr secret key (raw 32-byte scalar) */
270
- nostrSecretKey: Uint8Array;
271
- /** EVM address (checksummed, 0x-prefixed) */
272
- evmAddress: string;
273
- /** EVM private key (raw 32 bytes) */
274
- evmPrivateKey: Uint8Array;
275
- /** BIP-44 derivation path used for Nostr key */
276
- nostrDerivationPath: string;
277
- /** BIP-44 derivation path used for EVM key */
278
- evmDerivationPath: string;
279
- /** Base58-encoded Solana public key — mill only, omitted for town/dvm */
280
- solanaAddress?: string;
281
- /** Mina public key hex — mill only, omitted for town/dvm */
282
- minaAddress?: string;
283
- }
284
- /** Map of node type to its derived keys */
285
- interface DerivedNodeKeys {
286
- town: NodeKeys;
287
- mill: NodeKeys;
288
- dvm: NodeKeys;
289
- }
290
- /** Summary info for display (no secrets) */
291
- interface NodeKeyInfo {
292
- /** Node type */
293
- nodeType: NodeType$1;
294
- /** Nostr public key (hex) */
295
- nostrPubkey: string;
296
- /** EVM address (checksummed) */
297
- evmAddress: string;
298
- /** Nostr derivation path */
299
- nostrDerivationPath: string;
300
- /** EVM derivation path */
301
- evmDerivationPath: string;
302
- /** Base58-encoded Solana public key — mill only, omitted for town/dvm */
303
- solanaAddress?: string;
304
- /** Mina public key hex — mill only, omitted for town/dvm */
305
- minaAddress?: string;
306
- }
307
- /** Persisted wallet state (in memory after decryption) */
308
- interface WalletState {
309
- /** All derived node keys */
310
- keys: DerivedNodeKeys;
311
- }
312
- /** Encrypted wallet file format (JSON, all fields base64-encoded) */
313
- interface EncryptedWallet {
314
- /** scrypt salt (base64) */
315
- salt: string;
316
- /** AES-GCM initialization vector (base64) */
317
- iv: string;
318
- /** AES-256-GCM ciphertext (base64) */
319
- ciphertext: string;
320
- /** AES-GCM authentication tag (base64) */
321
- tag: string;
96
+ interface PeerEntry {
97
+ /** Node type identifier (e.g., 'town', 'mill', 'dvm') */
98
+ id: string;
99
+ /** Relationship to connector nodes are always children */
100
+ relation: 'child';
101
+ /** BTP WebSocket URL for Docker-internal communication */
102
+ btpUrl: string;
103
+ /** Asset code for ILP packets (e.g., 'USD') */
104
+ assetCode: string;
105
+ /** Asset scale (e.g., 6 for micro-units) */
106
+ assetScale: number;
322
107
  }
323
-
324
108
  /**
325
- * WalletManager — HD key derivation for Townhouse (Story 21.4, Task 1).
109
+ /**
110
+ * Hidden-service configuration for the connector's inbound BTP path.
111
+ *
112
+ * When set under transport.hiddenService, the connector boots the
113
+ * `@anyone-protocol/anyone-client` SDK in-process (Story 35.5 of the
114
+ * connector repo, "ManagedAnonClient") which spawns the `anon` binary
115
+ * and publishes a v3 hidden service. The .anyone hostname is read from
116
+ * `${dir}/hostname` after publish and substituted into the connector's
117
+ * externalUrl as `wss://<hostname>.anyone/btp`.
326
118
  *
327
- * Single BIP-39 mnemonic, deterministic HD derivation per node type.
328
- * Uses BIP-44 paths with distinct account indices per node type:
329
- * - Town: account 0
330
- * - Mill: account 1
331
- * - DVM: account 2
119
+ * Operator surface lives at transport.hiddenService.{dir, port}; the
120
+ * connector's wire format is more verbose (transport.managedOptions.*)
121
+ * config-generator handles the translation.
332
122
  *
333
- * Nostr keys use NIP-06 coin type 1237: m/44'/1237'/{account}'/0/0
334
- * EVM keys use standard coin type 60: m/44'/60'/{account}'/0/0
335
- */
336
-
337
- /**
338
- * WalletManager handles mnemonic generation, key derivation, and in-memory
339
- * key lifecycle for Townhouse node operations.
123
+ * Per-townhouse-instance keypair: the secret key under `${dir}/` is the
124
+ * .anyone identity. Persist it across redeploys to keep the address stable;
125
+ * delete it to rotate.
340
126
  */
341
- declare class WalletManager {
342
- private readonly config;
343
- private state;
344
- constructor(config: WalletManagerConfig);
345
- /** Path to the encrypted wallet file */
346
- get encryptedPath(): string;
347
- /**
348
- * Generate a new 12-word BIP-39 mnemonic and derive all node keys.
349
- * Returns the mnemonic (for one-time display) and the derived state.
350
- */
351
- generate(): Promise<{
352
- mnemonic: string;
353
- state: WalletState;
354
- }>;
355
- /**
356
- * Import an existing mnemonic (12 or 24 words) and derive all node keys.
357
- * Throws if mnemonic is invalid (wrong checksum, wrong word count, etc).
358
- */
359
- fromMnemonic(mnemonic: string): Promise<WalletState>;
360
- /**
361
- * Get derived keys for a specific node type.
362
- * Throws if wallet has not been initialized (call generate() or fromMnemonic() first).
363
- */
364
- getNodeKeys(nodeType: NodeType$1): NodeKeys;
365
- /**
366
- * Get display-safe info for all node types (no secrets).
367
- */
368
- getAllKeys(): NodeKeyInfo[];
369
- /**
370
- * List keys for all node types (alias for getAllKeys for API compatibility).
371
- */
372
- listKeys(): NodeKeyInfo[];
127
+ interface HiddenServiceConfig {
373
128
  /**
374
- * Zero all in-memory key material. After calling lock(),
375
- * getNodeKeys() and getAllKeys() will throw.
129
+ * Absolute path to the v3 hidden-service key directory inside the
130
+ * connector container. The connector creates `hs_ed25519_secret_key`,
131
+ * `hs_ed25519_public_key`, and `hostname` here on first boot, then
132
+ * reuses them on subsequent boots if present.
376
133
  */
377
- lock(): void;
134
+ dir: string;
378
135
  /**
379
- * Derive keys for all node types from a mnemonic.
136
+ * Hidden service port advertised on the .anyone address. Forwards to
137
+ * the connector's BTP server (typically same port as connector's
138
+ * btpServerPort, since the HS port = the port external peers dial).
380
139
  */
381
- private deriveAllKeys;
140
+ port: number;
382
141
  /**
383
- * Derive Nostr + EVM keys for a specific node type.
142
+ * Optional override for the externalUrl the connector advertises.
143
+ * Defaults to the literal "auto" when unset, which makes the connector
144
+ * resolve the .anyone hostname from `${dir}/hostname` at startup.
145
+ * Set explicitly only when forcing a specific .anyone address (rare).
384
146
  */
385
- private deriveNodeKeys;
147
+ externalUrl?: string;
148
+ /** Overall deadline for SOCKS port readiness (ms). Default 60000. */
149
+ startupTimeoutMs?: number;
150
+ /** Overall deadline for `sdk.stop()` (ms). Default 10000. */
151
+ stopTimeoutMs?: number;
386
152
  }
387
-
388
153
  /**
389
- * Wallet encryption/decryption for Townhouse (Story 21.4, Task 2).
154
+ * Runtime configuration for the standalone ILP connector.
155
+ * Generated by ConnectorConfigGenerator from TownhouseConfig.
156
+ */
157
+ interface ConnectorRuntimeConfig {
158
+ /** Admin API listen port */
159
+ adminPort: number;
160
+ /** Base ILP address for this connector */
161
+ ilpAddress: string;
162
+ /** List of child peer entries (one per active node) */
163
+ peers: PeerEntry[];
164
+ /** Transport configuration */
165
+ transport: {
166
+ /**
167
+ * Operator-facing transport selection. Maps to the connector's
168
+ * discriminated union internally (mode='ator' → type='socks5').
169
+ */
170
+ mode: 'ator' | 'direct';
171
+ /** SOCKS5 proxy URL (must be socks5h://) — required when mode='ator'. */
172
+ socksProxy?: string;
173
+ /**
174
+ * Externally reachable BTP URL the connector advertises to peers.
175
+ * Required when mode='ator' AND hiddenService is unset (operator runs
176
+ * their own anon binary externally). Ignored for mode='direct'.
177
+ * When hiddenService IS set and externalUrl is unset, the generator
178
+ * emits the literal "auto" so the connector resolves the .anyone
179
+ * hostname at startup.
180
+ */
181
+ externalUrl?: string;
182
+ /** Inbound hidden-service publication (Story 35.5 path). */
183
+ hiddenService?: HiddenServiceConfig;
184
+ };
185
+ }
186
+ /**
187
+ * Response from GET /health on the connector's healthCheckPort.
188
+ * Mirrors `HealthStatus` from `@toon-protocol/connector`.
189
+ */
190
+ interface HealthResponse {
191
+ status: 'healthy' | 'unhealthy' | 'starting' | 'degraded';
192
+ uptime: number;
193
+ peersConnected: number;
194
+ totalPeers: number;
195
+ timestamp: string;
196
+ nodeId?: string;
197
+ version?: string;
198
+ }
199
+ /**
200
+ * Per-peer ILP counter snapshot from GET /admin/metrics.json.
201
+ * Mirrors `AdminMetricsJsonPeer` from `@toon-protocol/connector`.
202
+ */
203
+ interface MetricsPeerEntry {
204
+ peerId: string;
205
+ connected: boolean;
206
+ packetsForwarded: number;
207
+ packetsRejected: number;
208
+ bytesSent: number;
209
+ /** Connector v3.7.0+ (toon-protocol/connector#73). Counts packets accepted
210
+ * via the self-delivery code path (route nextHop === connector's own
211
+ * nodeId). Older connectors omit this field — default to 0 at consumers. */
212
+ packetsLocallyDelivered?: number;
213
+ lastPacketAt: string | null;
214
+ }
215
+ /**
216
+ * Response from GET /admin/metrics.json on the connector's adminApi port.
217
+ * Mirrors `AdminMetricsJsonResponse` from `@toon-protocol/connector`.
218
+ */
219
+ interface MetricsResponse {
220
+ uptimeSeconds: number;
221
+ aggregate: {
222
+ packetsForwarded: number;
223
+ packetsRejected: number;
224
+ bytesSent: number;
225
+ /** Connector v3.7.0+ — see MetricsPeerEntry.packetsLocallyDelivered. */
226
+ packetsLocallyDelivered?: number;
227
+ };
228
+ peers: MetricsPeerEntry[];
229
+ timestamp: string;
230
+ }
231
+ /**
232
+ * Peer entry from GET /admin/peers on the connector's adminApi port.
233
+ * Mirrors the response of the connector's `router.get('/peers', …)` handler.
234
+ * Note: per-peer packet counters live on /admin/metrics.json, not here.
235
+ */
236
+ interface PeerStatus {
237
+ id: string;
238
+ connected: boolean;
239
+ ilpAddresses: string[];
240
+ routeCount: number;
241
+ }
242
+ /**
243
+ * Wrapper response from GET /admin/peers.
244
+ * Mirrors the connector's `router.get('/peers')` JSON envelope.
245
+ */
246
+ interface PeersResponse {
247
+ nodeId: string;
248
+ peerCount: number;
249
+ connectedCount: number;
250
+ peers: PeerStatus[];
251
+ }
252
+ /**
253
+ * Channel summary entry from GET /admin/channels on the connector's adminApi port.
254
+ * Mirrors `ChannelSummary` from `@toon-protocol/connector`
255
+ * (packages/connector/src/http/admin-api.ts ChannelSummary at v3.x).
390
256
  *
391
- * Uses Node.js crypto: scrypt for KDF, AES-256-GCM for authenticated encryption.
392
- * The mnemonic is the plaintext being encrypted.
257
+ * `status` is kept as `string` (not a union) because the connector's enum may
258
+ * grow without warning the contract canary catches shape drift, not enum domain.
393
259
  */
394
-
260
+ interface ChannelSummary {
261
+ channelId: string;
262
+ peerId: string;
263
+ chain: string;
264
+ status: string;
265
+ deposit: string;
266
+ lastActivity: string;
267
+ }
395
268
  /**
396
- * Encrypt a mnemonic with a password using scrypt + AES-256-GCM.
269
+ * Filter params for GET /packets on the connector admin API.
270
+ *
271
+ * Townhouse-Side Contract (§getPacketLog) — added in story 21.10.
272
+ * The connector must expose `GET /packets?ilpAddress=<>&since=<>&limit=<>`.
273
+ * If the running connector image does not expose this endpoint, the
274
+ * /nodes/:type/packets/timeseries route returns 503 and the contract canary
275
+ * will catch the drift. See packages/sdk/CONNECTOR_MIGRATION.md §Townhouse-Side Contract.
397
276
  */
398
- declare function encryptWallet(mnemonic: string, password: string): EncryptedWallet;
277
+ interface PacketLogFilter {
278
+ ilpAddress?: string;
279
+ since?: number;
280
+ limit?: number;
281
+ }
282
+ /** A single packet log entry returned by GET /packets */
283
+ interface PacketLogEntry {
284
+ ts: number;
285
+ ilpAddressFrom: string;
286
+ ilpAddressTo: string;
287
+ amount: string;
288
+ result: 'fulfill' | 'reject' | 'timeout';
289
+ }
399
290
  /**
400
- * Decrypt an encrypted wallet with a password.
401
- * Throws on wrong password (GCM auth tag verification failure).
291
+ * Response from GET /admin/hs-hostname on the connector's adminApi port.
292
+ * Mirrors the connector v3.5.0+ `HsHostnameResponse` (Story 44.1 / AC FR35).
293
+ * Both fields are null while the .anyone hidden-service bootstrap is in
294
+ * progress; both become non-null once the descriptor is published.
402
295
  */
403
- declare function decryptWallet(encrypted: EncryptedWallet, password: string): string;
296
+ interface HsHostnameResponse {
297
+ hostname: string | null;
298
+ publishedAt: string | null;
299
+ }
404
300
 
405
301
  /**
406
- * Wallet file I/O for Townhouse (Story 21.4, Task 2.2).
302
+ * Per-asset earnings row from GET /admin/earnings.json (endpoint added in connector v3.2.0).
303
+ * Mirrors `AdminEarningsByAsset` from `@toon-protocol/connector` admin-api.
407
304
  *
408
- * Persists encrypted wallet to disk with 0o600 permissions (owner-only).
409
- * Warns if existing file has world-readable permissions.
305
+ * Cumulative amounts are decimal-string bigints (JSON-safe for any asset scale).
306
+ * `claimsReceivedTotal` tracks value received from the peer (they paid us);
307
+ * `claimsSentTotal` tracks value forwarded to the peer (they earned).
410
308
  */
411
-
309
+ interface AssetEarnings {
310
+ assetCode: string;
311
+ assetScale: number;
312
+ claimsReceivedTotal: string;
313
+ claimsSentTotal: string;
314
+ netBalance: string;
315
+ lastClaimAt: string | null;
316
+ }
412
317
  /**
413
- * Save encrypted wallet to disk with restrictive permissions.
414
- * Creates parent directory if missing.
318
+ * Per-peer earnings entry from GET /admin/earnings.json.
319
+ * Mirrors `AdminEarningsJsonPeer` from
320
+ * `@toon-protocol/connector packages/connector/src/http/admin-api.ts:278-281`.
415
321
  */
416
- declare function saveWallet(path: string, encrypted: EncryptedWallet): Promise<void>;
322
+ interface PeerEarnings {
323
+ peerId: string;
324
+ byAsset: AssetEarnings[];
325
+ }
417
326
  /**
418
- * Load encrypted wallet from disk.
419
- * Returns null if file does not exist.
420
- * Warns (via returned flag) if file permissions are too open.
327
+ * Connector fee rollup from GET /admin/earnings.json.
328
+ * Mirrors `AdminEarningsConnectorFee` from
329
+ * `@toon-protocol/connector packages/connector/src/http/admin-api.ts:283-287`.
421
330
  */
422
- declare function loadWallet(path: string): Promise<{
423
- wallet: EncryptedWallet;
424
- permissionsWarning?: string;
425
- } | null>;
331
+ interface ConnectorFeeEntry {
332
+ assetCode: string;
333
+ assetScale: number;
334
+ total: string;
335
+ }
336
+ /**
337
+ * A single recent claim entry from GET /admin/earnings.json.
338
+ * Mirrors `AdminEarningsRecentClaim` from
339
+ * `@toon-protocol/connector packages/connector/src/http/admin-api.ts:289-296`.
340
+ */
341
+ interface RecentClaim {
342
+ peerId: string;
343
+ assetCode: string;
344
+ assetScale: number;
345
+ amount: string;
346
+ direction: 'inbound' | 'outbound';
347
+ at: string;
348
+ }
349
+ /**
350
+ * Typed wrapper around the connector's wire-level `timestamp: string` field.
351
+ * The connector's `AdminEarningsJsonResponse` carries a plain ISO-8601 string
352
+ * (`packages/connector/src/http/admin-api.ts:298-304`). Townhouse wraps it as
353
+ * a value object so dashboard consumers have a typed handle and the field can
354
+ * be extended (`epoch?`, `timezone?`) without breaking callers.
355
+ *
356
+ * `ConnectorAdminClient.getEarnings()` performs the wrap on the way out:
357
+ * `timestamp: { iso: rawString }`.
358
+ */
359
+ interface EarningsTimestamp {
360
+ iso: string;
361
+ }
362
+ /**
363
+ * Response from GET /admin/earnings.json on the connector's adminApi port.
364
+ * Mirrors `AdminEarningsJsonResponse` from
365
+ * `@toon-protocol/connector packages/connector/src/http/admin-api.ts:298-304`.
366
+ *
367
+ * NOTE: The connector's wire shape carries `timestamp: string`. Townhouse's
368
+ * `getEarnings()` adapts it to `timestamp: EarningsTimestamp` (value object).
369
+ *
370
+ * Returns HTTP 503 when the connector is started without settlement config
371
+ * (accountManager / claimReceiver not wired). Townhouse's apex always wires
372
+ * both; 503 in production indicates connector misconfiguration.
373
+ */
374
+ interface EarningsResponse {
375
+ uptimeSeconds: number;
376
+ peers: PeerEarnings[];
377
+ connectorFees: ConnectorFeeEntry[];
378
+ recentClaims: RecentClaim[];
379
+ timestamp: EarningsTimestamp;
380
+ }
381
+
382
+ /**
383
+ * Connector Admin Client for Townhouse (Story 21.3, contract aligned in 21.7.5).
384
+ *
385
+ * HTTP client for the connector's admin API endpoints. Paths and response
386
+ * shapes mirror the connector source-of-truth — see
387
+ * `@toon-protocol/connector` `packages/connector/src/http/{types,admin-api}.ts`.
388
+ *
389
+ * Uses Node.js native fetch (available in Node 20+).
390
+ *
391
+ * Two distinct HTTP servers live on the connector image:
392
+ * - healthCheckPort serves /health and /health/{live,ready}
393
+ * - adminApi.port serves /admin/* (peers, metrics.json, routes, channels, …)
394
+ *
395
+ * The base URL passed to this client must point at whichever server hosts
396
+ * the endpoint being called: pass the healthCheckPort base for `getHealth`
397
+ * and the adminApi.port base for `getPeers` / `getMetrics`. In practice
398
+ * Townhouse currently runs both ports on the same host, so callers either
399
+ * construct two clients or hit a shared base URL when the ports overlap.
400
+ */
401
+
402
+ declare class ConnectorAdminClient {
403
+ private readonly baseUrl;
404
+ private readonly timeoutMs;
405
+ /**
406
+ * @param baseUrl - Base URL for the connector admin API (e.g., 'http://localhost:9402')
407
+ * @param timeoutMs - Request timeout in milliseconds (default: 5000)
408
+ */
409
+ constructor(baseUrl: string, timeoutMs?: number);
410
+ /** Public read of the configured base URL (used by drill-command probes to derive a sibling client). */
411
+ getBaseUrl(): string;
412
+ /**
413
+ * GET /health on the admin-API port — checks HTTP reachability of the
414
+ * connector without validating the rich HealthStatus shape. Use this from
415
+ * the drill-command health probe when only the admin URL is available
416
+ * (port 9401), not the healthCheckPort (8080). The admin server's /health
417
+ * returns `{status:'healthy', service:'admin-api', nodeId, timestamp}` —
418
+ * a different shape from `getHealth()`'s validator. This method returns
419
+ * a coarse status from a 200 response and reads `nodeId` if present.
420
+ *
421
+ * @throws Error when connector is unreachable or returns non-2xx.
422
+ */
423
+ pingAdminLive(): Promise<{
424
+ status: 'healthy';
425
+ nodeId?: string;
426
+ }>;
427
+ /**
428
+ * GET /health — returns the connector's HealthStatus from the healthCheckPort server.
429
+ *
430
+ * @throws Error when connector is not running, returns non-200, or shape is invalid
431
+ */
432
+ getHealth(): Promise<HealthResponse>;
433
+ /**
434
+ * GET /admin/hs-hostname — returns the connector's published .anyone hidden-service
435
+ * hostname (Epic 45 / Story 44.1). Returns 200 with {hostname, publishedAt} both
436
+ * possibly null while bootstrap is in progress, both non-null once anon publishes.
437
+ * Returns 503 when the connector is anon-disabled (anon.enabled: false in config).
438
+ *
439
+ * @throws Error('connector is anon-disabled (HTTP 503)') on 503 — caller can match
440
+ * on this exact prefix for actionable diagnostics.
441
+ * @throws Error on non-200/503 status, network error, or shape-validation failure.
442
+ */
443
+ getHsHostname(): Promise<HsHostnameResponse>;
444
+ /**
445
+ * GET /admin/metrics.json — returns the connector's per-peer ILP counters
446
+ * with an aggregate rollup, mirroring `AdminMetricsJsonResponse`.
447
+ *
448
+ * @throws Error when connector is not running, returns non-200, or shape is invalid
449
+ */
450
+ getMetrics(): Promise<MetricsResponse>;
451
+ /**
452
+ * GET /admin/earnings.json — returns the connector's per-peer per-asset
453
+ * earnings projection, mirroring `AdminEarningsJsonResponse` (connector v3.2.0+).
454
+ *
455
+ * Source of truth: @toon-protocol/connector
456
+ * packages/connector/src/http/admin-api.ts:1864-1945
457
+ *
458
+ * Returns HTTP 503 when the connector is started without settlement config
459
+ * (accountManager / claimReceiver not wired). Townhouse's apex always wires
460
+ * both; 503 in production indicates connector misconfiguration.
461
+ *
462
+ * Wire-shape adaptation: the connector's `timestamp: string` field is
463
+ * wrapped into `{ iso: string }` on the way out (EarningsTimestamp).
464
+ *
465
+ * @throws Error when connector is not running, returns non-200, or shape is invalid
466
+ */
467
+ getEarnings(): Promise<EarningsResponse>;
468
+ /**
469
+ * GET /admin/peers — returns the connector's peer roster with route counts
470
+ * and ILP addresses. Returns the unwrapped peers array (the wrapper's
471
+ * nodeId / peerCount / connectedCount fields are dropped).
472
+ *
473
+ * @throws Error when connector is not running, returns non-200, or shape is invalid
474
+ */
475
+ getPeers(): Promise<PeerStatus[]>;
476
+ /**
477
+ * GET /admin/channels — returns the connector's payment-channel summaries
478
+ * across all registered chain providers. Multi-chain: one entry per channel
479
+ * regardless of chain.
480
+ *
481
+ * @throws Error when connector is not running, returns non-200, or shape is invalid
482
+ */
483
+ getChannels(): Promise<ChannelSummary[]>;
484
+ /**
485
+ * POST /admin/peers — register (or re-register, idempotent) a child peer
486
+ * with the connector. Used by the boot reconciler (Story 46.1) to
487
+ * re-register peers present in `nodes.yaml` but missing from the
488
+ * connector's runtime peer roster (e.g., after a connector restart).
489
+ *
490
+ * The connector's POST /admin/peers handler treats a POST whose `id`
491
+ * matches an existing peer as a re-registration (no-op for the peer
492
+ * itself; routes are appended). A POST with a new `id` triggers
493
+ * `addPeer()` and BTP connection setup.
494
+ *
495
+ * @param input.id - peer identifier (matches `nodes.yaml`'s `peerId` and
496
+ * the connector's `PeerStatus.id`).
497
+ * @param input.url - BTP WebSocket URL the connector dials. MUST start
498
+ * with `ws://` or `wss://` (the connector validates this).
499
+ * @param input.authToken - shared auth token; pass empty string for
500
+ * internal Townhouse peers (no auth).
501
+ * @param input.routes - optional ILP route prefixes to register against
502
+ * this peer. The reconciler passes the peer's ilpAddress.
503
+ * @param input.transport - optional per-peer transport selection
504
+ * (connector >= 3.6.2). `'direct'` forces the connector to bypass the
505
+ * global SOCKS5 transport for this peer, even when the apex itself
506
+ * runs in `transport.type: socks5` mode. Required for Docker-sibling
507
+ * peers in HS mode — the anon SOCKS5 proxy cannot resolve internal
508
+ * Docker hostnames. When omitted, the peer inherits the connector's
509
+ * global transport (back-compat with pre-3.6.2 connectors).
510
+ *
511
+ * @throws Error on non-2xx response, timeout, or connection refused.
512
+ */
513
+ registerPeer(input: {
514
+ id: string;
515
+ url: string;
516
+ authToken: string;
517
+ routes?: {
518
+ prefix: string;
519
+ priority?: number;
520
+ }[];
521
+ transport?: 'direct' | 'socks5';
522
+ relation?: 'parent' | 'peer' | 'child';
523
+ }): Promise<void>;
524
+ /**
525
+ * DELETE /admin/peers/:peerId?removeRoutes=true — deregister a child peer.
526
+ *
527
+ * Idempotent: a 404 from the connector (peer already removed) is treated as
528
+ * success so callers can safely use this as a rollback step without knowing
529
+ * whether the peer was ever registered.
530
+ *
531
+ * `removeRoutes=true` is always sent so the connector drops the ILP routing
532
+ * entries for this peer along with the BTP connection config.
533
+ *
534
+ * @throws Error on empty peerId (rejected at client, no network request made)
535
+ * @throws Error on non-2xx/404 response, timeout, or connection refused
536
+ */
537
+ removePeer(peerId: string): Promise<void>;
538
+ /**
539
+ * GET /packets — returns the connector's raw packet log filtered by the
540
+ * given criteria. Used by the timeseries aggregation route (story 21.10).
541
+ *
542
+ * Townhouse-Side Contract: see packages/sdk/CONNECTOR_MIGRATION.md §getPacketLog.
543
+ * If the connector image does not expose GET /packets, this method throws
544
+ * with a `ConnectorEndpointNotFound` error code so the route can return 503.
545
+ *
546
+ * @throws Error with code='ConnectorEndpointNotFound' when connector returns 404
547
+ * @throws Error when connector is not running, returns non-200, or shape is invalid
548
+ */
549
+ getPacketLog(filter?: PacketLogFilter): Promise<PacketLogEntry[]>;
550
+ /**
551
+ * Perform an HTTP GET request to the connector admin API.
552
+ * Wraps fetch with error handling for connection refused and non-200 responses.
553
+ */
554
+ private fetch;
555
+ }
426
556
 
427
557
  /**
428
558
  * Docker Orchestration Engine for Townhouse (Story 21.2).
@@ -432,6 +562,33 @@ declare function loadWallet(path: string): Promise<{
432
562
  * Uses dockerode for programmatic Docker control with DI for testability.
433
563
  */
434
564
 
565
+ interface RunDockerOptions {
566
+ timeout?: number;
567
+ maxBuffer?: number;
568
+ inheritStdio?: boolean;
569
+ /** Override the subprocess env. Defaults to process.env when omitted. */
570
+ env?: NodeJS.ProcessEnv;
571
+ }
572
+ type ExecFileAsyncSignature = (file: string, args: readonly string[], options?: RunDockerOptions) => Promise<{
573
+ stdout: string;
574
+ stderr: string;
575
+ }>;
576
+ /**
577
+ * Error thrown by DockerOrchestrator HS-path failures (Story 45.3).
578
+ * Carries the failed-service name + subprocess diagnostics so CLI consumers
579
+ * (Story 45.4) can render Sally's failure-state copy library (UX-DR5).
580
+ */
581
+ declare class OrchestratorError extends Error {
582
+ readonly service?: string;
583
+ readonly exitCode?: number;
584
+ readonly stderr?: string;
585
+ constructor(message: string, options?: {
586
+ service?: string;
587
+ exitCode?: number;
588
+ stderr?: string;
589
+ cause?: Error;
590
+ });
591
+ }
435
592
  /**
436
593
  * DockerOrchestrator manages the lifecycle of Townhouse containers.
437
594
  *
@@ -446,15 +603,47 @@ declare class DockerOrchestrator extends EventEmitter {
446
603
  private readonly walletManager;
447
604
  private activeNodes;
448
605
  private readonly statsCache;
449
- constructor(docker: Docker, config: TownhouseConfig, walletManager?: WalletManager);
606
+ private readonly profile;
607
+ private readonly composePath;
608
+ private readonly execFileAsync;
609
+ private readonly adminClientFactory;
610
+ constructor(docker: Docker, config: TownhouseConfig, walletManager?: WalletManager, options?: {
611
+ profile?: ComposeProfile;
612
+ composePath?: string;
613
+ execFileAsync?: ExecFileAsyncSignature;
614
+ adminClientFactory?: (baseUrl: string, timeoutMs: number) => ConnectorAdminClient;
615
+ });
450
616
  /**
451
- * Orchestrate full startup sequence:
452
- * 1. Ensure network exists
453
- * 2. Pull images (with progress)
454
- * 3. Start connector, wait for health
455
- * 4. Start enabled node containers in parallel
617
+ * Orchestrate full startup sequence. Branches on profile:
618
+ * - 'dev' (default): dockerode-based, preserves existing dev-stack behavior
619
+ * - 'hs': docker compose subprocess + HS hostname readiness gate
456
620
  */
457
621
  up(profiles: NodeType$1[]): Promise<void>;
622
+ private upDev;
623
+ /**
624
+ * Narrow `this.composePath` to a definite string. The constructor enforces
625
+ * this invariant for `profile: 'hs'`; this helper exists so the HS-path
626
+ * methods don't need a non-null assertion (lint-clean) and so a constructor
627
+ * regression surfaces as an `OrchestratorError` rather than a `TypeError`.
628
+ */
629
+ private requireComposePath;
630
+ /**
631
+ * validate that composePath is absolute and exists on disk before
632
+ * passing it to any subprocess call. Defence-in-depth — callers pass paths
633
+ * from materializeComposeTemplate so this should never fire in normal use.
634
+ */
635
+ private validateComposePath;
636
+ /** HS-mode startup: shell out to `docker compose up -d`, wait for HS hostname. */
637
+ private upHs;
638
+ /**
639
+ * Parse Docker Compose stderr for failed-service names and emit a
640
+ * containerState event per failed service so callers see the failure via
641
+ * the same channel dev-mode uses (AC #6 — "for each failed service
642
+ * identified, it emits..."). When no pattern matches, emit a single
643
+ * fallback event with name `'compose-up'`.
644
+ */
645
+ private surfaceComposeFailure;
646
+ private waitForHsHostname;
458
647
  /**
459
648
  * Regenerate connector config and restart the connector container
460
649
  * with updated environment variables (peer list).
@@ -473,12 +662,13 @@ declare class DockerOrchestrator extends EventEmitter {
473
662
  */
474
663
  removeNode(type: NodeType$1): Promise<void>;
475
664
  /**
476
- * Graceful shutdown stops containers in reverse order:
477
- * 1. Stop all node containers in parallel
478
- * 2. Stop connector
479
- * 3. Remove network
665
+ * Graceful shutdown. Branches on profile:
666
+ * - 'dev' (default): dockerode-based teardown
667
+ * - 'hs': docker compose subprocess
480
668
  */
481
669
  down(): Promise<void>;
670
+ private downDev;
671
+ private downHs;
482
672
  /**
483
673
  * Resolve the Nostr relay WebSocket URL for a Town node instance.
484
674
  *
@@ -529,6 +719,39 @@ declare class DockerOrchestrator extends EventEmitter {
529
719
  * Emits pullProgress events during download.
530
720
  */
531
721
  pullImages(profiles: NodeType$1[]): Promise<void>;
722
+ /**
723
+ * Pull a single image by its reference (tag or digest form).
724
+ *
725
+ * Skips the pull when the image already exists locally (matches against
726
+ * both RepoTags and RepoDigests so digest-form refs like
727
+ * `ghcr.io/toon-protocol/town@sha256:abc...` are found correctly).
728
+ * Throws `OrchestratorError` on pull failure.
729
+ */
730
+ pullImage(image: string): Promise<void>;
731
+ /**
732
+ * Start a child peer node via `docker compose --profile <type> up -d <type>`.
733
+ *
734
+ * HS-profile only — throws `OrchestratorError` when called on the dev profile.
735
+ *
736
+ * The `env` parameter supplies the per-node wallet secrets (e.g.
737
+ * `TOWN_SECRET_KEY`, `MILL_MNEMONIC`). It is layered on top of `process.env`
738
+ * so that PATH, HOME, and other process-level env vars are preserved for the
739
+ * docker CLI subprocess.
740
+ *
741
+ * Logging guard: the caller (nodes-lifecycle route) must NOT log the `env`
742
+ * argument — it contains secret keys and the wallet mnemonic.
743
+ */
744
+ startNodeViaCompose(type: NodeType$1, env: Record<string, string>): Promise<void>;
745
+ /**
746
+ * Stop and remove a child peer node via `docker compose stop` + `rm -f`.
747
+ *
748
+ * HS-profile only — throws `OrchestratorError` when called on the dev profile.
749
+ * Idempotent: stderr patterns indicating the service/container is already gone
750
+ * (`'no such service'`, `'no containers to remove'`, `'No such container'`)
751
+ * are treated as success so callers can run this as a rollback without
752
+ * worrying about the container's prior state.
753
+ */
754
+ stopNodeViaCompose(type: NodeType$1): Promise<void>;
532
755
  /**
533
756
  * Poll container health status via inspect().
534
757
  * Retries at configurable interval, throws on timeout.
@@ -575,207 +798,27 @@ declare class DockerOrchestrator extends EventEmitter {
575
798
  */
576
799
  private stopAndRemove;
577
800
  /**
578
- * Remove the townhouse-net network if it exists.
579
- */
580
- private removeNetwork;
581
- /**
582
- * Build environment variables for the connector container.
583
- * Delegates to ConnectorConfigGenerator for consistent config generation.
584
- */
585
- private buildConnectorEnv;
586
- /**
587
- * Build environment variables for a node container.
588
- * If a WalletManager is provided, injects per-node identity keys.
589
- */
590
- private buildNodeEnv;
591
- /**
592
- * Follow a Docker pull stream and emit progress events.
593
- */
594
- private followPullProgress;
595
- }
596
-
597
- /**
598
- * Connector types for Townhouse (Story 21.3).
599
- *
600
- * Defines the runtime configuration shape for the standalone ILP connector,
601
- * peer entries, and admin API response types.
602
- */
603
-
604
- /**
605
- * A peer entry representing a child node connected to the connector via BTP.
606
- * Each active node becomes a child peer of the connector.
607
- */
608
- interface PeerEntry {
609
- /** Node type identifier (e.g., 'town', 'mill', 'dvm') */
610
- id: string;
611
- /** Relationship to connector — nodes are always children */
612
- relation: 'child';
613
- /** BTP WebSocket URL for Docker-internal communication */
614
- btpUrl: string;
615
- /** Asset code for ILP packets (e.g., 'USD') */
616
- assetCode: string;
617
- /** Asset scale (e.g., 6 for micro-units) */
618
- assetScale: number;
619
- }
620
- /**
621
- /**
622
- * Hidden-service configuration for the connector's inbound BTP path.
623
- *
624
- * When set under transport.hiddenService, the connector boots the
625
- * `@anyone-protocol/anyone-client` SDK in-process (Story 35.5 of the
626
- * connector repo, "ManagedAnonClient") which spawns the `anon` binary
627
- * and publishes a v3 hidden service. The .anyone hostname is read from
628
- * `${dir}/hostname` after publish and substituted into the connector's
629
- * externalUrl as `wss://<hostname>.anyone/btp`.
630
- *
631
- * Operator surface lives at transport.hiddenService.{dir, port}; the
632
- * connector's wire format is more verbose (transport.managedOptions.*) —
633
- * config-generator handles the translation.
634
- *
635
- * Per-townhouse-instance keypair: the secret key under `${dir}/` is the
636
- * .anyone identity. Persist it across redeploys to keep the address stable;
637
- * delete it to rotate.
638
- */
639
- interface HiddenServiceConfig {
640
- /**
641
- * Absolute path to the v3 hidden-service key directory inside the
642
- * connector container. The connector creates `hs_ed25519_secret_key`,
643
- * `hs_ed25519_public_key`, and `hostname` here on first boot, then
644
- * reuses them on subsequent boots if present.
645
- */
646
- dir: string;
647
- /**
648
- * Hidden service port advertised on the .anyone address. Forwards to
649
- * the connector's BTP server (typically same port as connector's
650
- * btpServerPort, since the HS port = the port external peers dial).
651
- */
652
- port: number;
653
- /**
654
- * Optional override for the externalUrl the connector advertises.
655
- * Defaults to the literal "auto" when unset, which makes the connector
656
- * resolve the .anyone hostname from `${dir}/hostname` at startup.
657
- * Set explicitly only when forcing a specific .anyone address (rare).
658
- */
659
- externalUrl?: string;
660
- /** Overall deadline for SOCKS port readiness (ms). Default 60000. */
661
- startupTimeoutMs?: number;
662
- /** Overall deadline for `sdk.stop()` (ms). Default 10000. */
663
- stopTimeoutMs?: number;
664
- }
665
- /**
666
- * Runtime configuration for the standalone ILP connector.
667
- * Generated by ConnectorConfigGenerator from TownhouseConfig.
668
- */
669
- interface ConnectorRuntimeConfig {
670
- /** Admin API listen port */
671
- adminPort: number;
672
- /** Base ILP address for this connector */
673
- ilpAddress: string;
674
- /** List of child peer entries (one per active node) */
675
- peers: PeerEntry[];
676
- /** Transport configuration */
677
- transport: {
678
- /**
679
- * Operator-facing transport selection. Maps to the connector's
680
- * discriminated union internally (mode='ator' → type='socks5').
681
- */
682
- mode: 'ator' | 'direct';
683
- /** SOCKS5 proxy URL (must be socks5h://) — required when mode='ator'. */
684
- socksProxy?: string;
685
- /**
686
- * Externally reachable BTP URL the connector advertises to peers.
687
- * Required when mode='ator' AND hiddenService is unset (operator runs
688
- * their own anon binary externally). Ignored for mode='direct'.
689
- * When hiddenService IS set and externalUrl is unset, the generator
690
- * emits the literal "auto" so the connector resolves the .anyone
691
- * hostname at startup.
692
- */
693
- externalUrl?: string;
694
- /** Inbound hidden-service publication (Story 35.5 path). */
695
- hiddenService?: HiddenServiceConfig;
696
- };
697
- }
698
- /**
699
- * Response from GET /health on the connector's healthCheckPort.
700
- * Mirrors `HealthStatus` from `@toon-protocol/connector`.
701
- */
702
- interface HealthResponse {
703
- status: 'healthy' | 'unhealthy' | 'starting' | 'degraded';
704
- uptime: number;
705
- peersConnected: number;
706
- totalPeers: number;
707
- timestamp: string;
708
- nodeId?: string;
709
- version?: string;
710
- }
711
- /**
712
- * Per-peer ILP counter snapshot from GET /admin/metrics.json.
713
- * Mirrors `AdminMetricsJsonPeer` from `@toon-protocol/connector`.
714
- */
715
- interface MetricsPeerEntry {
716
- peerId: string;
717
- connected: boolean;
718
- packetsForwarded: number;
719
- packetsRejected: number;
720
- bytesSent: number;
721
- lastPacketAt: string | null;
722
- }
723
- /**
724
- * Response from GET /admin/metrics.json on the connector's adminApi port.
725
- * Mirrors `AdminMetricsJsonResponse` from `@toon-protocol/connector`.
726
- */
727
- interface MetricsResponse {
728
- uptimeSeconds: number;
729
- aggregate: {
730
- packetsForwarded: number;
731
- packetsRejected: number;
732
- bytesSent: number;
733
- };
734
- peers: MetricsPeerEntry[];
735
- timestamp: string;
736
- }
737
- /**
738
- * Peer entry from GET /admin/peers on the connector's adminApi port.
739
- * Mirrors the response of the connector's `router.get('/peers', …)` handler.
740
- * Note: per-peer packet counters live on /admin/metrics.json, not here.
741
- */
742
- interface PeerStatus {
743
- id: string;
744
- connected: boolean;
745
- ilpAddresses: string[];
746
- routeCount: number;
747
- }
748
- /**
749
- * Wrapper response from GET /admin/peers.
750
- * Mirrors the connector's `router.get('/peers')` JSON envelope.
751
- */
752
- interface PeersResponse {
753
- nodeId: string;
754
- peerCount: number;
755
- connectedCount: number;
756
- peers: PeerStatus[];
757
- }
758
- /**
759
- * Filter params for GET /packets on the connector admin API.
760
- *
761
- * Townhouse-Side Contract (§getPacketLog) — added in story 21.10.
762
- * The connector must expose `GET /packets?ilpAddress=<>&since=<>&limit=<>`.
763
- * If the running connector image does not expose this endpoint, the
764
- * /nodes/:type/packets/timeseries route returns 503 and the contract canary
765
- * will catch the drift. See packages/sdk/CONNECTOR_MIGRATION.md §Townhouse-Side Contract.
766
- */
767
- interface PacketLogFilter {
768
- ilpAddress?: string;
769
- since?: number;
770
- limit?: number;
771
- }
772
- /** A single packet log entry returned by GET /packets */
773
- interface PacketLogEntry {
774
- ts: number;
775
- ilpAddressFrom: string;
776
- ilpAddressTo: string;
777
- amount: string;
778
- result: 'fulfill' | 'reject' | 'timeout';
801
+ * Remove the townhouse-net network if it exists.
802
+ */
803
+ private removeNetwork;
804
+ /**
805
+ * Build environment variables for the connector container.
806
+ * Delegates to ConnectorConfigGenerator for consistent config generation.
807
+ */
808
+ private buildConnectorEnv;
809
+ /**
810
+ * Build environment variables for a node container.
811
+ * If a WalletManager is provided, injects per-node identity keys.
812
+ *
813
+ * Async because the DVM path may need to derive an RSA-4096 Arweave key
814
+ * via `walletManager.ensureArweaveKey('dvm')` — that derivation takes
815
+ * 5–30s on first call per unlocked wallet (cached thereafter).
816
+ */
817
+ private buildNodeEnv;
818
+ /**
819
+ * Follow a Docker pull stream and emit progress events.
820
+ */
821
+ private followPullProgress;
779
822
  }
780
823
 
781
824
  /**
@@ -853,74 +896,6 @@ declare class ConnectorConfigGenerator {
853
896
  private generateTransportConfig;
854
897
  }
855
898
 
856
- /**
857
- * Connector Admin Client for Townhouse (Story 21.3, contract aligned in 21.7.5).
858
- *
859
- * HTTP client for the connector's admin API endpoints. Paths and response
860
- * shapes mirror the connector source-of-truth — see
861
- * `@toon-protocol/connector` `packages/connector/src/http/{types,admin-api}.ts`.
862
- *
863
- * Uses Node.js native fetch (available in Node 20+).
864
- *
865
- * Two distinct HTTP servers live on the connector image:
866
- * - healthCheckPort serves /health and /health/{live,ready}
867
- * - adminApi.port serves /admin/* (peers, metrics.json, routes, channels, …)
868
- *
869
- * The base URL passed to this client must point at whichever server hosts
870
- * the endpoint being called: pass the healthCheckPort base for `getHealth`
871
- * and the adminApi.port base for `getPeers` / `getMetrics`. In practice
872
- * Townhouse currently runs both ports on the same host, so callers either
873
- * construct two clients or hit a shared base URL when the ports overlap.
874
- */
875
-
876
- declare class ConnectorAdminClient {
877
- private readonly baseUrl;
878
- private readonly timeoutMs;
879
- /**
880
- * @param baseUrl - Base URL for the connector admin API (e.g., 'http://localhost:9402')
881
- * @param timeoutMs - Request timeout in milliseconds (default: 5000)
882
- */
883
- constructor(baseUrl: string, timeoutMs?: number);
884
- /**
885
- * GET /health — returns the connector's HealthStatus from the healthCheckPort server.
886
- *
887
- * @throws Error when connector is not running, returns non-200, or shape is invalid
888
- */
889
- getHealth(): Promise<HealthResponse>;
890
- /**
891
- * GET /admin/metrics.json — returns the connector's per-peer ILP counters
892
- * with an aggregate rollup, mirroring `AdminMetricsJsonResponse`.
893
- *
894
- * @throws Error when connector is not running, returns non-200, or shape is invalid
895
- */
896
- getMetrics(): Promise<MetricsResponse>;
897
- /**
898
- * GET /admin/peers — returns the connector's peer roster with route counts
899
- * and ILP addresses. Returns the unwrapped peers array (the wrapper's
900
- * nodeId / peerCount / connectedCount fields are dropped).
901
- *
902
- * @throws Error when connector is not running, returns non-200, or shape is invalid
903
- */
904
- getPeers(): Promise<PeerStatus[]>;
905
- /**
906
- * GET /packets — returns the connector's raw packet log filtered by the
907
- * given criteria. Used by the timeseries aggregation route (story 21.10).
908
- *
909
- * Townhouse-Side Contract: see packages/sdk/CONNECTOR_MIGRATION.md §getPacketLog.
910
- * If the connector image does not expose GET /packets, this method throws
911
- * with a `ConnectorEndpointNotFound` error code so the route can return 503.
912
- *
913
- * @throws Error with code='ConnectorEndpointNotFound' when connector returns 404
914
- * @throws Error when connector is not running, returns non-200, or shape is invalid
915
- */
916
- getPacketLog(filter?: PacketLogFilter): Promise<PacketLogEntry[]>;
917
- /**
918
- * Perform an HTTP GET request to the connector admin API.
919
- * Wraps fetch with error handling for connection refused and non-200 responses.
920
- */
921
- private fetch;
922
- }
923
-
924
899
  /**
925
900
  * ATOR transport probe — periodically TCP-connects to the configured SOCKS5
926
901
  * proxy host:port and measures direct HTTPS latency for comparison.
@@ -970,36 +945,6 @@ declare class TransportProbe {
970
945
  private logTransition;
971
946
  }
972
947
 
973
- type ComposeProfile = 'dev' | 'hs';
974
- interface ComposeLoaderOptions {
975
- /** Override default `~/.townhouse/` write target. Used by tests. */
976
- townhouseHome?: string;
977
- /** Override the package-relative dist directory the loader reads from.
978
- * Defaults to the `dist/` adjacent to compose-loader.js at runtime.
979
- * Tests use this to point at fixture directories. */
980
- distDir?: string;
981
- }
982
- declare class ComposeLoaderError extends Error {
983
- constructor(message: string);
984
- }
985
- /**
986
- * Returns the rendered compose YAML for the requested profile.
987
- * For 'hs', digest substitutions are already applied (resolved at build time).
988
- * For 'dev', the YAML is returned verbatim (uses local `toon:*` image tags).
989
- * Throws `ComposeLoaderError` if the requested profile's YAML is unreadable.
990
- */
991
- declare function loadComposeTemplate(profile: ComposeProfile, options?: ComposeLoaderOptions): string;
992
- /**
993
- * Writes the resolved compose YAML to `<townhouseHome>/compose/<profile>.yml`
994
- * and copies `dist/image-manifest.json` to `<townhouseHome>/image-manifest.json`.
995
- * BOTH output files are written with mode 0o600 (NFR8 — operator-secret file mode).
996
- * Returns the absolute paths of the two files written.
997
- */
998
- declare function materializeComposeTemplate(profile: ComposeProfile, options?: ComposeLoaderOptions): {
999
- composePath: string;
1000
- manifestPath: string;
1001
- };
1002
-
1003
948
  /**
1004
949
  * Townhouse API — type definitions.
1005
950
  */
@@ -1035,6 +980,41 @@ interface DvmHealthResponse {
1035
980
  basePricePerByte: string;
1036
981
  jobsRecent: DvmJobsRecent;
1037
982
  }
983
+ /** Chains a Mill node can settle on. Inlined from packages/mill/src/wallet.ts. */
984
+ type MillChainKind = 'evm' | 'mina' | 'solana';
985
+ /** A configured swap pair, inlined from packages/core/src/types.ts (SwapPair). */
986
+ interface MillSwapPair {
987
+ from: {
988
+ assetCode: string;
989
+ assetScale: number;
990
+ chain: string;
991
+ };
992
+ to: {
993
+ assetCode: string;
994
+ assetScale: number;
995
+ chain: string;
996
+ };
997
+ rate: string;
998
+ minAmount?: string;
999
+ maxAmount?: string;
1000
+ }
1001
+ /**
1002
+ * Response shape for GET /health on the Mill BLS server. Inlined from
1003
+ * packages/mill/src/mill.ts (MillHealthResponse) — keep in sync.
1004
+ */
1005
+ interface MillHealthResponse {
1006
+ status: 'ok' | 'starting' | 'stopping' | 'stopped';
1007
+ version: string;
1008
+ nodePubkey: string;
1009
+ swapPairsCount: number;
1010
+ chains: readonly MillChainKind[];
1011
+ uptimeSec: number;
1012
+ inventory: Record<string, string>;
1013
+ /** Configured swap pairs — operator-config, no secrets. */
1014
+ swapPairs: MillSwapPair[];
1015
+ /** Per-asset available reserves, parallel to `inventory` (which is total). */
1016
+ inventoryAvailable: Record<string, string>;
1017
+ }
1038
1018
  /** Node types supported by Townhouse */
1039
1019
  type NodeType = 'town' | 'mill' | 'dvm';
1040
1020
  /** Runtime state of a node container */
@@ -1144,7 +1124,6 @@ interface TimeseriesBucket {
1144
1124
  interface PacketTimeseriesPayload {
1145
1125
  buckets: TimeseriesBucket[];
1146
1126
  }
1147
-
1148
1127
  /** Minimal common health shape; superset emitted by Town containers. */
1149
1128
  interface TownHealthPayload {
1150
1129
  status: 'ok' | 'starting' | 'stopping' | 'stopped' | 'error';
@@ -1407,4 +1386,656 @@ interface WizardInitialDeps {
1407
1386
  */
1408
1387
  declare function createWizardApiServer(initialDeps: WizardInitialDeps): Promise<ApiServer>;
1409
1388
 
1410
- export { type ApiConfig, type ApiDeps, type ApiServer, type BandwidthPayload, type BandwidthStats, ComposeLoaderError, type ComposeLoaderOptions, type ComposeProfile, ConfigValidationError, ConnectorAdminClient, type ConnectorConfig, ConnectorConfigGenerator, type ConnectorRuntimeConfig, type ContainerSpec, DEFAULT_ATOR_PROXY, type DepositAddressEntry, type DepositAddressesPayload, type DerivedNodeKeys, DockerOrchestrator, type DvmHealthResponse, type DvmNodeConfig, type EncryptedWallet, type HealthCheckOptions, type HealthResponse, type JobsByKindEntry, type JobsRecentPayload, type LoggingConfig, type MetricsPayload, type MetricsPeerEntry, type MetricsResponse, type MillNodeConfig, type MillSwapsRecentPayload, type NodeDetail, type NodeHealthPayload, type NodeInfo, type NodeKeyInfo, type NodeKeys, type NodeState, type NodeType$1 as NodeType, type NodesConfig, type NostrEventPayload, type OrchestratorEvents, type PacketLogEntry, type PacketLogFilter, type PacketTimeseriesPayload, type PeerEntry, type PeerStatus, type PeersResponse, type RevealRequest, type RevealResponse, type SwapByPairEntry, type TimeseriesBucket, type TownHealthPayload, type TownNodeConfig, type TownhouseConfig, type TransactionReceiptPayload, type TransportConfig, type TransportPatchRequest, type TransportPatchResponse, TransportProbe, type TransportStatusPayload, type WalletBalanceEntry, type WalletBalancesPayload, type WalletConfig, WalletManager, type WalletManagerConfig, type WalletState, type WithdrawDryRunResponse, type WithdrawRequest, type WithdrawResponse, type WithdrawSuccessResponse, type WizardInitRequest, type WizardProgressMessage, type WizardStatePayload, type WsBatchMessage, type WsConnectorRestartedMessage, type WsConnectorRestartingMessage, type WsHeartbeatMessage, type WsMessage, type WsMetricsMessage, type WsNodeStateMessage, type WsRelayEventsMessage, createApiServer, createWizardApiServer, decryptWallet, encryptWallet, getDefaultConfig, loadComposeTemplate, loadConfig, loadWallet, materializeComposeTemplate, saveConfig, saveWallet, validateConfig };
1389
+ /**
1390
+ * Hourly earnings snapshot writer (Story 47.3).
1391
+ *
1392
+ * Persists `claimsReceivedTotal` per (peerId × assetCode) — plus apex
1393
+ * `connectorFees[]` rows under `peerId: '__apex__'` — to
1394
+ * `${dirname(configPath)}/earnings-snapshots.jsonl` once per hour. Consumed
1395
+ * by `snapshot-reader.ts`'s `DeltaComputer` factory. Failure mode: any
1396
+ * per-tick error is logged via `logger.warn` and swallowed (the writer NEVER
1397
+ * throws into the apex event loop) — the next tick retries cleanly. Pruning
1398
+ * runs after each successful append (entries older than 13 months are
1399
+ * rewritten atomically). File mode is `0o600` on every write.
1400
+ *
1401
+ * @module
1402
+ * @since 47.3
1403
+ */
1404
+
1405
+ /**
1406
+ * One JSONL row in `earnings-snapshots.jsonl`.
1407
+ *
1408
+ * NOTE: apex routing-fee rows use `peerId: '__apex__'`. The field name
1409
+ * `claimsReceivedTotal` is technically a misnomer for apex rows — those
1410
+ * are connector routing fees, not received claims — but the uniform column
1411
+ * name keeps the JSONL schema simple and the reader doesn't need a special
1412
+ * case.
1413
+ */
1414
+ interface SnapshotEntry {
1415
+ /** ISO-8601 UTC timestamp of the tick boundary (e.g. '2026-05-12T15:00:00.000Z'). */
1416
+ ts: string;
1417
+ /** Connector peerId, OR the literal `'__apex__'` for apex routing-fee rows. */
1418
+ peerId: string;
1419
+ assetCode: string;
1420
+ /** Decimal-string cumulative (claims received for peers, routing-fee total for apex). */
1421
+ claimsReceivedTotal: string;
1422
+ }
1423
+ interface SnapshotWriterOptions {
1424
+ connectorAdmin: ConnectorAdminClient;
1425
+ /** Absolute path to `earnings-snapshots.jsonl`. */
1426
+ snapshotPath: string;
1427
+ /** Tick interval (ms). Default 3_600_000 (1 hour). */
1428
+ tickIntervalMs?: number;
1429
+ /** Injected clock for tests. Default `() => new Date()`. */
1430
+ now?: () => Date;
1431
+ /** Retention window in months. Default 13. */
1432
+ retentionMonths?: number;
1433
+ /** pino/Fastify-compatible logger; warn-only. */
1434
+ logger?: {
1435
+ warn(obj: object, msg?: string): void;
1436
+ };
1437
+ /**
1438
+ * Fire one tick immediately on `start()` instead of waiting for the first
1439
+ * interval. Default `false` (production). Tests set this to `true` to
1440
+ * assert append behavior without advancing fake timers.
1441
+ */
1442
+ fireOnStart?: boolean;
1443
+ }
1444
+ declare class SnapshotWriter {
1445
+ private readonly opts;
1446
+ private timer;
1447
+ private tickPending;
1448
+ constructor(opts: SnapshotWriterOptions);
1449
+ start(): void;
1450
+ stop(): void;
1451
+ /** Exposed for test ergonomics — runs one full append+prune cycle. */
1452
+ tick(): Promise<void>;
1453
+ private runTick;
1454
+ private appendEntries;
1455
+ private pruneIfNeeded;
1456
+ }
1457
+
1458
+ /**
1459
+ * `nodes.yaml` schema + read/write helpers (Story 46.1).
1460
+ *
1461
+ * `~/.townhouse/nodes.yaml` is the operator-managed source of truth for
1462
+ * enabled child nodes. The reconciler (see `../reconciler.ts`) converges
1463
+ * connector peer state to this file on every `townhouse hs up`.
1464
+ *
1465
+ * Architectural rule (Epic 46.2 dependency): yaml writes happen BEFORE
1466
+ * connector registration. The drift window resolves in the safe direction —
1467
+ * a yaml entry without a connector peer is re-registered on next boot; a
1468
+ * connector peer without a yaml entry is treated as `'external'` and left
1469
+ * alone.
1470
+ */
1471
+
1472
+ declare const NodesYamlEntrySchema: z.ZodObject<{
1473
+ id: z.ZodString;
1474
+ type: z.ZodEnum<["town", "mill", "dvm"]>;
1475
+ peerId: z.ZodString;
1476
+ ilpAddress: z.ZodString;
1477
+ derivationIndex: z.ZodNumber;
1478
+ enabledAt: z.ZodString;
1479
+ lastSeenAt: z.ZodNullable<z.ZodString>;
1480
+ }, "strict", z.ZodTypeAny, {
1481
+ type: "town" | "mill" | "dvm";
1482
+ id: string;
1483
+ peerId: string;
1484
+ ilpAddress: string;
1485
+ derivationIndex: number;
1486
+ enabledAt: string;
1487
+ lastSeenAt: string | null;
1488
+ }, {
1489
+ type: "town" | "mill" | "dvm";
1490
+ id: string;
1491
+ peerId: string;
1492
+ ilpAddress: string;
1493
+ derivationIndex: number;
1494
+ enabledAt: string;
1495
+ lastSeenAt: string | null;
1496
+ }>;
1497
+ declare const NodesYamlSchema: z.ZodEffects<z.ZodObject<{
1498
+ entries: z.ZodArray<z.ZodObject<{
1499
+ id: z.ZodString;
1500
+ type: z.ZodEnum<["town", "mill", "dvm"]>;
1501
+ peerId: z.ZodString;
1502
+ ilpAddress: z.ZodString;
1503
+ derivationIndex: z.ZodNumber;
1504
+ enabledAt: z.ZodString;
1505
+ lastSeenAt: z.ZodNullable<z.ZodString>;
1506
+ }, "strict", z.ZodTypeAny, {
1507
+ type: "town" | "mill" | "dvm";
1508
+ id: string;
1509
+ peerId: string;
1510
+ ilpAddress: string;
1511
+ derivationIndex: number;
1512
+ enabledAt: string;
1513
+ lastSeenAt: string | null;
1514
+ }, {
1515
+ type: "town" | "mill" | "dvm";
1516
+ id: string;
1517
+ peerId: string;
1518
+ ilpAddress: string;
1519
+ derivationIndex: number;
1520
+ enabledAt: string;
1521
+ lastSeenAt: string | null;
1522
+ }>, "many">;
1523
+ }, "strict", z.ZodTypeAny, {
1524
+ entries: {
1525
+ type: "town" | "mill" | "dvm";
1526
+ id: string;
1527
+ peerId: string;
1528
+ ilpAddress: string;
1529
+ derivationIndex: number;
1530
+ enabledAt: string;
1531
+ lastSeenAt: string | null;
1532
+ }[];
1533
+ }, {
1534
+ entries: {
1535
+ type: "town" | "mill" | "dvm";
1536
+ id: string;
1537
+ peerId: string;
1538
+ ilpAddress: string;
1539
+ derivationIndex: number;
1540
+ enabledAt: string;
1541
+ lastSeenAt: string | null;
1542
+ }[];
1543
+ }>, {
1544
+ entries: {
1545
+ type: "town" | "mill" | "dvm";
1546
+ id: string;
1547
+ peerId: string;
1548
+ ilpAddress: string;
1549
+ derivationIndex: number;
1550
+ enabledAt: string;
1551
+ lastSeenAt: string | null;
1552
+ }[];
1553
+ }, {
1554
+ entries: {
1555
+ type: "town" | "mill" | "dvm";
1556
+ id: string;
1557
+ peerId: string;
1558
+ ilpAddress: string;
1559
+ derivationIndex: number;
1560
+ enabledAt: string;
1561
+ lastSeenAt: string | null;
1562
+ }[];
1563
+ }>;
1564
+ type NodesYamlEntry = z.infer<typeof NodesYamlEntrySchema>;
1565
+ type NodesYaml = z.infer<typeof NodesYamlSchema>;
1566
+ /**
1567
+ * Read and validate `nodes.yaml` at the given path.
1568
+ *
1569
+ * Returns `{ entries: [] }` if the file does not exist (graceful first-run).
1570
+ * Throws a `ZodError` with a useful path if the file is present but invalid.
1571
+ */
1572
+ declare function readNodesYaml(path: string): Promise<NodesYaml>;
1573
+ /**
1574
+ * Write `nodes.yaml` atomically with file mode `0o600`.
1575
+ *
1576
+ * Atomic = write to `<path>.tmp` then `fs.rename`. On POSIX, rename is
1577
+ * atomic when source + destination live on the same filesystem (always true
1578
+ * for `~/.townhouse/nodes.yaml`). Prevents partial-write corruption if the
1579
+ * process is killed mid-write.
1580
+ */
1581
+ declare function writeNodesYaml(path: string, data: NodesYaml): Promise<void>;
1582
+
1583
+ /**
1584
+ * `PeerTypeResolver` (Story 46.1).
1585
+ *
1586
+ * The connector is a generic ILP router — it has no concept of
1587
+ * `'town' | 'mill' | 'dvm'`. Townhouse owns the type concept entirely
1588
+ * via this resolver, which is the single translation layer between
1589
+ * connector `peerId` values and operator-meaningful node types.
1590
+ *
1591
+ * Architectural rule (Epic 46 planning §Architectural Layering):
1592
+ * downstream consumers (Epic 47 aggregator, Epic 48 TUI, Epic 49 telemetry)
1593
+ * MUST call through this resolver — they never hardcode peer-to-type
1594
+ * mappings.
1595
+ *
1596
+ * The resolver is rebuilt from a `NodesYaml` snapshot — prefer immutable
1597
+ * rebuild (re-instantiate) over mutable update for testability.
1598
+ */
1599
+
1600
+ declare class PeerTypeResolver {
1601
+ private readonly map;
1602
+ constructor(yaml: NodesYaml);
1603
+ /**
1604
+ * Resolve a connector `peerId` to its operator-declared node type.
1605
+ * Returns `'external'` for unknown peerIds (legitimate non-Townhouse
1606
+ * peers running through the same connector).
1607
+ */
1608
+ resolvePeerType(peerId: string): NodeType$1 | 'external';
1609
+ }
1610
+
1611
+ /**
1612
+ * Earnings aggregator (Story 47.2).
1613
+ *
1614
+ * Aggregates connector-reported earnings into the canonical
1615
+ * `{ status, apex, peers }` shape consumed by the host-API
1616
+ * `/api/earnings` endpoint.
1617
+ *
1618
+ * Source of truth: `connectorAdmin.getEarnings()` (Story 47.1).
1619
+ * Peer-type attribution via `PeerTypeResolver` (Story 46.1); the resolver
1620
+ * buckets unmatched peerIds as `'external'` (enforcement lives in the
1621
+ * resolver, not here — we trust its contract).
1622
+ *
1623
+ * Failure mode: if `getEarnings()` throws (network, 503-when-disabled,
1624
+ * shape drift), returns the empty payload with
1625
+ * `status: 'connector_unavailable'`. The route returns 200 either way;
1626
+ * operators see zeros plus a UI banner rather than a 5xx. An injected
1627
+ * `logger.warn` (Fastify / pino-compatible) is called on failure so ops
1628
+ * can distinguish "connector outage" from "no earnings yet."
1629
+ *
1630
+ * @module
1631
+ * @since 47.2
1632
+ */
1633
+
1634
+ /**
1635
+ * Per-asset cumulative + delta breakdown. `lifetime` is the connector's
1636
+ * cumulative `claimsReceivedTotal` (decimal-string bigint at `assetScale`
1637
+ * decimals). `today` / `month` / `year` are deltas computed by Story 47.3's
1638
+ * snapshot-reader; until the `deltaComputer` dep is provided, they stub
1639
+ * to '0'. Asset-scale interpretation (USD: 6, ETH: 18, sats: 0) is the
1640
+ * dashboard's job — the aggregator never collapses to a unit.
1641
+ */
1642
+ interface PerAsset {
1643
+ lifetime: string;
1644
+ today: string;
1645
+ month: string;
1646
+ year: string;
1647
+ }
1648
+ /** Per-peer earnings entry in the aggregator output. */
1649
+ interface NodeEarnings {
1650
+ id: string;
1651
+ type: NodeType$1 | 'external';
1652
+ byAsset: Record<string, PerAsset>;
1653
+ /** Max `lastClaimAt` across this peer's assets, or `null` if none. Added in 47.4. */
1654
+ lastClaimAt: string | null;
1655
+ }
1656
+ /**
1657
+ * Wire-level status for the aggregator response.
1658
+ *
1659
+ * `'ok'` — `getEarnings()` succeeded; payload reflects connector state.
1660
+ * `'connector_unavailable'` — `getEarnings()` threw (network, 503, shape
1661
+ * drift); apex + peers are empty. The dashboard renders a banner.
1662
+ */
1663
+ type AggregatedEarningsStatus = 'ok' | 'connector_unavailable';
1664
+ /** Top-level aggregator output. Extended in 47.4 with dashboard fields. */
1665
+ interface AggregatedEarnings {
1666
+ status: AggregatedEarningsStatus;
1667
+ apex: {
1668
+ routingFees: Record<string, PerAsset>;
1669
+ };
1670
+ peers: NodeEarnings[];
1671
+ /** Pass-through from connector `recentClaims`. Empty array on connector outage. */
1672
+ recentClaims: RecentClaim[];
1673
+ /** Sum of `getMetrics().peers[].packetsForwarded` PLUS `packetsLocallyDelivered`
1674
+ * (connector v3.7.0+, toon-protocol/connector#73 — counts events that landed
1675
+ * via the self-delivery route, where the connector's in-process relay accepts
1676
+ * the event locally rather than forwarding to a remote peer). 0 on connector
1677
+ * outage or metrics failure. */
1678
+ eventsRelayed: number;
1679
+ /** From `getMetrics().uptimeSeconds`. 0 on connector outage or metrics failure. */
1680
+ uptimeSeconds: number;
1681
+ }
1682
+ /** Resolves TODAY / MONTH / YEAR deltas for a (scope, assetCode) tuple. */
1683
+ type DeltaComputer = (params: {
1684
+ /** Either a connector peerId or the literal `'__apex__'` for routing-fee rows. */
1685
+ scope: string;
1686
+ assetCode: string;
1687
+ /** Current cumulative (matches the lifetime value in the response). */
1688
+ currentLifetime: string;
1689
+ }) => Promise<{
1690
+ today: string;
1691
+ month: string;
1692
+ year: string;
1693
+ }>;
1694
+ /**
1695
+ * Minimal logger contract; Fastify `request.log` and pino satisfy it.
1696
+ * Kept narrow so tests can pass a `{ warn: vi.fn() }` stub.
1697
+ */
1698
+ interface AggregatorLogger {
1699
+ warn(obj: object, msg?: string): void;
1700
+ }
1701
+ interface AggregateEarningsInput {
1702
+ connectorAdmin: ConnectorAdminClient;
1703
+ peerTypeResolver: PeerTypeResolver;
1704
+ /**
1705
+ * Optional delta computer (Story 47.3). When omitted, all PerAsset
1706
+ * `today` / `month` / `year` fields stub to '0'. The route layer (47.4)
1707
+ * wires the snapshot-backed implementation. A rejection on a single
1708
+ * asset stubs that asset's deltas to '0' and emits `logger.warn`; one
1709
+ * bad asset never breaks the aggregate.
1710
+ */
1711
+ deltaComputer?: DeltaComputer;
1712
+ /**
1713
+ * Optional logger. When provided, `getEarnings()` failures and
1714
+ * `deltaComputer` rejections are surfaced via `logger.warn` so ops can
1715
+ * distinguish a connector outage from "no earnings yet."
1716
+ */
1717
+ logger?: AggregatorLogger;
1718
+ }
1719
+
1720
+ /**
1721
+ * Snapshot reader + `DeltaComputer` factory (Story 47.3).
1722
+ *
1723
+ * Reads `earnings-snapshots.jsonl` and computes TODAY/MONTH/YEAR deltas vs.
1724
+ * UTC boundaries (midnight, 1st-of-month, 1st-of-year). Tolerates malformed
1725
+ * lines (skip) and clock-skewed snapshots (filter `ts > now`). Returns `'0'`
1726
+ * when no boundary snapshot exists yet.
1727
+ *
1728
+ * @module
1729
+ * @since 47.3
1730
+ */
1731
+
1732
+ /** ISO of the most recent UTC midnight <= ref. */
1733
+ declare function utcDayBoundary(ref: Date): string;
1734
+ /** ISO of the first instant of the current calendar month in UTC. */
1735
+ declare function utcMonthBoundary(ref: Date): string;
1736
+ /** ISO of the first instant of the current calendar year in UTC. */
1737
+ declare function utcYearBoundary(ref: Date): string;
1738
+ /**
1739
+ * Construct a `DeltaComputer` (Story 47.2's type) backed by the snapshot
1740
+ * file at `snapshotPath`. The returned function is the one wired into
1741
+ * `aggregateEarnings({ ..., deltaComputer })` by Story 47.4's route.
1742
+ *
1743
+ * Reads the snapshot file once per DeltaComputer call (single-pass), then
1744
+ * resolves all three boundaries (today/month/year) in-memory from the parsed
1745
+ * map. No cross-call cache in v1 — see Open Question 6 in story notes.
1746
+ */
1747
+ declare function createDeltaComputer(opts: {
1748
+ snapshotPath: string;
1749
+ /** Optional clock injection for tests. Default `() => new Date()`. */
1750
+ now?: () => Date;
1751
+ }): DeltaComputer;
1752
+
1753
+ /**
1754
+ * Image manifest reader for Townhouse (Story 46.2).
1755
+ *
1756
+ * `~/.townhouse/image-manifest.json` is materialized by `compose-loader.ts`
1757
+ * during `townhouse hs up`. It maps node types to their digest-pinned image
1758
+ * refs, consumed by `POST /api/nodes` step 2 (pull image).
1759
+ */
1760
+
1761
+ declare const ImageManifestSchema: z.ZodObject<{
1762
+ schemaVersion: z.ZodLiteral<1>;
1763
+ townhouseVersion: z.ZodString;
1764
+ builtAt: z.ZodString;
1765
+ images: z.ZodObject<{
1766
+ 'townhouse-api': z.ZodObject<{
1767
+ name: z.ZodString;
1768
+ tag: z.ZodString;
1769
+ digest: z.ZodString;
1770
+ }, "strict", z.ZodTypeAny, {
1771
+ name: string;
1772
+ tag: string;
1773
+ digest: string;
1774
+ }, {
1775
+ name: string;
1776
+ tag: string;
1777
+ digest: string;
1778
+ }>;
1779
+ town: z.ZodObject<{
1780
+ name: z.ZodString;
1781
+ tag: z.ZodString;
1782
+ digest: z.ZodString;
1783
+ }, "strict", z.ZodTypeAny, {
1784
+ name: string;
1785
+ tag: string;
1786
+ digest: string;
1787
+ }, {
1788
+ name: string;
1789
+ tag: string;
1790
+ digest: string;
1791
+ }>;
1792
+ mill: z.ZodObject<{
1793
+ name: z.ZodString;
1794
+ tag: z.ZodString;
1795
+ digest: z.ZodString;
1796
+ }, "strict", z.ZodTypeAny, {
1797
+ name: string;
1798
+ tag: string;
1799
+ digest: string;
1800
+ }, {
1801
+ name: string;
1802
+ tag: string;
1803
+ digest: string;
1804
+ }>;
1805
+ dvm: z.ZodObject<{
1806
+ name: z.ZodString;
1807
+ tag: z.ZodString;
1808
+ digest: z.ZodString;
1809
+ }, "strict", z.ZodTypeAny, {
1810
+ name: string;
1811
+ tag: string;
1812
+ digest: string;
1813
+ }, {
1814
+ name: string;
1815
+ tag: string;
1816
+ digest: string;
1817
+ }>;
1818
+ connector: z.ZodObject<{
1819
+ name: z.ZodString;
1820
+ tag: z.ZodString;
1821
+ digest: z.ZodString;
1822
+ }, "strict", z.ZodTypeAny, {
1823
+ name: string;
1824
+ tag: string;
1825
+ digest: string;
1826
+ }, {
1827
+ name: string;
1828
+ tag: string;
1829
+ digest: string;
1830
+ }>;
1831
+ }, "strict", z.ZodTypeAny, {
1832
+ town: {
1833
+ name: string;
1834
+ tag: string;
1835
+ digest: string;
1836
+ };
1837
+ mill: {
1838
+ name: string;
1839
+ tag: string;
1840
+ digest: string;
1841
+ };
1842
+ dvm: {
1843
+ name: string;
1844
+ tag: string;
1845
+ digest: string;
1846
+ };
1847
+ 'townhouse-api': {
1848
+ name: string;
1849
+ tag: string;
1850
+ digest: string;
1851
+ };
1852
+ connector: {
1853
+ name: string;
1854
+ tag: string;
1855
+ digest: string;
1856
+ };
1857
+ }, {
1858
+ town: {
1859
+ name: string;
1860
+ tag: string;
1861
+ digest: string;
1862
+ };
1863
+ mill: {
1864
+ name: string;
1865
+ tag: string;
1866
+ digest: string;
1867
+ };
1868
+ dvm: {
1869
+ name: string;
1870
+ tag: string;
1871
+ digest: string;
1872
+ };
1873
+ 'townhouse-api': {
1874
+ name: string;
1875
+ tag: string;
1876
+ digest: string;
1877
+ };
1878
+ connector: {
1879
+ name: string;
1880
+ tag: string;
1881
+ digest: string;
1882
+ };
1883
+ }>;
1884
+ }, "strict", z.ZodTypeAny, {
1885
+ schemaVersion: 1;
1886
+ townhouseVersion: string;
1887
+ builtAt: string;
1888
+ images: {
1889
+ town: {
1890
+ name: string;
1891
+ tag: string;
1892
+ digest: string;
1893
+ };
1894
+ mill: {
1895
+ name: string;
1896
+ tag: string;
1897
+ digest: string;
1898
+ };
1899
+ dvm: {
1900
+ name: string;
1901
+ tag: string;
1902
+ digest: string;
1903
+ };
1904
+ 'townhouse-api': {
1905
+ name: string;
1906
+ tag: string;
1907
+ digest: string;
1908
+ };
1909
+ connector: {
1910
+ name: string;
1911
+ tag: string;
1912
+ digest: string;
1913
+ };
1914
+ };
1915
+ }, {
1916
+ schemaVersion: 1;
1917
+ townhouseVersion: string;
1918
+ builtAt: string;
1919
+ images: {
1920
+ town: {
1921
+ name: string;
1922
+ tag: string;
1923
+ digest: string;
1924
+ };
1925
+ mill: {
1926
+ name: string;
1927
+ tag: string;
1928
+ digest: string;
1929
+ };
1930
+ dvm: {
1931
+ name: string;
1932
+ tag: string;
1933
+ digest: string;
1934
+ };
1935
+ 'townhouse-api': {
1936
+ name: string;
1937
+ tag: string;
1938
+ digest: string;
1939
+ };
1940
+ connector: {
1941
+ name: string;
1942
+ tag: string;
1943
+ digest: string;
1944
+ };
1945
+ };
1946
+ }>;
1947
+ type ImageManifest = z.infer<typeof ImageManifestSchema>;
1948
+ /**
1949
+ * Read and validate `image-manifest.json` at the given path.
1950
+ *
1951
+ * Throws ENOENT if the file is missing — there is no graceful fallback for a
1952
+ * missing manifest; it means `townhouse hs up` was not run first.
1953
+ * Throws `ZodError` with a useful path if the file is present but invalid.
1954
+ */
1955
+ declare function readImageManifest(path: string): Promise<ImageManifest>;
1956
+
1957
+ /**
1958
+ * Boot reconciler (Story 46.1).
1959
+ *
1960
+ * Converges connector peer state to `~/.townhouse/nodes.yaml` (truth) on
1961
+ * every `townhouse hs up`. Reads yaml + connector peers, diffs them,
1962
+ * re-registers any yaml entries missing from the connector, and logs
1963
+ * connector peers without yaml entries as `'external'` (left alone).
1964
+ *
1965
+ * Container lifecycle is OUT of scope — that lives in Epic 46.2.
1966
+ */
1967
+
1968
+ /** Action recorded for a single divergence. */
1969
+ type DivergenceAction = 'reregistered' | 'reregister-failed' | 'external';
1970
+ /** A single divergence record for the reconciler log. */
1971
+ interface DivergenceLog {
1972
+ timestamp: string;
1973
+ peerId: string;
1974
+ action: DivergenceAction;
1975
+ detail?: string;
1976
+ }
1977
+ /** Summary returned by `reconcile()` so callers can surface partial-failure counts. */
1978
+ interface ReconcileSummary {
1979
+ reregistered: number;
1980
+ failed: number;
1981
+ external: number;
1982
+ }
1983
+ declare class BootReconciler {
1984
+ private readonly adminClient;
1985
+ private readonly nodesYamlPath;
1986
+ private readonly reconcilerLogPath;
1987
+ private logDirEnsured;
1988
+ private logFileChmodEnsured;
1989
+ constructor(adminClient: Pick<ConnectorAdminClient, 'getPeers' | 'registerPeer'>, nodesYamlPath: string, reconcilerLogPath: string);
1990
+ /**
1991
+ * Diff `nodes.yaml` (truth) against `GET /admin/peers` (derived state)
1992
+ * and converge.
1993
+ *
1994
+ * Ordering rule (Epic 46.2 dependency — load-bearing):
1995
+ * `nodes.yaml` write happens BEFORE connector registration
1996
+ * (`POST /admin/peers`).
1997
+ *
1998
+ * The drift window resolves in the safe direction:
1999
+ * - yaml entry without a connector peer = harmless. The reconciler
2000
+ * re-registers it on next `hs up` (this method does that).
2001
+ * - connector peer without a yaml entry = treated as `'external'` and
2002
+ * left alone (operators may legitimately route non-Townhouse peers
2003
+ * through the same connector).
2004
+ *
2005
+ * The unsafe direction (register first, then write yaml) creates a
2006
+ * window where the connector routes to a peer Townhouse cannot clean
2007
+ * up. Epic 46.2's provisioning pipeline MUST honor the yaml-first rule.
2008
+ *
2009
+ * Failures fetching `getPeers()` are surfaced (not swallowed) so the
2010
+ * caller in `handleHsUp` can decide whether to treat reconciler
2011
+ * divergence as fatal. (Today: non-fatal — see cli.ts wire point.)
2012
+ *
2013
+ * Per-divergence appendLog failures are caught so a single log-write
2014
+ * failure does not abort the rest of the reconciliation pass.
2015
+ */
2016
+ reconcile(): Promise<ReconcileSummary>;
2017
+ /**
2018
+ * Compute divergences without mutating the connector. Exposed for
2019
+ * testability — production callers use `reconcile()`.
2020
+ */
2021
+ private diff;
2022
+ /**
2023
+ * Append one divergence record without aborting the whole reconciliation
2024
+ * pass on a single log-write failure (disk full, EACCES, etc.). Failures
2025
+ * are themselves logged to stderr — not silently swallowed — so the
2026
+ * operator can see them in the same `hs up` session.
2027
+ */
2028
+ private tryAppendLog;
2029
+ /**
2030
+ * Append one divergence record to the reconciler log as a single line of
2031
+ * JSON (jsonl-style — easy to grep, easy to parse).
2032
+ *
2033
+ * `mkdir` runs once per reconciler instance. `chmod 0o600` on the log file
2034
+ * also runs once — `fs.appendFile`'s `mode` option only applies on
2035
+ * creation, so without a post-create chmod a pre-existing log file with
2036
+ * permissive mode would never be tightened.
2037
+ */
2038
+ private appendLog;
2039
+ }
2040
+
2041
+ export { type AggregateEarningsInput, type AggregatedEarnings, type AggregatedEarningsStatus, type AggregatorLogger, type ApiDeps, type ApiServer, type BandwidthPayload, BandwidthStats, BootReconciler, ComposeProfile, ConfigValidationError, ConnectorAdminClient, ConnectorConfigGenerator, type ConnectorRuntimeConfig, DEFAULT_ATOR_PROXY, type DeltaComputer, type DepositAddressEntry, type DepositAddressesPayload, type DivergenceAction, type DivergenceLog, DockerOrchestrator, type DvmHealthResponse, EncryptedWallet, HealthCheckOptions, type HealthResponse, type HsHostnameResponse, type ImageManifest, ImageManifestSchema, type JobsByKindEntry, type JobsRecentPayload, type MetricsPayload, type MetricsPeerEntry, type MetricsResponse, type MillHealthResponse, type MillSwapsRecentPayload, type NodeDetail, type NodeEarnings, type NodeHealthPayload, type NodeInfo, type NodeState, NodeType$1 as NodeType, type NodesYaml, type NodesYamlEntry, NodesYamlEntrySchema, NodesYamlSchema, type NostrEventPayload, OrchestratorError, type PacketLogEntry, type PacketLogFilter, type PacketTimeseriesPayload, type PeerEntry, type PeerStatus, PeerTypeResolver, type PeersResponse, type PerAsset, type ReconcileSummary, type RevealRequest, type RevealResponse, type SnapshotEntry, SnapshotWriter, type SnapshotWriterOptions, type SwapByPairEntry, type TimeseriesBucket, type TownHealthPayload, TownhouseConfig, type TransactionReceiptPayload, type TransportPatchRequest, type TransportPatchResponse, TransportProbe, type TransportStatusPayload, type WalletBalanceEntry, type WalletBalancesPayload, WalletManager, type WithdrawDryRunResponse, type WithdrawRequest, type WithdrawResponse, type WithdrawSuccessResponse, type WizardInitRequest, type WizardProgressMessage, type WizardStatePayload, type WsBatchMessage, type WsConnectorRestartedMessage, type WsConnectorRestartingMessage, type WsHeartbeatMessage, type WsMessage, type WsMetricsMessage, type WsNodeStateMessage, type WsRelayEventsMessage, createApiServer, createDeltaComputer, createWizardApiServer, decryptWallet, encryptWallet, getDefaultConfig, loadConfig, loadWallet, readImageManifest, readNodesYaml, saveConfig, saveWallet, utcDayBoundary, utcMonthBoundary, utcYearBoundary, validateConfig, writeNodesYaml };