@reclaimprotocol/agent 0.1.23 → 0.1.25

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 (149) hide show
  1. package/README.md +56 -20
  2. package/lib/authoring/backend.d.ts +5 -4
  3. package/lib/authoring/tools.js +30 -30
  4. package/lib/cdp/capture-engine.js +8 -7
  5. package/lib/cdp/claims.d.ts +21 -0
  6. package/lib/cdp/claims.js +129 -0
  7. package/lib/cdp/container.d.ts +85 -0
  8. package/lib/cdp/container.js +481 -0
  9. package/lib/cdp/geo.d.ts +10 -0
  10. package/lib/cdp/geo.js +36 -0
  11. package/lib/cdp/index.d.ts +1 -0
  12. package/lib/cdp/index.js +1 -0
  13. package/lib/live/cloudflared.d.ts +15 -0
  14. package/lib/live/cloudflared.js +268 -0
  15. package/lib/live/tunnel.d.ts +26 -0
  16. package/lib/live/tunnel.js +160 -0
  17. package/lib/mcp/api/operations.gen.js +34 -26
  18. package/lib/mcp/api/to-zod.d.ts +1 -1
  19. package/lib/mcp/api/to-zod.js +1 -1
  20. package/lib/mcp/api/tools.js +1 -1
  21. package/lib/mcp/instructions.d.ts +15 -2
  22. package/lib/mcp/instructions.js +102 -38
  23. package/lib/mcp/start.js +62 -6
  24. package/lib/mcp/tools/agent/analyze.js +5 -1
  25. package/lib/mcp/tools/agent/attach.d.ts +29 -2
  26. package/lib/mcp/tools/agent/attach.js +310 -24
  27. package/lib/mcp/tools/agent/build.d.ts +18 -8
  28. package/lib/mcp/tools/agent/build.js +30 -12
  29. package/lib/mcp/tools/agent/capture.js +5 -1
  30. package/lib/mcp/tools/agent/eval.js +3 -1
  31. package/lib/mcp/tools/agent/find.js +6 -5
  32. package/lib/mcp/tools/agent/how-it-works.d.ts +15 -7
  33. package/lib/mcp/tools/agent/how-it-works.js +57 -17
  34. package/lib/mcp/tools/agent/index.d.ts +1 -2
  35. package/lib/mcp/tools/agent/index.js +1 -1
  36. package/lib/mcp/tools/agent/live-view.d.ts +17 -0
  37. package/lib/mcp/tools/agent/live-view.js +146 -0
  38. package/lib/mcp/tools/agent/pod-proof.d.ts +8 -0
  39. package/lib/mcp/tools/agent/pod-proof.js +64 -0
  40. package/lib/mcp/tools/agent/propose.js +4 -2
  41. package/lib/mcp/tools/agent/publish.js +47 -77
  42. package/lib/mcp/tools/agent/session.d.ts +16 -1
  43. package/lib/mcp/tools/agent/session.js +32 -7
  44. package/lib/mcp/tools/authenticate/authenticate.js +26 -13
  45. package/lib/mcp/tools/mode/mode.d.ts +1 -1
  46. package/lib/mcp/tools/mode/mode.js +10 -22
  47. package/lib/old/client.d.ts +1 -1
  48. package/lib/old/client.js +1 -1
  49. package/lib/old/instructions.d.ts +9 -1
  50. package/lib/old/instructions.js +4 -6
  51. package/lib/old/login-cdp.d.ts +2 -2
  52. package/lib/old/login-cdp.js +46 -6
  53. package/lib/old/to-register.d.ts +3 -2
  54. package/lib/old/to-register.js +1 -1
  55. package/lib/old/tools/authenticate.js +9 -1
  56. package/lib/old/tools/get-provider-info.js +6 -5
  57. package/lib/old/tools/issue-app-credentials.js +3 -2
  58. package/lib/old/tools/publish.d.ts +1 -1
  59. package/lib/old/tools/publish.js +90 -131
  60. package/lib/old/tools/update-provider-metadata.d.ts +1 -1
  61. package/lib/old/tools/update-provider-metadata.js +1 -1
  62. package/lib/old/tools/verify-sdk-setup.js +1 -1
  63. package/lib/proof/attestor.d.ts +3 -3
  64. package/lib/proof/debug-response-dump.js +4 -4
  65. package/lib/proof/index.d.ts +1 -0
  66. package/lib/proof/index.js +1 -0
  67. package/lib/proof/page-replay.d.ts +1 -1
  68. package/lib/proof/page-replay.js +1 -1
  69. package/lib/proof/pod-prover.d.ts +47 -0
  70. package/lib/proof/pod-prover.js +155 -0
  71. package/lib/provider/dom-xpath.js +11 -9
  72. package/lib/provider/draft.d.ts +10 -7
  73. package/lib/provider/draft.js +11 -9
  74. package/lib/provider/injection-doc.d.ts +23 -1
  75. package/lib/provider/injection-doc.js +34 -21
  76. package/lib/provider/match-redaction-warning.d.ts +2 -2
  77. package/lib/provider/match-redaction-warning.js +3 -3
  78. package/lib/provider/matcher.js +13 -12
  79. package/lib/provider/secrets.d.ts +3 -3
  80. package/lib/provider/secrets.js +3 -3
  81. package/lib/provider/to-version.d.ts +7 -6
  82. package/lib/provider/to-version.js +3 -3
  83. package/lib/tools/registry.d.ts +5 -5
  84. package/lib/tools/registry.js +5 -5
  85. package/package.json +3 -3
  86. package/samples/demo-server/README.md +7 -6
  87. package/skill/SKILL.builder.md +356 -189
  88. package/skill/SKILL.common.md +400 -97
  89. package/skill/SKILL.old.md +340 -155
  90. package/skill/builder-mode.md +60 -17
  91. package/skill/hash-validation.md +170 -0
  92. package/skill/interception.md +236 -0
  93. package/skill/js-sdk-integration.md +13 -7
  94. package/skill/old-mode.md +62 -21
  95. package/skill/user-script.md +61 -0
  96. package/src/authoring/backend.ts +5 -4
  97. package/src/authoring/tools.ts +31 -30
  98. package/src/cdp/capture-engine.ts +8 -7
  99. package/src/cdp/claims.ts +153 -0
  100. package/src/cdp/container.ts +593 -0
  101. package/src/cdp/geo.ts +52 -0
  102. package/src/cdp/index.ts +1 -0
  103. package/src/consts.ts +1 -0
  104. package/src/live/cloudflared.ts +348 -0
  105. package/src/live/tunnel.ts +208 -0
  106. package/src/mcp/api/operations.gen.ts +34 -26
  107. package/src/mcp/api/to-zod.ts +1 -1
  108. package/src/mcp/api/tools.ts +1 -1
  109. package/src/mcp/instructions.ts +122 -48
  110. package/src/mcp/start.ts +69 -5
  111. package/src/mcp/tools/agent/analyze.ts +5 -1
  112. package/src/mcp/tools/agent/attach.ts +367 -26
  113. package/src/mcp/tools/agent/build.ts +35 -16
  114. package/src/mcp/tools/agent/capture.ts +5 -1
  115. package/src/mcp/tools/agent/eval.ts +4 -1
  116. package/src/mcp/tools/agent/find.ts +6 -5
  117. package/src/mcp/tools/agent/how-it-works.ts +62 -21
  118. package/src/mcp/tools/agent/index.ts +6 -2
  119. package/src/mcp/tools/agent/live-view.ts +182 -0
  120. package/src/mcp/tools/agent/pod-proof.ts +90 -0
  121. package/src/mcp/tools/agent/propose.ts +4 -2
  122. package/src/mcp/tools/agent/publish.ts +52 -77
  123. package/src/mcp/tools/agent/session.ts +33 -6
  124. package/src/mcp/tools/authenticate/authenticate.ts +28 -13
  125. package/src/mcp/tools/mode/mode.ts +10 -22
  126. package/src/old/client.ts +2 -2
  127. package/src/old/instructions.ts +4 -10
  128. package/src/old/login-cdp.ts +50 -6
  129. package/src/old/to-register.ts +3 -2
  130. package/src/old/tools/authenticate.ts +9 -1
  131. package/src/old/tools/get-provider-info.ts +6 -5
  132. package/src/old/tools/issue-app-credentials.ts +3 -2
  133. package/src/old/tools/publish.ts +95 -131
  134. package/src/old/tools/update-provider-metadata.ts +1 -1
  135. package/src/old/tools/verify-sdk-setup.ts +1 -1
  136. package/src/proof/attestor.ts +3 -3
  137. package/src/proof/debug-response-dump.ts +4 -4
  138. package/src/proof/index.ts +8 -0
  139. package/src/proof/page-replay.ts +1 -1
  140. package/src/proof/pod-prover.ts +231 -0
  141. package/src/provider/dom-xpath.ts +11 -9
  142. package/src/provider/draft.ts +13 -10
  143. package/src/provider/injection-doc.ts +37 -24
  144. package/src/provider/match-redaction-warning.ts +3 -3
  145. package/src/provider/matcher.ts +13 -12
  146. package/src/provider/secrets.ts +3 -3
  147. package/src/provider/to-version.ts +11 -9
  148. package/src/tools/registry.ts +5 -5
  149. package/skill/injection-api.md +0 -364
