mppx 0.8.12 → 0.8.13

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 (193) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +16 -1
  3. package/dist/cli/account.d.ts +88 -0
  4. package/dist/cli/account.d.ts.map +1 -1
  5. package/dist/cli/account.js +39 -9
  6. package/dist/cli/account.js.map +1 -1
  7. package/dist/cli/cli.d.ts +2 -1
  8. package/dist/cli/cli.d.ts.map +1 -1
  9. package/dist/cli/cli.js +59 -2
  10. package/dist/cli/cli.js.map +1 -1
  11. package/dist/cli/sessions/Manager.d.ts +31 -0
  12. package/dist/cli/sessions/Manager.d.ts.map +1 -0
  13. package/dist/cli/sessions/Manager.js +56 -0
  14. package/dist/cli/sessions/Manager.js.map +1 -0
  15. package/dist/cli/sessions/commands.d.ts +36 -0
  16. package/dist/cli/sessions/commands.d.ts.map +1 -0
  17. package/dist/cli/sessions/commands.js +407 -0
  18. package/dist/cli/sessions/commands.js.map +1 -0
  19. package/dist/cli/sessions/request.d.ts +35 -0
  20. package/dist/cli/sessions/request.d.ts.map +1 -0
  21. package/dist/cli/sessions/request.js +271 -0
  22. package/dist/cli/sessions/request.js.map +1 -0
  23. package/dist/cli/sessions/store.d.ts +134 -0
  24. package/dist/cli/sessions/store.d.ts.map +1 -0
  25. package/dist/cli/sessions/store.js +723 -0
  26. package/dist/cli/sessions/store.js.map +1 -0
  27. package/dist/cli/utils.d.ts +2 -0
  28. package/dist/cli/utils.d.ts.map +1 -1
  29. package/dist/cli/utils.js +12 -0
  30. package/dist/cli/utils.js.map +1 -1
  31. package/dist/cli/validate/index.d.ts.map +1 -1
  32. package/dist/cli/validate/index.js +12 -6
  33. package/dist/cli/validate/index.js.map +1 -1
  34. package/dist/cli/validate/messages.d.ts +2 -0
  35. package/dist/cli/validate/messages.d.ts.map +1 -0
  36. package/dist/cli/validate/messages.js +8 -0
  37. package/dist/cli/validate/messages.js.map +1 -0
  38. package/dist/client/node.d.ts +29 -0
  39. package/dist/client/node.d.ts.map +1 -0
  40. package/dist/client/node.js +177 -0
  41. package/dist/client/node.js.map +1 -0
  42. package/dist/internal/types.d.ts +24 -0
  43. package/dist/internal/types.d.ts.map +1 -1
  44. package/dist/stripe/server/Charge.d.ts +8 -4
  45. package/dist/stripe/server/Charge.d.ts.map +1 -1
  46. package/dist/stripe/server/Charge.js.map +1 -1
  47. package/dist/stripe/server/internal/html.gen.d.ts +1 -1
  48. package/dist/stripe/server/internal/html.gen.d.ts.map +1 -1
  49. package/dist/stripe/server/internal/html.gen.js +1 -1
  50. package/dist/stripe/server/internal/html.gen.js.map +1 -1
  51. package/dist/tempo/client/Methods.d.ts +1 -1
  52. package/dist/tempo/internal/types.d.ts +10 -1
  53. package/dist/tempo/internal/types.d.ts.map +1 -1
  54. package/dist/tempo/legacy/client/Session.d.ts +2 -2
  55. package/dist/tempo/legacy/server/Session.d.ts +3 -3
  56. package/dist/tempo/legacy/server/Session.d.ts.map +1 -1
  57. package/dist/tempo/legacy/server/Session.js.map +1 -1
  58. package/dist/tempo/server/Charge.d.ts +3 -2
  59. package/dist/tempo/server/Charge.d.ts.map +1 -1
  60. package/dist/tempo/server/Charge.js.map +1 -1
  61. package/dist/tempo/server/Methods.d.ts +2 -23
  62. package/dist/tempo/server/Methods.d.ts.map +1 -1
  63. package/dist/tempo/server/Methods.js +2 -2
  64. package/dist/tempo/server/Methods.js.map +1 -1
  65. package/dist/tempo/server/Subscription.d.ts +3 -2
  66. package/dist/tempo/server/Subscription.d.ts.map +1 -1
  67. package/dist/tempo/server/Subscription.js.map +1 -1
  68. package/dist/tempo/server/index.d.ts +1 -1
  69. package/dist/tempo/server/index.d.ts.map +1 -1
  70. package/dist/tempo/server/index.js.map +1 -1
  71. package/dist/tempo/server/internal/html.gen.d.ts +1 -1
  72. package/dist/tempo/server/internal/html.gen.d.ts.map +1 -1
  73. package/dist/tempo/server/internal/html.gen.js +1 -1
  74. package/dist/tempo/server/internal/html.gen.js.map +1 -1
  75. package/dist/tempo/session/Snapshot.d.ts +9 -0
  76. package/dist/tempo/session/Snapshot.d.ts.map +1 -1
  77. package/dist/tempo/session/Snapshot.js +6 -0
  78. package/dist/tempo/session/Snapshot.js.map +1 -1
  79. package/dist/tempo/session/client/ChannelOps.d.ts.map +1 -1
  80. package/dist/tempo/session/client/ChannelOps.js +11 -2
  81. package/dist/tempo/session/client/ChannelOps.js.map +1 -1
  82. package/dist/tempo/session/client/CredentialState.d.ts +21 -1
  83. package/dist/tempo/session/client/CredentialState.d.ts.map +1 -1
  84. package/dist/tempo/session/client/CredentialState.js +66 -1
  85. package/dist/tempo/session/client/CredentialState.js.map +1 -1
  86. package/dist/tempo/session/client/Session.d.ts +1 -1
  87. package/dist/tempo/session/client/SessionManager.d.ts +2 -2
  88. package/dist/tempo/session/client/SessionManager.d.ts.map +1 -1
  89. package/dist/tempo/session/client/SessionManager.js +128 -30
  90. package/dist/tempo/session/client/SessionManager.js.map +1 -1
  91. package/dist/tempo/session/client/Transports.d.ts +11 -2
  92. package/dist/tempo/session/client/Transports.d.ts.map +1 -1
  93. package/dist/tempo/session/client/Transports.js +33 -9
  94. package/dist/tempo/session/client/Transports.js.map +1 -1
  95. package/dist/tempo/session/client/internal/SessionManager.d.ts +19 -0
  96. package/dist/tempo/session/client/internal/SessionManager.d.ts.map +1 -0
  97. package/dist/tempo/session/client/internal/SessionManager.js +13 -0
  98. package/dist/tempo/session/client/internal/SessionManager.js.map +1 -0
  99. package/dist/tempo/session/precompile/Chain.js +13 -4
  100. package/dist/tempo/session/precompile/Chain.js.map +1 -1
  101. package/dist/tempo/session/server/CredentialVerification.d.ts +3 -0
  102. package/dist/tempo/session/server/CredentialVerification.d.ts.map +1 -1
  103. package/dist/tempo/session/server/CredentialVerification.js +14 -0
  104. package/dist/tempo/session/server/CredentialVerification.js.map +1 -1
  105. package/dist/tempo/session/server/MeteredStream.d.ts +7 -1
  106. package/dist/tempo/session/server/MeteredStream.d.ts.map +1 -1
  107. package/dist/tempo/session/server/MeteredStream.js +5 -4
  108. package/dist/tempo/session/server/MeteredStream.js.map +1 -1
  109. package/dist/tempo/session/server/RequestState.d.ts +5 -1
  110. package/dist/tempo/session/server/RequestState.d.ts.map +1 -1
  111. package/dist/tempo/session/server/RequestState.js +10 -4
  112. package/dist/tempo/session/server/RequestState.js.map +1 -1
  113. package/dist/tempo/session/server/Session.d.ts +21 -6
  114. package/dist/tempo/session/server/Session.d.ts.map +1 -1
  115. package/dist/tempo/session/server/Session.js +4 -1
  116. package/dist/tempo/session/server/Session.js.map +1 -1
  117. package/dist/tempo/session/server/Settlement.d.ts +20 -0
  118. package/dist/tempo/session/server/Settlement.d.ts.map +1 -1
  119. package/dist/tempo/session/server/Settlement.js +20 -0
  120. package/dist/tempo/session/server/Settlement.js.map +1 -1
  121. package/dist/tempo/session/server/Ws.d.ts +2 -0
  122. package/dist/tempo/session/server/Ws.d.ts.map +1 -1
  123. package/dist/tempo/session/server/Ws.js.map +1 -1
  124. package/dist/tempo/session/server/index.d.ts +1 -1
  125. package/dist/tempo/session/server/index.d.ts.map +1 -1
  126. package/dist/tempo/subscription/KeyAuthorization.d.ts +21 -21
  127. package/dist/validation/core.d.ts.map +1 -1
  128. package/dist/validation/core.js +6 -2
  129. package/dist/validation/core.js.map +1 -1
  130. package/dist/viem/Client.d.ts.map +1 -1
  131. package/dist/viem/Client.js +24 -17
  132. package/dist/viem/Client.js.map +1 -1
  133. package/package.json +6 -1
  134. package/src/cli/account.ts +45 -10
  135. package/src/cli/cli.test.ts +165 -70
  136. package/src/cli/cli.ts +67 -2
  137. package/src/cli/mcp.test.ts +11 -0
  138. package/src/cli/sessions/Manager.test.ts +249 -0
  139. package/src/cli/sessions/Manager.ts +93 -0
  140. package/src/cli/sessions/commands.ts +444 -0
  141. package/src/cli/sessions/request.test.ts +51 -0
  142. package/src/cli/sessions/request.ts +353 -0
  143. package/src/cli/sessions/store.test.ts +581 -0
  144. package/src/cli/sessions/store.ts +940 -0
  145. package/src/cli/utils.test.ts +23 -0
  146. package/src/cli/utils.ts +10 -0
  147. package/src/cli/validate/index.ts +12 -14
  148. package/src/cli/validate/messages.ts +7 -0
  149. package/src/cli/validate.test.ts +38 -5
  150. package/src/client/node.test.ts +115 -0
  151. package/src/client/node.ts +247 -0
  152. package/src/internal/types.test-d.ts +21 -0
  153. package/src/internal/types.ts +33 -0
  154. package/src/server/Mppx.test-d.ts +42 -0
  155. package/src/stripe/Methods.test.ts +10 -0
  156. package/src/stripe/server/Charge.test-d.ts +66 -0
  157. package/src/stripe/server/Charge.ts +8 -5
  158. package/src/stripe/server/internal/html.gen.ts +1 -1
  159. package/src/tempo/internal/types.ts +13 -2
  160. package/src/tempo/legacy/server/Defaults.test-d.ts +9 -0
  161. package/src/tempo/legacy/server/Session.ts +6 -5
  162. package/src/tempo/server/Charge.ts +6 -4
  163. package/src/tempo/server/Methods.ts +5 -4
  164. package/src/tempo/server/Subscription.ts +6 -4
  165. package/src/tempo/server/index.ts +5 -1
  166. package/src/tempo/server/internal/html.gen.ts +1 -1
  167. package/src/tempo/session/README.md +201 -0
  168. package/src/tempo/session/Snapshot.ts +21 -0
  169. package/src/tempo/session/client/ChannelOps.test.ts +40 -0
  170. package/src/tempo/session/client/ChannelOps.ts +12 -2
  171. package/src/tempo/session/client/CredentialState.test.ts +2 -2
  172. package/src/tempo/session/client/CredentialState.ts +103 -1
  173. package/src/tempo/session/client/Session.test.ts +3 -3
  174. package/src/tempo/session/client/SessionManager.test.ts +137 -4
  175. package/src/tempo/session/client/SessionManager.ts +139 -33
  176. package/src/tempo/session/client/Transports.test.ts +150 -8
  177. package/src/tempo/session/client/Transports.ts +48 -10
  178. package/src/tempo/session/client/internal/SessionManager.ts +36 -0
  179. package/src/tempo/session/precompile/Chain.test.ts +26 -0
  180. package/src/tempo/session/precompile/Chain.ts +17 -4
  181. package/src/tempo/session/server/CredentialVerification.ts +18 -1
  182. package/src/tempo/session/server/MeteredStream.ts +12 -5
  183. package/src/tempo/session/server/RequestState.test.ts +39 -3
  184. package/src/tempo/session/server/RequestState.ts +13 -6
  185. package/src/tempo/session/server/Session.test.ts +461 -0
  186. package/src/tempo/session/server/Session.ts +31 -8
  187. package/src/tempo/session/server/Settlement.ts +45 -0
  188. package/src/tempo/session/server/Ws.test.ts +113 -0
  189. package/src/tempo/session/server/Ws.ts +2 -0
  190. package/src/tempo/session/server/index.ts +2 -0
  191. package/src/validation/core.ts +7 -1
  192. package/src/viem/Client.test.ts +44 -1
  193. package/src/viem/Client.ts +31 -17
