@reclaimprotocol/agent 0.1.18 → 0.1.20

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 (158) hide show
  1. package/README.md +6 -2
  2. package/lib/authoring/backend.d.ts +4 -0
  3. package/lib/authoring/tools.js +4 -1
  4. package/lib/cdp/capture.d.ts +2 -2
  5. package/lib/cdp/capture.js +25 -21
  6. package/lib/cdp/client.d.ts +39 -1
  7. package/lib/cdp/client.js +125 -1
  8. package/lib/mcp/api/operations.gen.js +33 -9
  9. package/lib/mcp/instructions.js +27 -3
  10. package/lib/mcp/start.js +12 -8
  11. package/lib/mcp/tools/agent/attach.d.ts +18 -4
  12. package/lib/mcp/tools/agent/attach.js +142 -52
  13. package/lib/mcp/tools/agent/build.d.ts +1 -1
  14. package/lib/mcp/tools/agent/build.js +5 -3
  15. package/lib/mcp/tools/agent/capture.d.ts +1 -0
  16. package/lib/mcp/tools/agent/capture.js +8 -1
  17. package/lib/mcp/tools/agent/eval.js +2 -3
  18. package/lib/mcp/tools/agent/how-it-works.d.ts +1 -1
  19. package/lib/mcp/tools/agent/how-it-works.js +1 -1
  20. package/lib/mcp/tools/agent/publish.js +22 -1
  21. package/lib/mcp/tools/agent/session.d.ts +2 -2
  22. package/lib/mcp/tools/agent/session.js +21 -5
  23. package/lib/mcp/tools/agent/shared.js +4 -6
  24. package/lib/mcp/tools/authenticate/authenticate.d.ts +1 -1
  25. package/lib/mcp/tools/authenticate/authenticate.js +10 -4
  26. package/lib/mcp/tools/authenticate/builder-access.d.ts +8 -0
  27. package/lib/mcp/tools/authenticate/builder-access.js +31 -0
  28. package/lib/mcp/tools/authenticate/index.d.ts +1 -0
  29. package/lib/mcp/tools/authenticate/index.js +1 -0
  30. package/lib/old/login-cdp.js +11 -3
  31. package/lib/old/tools/publish.js +23 -1
  32. package/lib/provider/draft.d.ts +20 -0
  33. package/lib/provider/draft.js +75 -51
  34. package/lib/provider/index.d.ts +1 -1
  35. package/lib/provider/index.js +1 -1
  36. package/lib/provider/secrets.d.ts +37 -0
  37. package/lib/provider/secrets.js +147 -6
  38. package/lib/provider/to-version.d.ts +7 -0
  39. package/lib/provider/to-version.js +11 -1
  40. package/package.json +2 -2
  41. package/skill/SKILL.builder.md +43 -95
  42. package/skill/SKILL.common.md +102 -0
  43. package/skill/SKILL.old.md +20 -74
  44. package/skill/builder-mode.md +2 -2
  45. package/skill/injection-api.md +95 -10
  46. package/skill/old-mode.md +2 -2
  47. package/src/authoring/backend.ts +4 -0
  48. package/src/authoring/tools.ts +4 -1
  49. package/src/cdp/capture.ts +24 -24
  50. package/src/cdp/client.ts +197 -2
  51. package/src/mcp/api/operations.gen.ts +33 -9
  52. package/src/mcp/instructions.ts +36 -3
  53. package/src/mcp/start.ts +13 -8
  54. package/src/mcp/tools/agent/attach.ts +198 -57
  55. package/src/mcp/tools/agent/build.ts +9 -2
  56. package/src/mcp/tools/agent/capture.ts +10 -1
  57. package/src/mcp/tools/agent/eval.ts +2 -3
  58. package/src/mcp/tools/agent/how-it-works.ts +1 -1
  59. package/src/mcp/tools/agent/publish.ts +22 -1
  60. package/src/mcp/tools/agent/session.ts +29 -8
  61. package/src/mcp/tools/agent/shared.ts +5 -10
  62. package/src/mcp/tools/authenticate/authenticate.ts +14 -4
  63. package/src/mcp/tools/authenticate/builder-access.ts +42 -0
  64. package/src/mcp/tools/authenticate/index.ts +4 -0
  65. package/src/old/login-cdp.ts +13 -3
  66. package/src/old/tools/publish.ts +25 -3
  67. package/src/provider/draft.ts +98 -56
  68. package/src/provider/index.ts +9 -1
  69. package/src/provider/secrets.ts +171 -6
  70. package/src/provider/to-version.ts +12 -1
  71. package/lib/authoring/find.d.ts +0 -3
  72. package/lib/authoring/find.js +0 -54
  73. package/lib/authoring/propose.d.ts +0 -3
  74. package/lib/authoring/propose.js +0 -109
  75. package/lib/authoring/replay.d.ts +0 -10
  76. package/lib/authoring/replay.js +0 -34
  77. package/lib/cli/args.d.ts +0 -14
  78. package/lib/cli/args.js +0 -19
  79. package/lib/cli/commands.d.ts +0 -1
  80. package/lib/cli/commands.js +0 -19
  81. package/lib/cli.d.ts +0 -1
  82. package/lib/cli.js +0 -7
  83. package/lib/mcp/credentials/authenticate.d.ts +0 -3
  84. package/lib/mcp/credentials/authenticate.js +0 -108
  85. package/lib/mcp/credentials/build.d.ts +0 -5
  86. package/lib/mcp/credentials/build.js +0 -18
  87. package/lib/mcp/credentials/cache.d.ts +0 -70
  88. package/lib/mcp/credentials/cache.js +0 -131
  89. package/lib/mcp/credentials/env-file.d.ts +0 -25
  90. package/lib/mcp/credentials/env-file.js +0 -71
  91. package/lib/mcp/credentials/import.d.ts +0 -2
  92. package/lib/mcp/credentials/import.js +0 -52
  93. package/lib/mcp/credentials/issue.d.ts +0 -2
  94. package/lib/mcp/credentials/issue.js +0 -84
  95. package/lib/mcp/credentials/keypair.d.ts +0 -17
  96. package/lib/mcp/credentials/keypair.js +0 -48
  97. package/lib/mcp/credentials/link.d.ts +0 -3
  98. package/lib/mcp/credentials/link.js +0 -107
  99. package/lib/mcp/credentials/list-cached.d.ts +0 -2
  100. package/lib/mcp/credentials/list-cached.js +0 -55
  101. package/lib/mcp/credentials/owner-key.d.ts +0 -23
  102. package/lib/mcp/credentials/owner-key.js +0 -58
  103. package/lib/mcp/credentials/paths.d.ts +0 -12
  104. package/lib/mcp/credentials/paths.js +0 -35
  105. package/lib/mcp/credentials/poll.d.ts +0 -27
  106. package/lib/mcp/credentials/poll.js +0 -61
  107. package/lib/mcp/credentials/register.d.ts +0 -18
  108. package/lib/mcp/credentials/register.js +0 -30
  109. package/lib/mcp/credentials/resolve-owner-key.d.ts +0 -12
  110. package/lib/mcp/credentials/resolve-owner-key.js +0 -68
  111. package/lib/mcp/credentials/session-cache.d.ts +0 -14
  112. package/lib/mcp/credentials/session-cache.js +0 -42
  113. package/lib/mcp/credentials/status.d.ts +0 -3
  114. package/lib/mcp/credentials/status.js +0 -76
  115. package/lib/mcp/register.d.ts +0 -38
  116. package/lib/mcp/register.js +0 -80
  117. package/lib/mcp/tools/analyze.d.ts +0 -3
  118. package/lib/mcp/tools/analyze.js +0 -26
  119. package/lib/mcp/tools/attach.d.ts +0 -11
  120. package/lib/mcp/tools/attach.js +0 -72
  121. package/lib/mcp/tools/capture.d.ts +0 -10
  122. package/lib/mcp/tools/capture.js +0 -142
  123. package/lib/mcp/tools/eval.d.ts +0 -5
  124. package/lib/mcp/tools/eval.js +0 -127
  125. package/lib/mcp/tools/find.d.ts +0 -3
  126. package/lib/mcp/tools/find.js +0 -60
  127. package/lib/mcp/tools/owner-key.d.ts +0 -2
  128. package/lib/mcp/tools/owner-key.js +0 -63
  129. package/lib/mcp/tools/proof.d.ts +0 -3
  130. package/lib/mcp/tools/proof.js +0 -214
  131. package/lib/mcp/tools/propose.d.ts +0 -9
  132. package/lib/mcp/tools/propose.js +0 -75
  133. package/lib/mcp/tools/publish.d.ts +0 -3
  134. package/lib/mcp/tools/publish.js +0 -59
  135. package/lib/mcp/tools/replay.d.ts +0 -3
  136. package/lib/mcp/tools/replay.js +0 -46
  137. package/lib/mcp/tools/session.d.ts +0 -10
  138. package/lib/mcp/tools/session.js +0 -29
  139. package/lib/mcp/tools/verification/diagnose.d.ts +0 -11
  140. package/lib/mcp/tools/verification/diagnose.js +0 -132
  141. package/lib/mcp/verifications/build.d.ts +0 -5
  142. package/lib/mcp/verifications/build.js +0 -14
  143. package/lib/mcp/verifications/create.d.ts +0 -3
  144. package/lib/mcp/verifications/create.js +0 -57
  145. package/lib/mcp/verifications/find.d.ts +0 -3
  146. package/lib/mcp/verifications/find.js +0 -37
  147. package/lib/mcp/verifications/get.d.ts +0 -3
  148. package/lib/mcp/verifications/get.js +0 -26
  149. package/lib/mcp/verifications/update.d.ts +0 -3
  150. package/lib/mcp/verifications/update.js +0 -78
  151. package/lib/old/tools/get-version-config.d.ts +0 -17
  152. package/lib/old/tools/get-version-config.js +0 -47
  153. package/lib/routes.gen.d.ts +0 -271
  154. package/lib/routes.gen.js +0 -73
  155. package/lib/types/openapi.d.ts +0 -4
  156. package/lib/types/openapi.gen.d.ts +0 -3967
  157. package/lib/types/openapi.gen.js +0 -5
  158. package/lib/types/openapi.js +0 -1
