@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
package/lib/cli/args.d.ts DELETED
@@ -1,14 +0,0 @@
1
- export declare function parseCliArgs(argv: string[]): {
2
- values: {
3
- [longOption: string]: string | boolean | undefined;
4
- } & {
5
- 'base-url'?: string | boolean | undefined;
6
- token?: string | boolean | undefined;
7
- param?: (string | boolean)[] | undefined;
8
- query?: (string | boolean)[] | undefined;
9
- body?: string | boolean | undefined;
10
- help?: string | boolean | undefined;
11
- version?: string | boolean | undefined;
12
- };
13
- positionals: string[];
14
- };
package/lib/cli/args.js DELETED
@@ -1,19 +0,0 @@
1
- import { parseArgs as nodeParseArgs } from 'node:util';
2
- // Placeholder. Final shape decided once the backend openapi stabilises and
3
- // the CLI surface is fleshed out (see AGENTS.md → "CLI").
4
- export function parseCliArgs(argv) {
5
- return nodeParseArgs({
6
- args: argv,
7
- options: {
8
- 'base-url': { type: 'string' },
9
- token: { type: 'string' },
10
- param: { type: 'string', multiple: true },
11
- query: { type: 'string', multiple: true },
12
- body: { type: 'string' },
13
- help: { type: 'boolean', short: 'h' },
14
- version: { type: 'boolean', short: 'v' },
15
- },
16
- allowPositionals: true,
17
- strict: false,
18
- });
19
- }
@@ -1 +0,0 @@
1
- export declare function run(argv: string[]): Promise<void>;
@@ -1,19 +0,0 @@
1
- import { notImplemented } from '@hapi/boom';
2
- import { DESCRIPTION, NAME, VERSION } from "../pkg.js";
3
- import { parseCliArgs } from "./args.js";
4
- // Entry point for the `reclaim` bin. Placeholder until backend openapi
5
- // finalises — `--version` and `--help` work; everything else throws.
6
- export async function run(argv) {
7
- const parsed = parseCliArgs(argv);
8
- if (parsed.values['version']) {
9
- process.stdout.write(`${NAME} ${VERSION}\n`);
10
- return;
11
- }
12
- if (parsed.values['help']) {
13
- process.stdout.write(`${NAME} ${VERSION}\n${DESCRIPTION}\n\n` +
14
- 'Usage: reclaim call <OperationId> ' +
15
- '[--param k=v] [--query k=v] [--body <json>]\n');
16
- return;
17
- }
18
- throw notImplemented('reclaim CLI: pending @reclaimprotocol/app spec finalisation');
19
- }
package/lib/cli.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/lib/cli.js DELETED
@@ -1,7 +0,0 @@
1
- #!/usr/bin/env node
2
- import { run } from "./cli/commands.js";
3
- import { LOGGER } from "./logger.js";
4
- run(process.argv.slice(2)).catch((err) => {
5
- LOGGER.error({ err }, 'cli failed');
6
- process.exitCode = 1;
7
- });
@@ -1,3 +0,0 @@
1
- import type { ReclaimClient } from '@reclaimprotocol/client';
2
- import { type RegisteredTool } from '../server.ts';
3
- export declare function authenticateTool(client: ReclaimClient): RegisteredTool;
@@ -1,108 +0,0 @@
1
- import { defineTool } from "../server.js";
2
- import { writeSession } from "./session-cache.js";
3
- export function authenticateTool(client) {
4
- return defineTool({
5
- name: 'reclaim_authenticate',
6
- description: 'Authorize the CLI / MCP to make authenticated API calls by having ' +
7
- 'the user sign in on the dashboard. Two steps:\n\n' +
8
- 'Step 1 — call with no arguments. Returns a `code` and `attachUrl`. ' +
9
- 'Tell the user to open the URL, sign in, and authorize.\n\n' +
10
- 'Step 2 — once the user says they have authorized, call again ' +
11
- 'with the same `code` from step 1 to check if confirmed. ' +
12
- 'Returns `LINKED` with a 2-day bearer token when confirmed, ' +
13
- '`PENDING` if not yet, or `EXPIRED` if too long has passed.\n\n' +
14
- 'The token is cached in ~/.reclaim/session.json automatically.\n\n' +
15
- 'To then link a credential to an org (needed only to use it ' +
16
- 'for verification in production), use the token with the ' +
17
- 'generated tools: `list_orgs` → `link_credential` with the ' +
18
- "credential's `address` and the target `orgId`.",
19
- inputSchema: {
20
- type: 'object',
21
- properties: {
22
- code: {
23
- type: 'string',
24
- pattern: '^[A-HJ-NP-Z2-9]{5}$',
25
- description: '5-character code from a previous step-1 call. ' +
26
- 'When provided, checks whether the user has ' +
27
- 'confirmed that session instead of opening a new one.',
28
- },
29
- },
30
- },
31
- }, async (args) => {
32
- // Step 2: check an existing session
33
- if (args.code) {
34
- return checkSession(client, args.code);
35
- }
36
- // Step 1: open a new auth-only session
37
- const sessionResult = (await client.call('CreateAttachSession'));
38
- const session = sessionResult.data;
39
- return {
40
- status: 'PENDING',
41
- code: session.code,
42
- attachUrl: session.attachUrl,
43
- expiresAt: session.expiresAt,
44
- instructions: `Open ${session.attachUrl} in your browser, sign in, and click ` +
45
- '"Authorize this device". ' +
46
- 'Once done, call authenticate again with code: ' +
47
- `"${session.code}" to confirm.`,
48
- };
49
- });
50
- }
51
- async function checkSession(client, code) {
52
- let session;
53
- try {
54
- const sessionResult = (await client.call('GetAttachSession', {
55
- params: { code }
56
- }));
57
- session = sessionResult.data;
58
- }
59
- catch (err) {
60
- const status = err.status;
61
- if (status === 404) {
62
- return {
63
- status: 'NOT_FOUND',
64
- hint: 'Session not found — it may have expired (15-min window). ' +
65
- 'Call authenticate without a code to start a new session.',
66
- };
67
- }
68
- throw new Error(`Failed to check session: ${err.message}`);
69
- }
70
- if (session.status === 'LINKED') {
71
- const token = session.token?.trim();
72
- if (token) {
73
- writeSession({
74
- token,
75
- expiresAt: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
76
- });
77
- client.setToken(token);
78
- return {
79
- status: 'LINKED',
80
- token,
81
- note: 'Token cached in ~/.reclaim/session.json and active now.',
82
- };
83
- }
84
- return {
85
- status: 'LINKED_NO_TOKEN',
86
- hint: 'Session confirmed but no token issued. ' +
87
- 'Restart the backend (npm run dev) and try again.',
88
- };
89
- }
90
- if (session.status === 'EXPIRED') {
91
- return {
92
- status: 'EXPIRED',
93
- hint: 'Session expired (15-min window passed). ' +
94
- 'Call authenticate without a code to start a new session.',
95
- };
96
- }
97
- // Still PENDING
98
- return {
99
- status: 'PENDING',
100
- code: session.code,
101
- attachUrl: session.attachUrl,
102
- hint: 'Session is still waiting. ' +
103
- `Make sure you opened ${session.attachUrl}, ` +
104
- 'signed in, and clicked "Authorize this device". ' +
105
- `Call authenticate again with code: "${session.code}"` +
106
- ' once you have done so.',
107
- };
108
- }
@@ -1,5 +0,0 @@
1
- import type { ReclaimClient } from '@reclaimprotocol/client';
2
- import type { RegisteredTool } from '../server.ts';
3
- /** Credential lifecycle tools — build the flat list of RegisteredTool
4
- * entries. Mirrors buildAgentTools() in mcp/register.ts. */
5
- export declare function buildCredentialTools(client: ReclaimClient): RegisteredTool[];
@@ -1,18 +0,0 @@
1
- import { authenticateTool } from "./authenticate.js";
2
- import { importTool } from "./import.js";
3
- import { issueTool } from "./issue.js";
4
- import { listCachedTool } from "./list-cached.js";
5
- import { resolveOwnerKeyTool } from "./resolve-owner-key.js";
6
- import { statusTool } from "./status.js";
7
- /** Credential lifecycle tools — build the flat list of RegisteredTool
8
- * entries. Mirrors buildAgentTools() in mcp/register.ts. */
9
- export function buildCredentialTools(client) {
10
- return [
11
- authenticateTool(client),
12
- listCachedTool(),
13
- resolveOwnerKeyTool(),
14
- issueTool(),
15
- importTool(),
16
- statusTool(client),
17
- ];
18
- }
@@ -1,70 +0,0 @@
1
- export type CachedCredential = {
2
- address: string;
3
- privateKey: string;
4
- label?: string;
5
- orgId?: string;
6
- createdAt: string;
7
- /** Project dir where this credential was first created. */
8
- createdIn: string;
9
- /** All project dirs this credential has been used in ("used by"). */
10
- projectDirs: string[];
11
- };
12
- type CacheFile = {
13
- version: 1;
14
- credentials: CachedCredential[];
15
- };
16
- /**
17
- * Read the cache file. Returns an empty doc if missing. Surface-level
18
- * shape errors fall back to empty — we'd rather lose the cache than
19
- * crash the CLI on a corrupted file the user can re-create.
20
- */
21
- export declare function readCache(): CacheFile;
22
- /**
23
- * Write the cache file with strict permissions. The directory gets
24
- * `0700` and the file `0600` — same posture as `~/.ssh`. We rewrite
25
- * the whole doc each save; the file is tiny and the alternative
26
- * (append-only) loses our ability to deduplicate `projectDirs`.
27
- */
28
- export declare function writeCache(doc: CacheFile): void;
29
- /**
30
- * Upsert a credential entry. If a row already exists for `address`,
31
- * we merge the new `projectDirs` into the existing list, refresh
32
- * mutable fields, and keep the original `createdAt` / `createdIn`
33
- * (backfilling `createdIn` from the new entry when an old row lacks it).
34
- */
35
- export declare function upsertCredential(entry: CachedCredential): CachedCredential;
36
- /** Look up a cached credential by address. Case-insensitive. */
37
- export declare function findCached(address: string): CachedCredential | undefined;
38
- export type SuggestionReason = 'createdIn' | 'usedIn' | 'newest';
39
- export type CredentialSuggestion = {
40
- credential: CachedCredential;
41
- reason: SuggestionReason;
42
- };
43
- /**
44
- * Pick the best cached credential for `dir`. Ranking tiers:
45
- * 1. created in `dir` (reason: 'createdIn')
46
- * 2. previously used in `dir` (reason: 'usedIn')
47
- * 3. most recently created (reason: 'newest')
48
- * Within every tier, newest `createdAt` wins; address ascending is the
49
- * final deterministic tie-break. Returns undefined only on an empty cache.
50
- *
51
- * Pass a pre-read `creds` array to avoid a redundant `readCache()` (and to
52
- * rank against the same snapshot the caller already holds).
53
- */
54
- export declare function suggestCredentialForDir(dir: string, creds?: CachedCredential[]): CredentialSuggestion | undefined;
55
- /**
56
- * Resolve the private key to sign attestor proofs with (the claim
57
- * "owner"). Reuses the app credential rather than a dedicated key — for
58
- * build-time test proofs the developer is both the app and the proof
59
- * owner, and the owner identity is immaterial to whether the provider's
60
- * matching works.
61
- *
62
- * The owner is chosen up front (see the `resolve_owner_key` tool) and
63
- * passed by `address`; this just fetches the matching private key:
64
- * - the `RECLAIM_PRIVATE_KEY` env / project `.env` key, if it derives
65
- * to `address` (the dev pinned it), else
66
- * - the cached credential with that address.
67
- * Returns undefined when no key for `address` is known.
68
- */
69
- export declare function resolveOwnerPrivateKey(address: string): string | undefined;
70
- export {};
@@ -1,131 +0,0 @@
1
- import { deriveFromPrivateKey } from '@reclaimprotocol/client';
2
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from 'node:fs';
3
- import { credentialsCachePath, findProjectRoot, reclaimHomeDirPath } from "../../paths.js";
4
- import { readPrivateKeyFromEnvFile } from "./env-file.js";
5
- const EMPTY = { version: 1, credentials: [] };
6
- /**
7
- * Read the cache file. Returns an empty doc if missing. Surface-level
8
- * shape errors fall back to empty — we'd rather lose the cache than
9
- * crash the CLI on a corrupted file the user can re-create.
10
- */
11
- export function readCache() {
12
- const path = credentialsCachePath();
13
- if (!existsSync(path)) {
14
- return { ...EMPTY };
15
- }
16
- try {
17
- const raw = readFileSync(path, 'utf8');
18
- const parsed = JSON.parse(raw);
19
- if (parsed.version !== 1 || !Array.isArray(parsed.credentials)) {
20
- return { ...EMPTY };
21
- }
22
- return parsed;
23
- }
24
- catch {
25
- return { ...EMPTY };
26
- }
27
- }
28
- /**
29
- * Write the cache file with strict permissions. The directory gets
30
- * `0700` and the file `0600` — same posture as `~/.ssh`. We rewrite
31
- * the whole doc each save; the file is tiny and the alternative
32
- * (append-only) loses our ability to deduplicate `projectDirs`.
33
- */
34
- export function writeCache(doc) {
35
- const dir = reclaimHomeDirPath();
36
- if (!existsSync(dir)) {
37
- mkdirSync(dir, { recursive: true, mode: 0o700 });
38
- }
39
- chmodSync(dir, 0o700);
40
- const path = credentialsCachePath();
41
- writeFileSync(path, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 });
42
- chmodSync(path, 0o600);
43
- }
44
- /**
45
- * Upsert a credential entry. If a row already exists for `address`,
46
- * we merge the new `projectDirs` into the existing list, refresh
47
- * mutable fields, and keep the original `createdAt` / `createdIn`
48
- * (backfilling `createdIn` from the new entry when an old row lacks it).
49
- */
50
- export function upsertCredential(entry) {
51
- const doc = readCache();
52
- const idx = doc.credentials.findIndex((c) => c.address === entry.address.toLowerCase());
53
- const merged = {
54
- ...entry,
55
- address: entry.address.toLowerCase(),
56
- projectDirs: Array.from(new Set([
57
- ...(doc.credentials[idx]?.projectDirs ?? []),
58
- ...entry.projectDirs,
59
- ])),
60
- createdAt: doc.credentials[idx]?.createdAt ?? entry.createdAt,
61
- createdIn: doc.credentials[idx]?.createdIn ?? entry.createdIn,
62
- };
63
- if (idx >= 0) {
64
- doc.credentials[idx] = merged;
65
- }
66
- else {
67
- doc.credentials.unshift(merged);
68
- }
69
- writeCache(doc);
70
- return merged;
71
- }
72
- /** Look up a cached credential by address. Case-insensitive. */
73
- export function findCached(address) {
74
- const doc = readCache();
75
- const lc = address.toLowerCase();
76
- return doc.credentials.find((c) => c.address === lc);
77
- }
78
- /**
79
- * Pick the best cached credential for `dir`. Ranking tiers:
80
- * 1. created in `dir` (reason: 'createdIn')
81
- * 2. previously used in `dir` (reason: 'usedIn')
82
- * 3. most recently created (reason: 'newest')
83
- * Within every tier, newest `createdAt` wins; address ascending is the
84
- * final deterministic tie-break. Returns undefined only on an empty cache.
85
- *
86
- * Pass a pre-read `creds` array to avoid a redundant `readCache()` (and to
87
- * rank against the same snapshot the caller already holds).
88
- */
89
- export function suggestCredentialForDir(dir, creds = readCache().credentials) {
90
- if (creds.length === 0) {
91
- return undefined;
92
- }
93
- const byNewest = (a, b) => {
94
- return (b.createdAt ?? '').localeCompare(a.createdAt ?? '') ||
95
- a.address.localeCompare(b.address);
96
- };
97
- const createdHere = creds.filter((c) => c.createdIn === dir).sort(byNewest);
98
- if (createdHere[0]) {
99
- return { credential: createdHere[0], reason: 'createdIn' };
100
- }
101
- const usedHere = creds
102
- .filter((c) => c.projectDirs.includes(dir))
103
- .sort(byNewest);
104
- if (usedHere[0]) {
105
- return { credential: usedHere[0], reason: 'usedIn' };
106
- }
107
- return { credential: [...creds].sort(byNewest)[0], reason: 'newest' };
108
- }
109
- /**
110
- * Resolve the private key to sign attestor proofs with (the claim
111
- * "owner"). Reuses the app credential rather than a dedicated key — for
112
- * build-time test proofs the developer is both the app and the proof
113
- * owner, and the owner identity is immaterial to whether the provider's
114
- * matching works.
115
- *
116
- * The owner is chosen up front (see the `resolve_owner_key` tool) and
117
- * passed by `address`; this just fetches the matching private key:
118
- * - the `RECLAIM_PRIVATE_KEY` env / project `.env` key, if it derives
119
- * to `address` (the dev pinned it), else
120
- * - the cached credential with that address.
121
- * Returns undefined when no key for `address` is known.
122
- */
123
- export function resolveOwnerPrivateKey(address) {
124
- const target = address.toLowerCase();
125
- const envKey = process.env.RECLAIM_PRIVATE_KEY ??
126
- readPrivateKeyFromEnvFile(findProjectRoot(process.cwd()));
127
- if (envKey && deriveFromPrivateKey(envKey).address === target) {
128
- return envKey;
129
- }
130
- return findCached(target)?.privateKey;
131
- }
@@ -1,25 +0,0 @@
1
- export type EnvWriteResult = {
2
- envPath: string;
3
- gitignorePath: string;
4
- gitignoreAppended: boolean;
5
- };
6
- /**
7
- * Idempotently set `RECLAIM_PRIVATE_KEY` in the project's `.env`, then
8
- * `chmod 0600` it. The private key is the only secret we write — the
9
- * ETH address (and public key) are derived from it on demand, so there
10
- * is no separate address variable to keep in sync. Existing variables
11
- * are replaced in place; other lines are preserved verbatim so we
12
- * don't trample on unrelated config the user wrote by hand.
13
- *
14
- * Also appends `.env` to the project's `.gitignore` if it isn't
15
- * already listed.
16
- */
17
- export declare function writeAppCredentialsToEnv(projectDir: string, privateKey: string): EnvWriteResult;
18
- /**
19
- * Read `RECLAIM_PRIVATE_KEY` back out of the project's `.env`, if set.
20
- * Read live (not from `process.env`) so a credential written by
21
- * `issue_credentials` / `import_credentials` is picked up immediately,
22
- * without a Claude Code restart. Returns undefined when the file or the
23
- * variable is absent.
24
- */
25
- export declare function readPrivateKeyFromEnvFile(projectDir: string): string | undefined;
@@ -1,71 +0,0 @@
1
- import { appendFileSync, chmodSync, existsSync, readFileSync, writeFileSync, } from 'node:fs';
2
- import { join } from 'node:path';
3
- const PRIVATE_KEY = 'RECLAIM_PRIVATE_KEY';
4
- const GITIGNORE_LINE = '.env';
5
- /**
6
- * Idempotently set `RECLAIM_PRIVATE_KEY` in the project's `.env`, then
7
- * `chmod 0600` it. The private key is the only secret we write — the
8
- * ETH address (and public key) are derived from it on demand, so there
9
- * is no separate address variable to keep in sync. Existing variables
10
- * are replaced in place; other lines are preserved verbatim so we
11
- * don't trample on unrelated config the user wrote by hand.
12
- *
13
- * Also appends `.env` to the project's `.gitignore` if it isn't
14
- * already listed.
15
- */
16
- export function writeAppCredentialsToEnv(projectDir, privateKey) {
17
- const envPath = join(projectDir, '.env');
18
- const lines = existsSync(envPath)
19
- ? readFileSync(envPath, 'utf8').split('\n')
20
- : [];
21
- setOrInsert(lines, PRIVATE_KEY, privateKey);
22
- const body = lines.join('\n').replace(/\n+$/, '') + '\n';
23
- writeFileSync(envPath, body, { mode: 0o600 });
24
- chmodSync(envPath, 0o600);
25
- const gitignorePath = join(projectDir, '.gitignore');
26
- const gitignoreAppended = ensureLine(gitignorePath, GITIGNORE_LINE);
27
- return { envPath, gitignorePath, gitignoreAppended };
28
- }
29
- /**
30
- * Read `RECLAIM_PRIVATE_KEY` back out of the project's `.env`, if set.
31
- * Read live (not from `process.env`) so a credential written by
32
- * `issue_credentials` / `import_credentials` is picked up immediately,
33
- * without a Claude Code restart. Returns undefined when the file or the
34
- * variable is absent.
35
- */
36
- export function readPrivateKeyFromEnvFile(projectDir) {
37
- const envPath = join(projectDir, '.env');
38
- if (!existsSync(envPath)) {
39
- return undefined;
40
- }
41
- const prefix = `${PRIVATE_KEY}=`;
42
- const line = readFileSync(envPath, 'utf8')
43
- .split('\n')
44
- .find((l) => l.startsWith(prefix));
45
- const value = line?.slice(prefix.length).trim();
46
- return value || undefined;
47
- }
48
- function setOrInsert(lines, key, value) {
49
- const prefix = `${key}=`;
50
- const idx = lines.findIndex((l) => l.startsWith(prefix));
51
- const next = `${key}=${value}`;
52
- if (idx >= 0) {
53
- lines[idx] = next;
54
- return;
55
- }
56
- lines.push(next);
57
- }
58
- function ensureLine(path, line) {
59
- if (!existsSync(path)) {
60
- writeFileSync(path, line + '\n', { mode: 0o644 });
61
- return true;
62
- }
63
- const body = readFileSync(path, 'utf8');
64
- const present = body.split('\n').some((l) => l.trim() === line);
65
- if (present) {
66
- return false;
67
- }
68
- const suffix = body.endsWith('\n') ? '' : '\n';
69
- appendFileSync(path, suffix + line + '\n');
70
- return true;
71
- }
@@ -1,2 +0,0 @@
1
- import { type RegisteredTool } from '../server.ts';
2
- export declare function importTool(): RegisteredTool;
@@ -1,52 +0,0 @@
1
- import { deriveFromPrivateKey } from '@reclaimprotocol/client';
2
- import { findProjectRoot } from "../../paths.js";
3
- import { defineTool } from "../server.js";
4
- import { persistCredentialLocally } from "./register.js";
5
- export function importTool() {
6
- return defineTool({
7
- name: 'import_credentials',
8
- description: 'Import an existing Reclaim app credential the user ' +
9
- 'already holds elsewhere. Provide the private key ' +
10
- '(0x-prefixed hex, 64 chars); we derive the address ' +
11
- 'locally and cache it. By default also writes ' +
12
- 'RECLAIM_PRIVATE_KEY to the project .env (0600) and appends ' +
13
- '.env to .gitignore; pass `writeEnv: false` to keep it in ' +
14
- 'the local cache (memory) only and leave .env untouched. ' +
15
- 'ALWAYS ask the dev whether to save to .env before writing. ' +
16
- 'The credential stays local-only (SANDBOX); link it to an ' +
17
- 'org to use it in production.',
18
- inputSchema: {
19
- type: 'object',
20
- properties: {
21
- privateKey: {
22
- type: 'string',
23
- pattern: '^0x[0-9a-fA-F]{64}$',
24
- description: '0x-prefixed hex private key (64 hex chars / 32 bytes).',
25
- },
26
- label: {
27
- type: 'string',
28
- minLength: 1,
29
- maxLength: 100,
30
- },
31
- projectDir: {
32
- type: 'string',
33
- description: 'Project directory to write .env into. Defaults ' +
34
- 'to the closest ancestor of cwd containing ' +
35
- '.git or package.json.',
36
- },
37
- writeEnv: {
38
- type: 'boolean',
39
- description: 'Write RECLAIM_PRIVATE_KEY to the project .env ' +
40
- '(default true). Set false to cache in memory only, ' +
41
- 'without touching .env.',
42
- },
43
- },
44
- required: ['privateKey'],
45
- },
46
- }, async (args) => {
47
- const keypair = deriveFromPrivateKey(args.privateKey);
48
- const projectDir = findProjectRoot(args.projectDir || process.cwd());
49
- const persisted = persistCredentialLocally(keypair, args.label, projectDir, args.writeEnv ?? true);
50
- return { ...persisted };
51
- });
52
- }
@@ -1,2 +0,0 @@
1
- import { type RegisteredTool } from '../server.ts';
2
- export declare function issueTool(): RegisteredTool;
@@ -1,84 +0,0 @@
1
- import { generateKeypair } from '@reclaimprotocol/client';
2
- import { findProjectRoot } from "../../paths.js";
3
- import { defineTool } from "../server.js";
4
- import { findCached } from "./cache.js";
5
- import { persistCredentialLocally } from "./register.js";
6
- export function issueTool() {
7
- return defineTool({
8
- name: 'issue_credentials',
9
- description: 'Mint a fresh anonymous Reclaim app key-pair (or reuse ' +
10
- 'a cached one via `reuseCachedAppPk`) and cache it locally. ' +
11
- 'By default also writes RECLAIM_PRIVATE_KEY to the project ' +
12
- '.env (mode 0600) and appends .env to .gitignore; pass ' +
13
- '`writeEnv: false` to keep it in the local cache (memory) ' +
14
- 'only and leave .env untouched. ALWAYS ask the dev whether ' +
15
- 'to save to .env before writing it. The key-pair is ' +
16
- 'generated locally and is NOT registered with the server — ' +
17
- 'anonymous credentials operate in SANDBOX mode entirely ' +
18
- 'client-side. PREFER REUSE over generating a new credential ' +
19
- 'unless the user explicitly asks for a new app identity. To ' +
20
- 'use a credential for verification in production, link it to ' +
21
- 'an organization (via link_credential) and add billing.',
22
- inputSchema: {
23
- type: 'object',
24
- properties: {
25
- reuseCachedAppPk: {
26
- type: 'string',
27
- pattern: '^0x[0-9a-fA-F]{40}$',
28
- description: 'Lowercase ETH address of a cached credential ' +
29
- 'to reuse instead of minting a new one.',
30
- },
31
- label: {
32
- type: 'string',
33
- minLength: 1,
34
- maxLength: 100,
35
- description: 'Human label stored in the local cache.',
36
- },
37
- projectDir: {
38
- type: 'string',
39
- description: 'Project directory to write .env into. Defaults ' +
40
- 'to the closest ancestor of cwd containing ' +
41
- '.git or package.json.',
42
- },
43
- writeEnv: {
44
- type: 'boolean',
45
- description: 'Write RECLAIM_PRIVATE_KEY to the project .env ' +
46
- '(default true). Set false to cache the credential ' +
47
- 'in memory only, without touching .env.',
48
- },
49
- },
50
- },
51
- }, async (args) => {
52
- const projectDir = findProjectRoot(args.projectDir || process.cwd());
53
- let keypair;
54
- let reused = false;
55
- if (args.reuseCachedAppPk) {
56
- const cached = findCached(args.reuseCachedAppPk);
57
- if (!cached) {
58
- throw new Error(`No cached credential for ${args.reuseCachedAppPk}. ` +
59
- 'Call list_cached_credentials first.');
60
- }
61
- keypair = {
62
- address: cached.address,
63
- privateKey: cached.privateKey,
64
- };
65
- reused = true;
66
- }
67
- else {
68
- keypair = generateKeypair();
69
- }
70
- const writeEnv = args.writeEnv ?? true;
71
- const persisted = persistCredentialLocally(keypair, args.label, projectDir, writeEnv);
72
- return {
73
- reused,
74
- ...persisted,
75
- note: writeEnv
76
- ? 'Private key written to .env (and the local cache); it is ' +
77
- 'NOT in this response on purpose. The credential is ' +
78
- 'local-only (SANDBOX); link it to an org for production.'
79
- : 'Private key cached in memory only (.env untouched). Sign ' +
80
- 'proofs with it by passing run_proof({ ownerAddress }). The ' +
81
- 'credential is local-only (SANDBOX).',
82
- };
83
- });
84
- }