@@ -0,0 +1,940 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import * as fs from 'node:fs/promises'
3
+ import * as os from 'node:os'
4
+ import * as path from 'node:path'
5
+
6
+ import type { Address, Hex } from 'viem'
7
+
8
+ import * as Challenge from '../../Challenge.js'
9
+ import { resolveEscrow, type ChannelEntry } from '../../tempo/session/client/ChannelOps.js'
10
+ import {
11
+ deserializeEntry,
12
+ entryKey,
13
+ serializeEntry,
14
+ type ChannelStore,
15
+ type StoredChannel,
16
+ } from '../../tempo/session/client/ChannelStore.js'
17
+ import {
18
+ isTempoSessionChallenge,
19
+ type TempoSessionChallenge,
20
+ } from '../../tempo/session/client/Transports.js'
21
+ import type { SessionReceipt } from '../../tempo/session/precompile/Protocol.js'
22
+ import * as z from '../../zod.js'
23
+
24
+ const sessionStateVersion = 1 as const
25
+
26
+ /** Lifecycle state recorded for a managed CLI session. */
27
+ export type SessionStatus = 'opening' | 'open' | 'closing' | 'stale'
28
+
29
+ /** Account identity required to resume or close a managed session. */
30
+ export type SessionAccount = {
31
+ /** Optional mppx account name. */
32
+ name?: string | undefined
33
+ /** Payer wallet address. */
34
+ address: Address
35
+ }
36
+
37
+ /** Payment scope used to isolate preferred sessions and process locks. */
38
+ export type SessionScope = {
39
+ payer: Address
40
+ payee: Address
41
+ token: Address
42
+ escrow: Address
43
+ chainId: number
44
+ }
45
+
46
+ /** Durable session record returned by the CLI registry. */
47
+ export type ManagedSession = {
48
+ version: typeof sessionStateVersion
49
+ status: SessionStatus
50
+ channel: ChannelEntry
51
+ account: SessionAccount
52
+ endpoint: string
53
+ challenge: TempoSessionChallenge
54
+ receipt?: SessionReceipt | undefined
55
+ spent: bigint
56
+ units: number
57
+ createdAt: string
58
+ updatedAt: string
59
+ }
60
+
61
+ /** Input persisted by {@link SessionRegistry.upsert}. */
62
+ export type SessionUpsert = {
63
+ status: SessionStatus
64
+ channel: ChannelEntry
65
+ account: SessionAccount
66
+ endpoint: string
67
+ challenge: Challenge.Challenge
68
+ receipt?: SessionReceipt | undefined
69
+ spent?: bigint | undefined
70
+ units?: number | undefined
71
+ }
72
+
73
+ /** Dynamic context used when adapting the registry to the SDK channel store. */
74
+ export type SessionPersistenceContext = Omit<SessionUpsert, 'channel'>
75
+
76
+ /** Selection policy used by a persistent CLI request. */
77
+ export type SessionSelection = 'auto' | 'new' | Hex
78
+
79
+ /** Held process lock for a session scope. */
80
+ export type SessionLock = {
81
+ /** Releases the lock if this process still owns it. */
82
+ release(): Promise<void>
83
+ }
84
+
85
+ /** Filesystem-backed persistent session registry. */
86
+ export type SessionRegistry = {
87
+ /** Versioned registry root. */
88
+ readonly root: string
89
+ /** Returns a managed session by full channel ID. */
90
+ get(channelId: string): Promise<ManagedSession | undefined>
91
+ /** Lists managed sessions. */
92
+ list(): Promise<ManagedSession[]>
93
+ /** Creates or monotonically updates a managed session. */
94
+ upsert(input: SessionUpsert): Promise<ManagedSession>
95
+ /** Removes a validated managed session and its preferred mappings. */
96
+ remove(channelId: string): Promise<void>
97
+ /** Returns the preferred channel ID for a payer and payment scope. */
98
+ getPreferred(scope: SessionScope): Promise<Hex | undefined>
99
+ /** Sets the preferred channel after verifying it matches the scope. */
100
+ setPreferred(scope: SessionScope, channelId: string): Promise<void>
101
+ /** Clears the preferred channel, optionally only when it matches `channelId`. */
102
+ clearPreferred(scope: SessionScope, channelId?: string | undefined): Promise<void>
103
+ /** Acquires an exclusive process lock for a payer and payment scope. */
104
+ acquire(scope: SessionScope): Promise<SessionLock>
105
+ }
106
+
107
+ /** Options for {@link createSessionRegistry}. */
108
+ export type CreateSessionRegistryOptions = {
109
+ /** Override the versioned state root. */
110
+ stateRoot?: string | undefined
111
+ /** Host identity written to lock files. */
112
+ hostname?: string | undefined
113
+ /** Process ID written to lock files. */
114
+ pid?: number | undefined
115
+ /** Clock used for persisted timestamps. */
116
+ now?: (() => Date) | undefined
117
+ /** Process liveness probe used for same-host lock reclamation. */
118
+ isProcessAlive?: ((pid: number) => boolean) | undefined
119
+ }
120
+
121
+ /** Invalid, corrupt, or inconsistent persistent session state. */
122
+ export class SessionStateError extends Error {
123
+ override readonly name = 'SessionStateError'
124
+ readonly code = 'SESSION_STATE_INVALID'
125
+ readonly file?: string | undefined
126
+
127
+ constructor(message: string, options: { cause?: unknown; file?: string | undefined } = {}) {
128
+ super(message, options.cause === undefined ? undefined : { cause: options.cause })
129
+ this.file = options.file
130
+ }
131
+ }
132
+
133
+ /** A session scope currently owned by another live process. */
134
+ export class SessionBusyError extends Error {
135
+ override readonly name = 'SessionBusyError'
136
+ readonly code = 'SESSION_BUSY'
137
+ readonly exitCode = 75
138
+ readonly scope: string
139
+ readonly owner: { hostname: string; pid: number }
140
+
141
+ constructor(scope: string, owner: { hostname: string; pid: number }) {
142
+ super(`Session scope is busy in process ${owner.pid} on ${owner.hostname}.`)
143
+ this.scope = scope
144
+ this.owner = owner
145
+ }
146
+ }
147
+
148
+ const storedChannelSchema = z.object({
149
+ channelId: z.hash(),
150
+ cumulativeAmount: z.string(),
151
+ deposit: z.string(),
152
+ descriptor: z.object({
153
+ payer: z.address(),
154
+ payee: z.address(),
155
+ operator: z.address(),
156
+ token: z.address(),
157
+ salt: z.hash(),
158
+ authorizedSigner: z.address(),
159
+ expiringNonceHash: z.hash(),
160
+ }),
161
+ escrow: z.address(),
162
+ chainId: z.number(),
163
+ opened: z.boolean(),
164
+ })
165
+ const accountSchema = z.object({
166
+ name: z.optional(z.string()),
167
+ address: z.address(),
168
+ })
169
+ const receiptSchema = z.object({
170
+ method: z.literal('tempo'),
171
+ intent: z.literal('session'),
172
+ status: z.literal('success'),
173
+ timestamp: z.string(),
174
+ reference: z.string(),
175
+ challengeId: z.string(),
176
+ channelId: z.hash(),
177
+ acceptedCumulative: z.string(),
178
+ spent: z.string(),
179
+ units: z.optional(z.number()),
180
+ txHash: z.optional(z.hash()),
181
+ })
182
+ const storedSessionSchema = z.object({
183
+ version: z.literal(sessionStateVersion),
184
+ method: z.literal('tempo'),
185
+ intent: z.literal('session'),
186
+ status: z.enum(['opening', 'open', 'closing', 'stale']),
187
+ channel: storedChannelSchema,
188
+ account: accountSchema,
189
+ endpoint: z.string(),
190
+ challenge: Challenge.Schema,
191
+ receipt: z.optional(receiptSchema),
192
+ spent: z.string(),
193
+ units: z.number(),
194
+ createdAt: z.string(),
195
+ updatedAt: z.string(),
196
+ })
197
+ const preferredSessionSchema = z.object({
198
+ version: z.literal(sessionStateVersion),
199
+ channelId: z.hash(),
200
+ })
201
+ const lockOwnerSchema = z.object({
202
+ version: z.literal(sessionStateVersion),
203
+ scope: z.string(),
204
+ hostname: z.string(),
205
+ pid: z.number(),
206
+ token: z.string(),
207
+ createdAt: z.string(),
208
+ })
209
+
210
+ type StoredManagedSession = Omit<
211
+ z.infer<typeof storedSessionSchema>,
212
+ 'account' | 'challenge' | 'channel' | 'receipt'
213
+ > & {
214
+ account: SessionAccount
215
+ challenge: TempoSessionChallenge
216
+ channel: StoredChannel
217
+ receipt?: SessionReceipt | undefined
218
+ }
219
+ type PreferredSession = z.infer<typeof preferredSessionSchema>
220
+ type LockOwner = z.infer<typeof lockOwnerSchema>
221
+
222
+ function parseStored<schema extends z.ZodMiniType>(
223
+ schema: schema,
224
+ value: unknown,
225
+ file: string | undefined,
226
+ message: string,
227
+ ): z.output<schema> {
228
+ const parsed = schema.safeParse(value)
229
+ if (!parsed.success) throw stateError(file, message, parsed.error)
230
+ return parsed.data
231
+ }
232
+
233
+ type RegistryPaths = {
234
+ root: string
235
+ channels: string
236
+ locks: string
237
+ preferred: string
238
+ }
239
+
240
+ /** Returns the stable payer-qualified key for a persistent session scope. */
241
+ export function sessionScopeKey(scope: SessionScope): string {
242
+ const normalized = normalizeScope(scope)
243
+ return [
244
+ normalized.payer,
245
+ normalized.payee,
246
+ normalized.token,
247
+ normalized.escrow,
248
+ normalized.chainId,
249
+ ].join(':')
250
+ }
251
+
252
+ /** Returns the persistent payment scope for a channel. */
253
+ export function sessionScope(channel: ChannelEntry): SessionScope {
254
+ return {
255
+ payer: channel.descriptor.payer,
256
+ payee: channel.descriptor.payee,
257
+ token: channel.descriptor.token,
258
+ escrow: channel.escrow,
259
+ chainId: channel.chainId,
260
+ }
261
+ }
262
+
263
+ /** Creates a filesystem-backed CLI session registry. */
264
+ export function createSessionRegistry(options: CreateSessionRegistryOptions = {}): SessionRegistry {
265
+ const root = options.stateRoot ?? sessionStateRoot()
266
+ const paths: RegistryPaths = {
267
+ root,
268
+ channels: path.join(root, 'channels'),
269
+ locks: path.join(root, 'locks'),
270
+ preferred: path.join(root, 'preferred'),
271
+ }
272
+ const hostname = options.hostname ?? os.hostname()
273
+ const pid = options.pid ?? process.pid
274
+ const now = options.now ?? (() => new Date())
275
+ const isProcessAlive = options.isProcessAlive ?? processIsAlive
276
+
277
+ async function ensureDirectories(): Promise<void> {
278
+ for (const directory of [paths.root, paths.channels, paths.locks, paths.preferred]) {
279
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 })
280
+ await fs.chmod(directory, 0o700)
281
+ }
282
+ }
283
+
284
+ async function get(channelId: string): Promise<ManagedSession | undefined> {
285
+ const normalizedId = normalizeChannelId(channelId)
286
+ const file = channelFile(paths, normalizedId)
287
+ const value = await readJson(file)
288
+ if (value === undefined) return undefined
289
+ const record = parseStoredSession(value, file)
290
+ if (record.channel.channelId.toLowerCase() !== normalizedId)
291
+ throw stateError(file, 'Session filename does not match its channel ID.')
292
+ return deserializeSession(record)
293
+ }
294
+
295
+ async function list(): Promise<ManagedSession[]> {
296
+ let entries: import('node:fs').Dirent[]
297
+ try {
298
+ entries = await fs.readdir(paths.channels, { withFileTypes: true })
299
+ } catch (error) {
300
+ if (hasCode(error, 'ENOENT')) return []
301
+ throw stateError(paths.channels, 'Unable to list managed sessions.', error)
302
+ }
303
+
304
+ const records: ManagedSession[] = []
305
+ for (const entry of entries) {
306
+ if (!entry.isFile() || entry.name.includes('.tmp-')) continue
307
+ if (!entry.name.endsWith('.json')) continue
308
+ const channelId = entry.name.slice(0, -'.json'.length)
309
+ normalizeChannelId(channelId)
310
+ const record = await get(channelId)
311
+ if (record) records.push(record)
312
+ }
313
+ return records.sort((left, right) => left.createdAt.localeCompare(right.createdAt))
314
+ }
315
+
316
+ async function upsert(input: SessionUpsert): Promise<ManagedSession> {
317
+ await ensureDirectories()
318
+ const channel = sanitizeChannel(input.channel)
319
+ const normalizedId = normalizeChannelId(channel.channelId)
320
+ const file = channelFile(paths, normalizedId)
321
+ const previousValue = await readJson(file)
322
+ const previous =
323
+ previousValue === undefined ? undefined : parseStoredSession(previousValue, file)
324
+ if (previous) assertSameSession(previous, input, file)
325
+
326
+ const challenge = parseSessionChallenge(input.challenge, file)
327
+ assertChallengeMatchesChannel(challenge, channel, file)
328
+ const receipt = input.receipt
329
+ ? sanitizeReceipt(input.receipt, channel.channelId, file)
330
+ : undefined
331
+ const previousChannel = previous ? deserializeEntry(previous.channel) : undefined
332
+ const cumulativeAmount = maxBigInt(
333
+ channel.cumulativeAmount,
334
+ previousChannel?.cumulativeAmount ?? 0n,
335
+ )
336
+ const spent = maxBigInt(
337
+ input.spent ?? 0n,
338
+ receipt ? BigInt(receipt.spent) : 0n,
339
+ previous ? BigInt(previous.spent) : 0n,
340
+ )
341
+ if (spent > cumulativeAmount)
342
+ throw stateError(file, 'Session spend exceeds the locally authorized cumulative amount.')
343
+
344
+ const storedChannel = sanitizeStoredChannel(
345
+ serializeEntry({ ...channel, cumulativeAmount }),
346
+ file,
347
+ )
348
+ const timestamp = monotonicTimestamp(previous?.updatedAt, now(), file)
349
+ const latestReceipt = selectLatestReceipt(previous?.receipt, receipt)
350
+ const account = sanitizeAccount(input.account, file)
351
+ const record: StoredManagedSession = {
352
+ version: sessionStateVersion,
353
+ method: 'tempo',
354
+ intent: 'session',
355
+ status: input.status,
356
+ channel: storedChannel,
357
+ account: {
358
+ ...(account.name !== undefined
359
+ ? { name: account.name }
360
+ : previous?.account.name !== undefined
361
+ ? { name: previous.account.name }
362
+ : {}),
363
+ address: account.address,
364
+ },
365
+ endpoint: sessionResourceUrl(input.endpoint, file),
366
+ challenge,
367
+ ...(latestReceipt !== undefined && { receipt: latestReceipt }),
368
+ spent: spent.toString(),
369
+ units: Math.max(previous?.units ?? 0, input.units ?? 0, receipt?.units ?? 0),
370
+ createdAt: previous?.createdAt ?? timestamp,
371
+ updatedAt: timestamp,
372
+ }
373
+ const parsed = parseStoredSession(record, file)
374
+ await writeJsonAtomic(file, parsed)
375
+ return deserializeSession(parsed)
376
+ }
377
+
378
+ async function getPreferred(scope: SessionScope): Promise<Hex | undefined> {
379
+ const file = preferredFile(paths, scope)
380
+ const value = await readJson(file)
381
+ if (value === undefined) return undefined
382
+ const { channelId } = parseStored(
383
+ preferredSessionSchema,
384
+ value,
385
+ file,
386
+ 'Preferred session is invalid.',
387
+ )
388
+ const record = await get(channelId)
389
+ if (!record) throw stateError(file, `Preferred session ${channelId} does not exist.`)
390
+ assertChannelScope(record.channel, scope, file)
391
+ return channelId as Hex
392
+ }
393
+
394
+ async function setPreferred(scope: SessionScope, channelId: string): Promise<void> {
395
+ const normalizedId = normalizeChannelId(channelId)
396
+ const record = await get(normalizedId)
397
+ const file = preferredFile(paths, scope)
398
+ if (!record) throw stateError(file, `Session ${normalizedId} does not exist.`)
399
+ assertChannelScope(record.channel, scope, file)
400
+ await writeJsonAtomic(file, {
401
+ version: sessionStateVersion,
402
+ channelId: normalizedId as Hex,
403
+ } satisfies PreferredSession)
404
+ }
405
+
406
+ async function clearPreferred(
407
+ scope: SessionScope,
408
+ channelId?: string | undefined,
409
+ ): Promise<void> {
410
+ const file = preferredFile(paths, scope)
411
+ const normalizedId = channelId === undefined ? undefined : normalizeChannelId(channelId)
412
+ const value = await readJson(file)
413
+ if (value === undefined) return
414
+ const current = parseStored(
415
+ preferredSessionSchema,
416
+ value,
417
+ file,
418
+ 'Preferred session is invalid.',
419
+ ).channelId
420
+ if (normalizedId && current.toLowerCase() !== normalizedId) return
421
+ await removeFile(file, 'Unable to clear preferred session.')
422
+ }
423
+
424
+ async function remove(channelId: string): Promise<void> {
425
+ const normalizedId = normalizeChannelId(channelId)
426
+ const record = await get(normalizedId)
427
+ if (!record) return
428
+ await clearPreferred(sessionScope(record.channel), normalizedId)
429
+ const file = channelFile(paths, normalizedId)
430
+ await removeFile(file, 'Unable to remove session.')
431
+ }
432
+
433
+ async function acquireKey(scope: string): Promise<SessionLock> {
434
+ await ensureDirectories()
435
+ const file = lockFile(paths, scope)
436
+ for (let attempt = 0; attempt < 3; attempt++) {
437
+ const owner: LockOwner = {
438
+ version: sessionStateVersion,
439
+ scope,
440
+ hostname,
441
+ pid,
442
+ token: randomUUID(),
443
+ createdAt: now().toISOString(),
444
+ }
445
+ try {
446
+ await createLock(file, owner)
447
+ if (await fileExists(deadLockClaimFile(file))) {
448
+ await removeOwnedLock(file, owner)
449
+ continue
450
+ }
451
+ return {
452
+ async release() {
453
+ await removeOwnedLock(file, owner)
454
+ },
455
+ }
456
+ } catch (error) {
457
+ if (!hasCode(error, 'EEXIST')) throw error
458
+ }
459
+
460
+ const value = await readJson(file)
461
+ if (value === undefined) continue
462
+ const current = parseStored(lockOwnerSchema, value, file, 'Session lock is invalid.')
463
+ if (current.scope !== scope) throw stateError(file, 'Session lock scope is invalid.')
464
+ if (current.hostname !== hostname || isProcessAlive(current.pid))
465
+ throw new SessionBusyError(scope, current)
466
+ await removeDeadLock(file, current)
467
+ }
468
+ const value = await readJson(file)
469
+ if (value === undefined) throw stateError(file, 'Unable to acquire session lock.')
470
+ const owner = parseStored(lockOwnerSchema, value, file, 'Session lock is invalid.')
471
+ throw new SessionBusyError(scope, owner)
472
+ }
473
+
474
+ async function acquire(scope: SessionScope): Promise<SessionLock> {
475
+ return acquireKey(sessionScopeKey(scope))
476
+ }
477
+
478
+ return {
479
+ root,
480
+ get,
481
+ list,
482
+ upsert,
483
+ remove,
484
+ getPreferred,
485
+ setPreferred,
486
+ clearPreferred,
487
+ acquire,
488
+ }
489
+ }
490
+
491
+ /** Adapts a persistent registry selection to the session manager's channel store. */
492
+ export function toChannelStore(
493
+ registry: SessionRegistry,
494
+ options: {
495
+ scope: SessionScope
496
+ selection: SessionSelection
497
+ context: () => SessionPersistenceContext
498
+ onNewChannel?: ((channel: ChannelEntry) => void) | undefined
499
+ },
500
+ ): ChannelStore {
501
+ const expectedKey = scopeEntryKey(options.scope)
502
+ let selectedChannelId: Hex | undefined =
503
+ options.selection === 'auto' || options.selection === 'new'
504
+ ? undefined
505
+ : (normalizeChannelId(options.selection) as Hex)
506
+
507
+ function assertKey(key: string): void {
508
+ if (key.toLowerCase() !== expectedKey)
509
+ throw new SessionStateError('Session manager requested an unexpected payment scope.')
510
+ }
511
+
512
+ async function selected(reusableOnly = true): Promise<ManagedSession | undefined> {
513
+ if (options.selection === 'new' && !selectedChannelId) return undefined
514
+ const channelId = selectedChannelId ?? (await registry.getPreferred(options.scope))
515
+ if (!channelId) return undefined
516
+ const record = await registry.get(channelId)
517
+ if (!record) throw new SessionStateError(`Session ${channelId} does not exist.`)
518
+ assertChannelScope(record.channel, options.scope)
519
+ if (reusableOnly && (record.status !== 'open' || !record.channel.opened)) return undefined
520
+ selectedChannelId = channelId
521
+ return record
522
+ }
523
+
524
+ return {
525
+ async get(key) {
526
+ assertKey(key)
527
+ return (await selected())?.channel
528
+ },
529
+ async set(channel) {
530
+ assertKey(entryKey(channel))
531
+ assertChannelScope(channel, options.scope)
532
+ if (selectedChannelId && selectedChannelId.toLowerCase() !== channel.channelId.toLowerCase())
533
+ throw new SessionStateError(
534
+ `Session manager selected ${selectedChannelId}, but attempted to store ${channel.channelId}.`,
535
+ )
536
+ if (!selectedChannelId) options.onNewChannel?.(channel)
537
+ const record = await registry.upsert({ ...options.context(), channel })
538
+ selectedChannelId = record.channel.channelId
539
+ await registry.setPreferred(options.scope, record.channel.channelId)
540
+ },
541
+ async delete(key) {
542
+ assertKey(key)
543
+ const record = await selected(false)
544
+ if (!record) return
545
+ const context = options.context()
546
+ await registry.upsert({
547
+ ...record,
548
+ ...context,
549
+ status: context.status === 'closing' ? 'closing' : 'stale',
550
+ channel: record.channel,
551
+ spent: context.spent ?? record.spent,
552
+ units: context.units ?? record.units,
553
+ })
554
+ if (context.status !== 'closing')
555
+ await registry.clearPreferred(options.scope, record.channel.channelId)
556
+ selectedChannelId = undefined
557
+ },
558
+ }
559
+ }
560
+
561
+ function sessionStateRoot(): string {
562
+ const stateHome = process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state')
563
+ return path.join(stateHome, 'mppx', 'sessions', `v${sessionStateVersion}`)
564
+ }
565
+
566
+ function channelFile(paths: RegistryPaths, channelId: string): string {
567
+ return path.join(paths.channels, `${channelId}.json`)
568
+ }
569
+
570
+ function lockFile(paths: RegistryPaths, scope: string): string {
571
+ const digest = createHash('sha256').update(scope).digest('hex')
572
+ return path.join(paths.locks, `${digest}.lock`)
573
+ }
574
+
575
+ function preferredFile(paths: RegistryPaths, scope: SessionScope): string {
576
+ const digest = createHash('sha256').update(sessionScopeKey(scope)).digest('hex')
577
+ return path.join(paths.preferred, `${digest}.json`)
578
+ }
579
+
580
+ function normalizeChannelId(channelId: string): string {
581
+ return parseStored(
582
+ z.hash(),
583
+ channelId,
584
+ undefined,
585
+ `Invalid session channel ID: ${channelId}.`,
586
+ ).toLowerCase()
587
+ }
588
+
589
+ function normalizeAddress(value: unknown, label: string, file?: string | undefined): Address {
590
+ return parseStored(z.address(), value, file, `Invalid ${label}.`).toLowerCase() as Address
591
+ }
592
+
593
+ function normalizeScope(scope: SessionScope): SessionScope {
594
+ if (!Number.isSafeInteger(scope.chainId) || scope.chainId < 0)
595
+ throw new SessionStateError('Invalid session chain ID.')
596
+ return {
597
+ payer: normalizeAddress(scope.payer, 'session payer'),
598
+ payee: normalizeAddress(scope.payee, 'session payee'),
599
+ token: normalizeAddress(scope.token, 'session token'),
600
+ escrow: normalizeAddress(scope.escrow, 'session escrow'),
601
+ chainId: scope.chainId,
602
+ }
603
+ }
604
+
605
+ function scopeEntryKey(scope: SessionScope): string {
606
+ const normalized = normalizeScope(scope)
607
+ return [normalized.payee, normalized.token, normalized.escrow, normalized.chainId].join(':')
608
+ }
609
+
610
+ /** Returns the exact HTTP resource URL persisted for session management. */
611
+ export function sessionResourceUrl(endpoint: unknown, file?: string | undefined): string {
612
+ if (typeof endpoint !== 'string') throw stateError(file, 'Session endpoint is invalid.')
613
+ let parsed: URL
614
+ try {
615
+ parsed = new URL(endpoint)
616
+ } catch (cause) {
617
+ throw stateError(file, 'Session endpoint is invalid.', cause)
618
+ }
619
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
620
+ throw stateError(file, 'Session endpoint must use HTTP or HTTPS.')
621
+ if (parsed.username || parsed.password)
622
+ throw stateError(file, 'Session endpoint must not contain credentials.')
623
+ const fragment = endpoint.indexOf('#')
624
+ return fragment === -1 ? endpoint : endpoint.slice(0, fragment)
625
+ }
626
+
627
+ function sanitizeAccount(value: unknown, file?: string | undefined): SessionAccount {
628
+ return parseStored(accountSchema, value, file, 'Session account is invalid.') as SessionAccount
629
+ }
630
+
631
+ function sanitizeChannel(channel: ChannelEntry): ChannelEntry {
632
+ const stored = sanitizeStoredChannel(serializeEntry(channel))
633
+ return deserializeEntry(stored)
634
+ }
635
+
636
+ function sanitizeStoredChannel(value: unknown, file?: string | undefined): StoredChannel {
637
+ return parseStored(
638
+ storedChannelSchema,
639
+ value,
640
+ file,
641
+ 'Stored session channel is invalid.',
642
+ ) as StoredChannel
643
+ }
644
+
645
+ function parseSessionChallenge(value: unknown, file?: string | undefined): TempoSessionChallenge {
646
+ const parsed = Challenge.Schema.safeParse(value)
647
+ if (!parsed.success || !isTempoSessionChallenge(parsed.data))
648
+ throw stateError(file, 'Stored session challenge is invalid.')
649
+ return parsed.data
650
+ }
651
+
652
+ function sanitizeReceipt(
653
+ value: unknown,
654
+ channelId: string,
655
+ file?: string | undefined,
656
+ ): SessionReceipt {
657
+ const receipt = parseStored(
658
+ receiptSchema,
659
+ value,
660
+ file,
661
+ 'Stored session receipt is invalid.',
662
+ ) as SessionReceipt
663
+ if (receipt.channelId !== channelId.toLowerCase())
664
+ throw stateError(file, 'Stored session receipt has a different channel ID.')
665
+ if (receipt.reference.toLowerCase() !== channelId.toLowerCase())
666
+ throw stateError(file, 'Stored session receipt has a different reference.')
667
+ if (BigInt(receipt.spent) > BigInt(receipt.acceptedCumulative))
668
+ throw stateError(file, 'Stored session receipt spend exceeds its accepted amount.')
669
+ return receipt
670
+ }
671
+
672
+ function parseStoredSession(value: unknown, file: string): StoredManagedSession {
673
+ const candidate = parseStored(storedSessionSchema, value, file, 'Stored session is invalid.')
674
+ const { receipt: candidateReceipt, ...rest } = candidate
675
+ const channel = candidate.channel as StoredChannel
676
+ const account = candidate.account as SessionAccount
677
+ if (account.address.toLowerCase() !== channel.descriptor.payer.toLowerCase())
678
+ throw stateError(file, 'Stored session account does not match the channel payer.')
679
+ const receipt = candidateReceipt
680
+ ? sanitizeReceipt(candidateReceipt, channel.channelId, file)
681
+ : undefined
682
+ const spent = candidate.spent
683
+ const cumulativeAmount = BigInt(channel.cumulativeAmount)
684
+ if (BigInt(spent) > cumulativeAmount)
685
+ throw stateError(file, 'Stored session spend exceeds its cumulative authorization.')
686
+ if (receipt && BigInt(receipt.acceptedCumulative) > cumulativeAmount)
687
+ throw stateError(file, 'Stored receipt exceeds the cumulative authorization.')
688
+ if (Date.parse(candidate.updatedAt) < Date.parse(candidate.createdAt))
689
+ throw stateError(file, 'Stored session timestamps are not monotonic.')
690
+ const endpoint = sessionResourceUrl(candidate.endpoint, file)
691
+ if (endpoint !== candidate.endpoint)
692
+ throw stateError(file, 'Stored session endpoint contains a fragment.')
693
+ const challenge = parseSessionChallenge(candidate.challenge, file)
694
+ assertChallengeMatchesChannel(challenge, deserializeEntry(channel), file)
695
+ return {
696
+ ...rest,
697
+ account,
698
+ channel,
699
+ endpoint,
700
+ challenge,
701
+ ...(receipt && { receipt }),
702
+ }
703
+ }
704
+
705
+ function deserializeSession(record: StoredManagedSession): ManagedSession {
706
+ return {
707
+ version: sessionStateVersion,
708
+ status: record.status,
709
+ channel: deserializeEntry(record.channel),
710
+ account: record.account,
711
+ endpoint: record.endpoint,
712
+ challenge: record.challenge,
713
+ ...(record.receipt && { receipt: record.receipt }),
714
+ spent: BigInt(record.spent),
715
+ units: record.units,
716
+ createdAt: record.createdAt,
717
+ updatedAt: record.updatedAt,
718
+ }
719
+ }
720
+
721
+ function assertSameSession(
722
+ previous: StoredManagedSession,
723
+ input: SessionUpsert,
724
+ file: string,
725
+ ): void {
726
+ const channel = sanitizeChannel(input.channel)
727
+ const account = sanitizeAccount(input.account, file)
728
+ const previousChannel = deserializeEntry(previous.channel)
729
+ if (JSON.stringify(channelIdentity(channel)) !== JSON.stringify(channelIdentity(previousChannel)))
730
+ throw stateError(file, 'Session update changed immutable channel identity.')
731
+ if (account.address.toLowerCase() !== previous.account.address.toLowerCase())
732
+ throw stateError(file, 'Session update changed the payer account.')
733
+ }
734
+
735
+ function channelIdentity(channel: ChannelEntry): object {
736
+ return {
737
+ channelId: channel.channelId.toLowerCase(),
738
+ descriptor: Object.fromEntries(
739
+ Object.entries(channel.descriptor).map(([key, value]) => [
740
+ key,
741
+ typeof value === 'string' ? value.toLowerCase() : value,
742
+ ]),
743
+ ),
744
+ escrow: channel.escrow.toLowerCase(),
745
+ chainId: channel.chainId,
746
+ }
747
+ }
748
+
749
+ function assertChallengeMatchesChannel(
750
+ challenge: Challenge.Challenge,
751
+ channel: ChannelEntry,
752
+ file?: string | undefined,
753
+ ): void {
754
+ const payee = normalizeAddress(challenge.request.recipient, 'challenge recipient', file)
755
+ const token = normalizeAddress(challenge.request.currency, 'challenge currency', file)
756
+ if (payee !== channel.descriptor.payee.toLowerCase())
757
+ throw stateError(file, 'Session challenge payee does not match the channel.')
758
+ if (token !== channel.descriptor.token.toLowerCase())
759
+ throw stateError(file, 'Session challenge token does not match the channel.')
760
+ if (resolveEscrow(challenge).toLowerCase() !== channel.escrow.toLowerCase())
761
+ throw stateError(file, 'Session challenge escrow does not match the channel.')
762
+ if (isObject(challenge.request.methodDetails)) {
763
+ const methodDetails = challenge.request.methodDetails
764
+ if (methodDetails.chainId !== undefined && methodDetails.chainId !== channel.chainId)
765
+ throw stateError(file, 'Session challenge chain does not match the channel.')
766
+ }
767
+ }
768
+
769
+ function assertChannelScope(
770
+ channel: ChannelEntry,
771
+ scope: SessionScope,
772
+ file?: string | undefined,
773
+ ): void {
774
+ const normalized = normalizeScope(scope)
775
+ if (
776
+ channel.descriptor.payer.toLowerCase() !== normalized.payer ||
777
+ channel.descriptor.payee.toLowerCase() !== normalized.payee ||
778
+ channel.descriptor.token.toLowerCase() !== normalized.token ||
779
+ channel.escrow.toLowerCase() !== normalized.escrow ||
780
+ channel.chainId !== normalized.chainId
781
+ )
782
+ throw stateError(file, 'Session channel does not match the selected payment scope.')
783
+ }
784
+
785
+ function selectLatestReceipt(
786
+ previous: SessionReceipt | undefined,
787
+ next: SessionReceipt | undefined,
788
+ ): SessionReceipt | undefined {
789
+ if (!previous) return next
790
+ if (!next) return previous
791
+ return Date.parse(next.timestamp) >= Date.parse(previous.timestamp) ? next : previous
792
+ }
793
+
794
+ function monotonicTimestamp(previous: string | undefined, next: Date, file: string): string {
795
+ if (!Number.isFinite(next.getTime())) throw stateError(file, 'Session clock is invalid.')
796
+ const nextTimestamp = next.toISOString()
797
+ if (!previous || Date.parse(nextTimestamp) >= Date.parse(previous)) return nextTimestamp
798
+ return previous
799
+ }
800
+
801
+ function maxBigInt(...values: bigint[]): bigint {
802
+ return values.reduce((maximum, value) => (value > maximum ? value : maximum), 0n)
803
+ }
804
+
805
+ async function readJson(file: string): Promise<unknown | undefined> {
806
+ let source: string
807
+ try {
808
+ source = await fs.readFile(file, 'utf8')
809
+ } catch (error) {
810
+ if (hasCode(error, 'ENOENT')) return undefined
811
+ throw stateError(file, 'Unable to read session state.', error)
812
+ }
813
+ try {
814
+ const value: unknown = JSON.parse(source)
815
+ return value
816
+ } catch (cause) {
817
+ throw stateError(file, 'Session state contains invalid JSON.', cause)
818
+ }
819
+ }
820
+
821
+ async function writeJsonAtomic(file: string, value: unknown): Promise<void> {
822
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 })
823
+ await fs.chmod(path.dirname(file), 0o700)
824
+ const temporary = `${file}.tmp-${process.pid}-${randomUUID()}`
825
+ let handle: fs.FileHandle | undefined
826
+ try {
827
+ handle = await fs.open(temporary, 'wx', 0o600)
828
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`, 'utf8')
829
+ await handle.sync()
830
+ await handle.close()
831
+ handle = undefined
832
+ await fs.rename(temporary, file)
833
+ await fs.chmod(file, 0o600)
834
+ await syncDirectory(path.dirname(file))
835
+ } catch (cause) {
836
+ await handle?.close().catch(() => undefined)
837
+ await fs.unlink(temporary).catch(() => undefined)
838
+ if (cause instanceof SessionStateError) throw cause
839
+ throw stateError(file, 'Unable to write session state.', cause)
840
+ }
841
+ }
842
+
843
+ async function createLock(file: string, owner: LockOwner): Promise<void> {
844
+ let handle: fs.FileHandle | undefined
845
+ try {
846
+ handle = await fs.open(file, 'wx', 0o600)
847
+ await handle.writeFile(`${JSON.stringify(owner)}\n`, 'utf8')
848
+ await handle.sync()
849
+ await handle.close()
850
+ handle = undefined
851
+ await syncDirectory(path.dirname(file))
852
+ } catch (error) {
853
+ await handle?.close().catch(() => undefined)
854
+ if (handle) await fs.unlink(file).catch(() => undefined)
855
+ throw error
856
+ }
857
+ }
858
+
859
+ async function removeDeadLock(file: string, expected: LockOwner): Promise<void> {
860
+ const claim = deadLockClaimFile(file)
861
+ try {
862
+ await fs.link(file, claim)
863
+ } catch (error) {
864
+ if (hasCode(error, 'EEXIST') || hasCode(error, 'ENOENT')) return
865
+ throw stateError(file, 'Unable to claim dead lock.', error)
866
+ }
867
+
868
+ try {
869
+ const currentValue = await readJson(claim)
870
+ if (currentValue === undefined) return
871
+ const current = parseStored(lockOwnerSchema, currentValue, claim, 'Session lock is invalid.')
872
+ if (current.token !== expected.token) return
873
+ await removeFile(file, 'Unable to reclaim dead lock.')
874
+ } finally {
875
+ await removeFile(claim, 'Unable to release dead lock claim.')
876
+ }
877
+ }
878
+
879
+ function deadLockClaimFile(file: string): string {
880
+ return `${file}.reclaim`
881
+ }
882
+
883
+ async function fileExists(file: string): Promise<boolean> {
884
+ try {
885
+ await fs.access(file)
886
+ return true
887
+ } catch (error) {
888
+ if (hasCode(error, 'ENOENT')) return false
889
+ throw stateError(file, 'Unable to inspect session lock.', error)
890
+ }
891
+ }
892
+
893
+ async function removeOwnedLock(file: string, expected: LockOwner): Promise<void> {
894
+ const currentValue = await readJson(file)
895
+ if (currentValue === undefined) return
896
+ const current = parseStored(lockOwnerSchema, currentValue, file, 'Session lock is invalid.')
897
+ if (current.token !== expected.token) return
898
+ await removeFile(file, 'Unable to release session lock.')
899
+ }
900
+
901
+ async function removeFile(file: string, message: string): Promise<void> {
902
+ try {
903
+ await fs.unlink(file)
904
+ await syncDirectory(path.dirname(file))
905
+ } catch (error) {
906
+ if (!hasCode(error, 'ENOENT')) throw stateError(file, message, error)
907
+ }
908
+ }
909
+
910
+ async function syncDirectory(directory: string): Promise<void> {
911
+ const handle = await fs.open(directory, 'r')
912
+ try {
913
+ await handle.sync()
914
+ } finally {
915
+ await handle.close()
916
+ }
917
+ }
918
+
919
+ function processIsAlive(pid: number): boolean {
920
+ try {
921
+ process.kill(pid, 0)
922
+ return true
923
+ } catch (error) {
924
+ if (hasCode(error, 'ESRCH')) return false
925
+ if (hasCode(error, 'EPERM')) return true
926
+ throw error
927
+ }
928
+ }
929
+
930
+ function isObject(value: unknown): value is Record<string, unknown> {
931
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
932
+ }
933
+
934
+ function hasCode(error: unknown, code: string): boolean {
935
+ return error instanceof Error && 'code' in error && error.code === code
936
+ }
937
+
938
+ function stateError(file: string | undefined, message: string, cause?: unknown): SessionStateError {
939
+ return new SessionStateError(message, { ...(cause !== undefined && { cause }), file })
940
+ }