@@ -1,72 +1,162 @@
1
- import { connectCdp } from "../../../cdp/client.js";
1
+ import { badRequest } from '@hapi/boom';
2
+ import assert from 'node:assert';
3
+ import { connectCdp, connectCdpUrl, } from "../../../cdp/client.js";
2
4
  import { defaultProfileDir, launchChrome, waitForCdpReady, } from "../../../cdp/launcher.js";
3
5
  import { defaultConfigPath } from "../../../config/store.js";
4
6
  import { defineTool } from "../../server.js";
5
- export function attachTool(state) {
7
+ const DEFAULT_DEPENDENCIES = {
8
+ connectLocal: connectCdp,
9
+ connectRemote: connectCdpUrl,
10
+ };
11
+ export function attachTool(state, builderClient, name = 'attach_browser', beforeReplace, dependencies = DEFAULT_DEPENDENCIES) {
6
12
  return defineTool({
7
- name: 'attach_chrome',
8
- description: 'Attach to a Chrome instance via CDP. ' +
9
- 'Auto-launches a dedicated-profile Chrome ' +
10
- 'on first call if no attachMode is persisted. ' +
11
- 'Persists the chosen mode in ~/.reclaim/config.json.',
13
+ name,
14
+ description: name === 'attach_chrome'
15
+ ? 'Backward-compatible alias for attach_browser.'
16
+ : 'Connect the provider-authoring tools to a browser. Choose '
17
+ + 'dedicated (launch local Chrome), attach (existing local CDP '
18
+ + 'port), builder (quota-accounted Popcorn browser with a '
19
+ + 'shareable live view), or custom (caller-supplied CDP '
20
+ + 'websocket). '
21
+ + 'Builder and custom CDP credentials are held in memory and never '
22
+ + 'returned.',
12
23
  inputSchema: {
13
24
  type: 'object',
14
25
  properties: {
15
- attachMode: { type: 'string', enum: ['dedicated', 'attach'] },
16
- port: { type: 'number' },
26
+ mode: {
27
+ type: 'string',
28
+ enum: ['dedicated', 'attach', 'builder', 'custom'],
29
+ },
30
+ attachMode: {
31
+ type: 'string',
32
+ enum: ['dedicated', 'attach'],
33
+ description: 'Deprecated local-mode alias for mode.',
34
+ },
35
+ port: { type: 'number', minimum: 1, maximum: 65535 },
36
+ orgId: { type: 'string', format: 'uuid' },
37
+ cdpUrl: { type: 'string', maxLength: 4000 },
38
+ liveViewUrl: { type: 'string', format: 'uri', maxLength: 4000 },
17
39
  },
18
40
  },
19
41
  }, async (parsed) => {
20
- let cfg = state.config.read()?.browser_agent;
21
- if (parsed.attachMode || parsed.port) {
22
- cfg = {
23
- attachMode: parsed.attachMode ?? cfg?.attachMode ?? 'dedicated',
24
- port: parsed.port ?? cfg?.port ?? 9222,
25
- };
26
- state.config.write({ browser_agent: cfg });
27
- }
28
- if (!cfg) {
42
+ const persisted = state.config.read()?.browser_agent;
43
+ const mode = parsed.mode ?? parsed.attachMode ?? persisted?.attachMode;
44
+ if (!mode) {
29
45
  return {
30
46
  needsChoice: true,
31
- message: 'First-run: choose attach mode. ' +
32
- 'Call attach_chrome again with attachMode="dedicated" ' +
33
- '(auto-launch a Chrome profile under ~/.reclaim/chrome-profile) ' +
34
- 'or attachMode="attach" ' +
35
- '(connect to a Chrome you launched yourself with ' +
36
- 'BOTH --remote-debugging-port=9222 AND ' +
37
- '--user-data-dir=<some-non-default-path>; ' +
38
- 'since Chrome 136 the debug-port flag is silently ' +
39
- 'ignored if the default profile is in use).',
47
+ message: 'Choose a browser mode and call attach_browser again: '
48
+ + '"dedicated" launches a local dedicated Chrome profile; '
49
+ + '"attach" connects to a local Chrome debugging port; '
50
+ + '"builder" creates a quota-accounted remote browser and '
51
+ + 'requires orgId; "custom" requires a CDP websocket URL.',
40
52
  configPath: defaultConfigPath(),
41
53
  };
42
54
  }
43
- if (cfg.attachMode === 'dedicated') {
44
- try {
45
- await waitForCdpReady(cfg.port, 500);
46
- }
47
- catch {
48
- launchChrome({ port: cfg.port, profileDir: defaultProfileDir() });
49
- await waitForCdpReady(cfg.port, 10000);
50
- }
55
+ const next = await connect(mode, parsed, persisted, builderClient, dependencies);
56
+ try {
57
+ await beforeReplace?.();
58
+ await disposeAttached(state);
51
59
  }
52
- else {
53
- await waitForCdpReady(cfg.port, 2000).catch(() => {
54
- throw new Error(`attach mode: nothing answering CDP on port ${cfg.port}. ` +
55
- 'Chrome must be launched with BOTH ' +
56
- `--remote-debugging-port=${cfg.port} AND ` +
57
- '--user-data-dir=<some-non-default-path>. ' +
58
- 'Since Chrome 136 (May 2025), the debug-port flag is ' +
59
- 'silently ignored when the default ' +
60
- "user profile is in use — that's why nothing opens the port. " +
61
- 'Either re-launch Chrome with ' +
62
- 'a custom --user-data-dir, or switch to attachMode="dedicated".');
63
- });
60
+ catch (err) {
61
+ await disposeState(next).catch(() => { });
62
+ throw err;
64
63
  }
65
- if (state.current) {
66
- await state.current.handles.close().catch(() => { });
64
+ state.current = next;
65
+ if (mode === 'dedicated' || mode === 'attach') {
66
+ state.config.write({
67
+ browser_agent: { attachMode: mode, port: next.port },
68
+ });
67
69
  }
68
- const handles = await connectCdp(cfg.port);
69
- state.current = { handles, port: cfg.port };
70
- return { attached: true, port: cfg.port, mode: cfg.attachMode };
70
+ return {
71
+ attached: true,
72
+ mode,
73
+ ...(next.port ? { port: next.port } : {}),
74
+ ...(next.browserSessionId
75
+ ? { browserSessionId: next.browserSessionId }
76
+ : {}),
77
+ ...(next.liveViewUrl ? { liveViewUrl: next.liveViewUrl } : {}),
78
+ };
71
79
  });
72
80
  }
81
+ export async function disposeAttached(state) {
82
+ const current = state.current;
83
+ if (!current) {
84
+ return;
85
+ }
86
+ delete state.current;
87
+ await disposeState(current);
88
+ }
89
+ async function connect(mode, parsed, persisted, builderClient, dependencies) {
90
+ if (mode === 'builder') {
91
+ assert(builderClient, badRequest('Builder browser service is unavailable'));
92
+ assert(parsed.orgId, badRequest('orgId is required for builder mode'));
93
+ const { data } = await builderClient.call('CreateAgentBrowserSession', {
94
+ params: { orgId: parsed.orgId },
95
+ });
96
+ let handles;
97
+ try {
98
+ handles = await dependencies.connectRemote(data.cdpUrl);
99
+ }
100
+ catch (err) {
101
+ await builderClient.call('DisposeAgentBrowserSession', {
102
+ params: {
103
+ orgId: parsed.orgId,
104
+ browserSessionId: data.id,
105
+ },
106
+ }).catch(() => { });
107
+ throw err;
108
+ }
109
+ return {
110
+ handles,
111
+ mode,
112
+ liveViewUrl: data.liveViewUrl,
113
+ browserSessionId: data.id,
114
+ orgId: parsed.orgId,
115
+ disposeRemote: async () => {
116
+ await builderClient.call('DisposeAgentBrowserSession', {
117
+ params: {
118
+ orgId: parsed.orgId,
119
+ browserSessionId: data.id,
120
+ },
121
+ });
122
+ },
123
+ };
124
+ }
125
+ if (mode === 'custom') {
126
+ assert(parsed.cdpUrl, badRequest('cdpUrl is required for custom mode'));
127
+ const url = new URL(parsed.cdpUrl);
128
+ assert(url.protocol === 'ws:' || url.protocol === 'wss:', badRequest('cdpUrl must use ws:// or wss://'));
129
+ return {
130
+ handles: await dependencies.connectRemote(parsed.cdpUrl),
131
+ mode,
132
+ ...(parsed.liveViewUrl ? { liveViewUrl: parsed.liveViewUrl } : {}),
133
+ };
134
+ }
135
+ const port = parsed.port ?? persisted?.port ?? 9222;
136
+ if (mode === 'dedicated') {
137
+ try {
138
+ await waitForCdpReady(port, 500);
139
+ }
140
+ catch {
141
+ launchChrome({ port, profileDir: defaultProfileDir() });
142
+ await waitForCdpReady(port, 10000);
143
+ }
144
+ }
145
+ else {
146
+ await waitForCdpReady(port, 2000).catch(() => {
147
+ throw new Error(`attach mode: nothing answering CDP on port ${port}. Chrome must `
148
+ + `be launched with --remote-debugging-port=${port} AND `
149
+ + '--user-data-dir=<some-non-default-path>. Chrome 136+ ignores '
150
+ + 'the debugging flag for the default profile.');
151
+ });
152
+ }
153
+ return { handles: await dependencies.connectLocal(port), mode, port };
154
+ }
155
+ async function disposeState(state) {
156
+ try {
157
+ await state.handles.close();
158
+ }
159
+ finally {
160
+ await state.disposeRemote?.();
161
+ }
162
+ }
@@ -26,4 +26,4 @@ export interface AgentState {
26
26
  * Pass `client` to include the builder `create_provider_version_from_capture`;
27
27
  * omit it (e.g. OLD-devtools mode) to register only the backend-independent
28
28
  * capture/proof tools — old mode supplies its own publish tool. */
29
- export declare function buildAgentTools(client?: ReclaimClient): RegisteredTool[];
29
+ export declare function buildAgentTools(client?: ReclaimClient, builderClient?: ReclaimClient | undefined): RegisteredTool[];
@@ -13,7 +13,7 @@ import { ConfigStore } from "../../../config/store.js";
13
13
  import { ensureAttestorCrypto } from "../../../proof/proof-core.js";
14
14
  import { analyzeTool } from "./analyze.js";
15
15
  import { attachTool } from "./attach.js";
16
- import { captureTools } from "./capture.js";
16
+ import { captureTools, resetCaptures } from "./capture.js";
17
17
  import { listTabsTool } from "./eval.js";
18
18
  import { howItWorksTool } from "./how-it-works.js";
19
19
  import { createVersionFromCaptureTool } from "./publish.js";
@@ -30,14 +30,16 @@ function buildAgentState() {
30
30
  * Pass `client` to include the builder `create_provider_version_from_capture`;
31
31
  * omit it (e.g. OLD-devtools mode) to register only the backend-independent
32
32
  * capture/proof tools — old mode supplies its own publish tool. */
33
- export function buildAgentTools(client) {
33
+ export function buildAgentTools(client, builderClient = client) {
34
34
  const state = buildAgentState();
35
35
  ensureAttestorCrypto();
36
36
  const tools = [];
37
37
  // Stateless docs tool — serve the mode-specific authoring guide to any
38
38
  // client. No `client` ⇒ old-devtools mode (see `mcp/start.ts`).
39
39
  tools.push(howItWorksTool(!client));
40
- tools.push(attachTool(state.attach));
40
+ const beforeReplace = () => resetCaptures(state.captures);
41
+ tools.push(attachTool(state.attach, builderClient, 'attach_browser', beforeReplace));
42
+ tools.push(attachTool(state.attach, builderClient, 'attach_chrome', beforeReplace));
41
43
  tools.push(listTabsTool(state.attach));
42
44
  for (const t of captureTools(state.attach, state.captures)) {
43
45
  tools.push(t);
@@ -17,6 +17,7 @@ export interface CaptureStore {
17
17
  sessions: Map<string, CaptureEntry>;
18
18
  activeTab?: string;
19
19
  }
20
+ export declare function resetCaptures(captures: CaptureStore): Promise<void>;
20
21
  export declare function captureTools(attachRef: {
21
22
  current?: AttachState;
22
23
  }, captures: CaptureStore): RegisteredTool[];
@@ -1,10 +1,17 @@
1
1
  import { makeDraftStore } from "../../../authoring/index.js";
2
2
  import { startCapture } from "../../../cdp/capture.js";
3
3
  import { defineTool } from "../../server.js";
4
+ export async function resetCaptures(captures) {
5
+ for (const entry of captures.sessions.values()) {
6
+ await entry.session.stop().catch(() => { });
7
+ }
8
+ captures.sessions.clear();
9
+ delete captures.activeTab;
10
+ }
4
11
  export function captureTools(attachRef, captures) {
5
12
  const requireAttached = () => {
6
13
  if (!attachRef.current) {
7
- throw new Error('Not attached. Call attach_chrome first.');
14
+ throw new Error('Not attached. Call attach_browser first.');
8
15
  }
9
16
  return attachRef.current;
10
17
  };
@@ -1,4 +1,3 @@
1
- import { listTabs } from "../../../cdp/tabs.js";
2
1
  import { defineTool } from "../../server.js";
3
2
  /** The one browser tool that isn't session-bound: enumerate tabs so the caller
4
3
  * can pick one to `start_capture` on. Navigate/eval/wait are the shared
@@ -10,8 +9,8 @@ export function listTabsTool(attachRef) {
10
9
  inputSchema: { type: 'object', properties: {} },
11
10
  }, async () => {
12
11
  if (!attachRef.current) {
13
- throw new Error('Not attached. Call attach_chrome first.');
12
+ throw new Error('Not attached. Call attach_browser first.');
14
13
  }
15
- return { tabs: await listTabs(attachRef.current.port) };
14
+ return { tabs: await attachRef.current.handles.listTabs() };
16
15
  });
17
16
  }
@@ -6,6 +6,6 @@ import { type RegisteredTool } from '../../server.ts';
6
6
  * so any MCP client — not just Claude Code, which alone auto-loads skills — can
7
7
  * pull it. `oldMode` selects the backend-specific guide so the agent is never
8
8
  * told to call auth/publish tools that aren't registered in its mode.
9
- * Stateless: callable before `attach_chrome`.
9
+ * Stateless: callable before `attach_browser`.
10
10
  */
11
11
  export declare function howItWorksTool(oldMode: boolean): RegisteredTool;
@@ -7,7 +7,7 @@ import { defineTool } from "../../server.js";
7
7
  * so any MCP client — not just Claude Code, which alone auto-loads skills — can
8
8
  * pull it. `oldMode` selects the backend-specific guide so the agent is never
9
9
  * told to call auth/publish tools that aren't registered in its mode.
10
- * Stateless: callable before `attach_chrome`.
10
+ * Stateless: callable before `attach_browser`.
11
11
  */
12
12
  export function howItWorksTool(oldMode) {
13
13
  const guide = oldMode ? PROVIDER_GUIDE_OLD : PROVIDER_GUIDE_BUILDER;
@@ -181,7 +181,28 @@ export function createVersionFromCaptureTool(client) {
181
181
  type: 'array',
182
182
  description: 'Extra requests the injection script is allowed to fire ' +
183
183
  '(e.g. paginated API calls), as RequestSelectionTemplates. ' +
184
- '`multiple`/`required` default to true.',
184
+ '`multiple`/`required` default to true. ' +
185
+ '⚠️ BEFORE populating this to gate ' +
186
+ '`verifyProof(proof, { providerId })` (old-devtools calls the ' +
187
+ 'same concept `allowedInjectedRequestData` — same mechanics, ' +
188
+ 'different field name): this whole entry (url, method, body, ' +
189
+ 'responseMatches, responseRedactions) feeds a client-side ' +
190
+ 'hash-equality check, and `url` is hashed VERBATIM — no regex/ ' +
191
+ 'template resolution, even with `urlType: REGEX` or ' +
192
+ '`TEMPLATE`. If the real captured URL contains ANY per-session ' +
193
+ 'part (a tracking nonce, CSRF token, cache-busting timestamp), ' +
194
+ 'no declared spec can EVER hash-match a real proof — populating' +
195
+ ' this for such a provider makes verifyProof reject every real ' +
196
+ 'proof, which is worse than leaving it empty. Diff the same ' +
197
+ 'endpoint\'s captured URL across two separate sessions before ' +
198
+ 'wiring this up. If provider-hash validation keeps causing ' +
199
+ 'problems (unstable url, or any other persistent mismatch), ' +
200
+ 'the fallback on the verifying side is `verifyProof(proof, { ' +
201
+ 'dangerouslyDisableContentValidation: true })` — trusts only ' +
202
+ 'the attestor\'s signature, skips the hash-equality check ' +
203
+ 'entirely; see the "Provider-hash validation" section of the ' +
204
+ 'injection script\'s guide for the full mechanics and when to ' +
205
+ 'reach for it.',
185
206
  items: ALLOWED_JS_REQUEST_SCHEMA,
186
207
  },
187
208
  interceptorOptions: {
@@ -1,7 +1,7 @@
1
1
  import type { ConfigStore } from '../../../config/store.ts';
2
2
  import { type RegisteredTool } from '../../server.ts';
3
- import type { AttachState } from './attach.ts';
4
- import type { CaptureStore } from './capture.ts';
3
+ import { type AttachState } from './attach.ts';
4
+ import { type CaptureStore } from './capture.ts';
5
5
  export declare function sessionTools(attachRef: {
6
6
  current?: AttachState;
7
7
  config: ConfigStore;
@@ -1,4 +1,6 @@
1
1
  import { defineTool } from "../../server.js";
2
+ import { disposeAttached } from "./attach.js";
3
+ import { resetCaptures } from "./capture.js";
2
4
  export function sessionTools(attachRef, captures) {
3
5
  return [
4
6
  defineTool({
@@ -8,22 +10,36 @@ export function sessionTools(attachRef, captures) {
8
10
  }, async () => ({
9
11
  config: attachRef.config.read()?.browser_agent,
10
12
  attached: Boolean(attachRef.current),
13
+ mode: attachRef.current?.mode,
11
14
  port: attachRef.current?.port,
15
+ liveViewUrl: attachRef.current?.liveViewUrl,
16
+ browserSessionId: attachRef.current?.browserSessionId,
17
+ orgId: attachRef.current?.orgId,
12
18
  captures: [...captures.sessions.keys()],
13
19
  activeTab: captures.activeTab,
14
20
  })),
21
+ defineTool({
22
+ name: 'dispose_browser',
23
+ description: 'Stop captures, disconnect the current browser, and immediately '
24
+ + 'delete a Builder-hosted Popcorn session. Custom CDP sessions '
25
+ + 'are disconnected but never deleted by Reclaim.',
26
+ inputSchema: { type: 'object', properties: {} },
27
+ }, async () => {
28
+ await resetAll(attachRef, captures);
29
+ return { disposed: true };
30
+ }),
15
31
  defineTool({
16
32
  name: 'reset_session',
17
33
  description: 'Stop all captures and clear capture state — drops every '
18
34
  + 'session\'s drafts and their in-memory secrets.',
19
35
  inputSchema: { type: 'object', properties: {} },
20
36
  }, async () => {
21
- for (const entry of captures.sessions.values()) {
22
- await entry.session.stop().catch(() => { });
23
- }
24
- captures.sessions.clear();
25
- delete captures.activeTab;
37
+ await resetAll(attachRef, captures);
26
38
  return { reset: true };
27
39
  }),
28
40
  ];
29
41
  }
42
+ async function resetAll(attachRef, captures) {
43
+ await resetCaptures(captures);
44
+ await disposeAttached(attachRef);
45
+ }
@@ -42,14 +42,12 @@ function withLocalOprfMode(provider) {
42
42
  * captured requests, prove via the in-process attestor, replay by re-fetch. */
43
43
  function localBackend(entry) {
44
44
  const { tabClient, session, drafts } = entry;
45
- // The per-tab CDP client is strongly typed to `keyof Commands`; the shared
46
- // tools drive it with dynamic method/event names, so view it as string-keyed.
47
- const client = tabClient;
48
45
  return {
49
46
  capture: session,
50
47
  drafts,
51
- sendCdp: (method, params) => client.send(method, params ?? {}),
48
+ sendCdp: (method, params) => tabClient.send(method, params ?? {}),
52
49
  waitForEvent: (method, timeoutMs) => new Promise((resolve) => {
50
+ let stopListening = () => { };
53
51
  const onEvent = () => {
54
52
  cleanup();
55
53
  resolve('fired');
@@ -60,9 +58,9 @@ function localBackend(entry) {
60
58
  }, timeoutMs);
61
59
  const cleanup = () => {
62
60
  clearTimeout(timer);
63
- client.removeListener(method, onEvent);
61
+ stopListening();
64
62
  };
65
- client.once(method, onEvent);
63
+ stopListening = tabClient.subscribeOnce(method, onEvent);
66
64
  }),
67
65
  replay: async (draft, opts) => {
68
66
  // Auth-bound check: re-fetch with the secrets dropped. replayProvider
@@ -1,3 +1,3 @@
1
1
  import type { ReclaimClient } from '@reclaimprotocol/client';
2
2
  import { type RegisteredTool } from '../../server.ts';
3
- export declare function authenticateTool(client: ReclaimClient): RegisteredTool;
3
+ export declare function authenticateTool(client: ReclaimClient, name?: 'reclaim_authenticate' | 'authenticate_builder'): RegisteredTool;
@@ -6,11 +6,17 @@ import { defineTool } from "../../server.js";
6
6
  import { writeSession } from "./session-cache.js";
7
7
  const SCOPE = 'openid profile email';
8
8
  const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
9
- export function authenticateTool(client) {
9
+ export function authenticateTool(client, name = 'reclaim_authenticate') {
10
10
  return defineTool({
11
- name: 'reclaim_authenticate',
12
- description: 'Authorize the CLI / MCP to make authenticated API calls. Opens the ' +
13
- 'browser to the builder sign-in page (standard OAuth 2.0 ' +
11
+ name,
12
+ description: (name === 'authenticate_builder'
13
+ ? 'Authenticate specifically with Builder. Available regardless '
14
+ + 'of '
15
+ + 'the selected publishing backend. '
16
+ : '')
17
+ + 'Authorize the CLI / MCP to make authenticated API calls. Opens '
18
+ + 'the '
19
+ + 'browser to the builder sign-in page (standard OAuth 2.0 ' +
14
20
  'authorization-code + PKCE with a localhost redirect) and waits for ' +
15
21
  'the user to sign in and approve. On success the access token is ' +
16
22
  'cached in ~/.reclaim/config.json and activated for this session.\n\n' +
@@ -0,0 +1,8 @@
1
+ import type { ReclaimClient } from '@reclaimprotocol/client';
2
+ import { type RegisteredTool } from '../../server.ts';
3
+ /** Legacy-devtools mode needs a distinct Builder login solely for allocating
4
+ * quota-accounted Popcorn sessions. Builder mode uses its native auth tool. */
5
+ export declare function buildBuilderAuthenticationTools(client: ReclaimClient): RegisteredTool[];
6
+ /** Legacy-devtools mode lacks generated Builder API tools, so it needs this
7
+ * narrow organization-discovery bridge for remote-browser allocation. */
8
+ export declare function buildBuilderOrganizationTools(client: ReclaimClient): RegisteredTool[];
@@ -0,0 +1,31 @@
1
+ import { defineTool } from "../../server.js";
2
+ import { authenticateTool } from "./authenticate.js";
3
+ /** Legacy-devtools mode needs a distinct Builder login solely for allocating
4
+ * quota-accounted Popcorn sessions. Builder mode uses its native auth tool. */
5
+ export function buildBuilderAuthenticationTools(client) {
6
+ return [authenticateTool(client, 'authenticate_builder')];
7
+ }
8
+ /** Legacy-devtools mode lacks generated Builder API tools, so it needs this
9
+ * narrow organization-discovery bridge for remote-browser allocation. */
10
+ export function buildBuilderOrganizationTools(client) {
11
+ return [
12
+ defineTool({
13
+ name: 'list_builder_organizations',
14
+ description: 'List organizations available to the authenticated Builder user. '
15
+ + 'Use an organization id from this result when calling '
16
+ + 'attach_browser with mode="builder". Available only in '
17
+ + 'legacy-devtools publishing mode; Builder mode uses list_orgs.',
18
+ inputSchema: {
19
+ type: 'object',
20
+ properties: {
21
+ cursor: { type: 'string', maxLength: 500 },
22
+ },
23
+ },
24
+ }, async ({ cursor }) => {
25
+ const { data } = await client.call('ListOrgs', {
26
+ query: { ...(cursor ? { cursor } : {}) },
27
+ });
28
+ return data;
29
+ }),
30
+ ];
31
+ }
@@ -1,2 +1,3 @@
1
+ export { buildBuilderAuthenticationTools, buildBuilderOrganizationTools, } from './builder-access.ts';
1
2
  export { buildCredentialTools, buildLocalCredentialTools } from './build.ts';
2
3
  export { readSession } from './session-cache.ts';
@@ -1,4 +1,5 @@
1
1
  // Barrel for the credential tool group: local eth proof-owner key (env/PEM)
2
2
  // and the org-token-authenticated builder tools. Import from here.
3
+ export { buildBuilderAuthenticationTools, buildBuilderOrganizationTools, } from "./builder-access.js";
3
4
  export { buildCredentialTools, buildLocalCredentialTools } from "./build.js";
4
5
  export { readSession } from "./session-cache.js";
@@ -113,15 +113,14 @@ export async function captureFirebaseTokenViaCdp(opts) {
113
113
  const { targetId } = await Target.createTarget({ url: loginUrl });
114
114
  try {
115
115
  const session = await handles.attachToTab(targetId);
116
- const { Runtime } = session;
117
116
  const deadline = Date.now() + timeoutMs;
118
117
  while (Date.now() < deadline) {
119
- const r = await Runtime.evaluate({
118
+ const result = await session.send('Runtime.evaluate', {
120
119
  expression: EXTRACT_TOKEN_JS,
121
120
  awaitPromise: true,
122
121
  returnByValue: true,
123
122
  });
124
- const value = r.result?.value;
123
+ const value = runtimeResultValue(result);
125
124
  if (typeof value === 'string' && value.length > 0) {
126
125
  return { token: value, closedBrowser: launchedByUs };
127
126
  }
@@ -146,3 +145,12 @@ export async function captureFirebaseTokenViaCdp(opts) {
146
145
  await handles.close().catch(() => { });
147
146
  }
148
147
  }
148
+ function runtimeResultValue(value) {
149
+ if (typeof value !== 'object' || !value || !('result' in value)) {
150
+ return undefined;
151
+ }
152
+ const result = value.result;
153
+ return typeof result === 'object' && result && 'value' in result
154
+ ? result.value
155
+ : undefined;
156
+ }
@@ -230,7 +230,29 @@ export function createVersionFromCaptureTool(client) {
230
230
  'the whole payload), template just that part with ' +
231
231
  '`{{paramName}}` and keep the rest as fixed literal text; see ' +
232
232
  'the "bodySniff" section of the customInjection field\'s guide ' +
233
- 'for the exact mechanics and a worked example.',
233
+ 'for the exact mechanics and a worked example. ' +
234
+ '⚠️ BEFORE populating this to gate ' +
235
+ '`verifyProof(proof, { providerId })`: this whole entry (url, ' +
236
+ 'method, body, responseMatches, responseRedactions) feeds a ' +
237
+ 'client-side hash-equality check, and `url` is hashed VERBATIM ' +
238
+ '— no regex/template resolution, even with `urlType: REGEX` or ' +
239
+ '`TEMPLATE`. If the real captured URL contains ANY per-session ' +
240
+ 'part (a tracking nonce, CSRF token, cache-busting timestamp), ' +
241
+ 'no declared spec can EVER hash-match a real proof, no matter ' +
242
+ 'how correct the rest of this entry is — populating' +
243
+ 'it for such ' +
244
+ 'a provider makes verifyProof reject every real proof,' +
245
+ 'which is ' +
246
+ 'worse than leaving this field empty. Diff the same endpoint\'s' +
247
+ ' captured URL across two separate sessions before wiring this ' +
248
+ 'up. If provider-hash validation keeps causing problems ' +
249
+ '(unstable url, or any other persistent mismatch), the ' +
250
+ 'fallback on the verifying side is `verifyProof(proof, { ' +
251
+ 'dangerouslyDisableContentValidation: true })` — trusts only ' +
252
+ 'the attestor\'s signature, skips the hash-equality check ' +
253
+ 'entirely; see the "Provider-hash validation" section of the ' +
254
+ 'customInjection field\'s guide for the full mechanics and ' +
255
+ 'when to reach for it.',
234
256
  items: {
235
257
  type: 'object',
236
258
  properties: {
@@ -37,4 +37,24 @@ export interface DraftResult {
37
37
  * `{{param}}`. Throwing discards the draft so the agent re-captures or
38
38
  * re-proposes rather than shipping a provider pinned to this one user. */
39
39
  export declare function assertPortableMatches(matches: ResponseMatch[], redactions: ResponseRedaction[], targets: DraftTarget[]): void;
40
+ /** Reject a draft that OPRF-hashes a target whose value ALSO appears in the
41
+ * request URL. The whole point of `hash` is that the attestor never sees
42
+ * the value in cleartext — but URL `paramValues` are always signed into the
43
+ * attestor's context in the clear (attestor-core: "those in URL... will be
44
+ * put into context and signed"), so a value that's both hashed in the
45
+ * response AND present in the URL is visible there anyway. This isn't a
46
+ * privacy nuance the author can weigh (unlike {@link assertPortableMatches}
47
+ * bare-literal cases) — it doesn't verify. Throwing here, at draft time,
48
+ * surfaces that immediately instead of a confusing later proof failure. */
49
+ export declare function assertNoOprfUrlConflict(url: string, targets: DraftTarget[], effectiveHashes: (OprfMode | undefined)[]): void;
50
+ /** Reject a draft whose URL bakes in a secret header/cookie's value beyond
51
+ * what write-redaction can actually hide there. A secret value used in the
52
+ * URL is NOT an automatic leak — write-redaction (`key-update`/`zk`) can
53
+ * redact it from the attestor's view up to {@link secretUrlCharBudget}
54
+ * characters, summed across every secret value that appears in that URL
55
+ * (not per-value). Below the budget the header buys real privacy; at or
56
+ * over it, the value is effectively visible regardless of hiding the
57
+ * header (same class of problem as {@link assertNoOprfUrlConflict} for
58
+ * OPRF-hashed targets, which has no such budget at all). */
59
+ export declare function assertNoSecretUrlConflict(url: string, secrets: Record<string, string>, writeRedactionMode?: ReclaimProvider['writeRedactionMode']): void;
40
60
  export declare function draftProvider(req: CapturedRequest, targets: DraftTarget[], name: string, hash?: OprfMode): DraftResult;