@@ -0,0 +1,61 @@
1
+ # User scripts (`jsUserScripts` / `customInjection`)
2
+
3
+ A provider can inject **plain JavaScript** that runs in the page before every
4
+ page load. Builder stores it as `webSettings.jsUserScripts`; old-devtools stores
5
+ it as `customInjection`. Identical semantics, different field name.
6
+
7
+ ## What the script is for
8
+
9
+ The verification client **already intercepts the page's network requests
10
+ automatically** — the script does not need to capture, forward, or "claim" them.
11
+ Its job is to get the page into the state where the target request happens,
12
+ using standard browser APIs:
13
+
14
+ - **Navigate** — `window.location.href = '…'`, `location.assign(…)`, the
15
+ history API.
16
+ - **Interact** — select an element and `.click()` it, submit a form, dispatch
17
+ events.
18
+ - **Wait** — poll the DOM until login/MFA completes or content loads, then
19
+ trigger the next step.
20
+
21
+ Write it like any page script. It runs before EVERY page load, so keep it
22
+ idempotent, cheap, and guarded against firing at the wrong time.
23
+
24
+ Both backends run it the same way: before every page load, including before the
25
+ first navigation to `initialUrl`/`loginUrl`.
26
+
27
+ ## `window.Reclaim` — rarely needed
28
+
29
+ `window.Reclaim` is an OPTIONAL bridge for a handful of edge cases. Most
30
+ providers never touch it, and **it does not do navigation** — use the standard
31
+ browser APIs above for that.
32
+
33
+ **On the Builder verification client it is installed but INERT.** Both
34
+ `window.Reclaim` and `window.reclaimInterceptor` are injected before every
35
+ document load, so a call won't throw — but the run never drains the
36
+ `Reclaim` outbox and never delivers traffic to
37
+ `reclaimInterceptor.addResponseMiddleware`, so nothing you send is acted on
38
+ and no middleware ever fires. Write Builder-targeted scripts in plain browser
39
+ JS unconditionally, and let the capture loop find the request itself.
40
+
41
+ Don't reach for it by default. When an edge case genuinely requires it, consult
42
+ the authoritative API surface rather than guessing:
43
+ <https://github.com/reclaimprotocol/provider-web-script-dev/blob/main/src/support/env.d.ts>
44
+
45
+ ## Declaring the requests the script fires
46
+
47
+ Requests the script triggers beyond the proven one (for example, pagination) are
48
+ declared as `allowedJsRequests` (Builder) / `allowedInjectedRequestData`
49
+ (old-devtools). Same concept, different field name.
50
+
51
+ ⚠️ **Before populating them to gate `verifyProof(proof, { providerId })`**, read
52
+ topic `hash-validation` — the declared `url` is hashed VERBATIM, so a
53
+ session-unique URL there makes `verifyProof` reject every real proof. Leaving
54
+ the field empty is better than populating it wrong.
55
+
56
+ ## Related topics
57
+
58
+ - `interception` — `injectionType`/`interceptorType`, live interception, and the
59
+ document-replay flag.
60
+ - `hash-validation` — `bodySniff`, and how `verifyProof({ providerId })` gates
61
+ on the provider's declared spec.
@@ -85,9 +85,10 @@ export interface AuthoringBackend {
85
85
  /** This session's drafts (propose → replay/run_proof). */
86
86
  readonly drafts: DraftStore
87
87
  /** Prove a drafted recipe. Local: attestor SDK (rich claim view). Remote: TEE
88
- * `/reclaim/prove` (lean, secret-free summary). Returns the environment's
89
- * display shape. A backend may record the proven recipe internally (e.g.
90
- * the cloud publish step) — that side effect is the backend's, not ours. */
88
+ * `/reclaim/prove` (lean, secret-free summary). Returns the environment's
89
+ * display shape. A backend may record the proven recipe internally (for
90
+ * example, the cloud publish step) — that side effect is the backend's, not
91
+ * ours. */
91
92
  prove(draft: Draft, opts?: ProveOptions): Promise<unknown>
92
93
  /**
93
94
  * Validate/replay a drafted recipe before proving. Both local and remote
@@ -96,7 +97,7 @@ export interface AuthoringBackend {
96
97
  * always reflects the real browser session. With `withoutSecrets` it is
97
98
  * the AUTH-BOUND check: re-issue anonymously (`credentials: 'omit'`, no
98
99
  * secret headers) and report whether the values are STILL extractable —
99
- * i.e. the endpoint is public. Without it, validate extraction for the
100
+ * that is, the endpoint is public. Without it, validate extraction for the
100
101
  * authenticated request. The shape is environment-specific and passed
101
102
  * straight through as the tool's result.
102
103
  */
@@ -116,7 +116,10 @@ export function authoringTools(
116
116
  defineTool<Record<string, unknown>>(
117
117
  {
118
118
  name: 'navigate',
119
- description: 'Navigate the browser tab to a URL, waiting for load.',
119
+ description:
120
+ 'Navigate the captured tab to a URL and wait for its load event. '
121
+ + 'Returns the URL the tab actually landed on, so you can detect a '
122
+ + 'redirect to a login page.',
120
123
  inputSchema: objectSchema(
121
124
  { url: { type: 'string' }, timeoutMs: { type: 'number' } },
122
125
  ['url'],
@@ -144,8 +147,10 @@ export function authoringTools(
144
147
  {
145
148
  name: 'eval_in_page',
146
149
  description:
147
- 'Evaluate a JavaScript expression in the page and return its value '
148
- + '(use to read the displayed value, check login state, etc.).',
150
+ 'Evaluate a JavaScript expression in the page and return its value. '
151
+ + 'Use it to read the value being proven out of the DOM, to check '
152
+ + 'login state, or to trigger the target request (for example, '
153
+ + '`location.reload()`).',
149
154
  inputSchema: objectSchema(
150
155
  { expression: { type: 'string' } }, ['expression'],
151
156
  ),
@@ -156,8 +161,10 @@ export function authoringTools(
156
161
  {
157
162
  name: 'wait_for_page',
158
163
  description:
159
- 'Poll a JavaScript expression until it is truthy or the timeout '
160
- + 'elapses (e.g. wait for the user to finish logging in).',
164
+ 'Poll a JavaScript expression once a second until it is truthy or '
165
+ + 'the timeout elapses. Use it to wait for content to appear. To '
166
+ + 'wait for a login, use wait_for_login instead — page JavaScript '
167
+ + 'cannot see the httpOnly session cookie.',
161
168
  inputSchema: objectSchema(
162
169
  { expression: { type: 'string' }, timeoutMs: { type: 'number' } },
163
170
  ['expression'],
@@ -183,26 +190,18 @@ export function authoringTools(
183
190
  {
184
191
  name: 'test_user_script',
185
192
  description:
186
- 'Dry-run a USER SCRIPT — the same thing as the `jsUserScripts` / '
187
- + '`customInjection` field on a published provider: plain browser '
188
- + 'JS that runs before every page load, used to drive navigation '
189
- + 'for data gated behind login/routing — in the LIVE attached tab, '
190
- + 'BEFORE publishing. Installs `script` via CDP so it runs on the '
191
- + 'next navigation exactly like the real field would, then reports '
192
- + 'whether it ran and any errors it threw. Catches bugs (e.g. a '
193
- + 'listener registered with setTimeout that never fires because the '
194
- + "page was already past 'load' by the time it ran) before they "
195
- + 'surface in a real end-user session instead of after. If '
196
- + '`navigateUrl` is given, navigates there after installing, then '
197
- + 'removes the script again once the result is read (self-cleaning '
198
- + '— safe to call repeatedly). Without `navigateUrl` the script is '
199
- + 'left installed for you to navigate yourself (any way you like) '
200
- + 'then re-call this tool, or read '
201
- + '`window.__reclaimUserScriptResult` via eval_in_page — in that '
202
- + 'manual mode it is NOT auto-removed and keeps running on every '
203
- + 'later navigation until a follow-up call with `navigateUrl` '
204
- + 'removes it, so avoid stacking several manual-mode calls in a '
205
- + 'row.',
193
+ 'Dry-run a USER SCRIPT (the `jsUserScripts` / `customInjection` '
194
+ + 'field) in the LIVE attached tab, BEFORE publishing. Installs '
195
+ + '`script` via CDP so it runs on the next navigation exactly as '
196
+ + 'the real field would, then reports whether it ran and what it '
197
+ + 'threw. With `navigateUrl`, it navigates there and removes the '
198
+ + 'script once the result is read — self-cleaning, safe to repeat. '
199
+ + 'WITHOUT `navigateUrl` the script stays installed (navigate '
200
+ + 'yourself, then re-call this tool or read '
201
+ + '`window.__reclaimUserScriptResult` via eval_in_page) and keeps '
202
+ + 'running on every later navigation until a call WITH '
203
+ + '`navigateUrl` removes it — so don\'t stack manual-mode calls. '
204
+ + 'Guide: how_it_works({ topic: "user-script" }).',
206
205
  inputSchema: objectSchema(
207
206
  {
208
207
  script: { type: 'string' },
@@ -246,8 +245,9 @@ export function authoringTools(
246
245
  'Installed for the NEXT navigation only — it did not run on '
247
246
  + 'the current page, and stays installed (runs on every later '
248
247
  + 'navigation too) until a follow-up call with navigateUrl '
249
- + 'removes it. Navigate now (e.g. the navigate tool), then read '
250
- + 'window.__reclaimUserScriptResult via eval_in_page, or call '
248
+ + 'removes it. Navigate now (for example, with the navigate '
249
+ + 'tool), then read window.__reclaimUserScriptResult via '
250
+ + 'eval_in_page, or call '
251
251
  + 'test_user_script again with navigateUrl.',
252
252
  }
253
253
  }
@@ -298,7 +298,8 @@ export function authoringTools(
298
298
  'List the NAMES of cookies currently set for the page (values are '
299
299
  + 'NEVER returned). The most reliable, language- and DOM-independent '
300
300
  + 'login signal: after the user logs in, an auth/session cookie '
301
- + 'appears (e.g. session/sid/token/auth/jwt/_user/logged_in). '
301
+ + 'appears (for example, session, sid, token, auth, jwt, _user, '
302
+ + 'logged_in). '
302
303
  + 'Includes httpOnly cookies the page JS cannot see.',
303
304
  inputSchema: objectSchema({}),
304
305
  },
@@ -354,8 +355,8 @@ export function authoringTools(
354
355
  'userFirstVisit', 'cf_', '_dd_', 'bcookie', 'bscookie', 'lidc',
355
356
  ].join('|') + ')', 'i')
356
357
  // A real session/auth cookie name. Deliberately NOT bare `token` — a
357
- // challenge/CSRF token (e.g. LinkedIn `chp_token`) contains it and is
358
- // set BEFORE auth completes. Any new httpOnly cookie is also a
358
+ // challenge/CSRF token (for example, LinkedIn `chp_token`) contains it
359
+ // and is set BEFORE auth completes. Any new httpOnly cookie is also a
359
360
  // candidate (server-set session cookies are usually httpOnly).
360
361
  const SESSION = /sess|sid|jwt|_session|auth|logged.?in|remember|li_at/i
361
362
  // Auth/challenge URL paths — while the page is still on one, login is
@@ -89,9 +89,10 @@ export function isStaticAsset(url: string): boolean {
89
89
  }
90
90
 
91
91
  /** Response Content-Types for static assets. The URL-extension filter misses
92
- * extension-less bundler/CDN URLs (e.g. `/assets/3b8f1c`), so we also drop by
93
- * MIME at response time. `text/html`, `application/json`, and `text/plain`
94
- * are NOT here — those are the document/API shapes recipes match. */
92
+ * extension-less bundler/CDN URLs (for example, `/assets/3b8f1c`), so we also
93
+ * drop by MIME at response time. `text/html`, `application/json`, and
94
+ * `text/plain` are NOT here — those are the document/API shapes recipes
95
+ * match. */
95
96
  const STATIC_ASSET_MIME_EXACT = new Set([
96
97
  'text/css',
97
98
  'application/javascript', 'text/javascript', 'application/x-javascript',
@@ -272,9 +273,9 @@ export function createCaptureEngine(opts: CaptureEngineOptions): CaptureEngine {
272
273
  function onResponseReceived(p: ResponseReceivedLike) {
273
274
  const f = inFlight.get(p.requestId)
274
275
  if(!f) {
275
- // No in-flight entry → the request was skipped (e.g. a static asset)
276
- // or never seen. Discard any buffered response extra-info so a skipped
277
- // asset can't leave a dangling entry.
276
+ // No in-flight entry → the request was skipped (for example, a static
277
+ // asset) or never seen. Discard any buffered response extra-info so a
278
+ // skipped asset can't leave a dangling entry.
278
279
  pendingResponseExtra.delete(p.requestId)
279
280
  return
280
281
  }
@@ -339,7 +340,7 @@ export function createCaptureEngine(opts: CaptureEngineOptions): CaptureEngine {
339
340
  r.finishedAt = Date.now()
340
341
  } catch{
341
342
  // Body might be unavailable for
342
- // some content-types (e.g. websocket). Skip.
343
+ // some content-types (for example, websocket). Skip.
343
344
  }
344
345
  }
345
346
  }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Which sessions are using which browser container.
3
+ *
4
+ * A container is worth sharing: about 2 GB of RAM and 7 to 17 seconds to start,
5
+ * so a developer running one session after another should get the same one back
6
+ * rather than pay for a new one each time.
7
+ *
8
+ * It can only be shared SEQUENTIALLY, and the profile is why. Every container
9
+ * mounts a host directory as Chromium's `user-data-dir`, and the runtime
10
+ * deletes `SingletonLock` on boot — so a second container on the same profile
11
+ * is a second writer on one cookie jar. Chromium does not support that, and the
12
+ * failure is silent corruption of the thing most worth keeping: the login.
13
+ *
14
+ * So each container gets a SLOT. A slot has one profile and at most one live
15
+ * claimant. A session adopts the first slot nobody holds; when the last claim
16
+ * on a slot goes, the container stops.
17
+ *
18
+ * State lives in a file because each MCP session is its own OS process, with
19
+ * no shared memory to count in. Claims are process ids, and liveness is a
20
+ * signal-0 check — the same test the orphan reaper uses. It fails the harmless
21
+ * way: a recycled pid keeps a container alive rather than pulling one out from
22
+ * under a running session.
23
+ */
24
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
25
+ import { dirname, join } from 'node:path'
26
+ import { LOGGER } from '../logger.ts'
27
+ import { reclaimHomeDirPath } from '../paths.ts'
28
+
29
+ /**
30
+ * Slot → the claim tokens currently held on it.
31
+ *
32
+ * A token is `<pid>.<n>`, not a bare pid, because one session can legitimately
33
+ * hold a slot twice: re-attaching adopts the container it is already running,
34
+ * and for a moment both the new handle and the old one are outstanding. With
35
+ * bare pids those two collapse into one entry, so releasing the OLD handle
36
+ * stops the container the new one just adopted. The `<n>` keeps them distinct;
37
+ * the `<pid>` is what liveness is checked against.
38
+ */
39
+ type ClaimFile = Record<string, string[]>
40
+
41
+ /** Distinguishes claims made by this same process. */
42
+ let claimSeq = 0
43
+
44
+ /** The pid a token belongs to, or 0 when it is malformed. */
45
+ function tokenPid(token: string): number {
46
+ const pid = Number(token.split('.')[0])
47
+ return Number.isInteger(pid) ? pid : 0
48
+ }
49
+
50
+ function claimsPath(): string {
51
+ return join(reclaimHomeDirPath(), 'browser-runtime-claims.json')
52
+ }
53
+
54
+ function read(): ClaimFile {
55
+ try {
56
+ const parsed = JSON.parse(readFileSync(claimsPath(), 'utf8')) as ClaimFile
57
+ // Drop claims whose process is gone: that is what makes a slot free again
58
+ // after a session was killed without cleaning up.
59
+ const live: ClaimFile = {}
60
+ for(const [slot, tokens] of Object.entries(parsed)) {
61
+ const alive = (Array.isArray(tokens) ? tokens : [])
62
+ .filter((token) => processAlive(tokenPid(token)))
63
+ if(alive.length) {
64
+ live[slot] = alive
65
+ }
66
+ }
67
+
68
+ return live
69
+ } catch{
70
+ // Missing or unreadable: nobody has claimed anything.
71
+ return {}
72
+ }
73
+ }
74
+
75
+ function write(claims: ClaimFile): void {
76
+ const path = claimsPath()
77
+ mkdirSync(dirname(path), { recursive: true })
78
+ // Write then rename, so a reader never sees a half-written file. Two sessions
79
+ // racing here means last-writer-wins on a file that is pruned on every read,
80
+ // which costs at most one redundant container.
81
+ const temp = `${path}.${process.pid}.tmp`
82
+ writeFileSync(temp, `${JSON.stringify(claims, null, '\t')}\n`)
83
+ renameSync(temp, path)
84
+ }
85
+
86
+ /** Whether a process is still running. Signal 0 checks without delivering. */
87
+ export function processAlive(pid: number): boolean {
88
+ if(!Number.isInteger(pid) || pid <= 0) {
89
+ return false
90
+ }
91
+
92
+ try {
93
+ process.kill(pid, 0)
94
+ return true
95
+ } catch(err) {
96
+ // EPERM means it exists but belongs to another user — alive either way.
97
+ return (err as NodeJS.ErrnoException).code === 'EPERM'
98
+ }
99
+ }
100
+
101
+ /** Slots with at least one live claimant, so a caller can avoid them. */
102
+ export function busySlots(): Set<string> {
103
+ return new Set(Object.keys(read()))
104
+ }
105
+
106
+ /**
107
+ * Slots THIS process already holds.
108
+ *
109
+ * Its own claim must not push it onto a new slot: re-attaching in one session
110
+ * should come back to the browser it is already running, not start a second.
111
+ */
112
+ export function ownSlots(): Set<string> {
113
+ const mine = new Set<string>()
114
+ for(const [slot, tokens] of Object.entries(read())) {
115
+ if(tokens.some((token) => tokenPid(token) === process.pid)) {
116
+ mine.add(slot)
117
+ }
118
+ }
119
+
120
+ return mine
121
+ }
122
+
123
+ /** Take a claim on `slot`. Returns the token to release it with. */
124
+ export function claim(slot: string): string {
125
+ const token = `${process.pid}.${++claimSeq}`
126
+ const claims = read()
127
+ claims[slot] = [...claims[slot] ?? [], token]
128
+ write(claims)
129
+ LOGGER.debug({ slot, held: claims[slot] }, 'claimed a browser slot')
130
+ return token
131
+ }
132
+
133
+ /**
134
+ * Give up this process's claim.
135
+ *
136
+ * Returns true when nobody is left, which is the caller's signal to stop the
137
+ * container. Returns false while another live session still holds it — stopping
138
+ * then would pull the browser out from under them.
139
+ */
140
+ export function release(slot: string, token: string): boolean {
141
+ const claims = read()
142
+ const remaining = (claims[slot] ?? []).filter((held) => held !== token)
143
+ if(remaining.length) {
144
+ claims[slot] = remaining
145
+ write(claims)
146
+ LOGGER.debug({ slot, remaining }, 'released a claim; others still hold it')
147
+ return false
148
+ }
149
+
150
+ delete claims[slot]
151
+ write(claims)
152
+ return true
153
+ }