crowdcode-mcp 0.5.3 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -2
- package/dist/chunk-ZPDTU2RK.js +49 -0
- package/dist/chunk-ZPDTU2RK.js.map +1 -0
- package/dist/cli.js +65 -4
- package/dist/cli.js.map +1 -1
- package/dist/preferences-JBW45B4W.js +9 -0
- package/dist/preferences-JBW45B4W.js.map +1 -0
- package/dist/{server-RXQAIERP.js → server-Q6FUDOBY.js} +128 -24
- package/dist/server-Q6FUDOBY.js.map +1 -0
- package/dist/skills/crowdcode/SKILL.md +66 -9
- package/package.json +1 -1
- package/dist/server-RXQAIERP.js.map +0 -1
package/README.md
CHANGED
|
@@ -110,8 +110,10 @@ proofs from the *actual payment*, not from a directory listing:
|
|
|
110
110
|
|
|
111
111
|
### `request_service` — record unmet paid demand
|
|
112
112
|
|
|
113
|
-
|
|
114
|
-
service
|
|
113
|
+
Before the final answer, reflect on actual obstacles that a concrete paid
|
|
114
|
+
service could have solved. Describe precise inputs, deliverables, acceptance
|
|
115
|
+
criteria, and the value of paying. A specific improvement to an inadequate
|
|
116
|
+
existing service qualifies; an attempted purchase is not required.
|
|
115
117
|
|
|
116
118
|
### `get_review_signing_payload` — usually unnecessary
|
|
117
119
|
|
|
@@ -165,3 +167,65 @@ requires CrowdCode backend 0.5.0.
|
|
|
165
167
|
[repo]: https://github.com/sr33j/crowdcode-mcp
|
|
166
168
|
[scoring]: https://github.com/sr33j/crowdcode-mcp/blob/main/docs/SCORING.md
|
|
167
169
|
[agentcash]: https://www.npmjs.com/package/agentcash
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
## Controls and review history
|
|
173
|
+
|
|
174
|
+
With the local MCP client, say **"Crowdcode off"**, **"Crowdcode on"**,
|
|
175
|
+
**"show my reviews"**, or **"delete review 123"** to your agent. It uses:
|
|
176
|
+
|
|
177
|
+
- `crowdcode_status()` — effective setting and saved default.
|
|
178
|
+
- `set_crowdcode_enabled(enabled, scope="session"|"default")` — a session
|
|
179
|
+
override lasts for this MCP connection. `default` saves the choice and clears
|
|
180
|
+
this connection's override. Other connections keep their explicit overrides;
|
|
181
|
+
connections without overrides read the saved default on every operation.
|
|
182
|
+
- `list_my_reviews(before_id?, limit=25)` — signed wallet-owned history,
|
|
183
|
+
newest first. Continue with `next_before_id` until it is null.
|
|
184
|
+
- `delete_my_review(review_id)` — permanently delete the selected review
|
|
185
|
+
belonging to the local wallet, recompute reputation, and clear derived
|
|
186
|
+
summaries. Keeps only a hashed replay key, not the deleted text, wallet, or
|
|
187
|
+
raw payment reference. Repeated deletion is harmless.
|
|
188
|
+
|
|
189
|
+
Turning CrowdCode off blocks score checks, request/review submission, and review
|
|
190
|
+
signing locally, before wallet creation or backend calls. It does not change the
|
|
191
|
+
agent's spending permissions. History, deletion, and controls still work. No
|
|
192
|
+
activity is queued or backfilled when re-enabled. A host sharing one MCP process
|
|
193
|
+
across conversations shares the session override; this is not a universal chat ID.
|
|
194
|
+
The directly hosted stateless MCP endpoint has no local on/off setting.
|
|
195
|
+
|
|
196
|
+
CLI equivalents for the persistent default:
|
|
197
|
+
|
|
198
|
+
```bash
|
|
199
|
+
npx crowdcode-mcp on
|
|
200
|
+
npx crowdcode-mcp off
|
|
201
|
+
npx crowdcode-mcp status
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Preferences live in `~/.crowdcode/preferences.json`; `CROWDCODE_CONFIG_PATH`
|
|
205
|
+
overrides the path. History/deletion use the original reviewing wallet without
|
|
206
|
+
creating one, and locally sign an operation-specific proof that expires within
|
|
207
|
+
five minutes. A wallet address alone cannot authorize access or deletion.
|
|
208
|
+
|
|
209
|
+
## End-of-task service requests
|
|
210
|
+
|
|
211
|
+
Before the final answer, the agent reflects on concrete paid services that would
|
|
212
|
+
have improved the actual task: failures, poor output, costly workarounds, and
|
|
213
|
+
avoidable detours. A request describes exact inputs, deliverables, acceptance
|
|
214
|
+
criteria, the real obstacle, and the reason to pay. An inadequate existing service
|
|
215
|
+
qualifies only with a specific improvement. Actual payment or spending authority
|
|
216
|
+
is not required to report demand; do not invent a budget. Generic local compute
|
|
217
|
+
and tools that already worked well do not qualify. Submit nothing when no gap
|
|
218
|
+
qualifies; don't duplicate a gap or evade the existing five-per-day wallet limit.
|
|
219
|
+
|
|
220
|
+
The local client can create its usual unfunded AgentCash-compatible wallet for a
|
|
221
|
+
request unless `CROWDCODE_DISABLE_WALLET_CREATE=1`. It never funds or spends from
|
|
222
|
+
that wallet. Existing invalid wallet files are never overwritten.
|
|
223
|
+
|
|
224
|
+
Re-run the installer to refresh the skill. For Claude Code it also installs a
|
|
225
|
+
local `Stop` reminder in `~/.claude/settings.json`, preserving existing hooks.
|
|
226
|
+
The dependency-free script at `~/.crowdcode/hooks/completion.cjs` neither reads
|
|
227
|
+
transcripts nor makes network calls. It prompts once at completion, asks the
|
|
228
|
+
agent to check the effective setting, skips reflection when off, and does not
|
|
229
|
+
loop or interrupt background work. Other clients use the bundled skill, MCP
|
|
230
|
+
instructions, and tool-result reminders; completion behavior there is best effort
|
|
231
|
+
because MCP does not supply a universal conversation-complete event.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// src/preferences.ts
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
3
|
+
import { dirname, join } from "path";
|
|
4
|
+
import { homedir } from "os";
|
|
5
|
+
import { randomUUID } from "crypto";
|
|
6
|
+
function preferencesPath() {
|
|
7
|
+
return process.env.CROWDCODE_CONFIG_PATH ?? join(homedir(), ".crowdcode", "preferences.json");
|
|
8
|
+
}
|
|
9
|
+
var Preferences = class {
|
|
10
|
+
constructor(path = preferencesPath()) {
|
|
11
|
+
this.path = path;
|
|
12
|
+
}
|
|
13
|
+
path;
|
|
14
|
+
override;
|
|
15
|
+
async status() {
|
|
16
|
+
let defaultEnabled = true;
|
|
17
|
+
try {
|
|
18
|
+
const data = JSON.parse(await readFile(this.path, "utf8"));
|
|
19
|
+
if (typeof data.enabled !== "boolean") throw new Error("Invalid CrowdCode preferences");
|
|
20
|
+
defaultEnabled = data.enabled;
|
|
21
|
+
} catch (error) {
|
|
22
|
+
if (error.code !== "ENOENT") throw error;
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
enabled: this.override ?? defaultEnabled,
|
|
26
|
+
default_enabled: defaultEnabled,
|
|
27
|
+
scope: this.override === void 0 ? "default" : "session",
|
|
28
|
+
session_boundary: "this MCP connection"
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
async set(enabled, scope = "session") {
|
|
32
|
+
if (scope === "default") {
|
|
33
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
34
|
+
const temporary = `${this.path}.${randomUUID()}.tmp`;
|
|
35
|
+
await writeFile(temporary, JSON.stringify({ enabled }) + "\n", { mode: 384 });
|
|
36
|
+
await rename(temporary, this.path);
|
|
37
|
+
this.override = void 0;
|
|
38
|
+
} else {
|
|
39
|
+
this.override = enabled;
|
|
40
|
+
}
|
|
41
|
+
return this.status();
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export {
|
|
46
|
+
preferencesPath,
|
|
47
|
+
Preferences
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=chunk-ZPDTU2RK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/preferences.ts"],"sourcesContent":["import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\n\nexport function preferencesPath(): string {\n return process.env.CROWDCODE_CONFIG_PATH ?? join(homedir(), \".crowdcode\", \"preferences.json\");\n}\n\n/** One instance per stdio connection. A persistent default never stores session state. */\nexport class Preferences {\n private override: boolean | undefined;\n constructor(private readonly path = preferencesPath()) {}\n\n async status() {\n let defaultEnabled = true;\n try {\n const data = JSON.parse(await readFile(this.path, \"utf8\"));\n if (typeof data.enabled !== \"boolean\") throw new Error(\"Invalid CrowdCode preferences\");\n defaultEnabled = data.enabled;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n return { enabled: this.override ?? defaultEnabled, default_enabled: defaultEnabled,\n scope: this.override === undefined ? \"default\" : \"session\",\n session_boundary: \"this MCP connection\" };\n }\n\n async set(enabled: boolean, scope: \"session\" | \"default\" = \"session\") {\n if (scope === \"default\") {\n await mkdir(dirname(this.path), { recursive: true });\n const temporary = `${this.path}.${randomUUID()}.tmp`;\n await writeFile(temporary, JSON.stringify({ enabled }) + \"\\n\", { mode: 0o600 });\n await rename(temporary, this.path);\n this.override = undefined;\n } else {\n this.override = enabled;\n }\n return this.status();\n }\n}\n"],"mappings":";AAAA,SAAS,OAAO,UAAU,QAAQ,iBAAiB;AACnD,SAAS,SAAS,YAAY;AAC9B,SAAS,eAAe;AACxB,SAAS,kBAAkB;AAEpB,SAAS,kBAA0B;AACxC,SAAO,QAAQ,IAAI,yBAAyB,KAAK,QAAQ,GAAG,cAAc,kBAAkB;AAC9F;AAGO,IAAM,cAAN,MAAkB;AAAA,EAEvB,YAA6B,OAAO,gBAAgB,GAAG;AAA1B;AAAA,EAA2B;AAAA,EAA3B;AAAA,EADrB;AAAA,EAGR,MAAM,SAAS;AACb,QAAI,iBAAiB;AACrB,QAAI;AACF,YAAM,OAAO,KAAK,MAAM,MAAM,SAAS,KAAK,MAAM,MAAM,CAAC;AACzD,UAAI,OAAO,KAAK,YAAY,UAAW,OAAM,IAAI,MAAM,+BAA+B;AACtF,uBAAiB,KAAK;AAAA,IACxB,SAAS,OAAO;AACd,UAAK,MAAgC,SAAS,SAAU,OAAM;AAAA,IAChE;AACA,WAAO;AAAA,MAAE,SAAS,KAAK,YAAY;AAAA,MAAgB,iBAAiB;AAAA,MAClE,OAAO,KAAK,aAAa,SAAY,YAAY;AAAA,MACjD,kBAAkB;AAAA,IAAsB;AAAA,EAC5C;AAAA,EAEA,MAAM,IAAI,SAAkB,QAA+B,WAAW;AACpE,QAAI,UAAU,WAAW;AACvB,YAAM,MAAM,QAAQ,KAAK,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACnD,YAAM,YAAY,GAAG,KAAK,IAAI,IAAI,WAAW,CAAC;AAC9C,YAAM,UAAU,WAAW,KAAK,UAAU,EAAE,QAAQ,CAAC,IAAI,MAAM,EAAE,MAAM,IAAM,CAAC;AAC9E,YAAM,OAAO,WAAW,KAAK,IAAI;AACjC,WAAK,WAAW;AAAA,IAClB,OAAO;AACL,WAAK,WAAW;AAAA,IAClB;AACA,WAAO,KAAK,OAAO;AAAA,EACrB;AACF;","names":[]}
|
package/dist/cli.js
CHANGED
|
@@ -7,6 +7,24 @@ import {
|
|
|
7
7
|
import { rm as rm2, stat as stat2 } from "fs/promises";
|
|
8
8
|
import { createInterface } from "readline/promises";
|
|
9
9
|
|
|
10
|
+
// src/completion-hook.ts
|
|
11
|
+
var COMPLETION_HOOK = `
|
|
12
|
+
let input = '';
|
|
13
|
+
process.stdin.setEncoding('utf8');
|
|
14
|
+
process.stdin.on('data', chunk => { input += chunk; });
|
|
15
|
+
process.stdin.on('end', () => {
|
|
16
|
+
try {
|
|
17
|
+
const event = JSON.parse(input);
|
|
18
|
+
if (event.hook_event_name !== 'Stop' || event.stop_hook_active) return;
|
|
19
|
+
if (Array.isArray(event.background_tasks) && event.background_tasks.length) return;
|
|
20
|
+
process.stdout.write(JSON.stringify({
|
|
21
|
+
decision: 'block',
|
|
22
|
+
reason: "CrowdCode completion check (once only): read crowdcode_status. If off, unavailable, or this turn only managed CrowdCode settings/reviews, finish immediately without reflection or submissions. Otherwise, if you have not already reflected for this completed task, consider the real failures, poor results, excessive cost, and detours: what specific reusable service would have been worth paying for? Call request_service only for worthwhile unmet needs, describing exact inputs, deliverables, acceptance criteria, the real obstacle, and why the outcome justifies payment. A specific improvement to an inadequate existing service qualifies; no actual purchase is needed. Skip local Python/runtime wishes and services that already worked well. Never invent a budget or repeat a submitted gap. If nothing qualifies, submit nothing. Then finish; do not reopen the user's task."
|
|
23
|
+
}));
|
|
24
|
+
} catch { /* A broken optional reminder must never trap the user. */ }
|
|
25
|
+
});
|
|
26
|
+
`;
|
|
27
|
+
|
|
10
28
|
// src/installer.ts
|
|
11
29
|
import { createHash } from "crypto";
|
|
12
30
|
import {
|
|
@@ -282,6 +300,22 @@ function mergeJsonMcpConfig(content, path = "config.json") {
|
|
|
282
300
|
return `${JSON.stringify(config, null, 2)}
|
|
283
301
|
`;
|
|
284
302
|
}
|
|
303
|
+
async function installCompletionHook(env) {
|
|
304
|
+
const settingsPath = join(env.homeDir, ".claude", "settings.json");
|
|
305
|
+
const settings = parseJsonConfig(await readOptional(settingsPath) ?? "{}", settingsPath);
|
|
306
|
+
const hooks = settings.hooks ?? {};
|
|
307
|
+
if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) throw new Error("Invalid Claude hooks settings");
|
|
308
|
+
const hookMap = hooks;
|
|
309
|
+
const stop = hookMap.Stop ?? [];
|
|
310
|
+
if (!Array.isArray(stop)) throw new Error("Invalid Claude Stop hooks settings");
|
|
311
|
+
const hookPath = join(env.homeDir, ".crowdcode", "hooks", "completion.cjs");
|
|
312
|
+
const installed = stop.some((entry) => Array.isArray(entry?.hooks) && entry.hooks.some((hook) => hook.type === "command" && hook.command === "node" && Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));
|
|
313
|
+
if (!installed) hookMap.Stop = [...stop, { hooks: [{ type: "command", command: "node", args: [hookPath], timeout: 5 }] }];
|
|
314
|
+
settings.hooks = hookMap;
|
|
315
|
+
await atomicWrite(hookPath, COMPLETION_HOOK);
|
|
316
|
+
const next = JSON.stringify(settings, null, 2) + "\n";
|
|
317
|
+
if (next !== await readOptional(settingsPath)) await atomicWrite(settingsPath, next);
|
|
318
|
+
}
|
|
285
319
|
async function configureClient(client, env) {
|
|
286
320
|
const path = getClientConfigPath(client, env);
|
|
287
321
|
const current = await readOptional(path) ?? "";
|
|
@@ -309,6 +343,7 @@ async function installForClients(clients, input = {}) {
|
|
|
309
343
|
let claudeMode = null;
|
|
310
344
|
if (clients.includes("claude-code")) {
|
|
311
345
|
claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);
|
|
346
|
+
await installCompletionHook(env);
|
|
312
347
|
}
|
|
313
348
|
const results = [];
|
|
314
349
|
for (const client of clients) {
|
|
@@ -364,7 +399,22 @@ async function doctorClients(clients = CORE_CLIENTS, input = {}) {
|
|
|
364
399
|
if (client === "claude-code") {
|
|
365
400
|
const skillPath = claudeCodeSkillDir(env.homeDir);
|
|
366
401
|
const skillCurrent = await readOptional(join(skillPath, "SKILL.md")) === expectedSkill;
|
|
367
|
-
|
|
402
|
+
let completionHookCurrent = false;
|
|
403
|
+
try {
|
|
404
|
+
const settings = JSON.parse(await readOptional(join(env.homeDir, ".claude", "settings.json")) ?? "{}");
|
|
405
|
+
const hookPath = join(env.homeDir, ".crowdcode", "hooks", "completion.cjs");
|
|
406
|
+
completionHookCurrent = await readOptional(hookPath) === COMPLETION_HOOK && Array.isArray(settings.hooks?.Stop) && settings.hooks.Stop.some((entry) => Array.isArray(entry?.hooks) && entry.hooks.some((hook) => hook.type === "command" && hook.command === "node" && Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));
|
|
407
|
+
} catch {
|
|
408
|
+
}
|
|
409
|
+
results.push({
|
|
410
|
+
client,
|
|
411
|
+
configPath,
|
|
412
|
+
mcpConfigured,
|
|
413
|
+
skillPath,
|
|
414
|
+
skillCurrent,
|
|
415
|
+
completionHookCurrent,
|
|
416
|
+
...!completionHookCurrent ? { detail: "Re-run install --client claude-code to refresh the completion reminder." } : {}
|
|
417
|
+
});
|
|
368
418
|
} else if (client === "claude-desktop") {
|
|
369
419
|
results.push({
|
|
370
420
|
client,
|
|
@@ -537,7 +587,7 @@ async function runDoctor(args) {
|
|
|
537
587
|
const results = await doctorClients(clients);
|
|
538
588
|
let healthy = true;
|
|
539
589
|
for (const result of results) {
|
|
540
|
-
const ok = result.mcpConfigured && result.skillCurrent;
|
|
590
|
+
const ok = result.mcpConfigured && result.skillCurrent && result.completionHookCurrent !== false;
|
|
541
591
|
healthy &&= ok;
|
|
542
592
|
console.error(
|
|
543
593
|
`${ok ? "ok" : "missing/stale"} ${result.client} MCP=${result.mcpConfigured ? "ok" : "missing"} skill=${result.skillCurrent ? "ok" : "missing/stale"}`
|
|
@@ -548,8 +598,10 @@ async function runDoctor(args) {
|
|
|
548
598
|
}
|
|
549
599
|
function printHelp() {
|
|
550
600
|
console.error(
|
|
551
|
-
`usage: crowdcode-mcp [serve|install|doctor|check <text>|clear-cache]
|
|
601
|
+
`usage: crowdcode-mcp [serve|on|off|status|install|doctor|check <text>|clear-cache]
|
|
552
602
|
serve start the stdio MCP server (default)
|
|
603
|
+
on/off save CrowdCode default (active session overrides take precedence)
|
|
604
|
+
status show the saved default for new connections
|
|
553
605
|
install install the CrowdCode skill and MCP config
|
|
554
606
|
[--client <client>] [--all-detected] [--yes]
|
|
555
607
|
doctor verify skill and MCP config [--client <client>] [--all-detected]
|
|
@@ -564,10 +616,19 @@ async function main() {
|
|
|
564
616
|
case void 0:
|
|
565
617
|
case "serve": {
|
|
566
618
|
routeStdoutToStderr();
|
|
567
|
-
const { startServer } = await import("./server-
|
|
619
|
+
const { startServer } = await import("./server-Q6FUDOBY.js");
|
|
568
620
|
await startServer();
|
|
569
621
|
break;
|
|
570
622
|
}
|
|
623
|
+
case "on":
|
|
624
|
+
case "off":
|
|
625
|
+
case "status": {
|
|
626
|
+
const { Preferences } = await import("./preferences-JBW45B4W.js");
|
|
627
|
+
const preferences = new Preferences();
|
|
628
|
+
const state = command === "status" ? await preferences.status() : await preferences.set(command === "on", "default");
|
|
629
|
+
console.log(JSON.stringify(state));
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
571
632
|
case "check":
|
|
572
633
|
await runCheck(rest.length > 0 ? rest.join(" ") : void 0);
|
|
573
634
|
break;
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/installer.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * crowdcode-mcp — CrowdCode MCP client with local-first PII redaction.\n *\n * Subcommands:\n * (none) | serve start the stdio MCP server (default)\n * install install the skill and configure supported agents\n * doctor verify skill and MCP installation state\n * check [text] show what the redaction pipeline does to sample text\n * clear-cache delete the downloaded model cache\n */\n\nimport { rm, stat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline/promises\";\nimport { getConfig } from \"./config.js\";\nimport {\n CORE_CLIENTS,\n detectClients,\n doctorClients,\n installForClients,\n type ClientId,\n} from \"./installer.js\";\n\n// stdout carries the MCP protocol in serve mode; anything that would print\n// there (transformers download progress, stray library logs) corrupts it.\n// Patch before any heavy import happens.\nfunction routeStdoutToStderr(): void {\n console.log = (...args: unknown[]) => console.error(...args);\n console.info = (...args: unknown[]) => console.error(...args);\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nasync function runCheck(argText: string | undefined): Promise<void> {\n const config = getConfig();\n const text = argText ?? (await readStdin());\n if (!text.trim()) {\n console.error('usage: crowdcode-mcp check \"some text\" (or pipe via stdin)');\n process.exit(2);\n }\n\n const { RedactionEngine } = await import(\"@crowdcode/redaction\");\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n\n if (!config.disableModel) {\n console.error(\n \"loading PII model (downloads ~15 MB to \" +\n config.cacheDir +\n \" on first run; deterministic recognizers work without it) ...\",\n );\n await engine.waitForModel();\n }\n\n const result = await engine.redact(text);\n const revealed = await engine.reveal(result.text);\n\n console.error(\"\");\n console.error(\"input: \" + JSON.stringify(text));\n console.error(\"redacted: \" + JSON.stringify(result.text));\n console.error(\"revealed: \" + JSON.stringify(revealed) + \" (local round-trip)\");\n console.error(\"\");\n console.error(\n `entities removed: ${result.entitiesRemoved} model active: ${result.modelActive}`,\n );\n console.error(\n \"only the redacted form would ever be sent to the CrowdCode backend.\",\n );\n}\n\nasync function runClearCache(): Promise<void> {\n const config = getConfig();\n try {\n await stat(config.cacheDir);\n } catch {\n console.error(`nothing to clear (${config.cacheDir} does not exist)`);\n return;\n }\n await rm(config.cacheDir, { recursive: true, force: true });\n console.error(`cleared ${config.cacheDir}`);\n}\n\ninterface InstallerFlags {\n clients: ClientId[];\n allDetected: boolean;\n yes: boolean;\n}\n\nfunction parseInstallerFlags(args: string[]): InstallerFlags {\n const clients: ClientId[] = [];\n let allDetected = false;\n let yes = false;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index]!;\n if (arg === \"--yes\" || arg === \"-y\") {\n yes = true;\n continue;\n }\n if (arg === \"--all-detected\") {\n allDetected = true;\n continue;\n }\n let value: string | undefined;\n if (arg === \"--client\") {\n value = args[++index];\n if (!value) throw new Error(\"--client requires a client identifier\");\n } else if (arg.startsWith(\"--client=\")) {\n value = arg.slice(\"--client=\".length);\n } else {\n throw new Error(`unknown install option: ${arg}`);\n }\n for (const candidate of value.split(\",\")) {\n if (!(CORE_CLIENTS as readonly string[]).includes(candidate)) {\n throw new Error(\n `unknown client ${JSON.stringify(candidate)}; use ${CORE_CLIENTS.join(\", \")}`,\n );\n }\n if (!clients.includes(candidate as ClientId)) clients.push(candidate as ClientId);\n }\n }\n if (allDetected && clients.length > 0) {\n throw new Error(\"use either --all-detected or --client, not both\");\n }\n return { clients, allDetected, yes };\n}\n\nasync function chooseInstallClients(flags: InstallerFlags): Promise<ClientId[]> {\n if (flags.clients.length > 0) return flags.clients;\n const detected = await detectClients();\n if (flags.allDetected) {\n if (detected.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n return detected;\n }\n if (flags.yes || !process.stdin.isTTY || !process.stderr.isTTY) {\n return detected.length > 0 ? detected : [...CORE_CLIENTS];\n }\n\n const defaults = detected.length > 0 ? detected : [...CORE_CLIENTS];\n console.error(\"Supported clients:\");\n CORE_CLIENTS.forEach((client, index) => {\n console.error(` ${index + 1}. ${client}${detected.includes(client) ? \" (detected)\" : \"\"}`);\n });\n const prompt = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await prompt.question(\n `Install for comma-separated names/numbers [${defaults.join(\",\")}]: `,\n );\n if (!answer.trim()) return defaults;\n const selected: ClientId[] = [];\n for (const token of answer.split(\",\").map((item) => item.trim())) {\n const numbered = Number(token);\n const client = Number.isInteger(numbered)\n ? CORE_CLIENTS[numbered - 1]\n : (token as ClientId);\n if (!client || !(CORE_CLIENTS as readonly string[]).includes(client)) {\n throw new Error(`unknown client selection: ${token}`);\n }\n if (!selected.includes(client)) selected.push(client);\n }\n return selected;\n } finally {\n prompt.close();\n }\n}\n\nasync function runInstall(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients = await chooseInstallClients(flags);\n const results = await installForClients(clients);\n console.error(\"CrowdCode installation complete:\");\n for (const result of results) {\n console.error(\n ` ${result.client}: MCP ${result.configPath}; skill ${result.skillPath} (${result.skillMode})`,\n );\n }\n console.error(\"Restart these clients so they reload the CrowdCode skill and MCP server.\");\n}\n\nasync function runDoctor(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients =\n flags.clients.length > 0\n ? flags.clients\n : flags.allDetected\n ? await detectClients()\n : [...CORE_CLIENTS];\n if (clients.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n const results = await doctorClients(clients);\n let healthy = true;\n for (const result of results) {\n const ok = result.mcpConfigured && result.skillCurrent;\n healthy &&= ok;\n console.error(\n `${ok ? \"ok\" : \"missing/stale\"} ${result.client}` +\n ` MCP=${result.mcpConfigured ? \"ok\" : \"missing\"}` +\n ` skill=${result.skillCurrent ? \"ok\" : \"missing/stale\"}`,\n );\n if (result.detail) console.error(` ${result.detail}`);\n }\n if (!healthy) process.exitCode = 1;\n}\n\nfunction printHelp(): void {\n console.error(\n \"usage: crowdcode-mcp [serve|install|doctor|check <text>|clear-cache]\\n\" +\n \" serve start the stdio MCP server (default)\\n\" +\n \" install install the CrowdCode skill and MCP config\\n\" +\n \" [--client <client>] [--all-detected] [--yes]\\n\" +\n \" doctor verify skill and MCP config [--client <client>] [--all-detected]\\n\" +\n \" check demo the local redaction pipeline on sample text\\n\" +\n \" clear-cache delete the downloaded model cache\\n\" +\n ` clients ${CORE_CLIENTS.join(\", \")}`,\n );\n}\n\nasync function main(): Promise<void> {\n const [, , command, ...rest] = process.argv;\n switch (command) {\n case undefined:\n case \"serve\": {\n routeStdoutToStderr();\n const { startServer } = await import(\"./server.js\");\n await startServer();\n break;\n }\n case \"check\":\n await runCheck(rest.length > 0 ? rest.join(\" \") : undefined);\n break;\n case \"install\":\n await runInstall(rest);\n break;\n case \"doctor\":\n await runDoctor(rest);\n break;\n case \"clear-cache\":\n await runClearCache();\n break;\n case \"--help\":\n case \"-h\":\n printHelp();\n break;\n default:\n console.error(`unknown command: ${command} (try --help)`);\n process.exit(2);\n }\n}\n\nmain().catch((err) => {\n console.error(\"crowdcode-mcp fatal:\", err);\n process.exit(1);\n});\n","import { createHash } from \"node:crypto\";\nimport {\n copyFile,\n lstat,\n mkdir,\n readFile,\n readlink,\n rename,\n rm,\n stat,\n symlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport const CORE_CLIENTS = [\n \"codex\",\n \"claude-code\",\n \"claude-desktop\",\n \"cursor\",\n] as const;\n\nexport type ClientId = (typeof CORE_CLIENTS)[number];\nexport type InstallerPlatform = \"darwin\" | \"linux\" | \"win32\";\n\nexport interface InstallerEnvironment {\n homeDir?: string;\n platform?: InstallerPlatform;\n env?: NodeJS.ProcessEnv;\n packageRoot?: string;\n now?: () => Date;\n}\n\ninterface InstallState {\n packageVersion: string;\n skillHash: string;\n installedAt: string;\n}\n\nexport interface ClientInstallResult {\n client: ClientId;\n configPath: string;\n skillPath: string;\n skillMode: \"canonical\" | \"symlink\" | \"copy\" | \"mcp-instructions\";\n}\n\nexport interface DoctorResult {\n client: ClientId;\n configPath: string;\n mcpConfigured: boolean;\n skillPath: string;\n skillCurrent: boolean;\n detail?: string;\n}\n\nconst MCP_SERVER = {\n command: \"npx\",\n args: [\"-y\", \"crowdcode-mcp@latest\"],\n};\n\nfunction resolvedEnvironment(input: InstallerEnvironment = {}) {\n const platform = input.platform ?? process.platform;\n if (platform !== \"darwin\" && platform !== \"linux\" && platform !== \"win32\") {\n throw new Error(`unsupported platform: ${platform}`);\n }\n return {\n homeDir: input.homeDir ?? homedir(),\n platform,\n env: input.env ?? process.env,\n packageRoot: input.packageRoot ?? findPackageRoot(import.meta.url),\n now: input.now ?? (() => new Date()),\n };\n}\n\nfunction findPackageRoot(moduleUrl: string): string {\n // installer.ts lives in src during development and is bundled into dist/cli.js\n // for publication. Both locations are exactly one directory below package.json.\n return resolve(dirname(fileURLToPath(moduleUrl)), \"..\");\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function lexists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readOptional(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nfunction hash(content: string): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nasync function packageVersion(packageRoot: string): Promise<string> {\n const parsed = JSON.parse(await readFile(join(packageRoot, \"package.json\"), \"utf8\"));\n if (typeof parsed.version !== \"string\") {\n throw new Error(\"crowdcode-mcp package.json has no version\");\n }\n return parsed.version;\n}\n\nasync function bundledSkill(packageRoot: string): Promise<string> {\n const packaged = join(packageRoot, \"dist\", \"skills\", \"crowdcode\", \"SKILL.md\");\n const content = await readOptional(packaged);\n if (content !== null) return content;\n\n // Development fallback. Published packages always use the dist asset.\n const source = resolve(packageRoot, \"../../skills/crowdcode/SKILL.md\");\n return readFile(source, \"utf8\");\n}\n\nfunction statePath(homeDir: string): string {\n return join(homeDir, \".crowdcode\", \"install-state.json\");\n}\n\nfunction canonicalSkillDir(homeDir: string): string {\n return join(homeDir, \".agents\", \"skills\", \"crowdcode\");\n}\n\nasync function loadState(homeDir: string): Promise<InstallState | null> {\n const raw = await readOptional(statePath(homeDir));\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<InstallState>;\n if (\n typeof parsed.packageVersion === \"string\" &&\n typeof parsed.skillHash === \"string\" &&\n typeof parsed.installedAt === \"string\"\n ) {\n return parsed as InstallState;\n }\n } catch {\n // Treat malformed state as unmanaged; user content is backed up below.\n }\n return null;\n}\n\nasync function atomicWrite(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temp = join(\n dirname(path),\n `.${basename(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n await writeFile(temp, content, { mode: 0o600 });\n try {\n await rename(temp, path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nfunction backupSuffix(now: Date): string {\n return now.toISOString().replace(/[:.]/g, \"-\");\n}\n\nasync function unusedBackupPath(path: string, now: Date): Promise<string> {\n const base = `${path}.backup-${backupSuffix(now)}`;\n let candidate = base;\n for (let index = 2; await lexists(candidate); index += 1) {\n candidate = `${base}-${index}`;\n }\n return candidate;\n}\n\nasync function replaceSkillDirectory(\n path: string,\n skill: string,\n managedHash: string | null,\n now: Date,\n): Promise<void> {\n let existingSkill: string | null;\n try {\n existingSkill = await readOptional(join(path, \"SKILL.md\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOTDIR\") existingSkill = null;\n else throw error;\n }\n const newHash = hash(skill);\n if (existingSkill !== null && hash(existingSkill) === newHash) return;\n\n if (await lexists(path)) {\n const existingIsManaged =\n existingSkill !== null && managedHash !== null && hash(existingSkill) === managedHash;\n if (existingIsManaged) {\n await rm(path, { recursive: true, force: true });\n } else {\n await rename(path, await unusedBackupPath(path, now));\n }\n }\n\n const temp = `${path}.installing-${process.pid}`;\n await rm(temp, { recursive: true, force: true });\n await mkdir(temp, { recursive: true });\n await writeFile(join(temp, \"SKILL.md\"), skill);\n await rename(temp, path);\n}\n\nasync function installCanonicalSkill(env: ReturnType<typeof resolvedEnvironment>) {\n const skill = await bundledSkill(env.packageRoot);\n const previous = await loadState(env.homeDir);\n const path = canonicalSkillDir(env.homeDir);\n await mkdir(dirname(path), { recursive: true });\n await replaceSkillDirectory(path, skill, previous?.skillHash ?? null, env.now());\n\n const nextState: InstallState = {\n packageVersion: await packageVersion(env.packageRoot),\n skillHash: hash(skill),\n installedAt: env.now().toISOString(),\n };\n await atomicWrite(statePath(env.homeDir), `${JSON.stringify(nextState, null, 2)}\\n`);\n return { path, skill, state: nextState };\n}\n\nfunction claudeCodeSkillDir(homeDir: string): string {\n return join(homeDir, \".claude\", \"skills\", \"crowdcode\");\n}\n\nasync function installClaudeCodeSkill(\n env: ReturnType<typeof resolvedEnvironment>,\n canonicalPath: string,\n skill: string,\n): Promise<\"symlink\" | \"copy\"> {\n const target = claudeCodeSkillDir(env.homeDir);\n await mkdir(dirname(target), { recursive: true });\n\n let targetManaged = false;\n try {\n const targetStat = await lstat(target);\n if (targetStat.isSymbolicLink()) {\n const link = await readlink(target);\n targetManaged = resolve(dirname(target), link) === canonicalPath;\n } else {\n const current = await readOptional(join(target, \"SKILL.md\"));\n targetManaged = current !== null && hash(current) === hash(skill);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n\n if (await lexists(target)) {\n if (targetManaged) await rm(target, { recursive: true, force: true });\n else await rename(target, await unusedBackupPath(target, env.now()));\n }\n\n if (env.platform !== \"win32\") {\n try {\n await symlink(relative(dirname(target), canonicalPath), target, \"dir\");\n return \"symlink\";\n } catch {\n // Some filesystems disallow symlinks. Fall through to a portable copy.\n }\n }\n\n await mkdir(target, { recursive: true });\n await copyFile(join(canonicalPath, \"SKILL.md\"), join(target, \"SKILL.md\"));\n return \"copy\";\n}\n\nfunction configBase(\n homeDir: string,\n platform: InstallerPlatform,\n env: NodeJS.ProcessEnv,\n): string {\n if (platform === \"win32\") {\n return env.APPDATA ?? join(homeDir, \"AppData\", \"Roaming\");\n }\n if (platform === \"darwin\") return join(homeDir, \"Library\", \"Application Support\");\n return env.XDG_CONFIG_HOME ?? join(homeDir, \".config\");\n}\n\nexport function getClientConfigPath(\n client: ClientId,\n input: InstallerEnvironment = {},\n): string {\n const env = resolvedEnvironment(input);\n switch (client) {\n case \"codex\":\n return join(env.env.CODEX_HOME ?? join(env.homeDir, \".codex\"), \"config.toml\");\n case \"claude-code\":\n return join(env.homeDir, \".claude.json\");\n case \"cursor\":\n return join(env.homeDir, \".cursor\", \"mcp.json\");\n case \"claude-desktop\":\n return join(\n configBase(env.homeDir, env.platform, env.env),\n \"Claude\",\n \"claude_desktop_config.json\",\n );\n }\n}\n\nfunction removeCrowdCodeTomlSection(content: string): string {\n const lines = content.split(/\\r?\\n/);\n const kept: string[] = [];\n let skipping = false;\n for (const line of lines) {\n const section = /^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/.exec(line);\n if (section) {\n const normalized = section[1]!.replace(/[\"']/g, \"\").replace(/\\s/g, \"\");\n skipping =\n normalized === \"mcp_servers.crowdcode\" ||\n normalized.startsWith(\"mcp_servers.crowdcode.\");\n if (skipping) continue;\n }\n if (!skipping) kept.push(line);\n }\n return kept.join(\"\\n\").trimEnd();\n}\n\nexport function mergeCodexConfig(content: string): string {\n const before = removeCrowdCodeTomlSection(content);\n const section = [\n \"[mcp_servers.crowdcode]\",\n `command = ${JSON.stringify(MCP_SERVER.command)}`,\n `args = ${JSON.stringify(MCP_SERVER.args)}`,\n ].join(\"\\n\");\n return `${before ? `${before}\\n\\n` : \"\"}${section}\\n`;\n}\n\nfunction parseJsonConfig(content: string, path: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(content) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"root must be an object\");\n }\n return parsed as Record<string, unknown>;\n } catch (error) {\n throw new Error(`cannot parse ${path}; no changes were written: ${(error as Error).message}`);\n }\n}\n\nexport function mergeJsonMcpConfig(content: string, path = \"config.json\"): string {\n const config = content.trim() ? parseJsonConfig(content, path) : {};\n const current = config.mcpServers;\n if (current !== undefined && (current === null || typeof current !== \"object\" || Array.isArray(current))) {\n throw new Error(`${path} has a non-object mcpServers value; no changes were written`);\n }\n config.mcpServers = {\n ...((current as Record<string, unknown> | undefined) ?? {}),\n crowdcode: MCP_SERVER,\n };\n return `${JSON.stringify(config, null, 2)}\\n`;\n}\n\nasync function configureClient(\n client: ClientId,\n env: ReturnType<typeof resolvedEnvironment>,\n): Promise<string> {\n const path = getClientConfigPath(client, env);\n const current = (await readOptional(path)) ?? \"\";\n const next =\n client === \"codex\" ? mergeCodexConfig(current) : mergeJsonMcpConfig(current, path);\n if (next !== current) await atomicWrite(path, next);\n return path;\n}\n\nexport async function detectClients(\n input: InstallerEnvironment = {},\n): Promise<ClientId[]> {\n const env = resolvedEnvironment(input);\n const markers: Record<ClientId, string[]> = {\n codex: [env.env.CODEX_HOME ?? join(env.homeDir, \".codex\")],\n \"claude-code\": [join(env.homeDir, \".claude\"), join(env.homeDir, \".claude.json\")],\n cursor: [join(env.homeDir, \".cursor\")],\n \"claude-desktop\": [dirname(getClientConfigPath(\"claude-desktop\", env))],\n };\n const detected: ClientId[] = [];\n for (const client of CORE_CLIENTS) {\n if ((await Promise.all(markers[client].map(exists))).some(Boolean)) detected.push(client);\n }\n return detected;\n}\n\nexport async function installForClients(\n clients: readonly ClientId[],\n input: InstallerEnvironment = {},\n): Promise<ClientInstallResult[]> {\n const env = resolvedEnvironment(input);\n const canonical = await installCanonicalSkill(env);\n let claudeMode: \"symlink\" | \"copy\" | null = null;\n if (clients.includes(\"claude-code\")) {\n claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);\n }\n\n const results: ClientInstallResult[] = [];\n for (const client of clients) {\n const configPath = await configureClient(client, env);\n if (client === \"claude-code\") {\n results.push({\n client,\n configPath,\n skillPath: claudeCodeSkillDir(env.homeDir),\n skillMode: claudeMode!,\n });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n skillPath: \"MCP initialize instructions\",\n skillMode: \"mcp-instructions\",\n });\n } else {\n results.push({\n client,\n configPath,\n skillPath: canonical.path,\n skillMode: \"canonical\",\n });\n }\n }\n return results;\n}\n\nfunction jsonHasCrowdCode(content: string): boolean {\n try {\n const parsed = JSON.parse(content) as {\n mcpServers?: Record<string, { command?: string; args?: string[] }>;\n };\n const server = parsed.mcpServers?.crowdcode;\n return server?.command === MCP_SERVER.command &&\n JSON.stringify(server.args) === JSON.stringify(MCP_SERVER.args);\n } catch {\n return false;\n }\n}\n\nfunction codexHasCrowdCode(content: string): boolean {\n const merged = removeCrowdCodeTomlSection(content);\n return merged !== content.trimEnd() &&\n /\\[mcp_servers\\.(?:[\"']?crowdcode[\"']?)\\]/.test(content) &&\n /crowdcode-mcp@latest/.test(content);\n}\n\nexport async function doctorClients(\n clients: readonly ClientId[] = CORE_CLIENTS,\n input: InstallerEnvironment = {},\n): Promise<DoctorResult[]> {\n const env = resolvedEnvironment(input);\n const expectedSkill = await bundledSkill(env.packageRoot);\n const canonicalPath = canonicalSkillDir(env.homeDir);\n const canonicalCurrent =\n (await readOptional(join(canonicalPath, \"SKILL.md\"))) === expectedSkill;\n const results: DoctorResult[] = [];\n\n for (const client of clients) {\n const configPath = getClientConfigPath(client, env);\n const config = (await readOptional(configPath)) ?? \"\";\n const mcpConfigured =\n client === \"codex\" ? codexHasCrowdCode(config) : jsonHasCrowdCode(config);\n if (client === \"claude-code\") {\n const skillPath = claudeCodeSkillDir(env.homeDir);\n const skillCurrent =\n (await readOptional(join(skillPath, \"SKILL.md\"))) === expectedSkill;\n results.push({ client, configPath, mcpConfigured, skillPath, skillCurrent });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: \"MCP initialize instructions\",\n skillCurrent: mcpConfigured,\n detail: \"Claude Desktop uses CrowdCode's MCP initialization instructions.\",\n });\n } else {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: canonicalPath,\n skillCurrent: canonicalCurrent,\n });\n }\n }\n return results;\n}\n"],"mappings":";;;;;;AAYA,SAAS,MAAAA,KAAI,QAAAC,aAAY;AACzB,SAAS,uBAAuB;;;ACbhC,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAC3D,SAAS,qBAAqB;AAEvB,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAmCA,IAAM,aAAa;AAAA,EACjB,SAAS;AAAA,EACT,MAAM,CAAC,MAAM,sBAAsB;AACrC;AAEA,SAAS,oBAAoB,QAA8B,CAAC,GAAG;AAC7D,QAAM,WAAW,MAAM,YAAY,QAAQ;AAC3C,MAAI,aAAa,YAAY,aAAa,WAAW,aAAa,SAAS;AACzE,UAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,EACrD;AACA,SAAO;AAAA,IACL,SAAS,MAAM,WAAW,QAAQ;AAAA,IAClC;AAAA,IACA,KAAK,MAAM,OAAO,QAAQ;AAAA,IAC1B,aAAa,MAAM,eAAe,gBAAgB,YAAY,GAAG;AAAA,IACjE,KAAK,MAAM,QAAQ,MAAM,oBAAI,KAAK;AAAA,EACpC;AACF;AAEA,SAAS,gBAAgB,WAA2B;AAGlD,SAAO,QAAQ,QAAQ,cAAc,SAAS,C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,IAAI,MAAM,OAAO,sBAAa;AAClD,YAAM,YAAY;AAClB;AAAA,IACF;AAAA,IACA,KAAK;AACH,YAAM,SAAS,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,MAAS;AAC3D;AAAA,IACF,KAAK;AACH,YAAM,WAAW,IAAI;AACrB;AAAA,IACF,KAAK;AACH,YAAM,UAAU,IAAI;AACpB;AAAA,IACF,KAAK;AACH,YAAM,cAAc;AACpB;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,gBAAU;AACV;AAAA,IACF;AACE,cAAQ,MAAM,oBAAoB,OAAO,eAAe;AACxD,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,wBAAwB,GAAG;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["rm","stat","stat","rm"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/completion-hook.ts","../src/installer.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * crowdcode-mcp — CrowdCode MCP client with local-first PII redaction.\n *\n * Subcommands:\n * (none) | serve start the stdio MCP server (default)\n * install install the skill and configure supported agents\n * doctor verify skill and MCP installation state\n * check [text] show what the redaction pipeline does to sample text\n * clear-cache delete the downloaded model cache\n */\n\nimport { rm, stat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline/promises\";\nimport { getConfig } from \"./config.js\";\nimport {\n CORE_CLIENTS,\n detectClients,\n doctorClients,\n installForClients,\n type ClientId,\n} from \"./installer.js\";\n\n// stdout carries the MCP protocol in serve mode; anything that would print\n// there (transformers download progress, stray library logs) corrupts it.\n// Patch before any heavy import happens.\nfunction routeStdoutToStderr(): void {\n console.log = (...args: unknown[]) => console.error(...args);\n console.info = (...args: unknown[]) => console.error(...args);\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nasync function runCheck(argText: string | undefined): Promise<void> {\n const config = getConfig();\n const text = argText ?? (await readStdin());\n if (!text.trim()) {\n console.error('usage: crowdcode-mcp check \"some text\" (or pipe via stdin)');\n process.exit(2);\n }\n\n const { RedactionEngine } = await import(\"@crowdcode/redaction\");\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n\n if (!config.disableModel) {\n console.error(\n \"loading PII model (downloads ~15 MB to \" +\n config.cacheDir +\n \" on first run; deterministic recognizers work without it) ...\",\n );\n await engine.waitForModel();\n }\n\n const result = await engine.redact(text);\n const revealed = await engine.reveal(result.text);\n\n console.error(\"\");\n console.error(\"input: \" + JSON.stringify(text));\n console.error(\"redacted: \" + JSON.stringify(result.text));\n console.error(\"revealed: \" + JSON.stringify(revealed) + \" (local round-trip)\");\n console.error(\"\");\n console.error(\n `entities removed: ${result.entitiesRemoved} model active: ${result.modelActive}`,\n );\n console.error(\n \"only the redacted form would ever be sent to the CrowdCode backend.\",\n );\n}\n\nasync function runClearCache(): Promise<void> {\n const config = getConfig();\n try {\n await stat(config.cacheDir);\n } catch {\n console.error(`nothing to clear (${config.cacheDir} does not exist)`);\n return;\n }\n await rm(config.cacheDir, { recursive: true, force: true });\n console.error(`cleared ${config.cacheDir}`);\n}\n\ninterface InstallerFlags {\n clients: ClientId[];\n allDetected: boolean;\n yes: boolean;\n}\n\nfunction parseInstallerFlags(args: string[]): InstallerFlags {\n const clients: ClientId[] = [];\n let allDetected = false;\n let yes = false;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index]!;\n if (arg === \"--yes\" || arg === \"-y\") {\n yes = true;\n continue;\n }\n if (arg === \"--all-detected\") {\n allDetected = true;\n continue;\n }\n let value: string | undefined;\n if (arg === \"--client\") {\n value = args[++index];\n if (!value) throw new Error(\"--client requires a client identifier\");\n } else if (arg.startsWith(\"--client=\")) {\n value = arg.slice(\"--client=\".length);\n } else {\n throw new Error(`unknown install option: ${arg}`);\n }\n for (const candidate of value.split(\",\")) {\n if (!(CORE_CLIENTS as readonly string[]).includes(candidate)) {\n throw new Error(\n `unknown client ${JSON.stringify(candidate)}; use ${CORE_CLIENTS.join(\", \")}`,\n );\n }\n if (!clients.includes(candidate as ClientId)) clients.push(candidate as ClientId);\n }\n }\n if (allDetected && clients.length > 0) {\n throw new Error(\"use either --all-detected or --client, not both\");\n }\n return { clients, allDetected, yes };\n}\n\nasync function chooseInstallClients(flags: InstallerFlags): Promise<ClientId[]> {\n if (flags.clients.length > 0) return flags.clients;\n const detected = await detectClients();\n if (flags.allDetected) {\n if (detected.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n return detected;\n }\n if (flags.yes || !process.stdin.isTTY || !process.stderr.isTTY) {\n return detected.length > 0 ? detected : [...CORE_CLIENTS];\n }\n\n const defaults = detected.length > 0 ? detected : [...CORE_CLIENTS];\n console.error(\"Supported clients:\");\n CORE_CLIENTS.forEach((client, index) => {\n console.error(` ${index + 1}. ${client}${detected.includes(client) ? \" (detected)\" : \"\"}`);\n });\n const prompt = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await prompt.question(\n `Install for comma-separated names/numbers [${defaults.join(\",\")}]: `,\n );\n if (!answer.trim()) return defaults;\n const selected: ClientId[] = [];\n for (const token of answer.split(\",\").map((item) => item.trim())) {\n const numbered = Number(token);\n const client = Number.isInteger(numbered)\n ? CORE_CLIENTS[numbered - 1]\n : (token as ClientId);\n if (!client || !(CORE_CLIENTS as readonly string[]).includes(client)) {\n throw new Error(`unknown client selection: ${token}`);\n }\n if (!selected.includes(client)) selected.push(client);\n }\n return selected;\n } finally {\n prompt.close();\n }\n}\n\nasync function runInstall(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients = await chooseInstallClients(flags);\n const results = await installForClients(clients);\n console.error(\"CrowdCode installation complete:\");\n for (const result of results) {\n console.error(\n ` ${result.client}: MCP ${result.configPath}; skill ${result.skillPath} (${result.skillMode})`,\n );\n }\n console.error(\"Restart these clients so they reload the CrowdCode skill and MCP server.\");\n}\n\nasync function runDoctor(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients =\n flags.clients.length > 0\n ? flags.clients\n : flags.allDetected\n ? await detectClients()\n : [...CORE_CLIENTS];\n if (clients.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n const results = await doctorClients(clients);\n let healthy = true;\n for (const result of results) {\n const ok = result.mcpConfigured && result.skillCurrent && result.completionHookCurrent !== false;\n healthy &&= ok;\n console.error(\n `${ok ? \"ok\" : \"missing/stale\"} ${result.client}` +\n ` MCP=${result.mcpConfigured ? \"ok\" : \"missing\"}` +\n ` skill=${result.skillCurrent ? \"ok\" : \"missing/stale\"}`,\n );\n if (result.detail) console.error(` ${result.detail}`);\n }\n if (!healthy) process.exitCode = 1;\n}\n\nfunction printHelp(): void {\n console.error(\n \"usage: crowdcode-mcp [serve|on|off|status|install|doctor|check <text>|clear-cache]\\n\" +\n \" serve start the stdio MCP server (default)\\n\" +\n \" on/off save CrowdCode default (active session overrides take precedence)\\n\" +\n \" status show the saved default for new connections\\n\" +\n \" install install the CrowdCode skill and MCP config\\n\" +\n \" [--client <client>] [--all-detected] [--yes]\\n\" +\n \" doctor verify skill and MCP config [--client <client>] [--all-detected]\\n\" +\n \" check demo the local redaction pipeline on sample text\\n\" +\n \" clear-cache delete the downloaded model cache\\n\" +\n ` clients ${CORE_CLIENTS.join(\", \")}`,\n );\n}\n\nasync function main(): Promise<void> {\n const [, , command, ...rest] = process.argv;\n switch (command) {\n case undefined:\n case \"serve\": {\n routeStdoutToStderr();\n const { startServer } = await import(\"./server.js\");\n await startServer();\n break;\n }\n case \"on\":\n case \"off\":\n case \"status\": {\n const { Preferences } = await import(\"./preferences.js\");\n const preferences = new Preferences();\n const state = command === \"status\" ? await preferences.status()\n : await preferences.set(command === \"on\", \"default\");\n console.log(JSON.stringify(state));\n break;\n }\n case \"check\":\n await runCheck(rest.length > 0 ? rest.join(\" \") : undefined);\n break;\n case \"install\":\n await runInstall(rest);\n break;\n case \"doctor\":\n await runDoctor(rest);\n break;\n case \"clear-cache\":\n await runClearCache();\n break;\n case \"--help\":\n case \"-h\":\n printHelp();\n break;\n default:\n console.error(`unknown command: ${command} (try --help)`);\n process.exit(2);\n }\n}\n\nmain().catch((err) => {\n console.error(\"crowdcode-mcp fatal:\", err);\n process.exit(1);\n});\n","/** Installed as a self-contained local Claude Code Stop hook. No network or transcript access. */\nexport const COMPLETION_HOOK = `\nlet input = '';\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', chunk => { input += chunk; });\nprocess.stdin.on('end', () => {\n try {\n const event = JSON.parse(input);\n if (event.hook_event_name !== 'Stop' || event.stop_hook_active) return;\n if (Array.isArray(event.background_tasks) && event.background_tasks.length) return;\n process.stdout.write(JSON.stringify({\n decision: 'block',\n reason: \"CrowdCode completion check (once only): read crowdcode_status. If off, unavailable, or this turn only managed CrowdCode settings/reviews, finish immediately without reflection or submissions. Otherwise, if you have not already reflected for this completed task, consider the real failures, poor results, excessive cost, and detours: what specific reusable service would have been worth paying for? Call request_service only for worthwhile unmet needs, describing exact inputs, deliverables, acceptance criteria, the real obstacle, and why the outcome justifies payment. A specific improvement to an inadequate existing service qualifies; no actual purchase is needed. Skip local Python/runtime wishes and services that already worked well. Never invent a budget or repeat a submitted gap. If nothing qualifies, submit nothing. Then finish; do not reopen the user's task.\"\n }));\n } catch { /* A broken optional reminder must never trap the user. */ }\n});\n`;\n\n","import { COMPLETION_HOOK } from \"./completion-hook.js\";\nimport { createHash } from \"node:crypto\";\nimport {\n copyFile,\n lstat,\n mkdir,\n readFile,\n readlink,\n rename,\n rm,\n stat,\n symlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport const CORE_CLIENTS = [\n \"codex\",\n \"claude-code\",\n \"claude-desktop\",\n \"cursor\",\n] as const;\n\nexport type ClientId = (typeof CORE_CLIENTS)[number];\nexport type InstallerPlatform = \"darwin\" | \"linux\" | \"win32\";\n\nexport interface InstallerEnvironment {\n homeDir?: string;\n platform?: InstallerPlatform;\n env?: NodeJS.ProcessEnv;\n packageRoot?: string;\n now?: () => Date;\n}\n\ninterface InstallState {\n packageVersion: string;\n skillHash: string;\n installedAt: string;\n}\n\nexport interface ClientInstallResult {\n client: ClientId;\n configPath: string;\n skillPath: string;\n skillMode: \"canonical\" | \"symlink\" | \"copy\" | \"mcp-instructions\";\n}\n\nexport interface DoctorResult {\n client: ClientId;\n configPath: string;\n mcpConfigured: boolean;\n skillPath: string;\n skillCurrent: boolean;\n completionHookCurrent?: boolean;\n detail?: string;\n}\n\nconst MCP_SERVER = {\n command: \"npx\",\n args: [\"-y\", \"crowdcode-mcp@latest\"],\n};\n\nfunction resolvedEnvironment(input: InstallerEnvironment = {}) {\n const platform = input.platform ?? process.platform;\n if (platform !== \"darwin\" && platform !== \"linux\" && platform !== \"win32\") {\n throw new Error(`unsupported platform: ${platform}`);\n }\n return {\n homeDir: input.homeDir ?? homedir(),\n platform,\n env: input.env ?? process.env,\n packageRoot: input.packageRoot ?? findPackageRoot(import.meta.url),\n now: input.now ?? (() => new Date()),\n };\n}\n\nfunction findPackageRoot(moduleUrl: string): string {\n // installer.ts lives in src during development and is bundled into dist/cli.js\n // for publication. Both locations are exactly one directory below package.json.\n return resolve(dirname(fileURLToPath(moduleUrl)), \"..\");\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function lexists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readOptional(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nfunction hash(content: string): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nasync function packageVersion(packageRoot: string): Promise<string> {\n const parsed = JSON.parse(await readFile(join(packageRoot, \"package.json\"), \"utf8\"));\n if (typeof parsed.version !== \"string\") {\n throw new Error(\"crowdcode-mcp package.json has no version\");\n }\n return parsed.version;\n}\n\nasync function bundledSkill(packageRoot: string): Promise<string> {\n const packaged = join(packageRoot, \"dist\", \"skills\", \"crowdcode\", \"SKILL.md\");\n const content = await readOptional(packaged);\n if (content !== null) return content;\n\n // Development fallback. Published packages always use the dist asset.\n const source = resolve(packageRoot, \"../../skills/crowdcode/SKILL.md\");\n return readFile(source, \"utf8\");\n}\n\nfunction statePath(homeDir: string): string {\n return join(homeDir, \".crowdcode\", \"install-state.json\");\n}\n\nfunction canonicalSkillDir(homeDir: string): string {\n return join(homeDir, \".agents\", \"skills\", \"crowdcode\");\n}\n\nasync function loadState(homeDir: string): Promise<InstallState | null> {\n const raw = await readOptional(statePath(homeDir));\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<InstallState>;\n if (\n typeof parsed.packageVersion === \"string\" &&\n typeof parsed.skillHash === \"string\" &&\n typeof parsed.installedAt === \"string\"\n ) {\n return parsed as InstallState;\n }\n } catch {\n // Treat malformed state as unmanaged; user content is backed up below.\n }\n return null;\n}\n\nasync function atomicWrite(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temp = join(\n dirname(path),\n `.${basename(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n await writeFile(temp, content, { mode: 0o600 });\n try {\n await rename(temp, path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nfunction backupSuffix(now: Date): string {\n return now.toISOString().replace(/[:.]/g, \"-\");\n}\n\nasync function unusedBackupPath(path: string, now: Date): Promise<string> {\n const base = `${path}.backup-${backupSuffix(now)}`;\n let candidate = base;\n for (let index = 2; await lexists(candidate); index += 1) {\n candidate = `${base}-${index}`;\n }\n return candidate;\n}\n\nasync function replaceSkillDirectory(\n path: string,\n skill: string,\n managedHash: string | null,\n now: Date,\n): Promise<void> {\n let existingSkill: string | null;\n try {\n existingSkill = await readOptional(join(path, \"SKILL.md\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOTDIR\") existingSkill = null;\n else throw error;\n }\n const newHash = hash(skill);\n if (existingSkill !== null && hash(existingSkill) === newHash) return;\n\n if (await lexists(path)) {\n const existingIsManaged =\n existingSkill !== null && managedHash !== null && hash(existingSkill) === managedHash;\n if (existingIsManaged) {\n await rm(path, { recursive: true, force: true });\n } else {\n await rename(path, await unusedBackupPath(path, now));\n }\n }\n\n const temp = `${path}.installing-${process.pid}`;\n await rm(temp, { recursive: true, force: true });\n await mkdir(temp, { recursive: true });\n await writeFile(join(temp, \"SKILL.md\"), skill);\n await rename(temp, path);\n}\n\nasync function installCanonicalSkill(env: ReturnType<typeof resolvedEnvironment>) {\n const skill = await bundledSkill(env.packageRoot);\n const previous = await loadState(env.homeDir);\n const path = canonicalSkillDir(env.homeDir);\n await mkdir(dirname(path), { recursive: true });\n await replaceSkillDirectory(path, skill, previous?.skillHash ?? null, env.now());\n\n const nextState: InstallState = {\n packageVersion: await packageVersion(env.packageRoot),\n skillHash: hash(skill),\n installedAt: env.now().toISOString(),\n };\n await atomicWrite(statePath(env.homeDir), `${JSON.stringify(nextState, null, 2)}\\n`);\n return { path, skill, state: nextState };\n}\n\nfunction claudeCodeSkillDir(homeDir: string): string {\n return join(homeDir, \".claude\", \"skills\", \"crowdcode\");\n}\n\nasync function installClaudeCodeSkill(\n env: ReturnType<typeof resolvedEnvironment>,\n canonicalPath: string,\n skill: string,\n): Promise<\"symlink\" | \"copy\"> {\n const target = claudeCodeSkillDir(env.homeDir);\n await mkdir(dirname(target), { recursive: true });\n\n let targetManaged = false;\n try {\n const targetStat = await lstat(target);\n if (targetStat.isSymbolicLink()) {\n const link = await readlink(target);\n targetManaged = resolve(dirname(target), link) === canonicalPath;\n } else {\n const current = await readOptional(join(target, \"SKILL.md\"));\n targetManaged = current !== null && hash(current) === hash(skill);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n\n if (await lexists(target)) {\n if (targetManaged) await rm(target, { recursive: true, force: true });\n else await rename(target, await unusedBackupPath(target, env.now()));\n }\n\n if (env.platform !== \"win32\") {\n try {\n await symlink(relative(dirname(target), canonicalPath), target, \"dir\");\n return \"symlink\";\n } catch {\n // Some filesystems disallow symlinks. Fall through to a portable copy.\n }\n }\n\n await mkdir(target, { recursive: true });\n await copyFile(join(canonicalPath, \"SKILL.md\"), join(target, \"SKILL.md\"));\n return \"copy\";\n}\n\nfunction configBase(\n homeDir: string,\n platform: InstallerPlatform,\n env: NodeJS.ProcessEnv,\n): string {\n if (platform === \"win32\") {\n return env.APPDATA ?? join(homeDir, \"AppData\", \"Roaming\");\n }\n if (platform === \"darwin\") return join(homeDir, \"Library\", \"Application Support\");\n return env.XDG_CONFIG_HOME ?? join(homeDir, \".config\");\n}\n\nexport function getClientConfigPath(\n client: ClientId,\n input: InstallerEnvironment = {},\n): string {\n const env = resolvedEnvironment(input);\n switch (client) {\n case \"codex\":\n return join(env.env.CODEX_HOME ?? join(env.homeDir, \".codex\"), \"config.toml\");\n case \"claude-code\":\n return join(env.homeDir, \".claude.json\");\n case \"cursor\":\n return join(env.homeDir, \".cursor\", \"mcp.json\");\n case \"claude-desktop\":\n return join(\n configBase(env.homeDir, env.platform, env.env),\n \"Claude\",\n \"claude_desktop_config.json\",\n );\n }\n}\n\nfunction removeCrowdCodeTomlSection(content: string): string {\n const lines = content.split(/\\r?\\n/);\n const kept: string[] = [];\n let skipping = false;\n for (const line of lines) {\n const section = /^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/.exec(line);\n if (section) {\n const normalized = section[1]!.replace(/[\"']/g, \"\").replace(/\\s/g, \"\");\n skipping =\n normalized === \"mcp_servers.crowdcode\" ||\n normalized.startsWith(\"mcp_servers.crowdcode.\");\n if (skipping) continue;\n }\n if (!skipping) kept.push(line);\n }\n return kept.join(\"\\n\").trimEnd();\n}\n\nexport function mergeCodexConfig(content: string): string {\n const before = removeCrowdCodeTomlSection(content);\n const section = [\n \"[mcp_servers.crowdcode]\",\n `command = ${JSON.stringify(MCP_SERVER.command)}`,\n `args = ${JSON.stringify(MCP_SERVER.args)}`,\n ].join(\"\\n\");\n return `${before ? `${before}\\n\\n` : \"\"}${section}\\n`;\n}\n\nfunction parseJsonConfig(content: string, path: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(content) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"root must be an object\");\n }\n return parsed as Record<string, unknown>;\n } catch (error) {\n throw new Error(`cannot parse ${path}; no changes were written: ${(error as Error).message}`);\n }\n}\n\nexport function mergeJsonMcpConfig(content: string, path = \"config.json\"): string {\n const config = content.trim() ? parseJsonConfig(content, path) : {};\n const current = config.mcpServers;\n if (current !== undefined && (current === null || typeof current !== \"object\" || Array.isArray(current))) {\n throw new Error(`${path} has a non-object mcpServers value; no changes were written`);\n }\n config.mcpServers = {\n ...((current as Record<string, unknown> | undefined) ?? {}),\n crowdcode: MCP_SERVER,\n };\n return `${JSON.stringify(config, null, 2)}\\n`;\n}\n\nasync function installCompletionHook(env: ReturnType<typeof resolvedEnvironment>): Promise<void> {\n const settingsPath = join(env.homeDir, \".claude\", \"settings.json\");\n const settings = parseJsonConfig((await readOptional(settingsPath)) ?? \"{}\", settingsPath);\n const hooks = settings.hooks ?? {};\n if (!hooks || typeof hooks !== \"object\" || Array.isArray(hooks)) throw new Error(\"Invalid Claude hooks settings\");\n const hookMap = hooks as Record<string, unknown>;\n const stop = hookMap.Stop ?? [];\n if (!Array.isArray(stop)) throw new Error(\"Invalid Claude Stop hooks settings\");\n const hookPath = join(env.homeDir, \".crowdcode\", \"hooks\", \"completion.cjs\");\n const installed = stop.some((entry: any) => Array.isArray(entry?.hooks) &&\n entry.hooks.some((hook: any) => hook.type === \"command\" && hook.command === \"node\" &&\n Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));\n if (!installed) hookMap.Stop = [...stop, { hooks: [{ type: \"command\", command: \"node\", args: [hookPath], timeout: 5 }] }];\n settings.hooks = hookMap;\n await atomicWrite(hookPath, COMPLETION_HOOK);\n const next = JSON.stringify(settings, null, 2) + \"\\n\";\n if (next !== await readOptional(settingsPath)) await atomicWrite(settingsPath, next);\n}\n\nasync function configureClient(\n client: ClientId,\n env: ReturnType<typeof resolvedEnvironment>,\n): Promise<string> {\n const path = getClientConfigPath(client, env);\n const current = (await readOptional(path)) ?? \"\";\n const next =\n client === \"codex\" ? mergeCodexConfig(current) : mergeJsonMcpConfig(current, path);\n if (next !== current) await atomicWrite(path, next);\n return path;\n}\n\nexport async function detectClients(\n input: InstallerEnvironment = {},\n): Promise<ClientId[]> {\n const env = resolvedEnvironment(input);\n const markers: Record<ClientId, string[]> = {\n codex: [env.env.CODEX_HOME ?? join(env.homeDir, \".codex\")],\n \"claude-code\": [join(env.homeDir, \".claude\"), join(env.homeDir, \".claude.json\")],\n cursor: [join(env.homeDir, \".cursor\")],\n \"claude-desktop\": [dirname(getClientConfigPath(\"claude-desktop\", env))],\n };\n const detected: ClientId[] = [];\n for (const client of CORE_CLIENTS) {\n if ((await Promise.all(markers[client].map(exists))).some(Boolean)) detected.push(client);\n }\n return detected;\n}\n\nexport async function installForClients(\n clients: readonly ClientId[],\n input: InstallerEnvironment = {},\n): Promise<ClientInstallResult[]> {\n const env = resolvedEnvironment(input);\n const canonical = await installCanonicalSkill(env);\n let claudeMode: \"symlink\" | \"copy\" | null = null;\n if (clients.includes(\"claude-code\")) {\n claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);\n await installCompletionHook(env);\n }\n\n const results: ClientInstallResult[] = [];\n for (const client of clients) {\n const configPath = await configureClient(client, env);\n if (client === \"claude-code\") {\n results.push({\n client,\n configPath,\n skillPath: claudeCodeSkillDir(env.homeDir),\n skillMode: claudeMode!,\n });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n skillPath: \"MCP initialize instructions\",\n skillMode: \"mcp-instructions\",\n });\n } else {\n results.push({\n client,\n configPath,\n skillPath: canonical.path,\n skillMode: \"canonical\",\n });\n }\n }\n return results;\n}\n\nfunction jsonHasCrowdCode(content: string): boolean {\n try {\n const parsed = JSON.parse(content) as {\n mcpServers?: Record<string, { command?: string; args?: string[] }>;\n };\n const server = parsed.mcpServers?.crowdcode;\n return server?.command === MCP_SERVER.command &&\n JSON.stringify(server.args) === JSON.stringify(MCP_SERVER.args);\n } catch {\n return false;\n }\n}\n\nfunction codexHasCrowdCode(content: string): boolean {\n const merged = removeCrowdCodeTomlSection(content);\n return merged !== content.trimEnd() &&\n /\\[mcp_servers\\.(?:[\"']?crowdcode[\"']?)\\]/.test(content) &&\n /crowdcode-mcp@latest/.test(content);\n}\n\nexport async function doctorClients(\n clients: readonly ClientId[] = CORE_CLIENTS,\n input: InstallerEnvironment = {},\n): Promise<DoctorResult[]> {\n const env = resolvedEnvironment(input);\n const expectedSkill = await bundledSkill(env.packageRoot);\n const canonicalPath = canonicalSkillDir(env.homeDir);\n const canonicalCurrent =\n (await readOptional(join(canonicalPath, \"SKILL.md\"))) === expectedSkill;\n const results: DoctorResult[] = [];\n\n for (const client of clients) {\n const configPath = getClientConfigPath(client, env);\n const config = (await readOptional(configPath)) ?? \"\";\n const mcpConfigured =\n client === \"codex\" ? codexHasCrowdCode(config) : jsonHasCrowdCode(config);\n if (client === \"claude-code\") {\n const skillPath = claudeCodeSkillDir(env.homeDir);\n const skillCurrent =\n (await readOptional(join(skillPath, \"SKILL.md\"))) === expectedSkill;\n let completionHookCurrent = false;\n try {\n const settings = JSON.parse((await readOptional(join(env.homeDir, \".claude\", \"settings.json\"))) ?? \"{}\");\n const hookPath = join(env.homeDir, \".crowdcode\", \"hooks\", \"completion.cjs\");\n completionHookCurrent = (await readOptional(hookPath)) === COMPLETION_HOOK &&\n Array.isArray(settings.hooks?.Stop) && settings.hooks.Stop.some((entry: any) =>\n Array.isArray(entry?.hooks) && entry.hooks.some((hook: any) =>\n hook.type === \"command\" && hook.command === \"node\" &&\n Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));\n } catch { /* Doctor reports malformed or missing hook configuration. */ }\n results.push({ client, configPath, mcpConfigured, skillPath, skillCurrent, completionHookCurrent,\n ...(!completionHookCurrent ? { detail: \"Re-run install --client claude-code to refresh the completion reminder.\" } : {}) });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: \"MCP initialize instructions\",\n skillCurrent: mcpConfigured,\n detail: \"Claude Desktop uses CrowdCode's MCP initialization instructions.\",\n });\n } else {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: canonicalPath,\n skillCurrent: canonicalCurrent,\n });\n }\n }\n return results;\n}\n"],"mappings":";;;;;;AAYA,SAAS,MAAAA,KAAI,QAAAC,aAAY;AACzB,SAAS,uBAAuB;;;ACZzB,IAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACA/B,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAC3D,SAAS,qBAAqB;AAEvB,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAoCA,IAAM,aAAa;AAAA,EACjB,SAAS;AAAA,EACT,MAAM,CAAC,MAAM,sBAAsB;AACrC;AAEA,SAAS,oBAAoB,QAA8B,CAAC,GAAG;AAC7D,QAAM,WAAW,MAAM,YAAY,QAAQ;AAC3C,MAAI,aAAa,YAAY,aAAa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AM,SAAS,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,MAAS;AAC3D;AAAA,IACF,KAAK;AACH,YAAM,WAAW,IAAI;AACrB;AAAA,IACF,KAAK;AACH,YAAM,UAAU,IAAI;AACpB;AAAA,IACF,KAAK;AACH,YAAM,cAAc;AACpB;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,gBAAU;AACV;AAAA,IACF;AACE,cAAQ,MAAM,oBAAoB,OAAO,eAAe;AACxD,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,wBAAwB,GAAG;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["rm","stat","stat","rm"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -7,6 +7,25 @@ import {
|
|
|
7
7
|
canonicalReviewPayload,
|
|
8
8
|
normalizePaymentProvider
|
|
9
9
|
} from "./chunk-4AUE77N3.js";
|
|
10
|
+
import {
|
|
11
|
+
Preferences
|
|
12
|
+
} from "./chunk-ZPDTU2RK.js";
|
|
13
|
+
|
|
14
|
+
// src/server.ts
|
|
15
|
+
import { z as z2 } from "zod";
|
|
16
|
+
|
|
17
|
+
// src/tools/manage-reviews.ts
|
|
18
|
+
function managementMessage(args) {
|
|
19
|
+
return [
|
|
20
|
+
"CrowdCode review management v1",
|
|
21
|
+
`action:${args.action}`,
|
|
22
|
+
`wallet:${args.wallet.toLowerCase()}`,
|
|
23
|
+
`review_id:${args.review_id ?? 0}`,
|
|
24
|
+
`before_id:${args.before_id ?? 0}`,
|
|
25
|
+
`limit:${args.limit ?? 0}`,
|
|
26
|
+
`expires_at:${args.expires_at}`
|
|
27
|
+
].join("\n");
|
|
28
|
+
}
|
|
10
29
|
|
|
11
30
|
// src/server.ts
|
|
12
31
|
import { RedactionEngine } from "@crowdcode/redaction";
|
|
@@ -64,10 +83,10 @@ var identityShape = {
|
|
|
64
83
|
var RATING_DESCRIPTION = "Rating 1-5. Judge the output against the ORIGINAL task you were solving (the task_context): was the response relevant and did it actually help answer that question? 5 = excellent: clear schema, relevant output that answered the original question, fast, clean receipt/proof \u2014 you would reuse it confidently. 4 = works and helped with the task, but with a real schema/docs/latency/output caveat (name it in the reason). 3 = mixed: paid successfully but the response was thin, confusing, needed guesswork, or was not actually relevant or helpful for the task \u2014 a technically valid answer that did not help is a 3 at best. 2 = paid but poor: client error, unclear failure, or hard to use. 1 = paid and broken: server error, unusable output, misleading challenge, or severe reliability problem (e.g. timeout). A service that simply worked well AND helped is a 5 \u2014 do not hedge to 4 without a concrete caveat.";
|
|
65
84
|
var requestServiceShape = {
|
|
66
85
|
service_description: z.string().describe(
|
|
67
|
-
"
|
|
86
|
+
"Concrete reusable paid offering: exact input, output or state change, acceptance criteria, and why the outcome justifies payment. Ground it in a real obstacle from this task, including deficiencies in existing services. Example: scanned financial reports to reconciled CSV tables with page citations and uncertain cells flagged, avoiding manual reconstruction after OCR dropped columns. No generic local compute or web search that worked well. Do not invent prices or spend authority."
|
|
68
87
|
),
|
|
69
88
|
task_context: z.string().nullish().describe(
|
|
70
|
-
"
|
|
89
|
+
"Include the real use case, what was attempted, the observed failure, poor quality, cost or detour, and why available alternatives fell short. Omit private details. A purchase need not have been attempted."
|
|
71
90
|
),
|
|
72
91
|
requester_wallet: z.string().nullish().describe(
|
|
73
92
|
"EVM 0x address identifying who is asking (rate-limit key). Auto-filled from your local agentcash wallet \u2014 only pass it to override."
|
|
@@ -109,7 +128,9 @@ var reviewServiceShape = {
|
|
|
109
128
|
var MIRRORED_REMOTE_TOOLS = [
|
|
110
129
|
"request_service",
|
|
111
130
|
"get_service_score",
|
|
112
|
-
"review_service"
|
|
131
|
+
"review_service",
|
|
132
|
+
"list_my_reviews",
|
|
133
|
+
"delete_my_review"
|
|
113
134
|
];
|
|
114
135
|
|
|
115
136
|
// src/tools/sign-review.ts
|
|
@@ -490,6 +511,7 @@ function withWalletInfo(payload, prepared) {
|
|
|
490
511
|
function createToolHandlers(deps) {
|
|
491
512
|
const { engine, upstream } = deps;
|
|
492
513
|
const config = getConfig();
|
|
514
|
+
const preferences = deps.preferences ?? new Preferences();
|
|
493
515
|
const walletOptions = {
|
|
494
516
|
walletDir: deps.wallet?.walletDir ?? config.walletDir,
|
|
495
517
|
autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,
|
|
@@ -499,6 +521,8 @@ function createToolHandlers(deps) {
|
|
|
499
521
|
let onboardingCtaShown = false;
|
|
500
522
|
async function forwardPayload(tool, args) {
|
|
501
523
|
const redacted = await redactArgs(engine, tool, args);
|
|
524
|
+
const stopped = await disabled();
|
|
525
|
+
if (stopped) return stopped.structuredContent;
|
|
502
526
|
try {
|
|
503
527
|
const result = await upstream.call(tool, redacted.args);
|
|
504
528
|
return withRedactionAttestation(result, {
|
|
@@ -509,14 +533,61 @@ function createToolHandlers(deps) {
|
|
|
509
533
|
return errorPayload(tool, err);
|
|
510
534
|
}
|
|
511
535
|
}
|
|
536
|
+
async function disabled() {
|
|
537
|
+
try {
|
|
538
|
+
if ((await preferences.status()).enabled) return null;
|
|
539
|
+
return toToolResult({
|
|
540
|
+
status: "disabled",
|
|
541
|
+
accepted: false,
|
|
542
|
+
enabled: false,
|
|
543
|
+
reason: "CrowdCode is off. Continue the user's task without CrowdCode. Do not retry or queue submissions. History, deletion, and settings remain available."
|
|
544
|
+
});
|
|
545
|
+
} catch {
|
|
546
|
+
return toToolResult({
|
|
547
|
+
status: "unavailable",
|
|
548
|
+
accepted: false,
|
|
549
|
+
error_code: "preferences_unavailable",
|
|
550
|
+
reason: "Cannot read CrowdCode preferences; no data was sent."
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
async function manageReviews(action, args) {
|
|
555
|
+
const wallet = await loadWallet({ ...walletOptions, autoCreate: false });
|
|
556
|
+
if (!wallet.account || !wallet.address) return toToolResult({
|
|
557
|
+
accepted: false,
|
|
558
|
+
error_code: wallet.errorCode ?? "wallet_unavailable",
|
|
559
|
+
reason: "Use the original reviewing wallet to access or delete its reviews. No wallet was created."
|
|
560
|
+
});
|
|
561
|
+
const expires_at = Math.floor(Date.now() / 1e3) + 300;
|
|
562
|
+
const message = managementMessage({ action, wallet: wallet.address, expires_at, ...args });
|
|
563
|
+
const authorization = await wallet.account.signMessage({ message });
|
|
564
|
+
const tool = action === "list" ? "list_my_reviews" : "delete_my_review";
|
|
565
|
+
try {
|
|
566
|
+
return toToolResult(await upstream.call(tool, {
|
|
567
|
+
...args,
|
|
568
|
+
reviewer_wallet: wallet.address,
|
|
569
|
+
expires_at,
|
|
570
|
+
authorization
|
|
571
|
+
}));
|
|
572
|
+
} catch (error) {
|
|
573
|
+
return toToolResult(errorPayload(tool, error));
|
|
574
|
+
}
|
|
575
|
+
}
|
|
512
576
|
return {
|
|
577
|
+
crowdcode_status: async () => toToolResult(await preferences.status()),
|
|
578
|
+
set_crowdcode_enabled: async (args) => toToolResult(await preferences.set(args.enabled, args.scope)),
|
|
579
|
+
list_my_reviews: async (args) => manageReviews("list", { ...args, limit: args.limit ?? 25 }),
|
|
580
|
+
delete_my_review: async (args) => manageReviews("delete", args),
|
|
513
581
|
request_service: async (args) => {
|
|
582
|
+
const stopped = await disabled();
|
|
583
|
+
if (stopped) return stopped;
|
|
514
584
|
let outgoing = args;
|
|
585
|
+
let walletCreated = false;
|
|
515
586
|
if (!outgoing.requester_wallet) {
|
|
516
587
|
const wallet = await loadWallet({
|
|
517
588
|
walletDir: walletOptions.walletDir,
|
|
518
589
|
env: walletOptions.env,
|
|
519
|
-
autoCreate:
|
|
590
|
+
autoCreate: walletOptions.autoCreate
|
|
520
591
|
});
|
|
521
592
|
if (wallet.errorCode === "wallet_configuration_error") {
|
|
522
593
|
return toToolResult({
|
|
@@ -529,11 +600,17 @@ function createToolHandlers(deps) {
|
|
|
529
600
|
}
|
|
530
601
|
if (wallet.address) {
|
|
531
602
|
outgoing = { ...outgoing, requester_wallet: wallet.address };
|
|
603
|
+
walletCreated = wallet.created === true;
|
|
532
604
|
}
|
|
533
605
|
}
|
|
534
|
-
return toToolResult(
|
|
606
|
+
return toToolResult({
|
|
607
|
+
...await forwardPayload("request_service", outgoing),
|
|
608
|
+
...walletCreated ? { wallet_created: true, wallet_source: "agentcash" } : {}
|
|
609
|
+
});
|
|
535
610
|
},
|
|
536
611
|
get_service_score: async (args) => {
|
|
612
|
+
const stopped = await disabled();
|
|
613
|
+
if (stopped) return stopped;
|
|
537
614
|
let payload;
|
|
538
615
|
try {
|
|
539
616
|
payload = await upstream.call("get_service_score", args);
|
|
@@ -558,9 +635,11 @@ function createToolHandlers(deps) {
|
|
|
558
635
|
};
|
|
559
636
|
}
|
|
560
637
|
}
|
|
561
|
-
return toToolResult(payload);
|
|
638
|
+
return toToolResult({ ...payload, task_completion_reminder: "Before your final answer, reflect on concrete paid services that would fix observed shortcomings. Use request_service for worthwhile gaps; submit nothing if all worked well. Respect CrowdCode off." });
|
|
562
639
|
},
|
|
563
640
|
get_review_signing_payload: async (args) => {
|
|
641
|
+
const stopped = await disabled();
|
|
642
|
+
if (stopped) return stopped;
|
|
564
643
|
const signingWallet = args.auto_sign === true ? await loadWallet(walletOptions) : null;
|
|
565
644
|
if (signingWallet?.errorCode === "wallet_configuration_error") {
|
|
566
645
|
return toToolResult({
|
|
@@ -600,6 +679,8 @@ function createToolHandlers(deps) {
|
|
|
600
679
|
});
|
|
601
680
|
},
|
|
602
681
|
review_service: async (args) => {
|
|
682
|
+
const stopped = await disabled();
|
|
683
|
+
if (stopped) return stopped;
|
|
603
684
|
const prepared = await prepareSignedReview(signingDeps, args, walletOptions);
|
|
604
685
|
if (prepared.wallet_error_code === "wallet_configuration_error") {
|
|
605
686
|
return toToolResult({
|
|
@@ -616,7 +697,7 @@ function createToolHandlers(deps) {
|
|
|
616
697
|
if (retryArgs !== null) {
|
|
617
698
|
payload = await forwardPayload("review_service", retryArgs);
|
|
618
699
|
}
|
|
619
|
-
return toToolResult(withWalletInfo(payload, prepared));
|
|
700
|
+
return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: "Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests." });
|
|
620
701
|
}
|
|
621
702
|
};
|
|
622
703
|
}
|
|
@@ -653,30 +734,53 @@ var SERVER_INSTRUCTIONS = [
|
|
|
653
734
|
"existing verified scoring weight; unpaid signed reviews share the same",
|
|
654
735
|
"history, score, and per-wallet/service/day influence cap.",
|
|
655
736
|
"",
|
|
656
|
-
"
|
|
657
|
-
"service
|
|
658
|
-
"
|
|
659
|
-
"
|
|
660
|
-
"
|
|
661
|
-
"
|
|
662
|
-
"
|
|
663
|
-
"
|
|
664
|
-
"
|
|
665
|
-
"
|
|
666
|
-
"
|
|
667
|
-
"
|
|
668
|
-
"
|
|
737
|
+
"Before the final answer to each substantive user task, reflect once: what concrete",
|
|
738
|
+
"paid service would have avoided an observed failure, poor result, expensive workaround,",
|
|
739
|
+
"or wrong turn? This applies even if no purchase was attempted. Call request_service",
|
|
740
|
+
"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).",
|
|
741
|
+
"Describe the real use case, precise input, deliverable, acceptance criteria, observed",
|
|
742
|
+
"shortcoming, and why someone would pay for that outcome. An inadequate existing service",
|
|
743
|
+
"qualifies if you name the specific improvement. No actual payment or spend authority",
|
|
744
|
+
"is required to report demand; do not invent a budget or claim the user agreed to pay.",
|
|
745
|
+
"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a",
|
|
746
|
+
"sellable remedy, and services that already worked well at reasonable cost. If nothing",
|
|
747
|
+
"qualifies, submit nothing. Never send secrets or private user data.",
|
|
748
|
+
"At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call",
|
|
749
|
+
"set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default",
|
|
750
|
+
"when they ask to remember it. Off overrides all automatic CrowdCode workflows:",
|
|
751
|
+
"continue the user's task, skip reflection, checks and submissions; never backfill.",
|
|
752
|
+
"Use list_my_reviews for 'show my reviews'; delete_my_review only for review IDs the",
|
|
753
|
+
"user asks to delete. These management tools remain available while CrowdCode is off."
|
|
669
754
|
].join("\n");
|
|
670
755
|
function buildServer(deps) {
|
|
671
756
|
const server = new McpServer(
|
|
672
|
-
{ name: "crowdcode", version: "0.
|
|
757
|
+
{ name: "crowdcode", version: "0.6.0" },
|
|
673
758
|
{ instructions: SERVER_INSTRUCTIONS }
|
|
674
759
|
);
|
|
675
760
|
const handlers = createToolHandlers(deps);
|
|
761
|
+
server.registerTool("crowdcode_status", {
|
|
762
|
+
description: "Read CrowdCode's effective on/off state and saved default locally. Check at task start.",
|
|
763
|
+
inputSchema: {},
|
|
764
|
+
annotations: { readOnlyHint: true }
|
|
765
|
+
}, () => handlers.crowdcode_status());
|
|
766
|
+
server.registerTool("set_crowdcode_enabled", {
|
|
767
|
+
description: "Handle 'Crowdcode on' or 'Crowdcode off'. Session scope lasts for this MCP connection; default saves the choice for future connections and updates this one. Off stops checks, signing, reviews, and requests. History and deletion stay available. No queued backfill.",
|
|
768
|
+
inputSchema: { enabled: z2.boolean(), scope: z2.enum(["session", "default"]).default("session") }
|
|
769
|
+
}, (args) => handlers.set_crowdcode_enabled(args));
|
|
770
|
+
server.registerTool("list_my_reviews", {
|
|
771
|
+
description: "Show reviews submitted by the local wallet, newest first, including review IDs for deletion. Follow next_before_id to see older reviews. Works while CrowdCode is off. Locally signs an expiring ownership proof; never creates a wallet.",
|
|
772
|
+
inputSchema: { before_id: z2.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), limit: z2.number().int().min(1).max(100).default(25) },
|
|
773
|
+
annotations: { readOnlyHint: true }
|
|
774
|
+
}, (args) => handlers.list_my_reviews(args));
|
|
775
|
+
server.registerTool("delete_my_review", {
|
|
776
|
+
description: "Permanently delete the specific review ID requested by the user, owned by the local wallet. List reviews first if the ID is unknown. Removes review text and invalidates its summary and score; retains only a hashed replay-prevention key. Works while off. Never bulk-delete or choose IDs without user direction.",
|
|
777
|
+
inputSchema: { review_id: z2.number().int().positive().max(Number.MAX_SAFE_INTEGER) },
|
|
778
|
+
annotations: { destructiveHint: true, idempotentHint: true }
|
|
779
|
+
}, (args) => handlers.delete_my_review(args));
|
|
676
780
|
server.registerTool(
|
|
677
781
|
"request_service",
|
|
678
782
|
{
|
|
679
|
-
description: "Record
|
|
783
|
+
description: "Record a concrete paid service that would have materially improved the task. Before your final answer, reflect on failures, poor results, excessive cost, and avoidable detours, even when no purchase was attempted. Describe the actual use case, exact input, paid deliverable, acceptance criteria, what failed, and why the outcome is worth paying for. Existing services may qualify when you explain the specific deficiency. Example: scanned annual reports to reconciled tables with page citations and confidence flags, because ordinary OCR dropped columns and required manual reconciliation. Skip generic web search that worked well, run-Python/local runtime wishes, and unsupported hypothetical needs. No payment or spending authority is needed; never invent a budget. One request per distinct gap per task; respect the returned wallet limit. Submit nothing if all worked well at reasonable cost. Free text is redacted locally.",
|
|
680
784
|
inputSchema: requestServiceShape
|
|
681
785
|
},
|
|
682
786
|
(args) => handlers.request_service(args)
|
|
@@ -729,11 +833,11 @@ async function startServer() {
|
|
|
729
833
|
const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);
|
|
730
834
|
const server = buildServer({ engine, upstream });
|
|
731
835
|
await server.connect(new StdioServerTransport());
|
|
732
|
-
void warnOnToolDrift(upstream);
|
|
836
|
+
if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);
|
|
733
837
|
}
|
|
734
838
|
export {
|
|
735
839
|
buildServer,
|
|
736
840
|
createToolHandlers,
|
|
737
841
|
startServer
|
|
738
842
|
};
|
|
739
|
-
//# sourceMappingURL=server-
|
|
843
|
+
//# sourceMappingURL=server-Q6FUDOBY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/tools/manage-reviews.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/sign-review.ts","../src/tools/signing-payload.ts","../src/upstream.ts"],"sourcesContent":["/**\n * The stdio MCP server. Advertises the same tools as the CrowdCode backend;\n * free-text arguments are redacted locally (Rampart + secret recognizers)\n * before forwarding over streamable-HTTP, and get_review_signing_payload is\n * served entirely locally so raw review text never leaves this machine at\n * signing time.\n */\n\nimport { z } from \"zod\";\nimport { Preferences } from \"./preferences.js\";\nimport { managementMessage } from \"./tools/manage-reviews.js\";\nimport { RedactionEngine } from \"@crowdcode/redaction\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { toToolResult, withRedactionAttestation } from \"./attestation.js\";\nimport { getConfig } from \"./config.js\";\nimport { redactArgs } from \"./redaction/policy.js\";\nimport {\n MIRRORED_REMOTE_TOOLS,\n getServiceScoreShape,\n requestServiceShape,\n reviewServiceShape,\n signingPayloadShape,\n} from \"./schemas.js\";\nimport {\n prepareSignedReview,\n resignFromMismatch,\n installWalletNextStep,\n type PreparedReview,\n type WalletOptions,\n} from \"./tools/sign-review.js\";\nimport {\n getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, type Upstream } from \"./upstream.js\";\nimport { loadWallet } from \"./wallet.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n preferences?: Preferences;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n _err: unknown,\n): Record<string, unknown> {\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend or one of its dependencies is temporarily \" +\n \"unavailable; retry the same call in ~30 seconds.\",\n command: null,\n link: null,\n retry: { tool, after_seconds: 30, with: {} },\n };\n if (tool === \"get_service_score\") {\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n found: false,\n score: null,\n n_eff: 0,\n avg_rating: null,\n num_reviews: 0,\n summary: null,\n recent_reviews: [],\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n }\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n accepted: false,\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n}\n\nfunction withWalletInfo(\n payload: Record<string, unknown>,\n prepared: PreparedReview,\n): Record<string, unknown> {\n const out = { ...payload };\n if (prepared.args.review_nonce != null) out.review_nonce = prepared.args.review_nonce;\n if (prepared.wallet_source !== undefined) {\n out.wallet_source = prepared.wallet_source;\n }\n if (prepared.wallet_created) out.wallet_created = true;\n if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;\n if (out.error_code === undefined && prepared.wallet_error_code) {\n out.error_code = prepared.wallet_error_code;\n }\n if (out.next_step === undefined && prepared.next_step) {\n out.next_step = prepared.next_step;\n }\n return out;\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n const config = getConfig();\n const preferences = deps.preferences ?? new Preferences();\n const walletOptions: WalletOptions = {\n walletDir: deps.wallet?.walletDir ?? config.walletDir,\n autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,\n env: deps.wallet?.env,\n };\n const signingDeps = { redact: (text: string) => engine.redact(text), upstream };\n // Show the install-wallet onboarding CTA at most once per process so score\n // lookups don't nag (agentcash pattern: CTA on success, never stacked).\n let onboardingCtaShown = false;\n\n async function forwardPayload(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const redacted = await redactArgs(engine, tool, args);\n const stopped = await disabled();\n if (stopped) return stopped.structuredContent;\n try {\n const result = await upstream.call(tool, redacted.args);\n return withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n });\n } catch (err) {\n return errorPayload(tool, err);\n }\n }\n\n async function disabled(): Promise<ToolResult | null> {\n try {\n if ((await preferences.status()).enabled) return null;\n return toToolResult({ status: \"disabled\", accepted: false, enabled: false,\n reason: \"CrowdCode is off. Continue the user's task without CrowdCode. Do not retry or queue submissions. History, deletion, and settings remain available.\" });\n } catch {\n return toToolResult({ status: \"unavailable\", accepted: false,\n error_code: \"preferences_unavailable\", reason: \"Cannot read CrowdCode preferences; no data was sent.\" });\n }\n }\n\n async function manageReviews(action: \"list\" | \"delete\", args: { review_id?: number; before_id?: number; limit?: number }) {\n const wallet = await loadWallet({ ...walletOptions, autoCreate: false });\n if (!wallet.account || !wallet.address) return toToolResult({ accepted: false,\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n reason: \"Use the original reviewing wallet to access or delete its reviews. No wallet was created.\" });\n const expires_at = Math.floor(Date.now() / 1000) + 300;\n const message = managementMessage({ action, wallet: wallet.address, expires_at, ...args });\n const authorization = await wallet.account.signMessage({ message });\n const tool = action === \"list\" ? \"list_my_reviews\" : \"delete_my_review\";\n try {\n return toToolResult(await upstream.call(tool, { ...args, reviewer_wallet: wallet.address,\n expires_at, authorization }));\n } catch (error) {\n return toToolResult(errorPayload(tool, error));\n }\n }\n\n return {\n crowdcode_status: async () => toToolResult(await preferences.status()),\n set_crowdcode_enabled: async (args: { enabled: boolean; scope?: \"session\" | \"default\" }) =>\n toToolResult(await preferences.set(args.enabled, args.scope)),\n list_my_reviews: async (args: { before_id?: number; limit?: number }) =>\n manageReviews(\"list\", { ...args, limit: args.limit ?? 25 }),\n delete_my_review: async (args: { review_id: number }) => manageReviews(\"delete\", args),\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n let outgoing = args;\n let walletCreated = false;\n if (!outgoing.requester_wallet) {\n // Demand needs an identity, not funds or permission to make a payment.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: walletOptions.autoCreate,\n });\n if (wallet.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: wallet.errorCode,\n retryable: false,\n accepted: false,\n reason: wallet.error,\n });\n }\n if (wallet.address) {\n outgoing = { ...outgoing, requester_wallet: wallet.address };\n walletCreated = wallet.created === true;\n }\n }\n return toToolResult({ ...await forwardPayload(\"request_service\", outgoing),\n ...(walletCreated ? { wallet_created: true, wallet_source: \"agentcash\" } : {}) });\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n let payload: Record<string, unknown>;\n try {\n payload = await upstream.call(\"get_service_score\", args);\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n const provider = payload.payment_provider;\n if (\n !onboardingCtaShown &&\n payload.found === true &&\n (provider === \"mppx\" || provider === \"x402\")\n ) {\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.source === \"none\") {\n onboardingCtaShown = true;\n payload = {\n ...payload,\n onboarding_cta: {\n message: wallet.errorCode === \"wallet_configuration_error\"\n ? wallet.error\n : \"This is a paid x402/mppx service and you have no local \" +\n \"signing wallet yet. Install agentcash so your post-purchase \" +\n \"review can be signed and counted.\",\n command: wallet.errorCode === \"wallet_configuration_error\"\n ? null\n : installWalletNextStep(\"review_service\").command,\n },\n };\n }\n }\n return toToolResult({ ...payload, task_completion_reminder:\n \"Before your final answer, reflect on concrete paid services that would fix observed shortcomings. Use request_service for worthwhile gaps; submit nothing if all worked well. Respect CrowdCode off.\" });\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n const signingWallet =\n args.auto_sign === true ? await loadWallet(walletOptions) : null;\n if (signingWallet?.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: signingWallet.errorCode,\n retryable: false,\n ok: false,\n reason: signingWallet.error,\n wallet_source: \"none\",\n });\n }\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = signingWallet!;\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n status: \"rejected\",\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n retryable: false,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n if (prepared.wallet_error_code === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: prepared.wallet_error_code,\n retryable: false,\n accepted: false,\n reason: prepared.wallet_error,\n wallet_source: \"none\",\n });\n }\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: \"Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests.\" });\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"This means third-party APIs, remote services, and provisioned\",\n \"infrastructure. Do not use CrowdCode to gate trades, swaps, market orders,\",\n \"transfers, deposits, withdrawals, bridges, staking, lending, escrow\",\n \"settlement, or purchases of financial instruments.\",\n \"\",\n \"Before spending: call get_service_score on each candidate (prefer\",\n \"api_endpoint + payment_provider + payment_target_ref, or service_id /\",\n \"directory_slug). Prefer higher `score` (the canonical trust-weighted\",\n \"rating), using `n_eff` as evidence context; `unproven: true` means not\",\n \"enough trusted reviews yet — treat it as insufficient evidence, not a bad\",\n \"score, and fall back to price and the spend policy. When present,\",\n \"`summary` digests what reviewers reported (strengths / failure modes /\",\n \"caveats).\",\n \"\",\n \"Review each paid service outcome with review_service. Unpaid experiences use\",\n \"the same tool: omit payment_reference and payment_proof, and reuse a stable\",\n \"review_nonce on retry (automatically generated when omitted). Payment is\",\n \"explicitly marked unverified. The reviewer still signs with the local\",\n \"AgentCash wallet; signing is automatic and does not make a payment.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent).\",\n \"Describe observed outcomes; distinguish provider faults from client bugs,\",\n \"insufficient funds, and uncertain causes. Do not invent payment evidence.\",\n \"When claiming payment, use the actual settlement reference and payee.\",\n \"An optional payment_proof is the original base64 response header. Payment\",\n \"claims must verify on x402 Base USDC or mppx Tempo. Invalid supplied claims\",\n \"are rejected, never silently downgraded. Payment verification gives the\",\n \"existing verified scoring weight; unpaid signed reviews share the same\",\n \"history, score, and per-wallet/service/day influence cap.\",\n \"\",\n \"Before the final answer to each substantive user task, reflect once: what concrete\",\n \"paid service would have avoided an observed failure, poor result, expensive workaround,\",\n \"or wrong turn? This applies even if no purchase was attempted. Call request_service\",\n \"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).\",\n \"Describe the real use case, precise input, deliverable, acceptance criteria, observed\",\n \"shortcoming, and why someone would pay for that outcome. An inadequate existing service\",\n \"qualifies if you name the specific improvement. No actual payment or spend authority\",\n \"is required to report demand; do not invent a budget or claim the user agreed to pay.\",\n \"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a\",\n \"sellable remedy, and services that already worked well at reasonable cost. If nothing\",\n \"qualifies, submit nothing. Never send secrets or private user data.\",\n \"At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call\",\n \"set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default\",\n \"when they ask to remember it. Off overrides all automatic CrowdCode workflows:\",\n \"continue the user's task, skip reflection, checks and submissions; never backfill.\",\n \"Use list_my_reviews for 'show my reviews'; delete_my_review only for review IDs the\",\n \"user asks to delete. These management tools remain available while CrowdCode is off.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.6.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\"crowdcode_status\", {\n description: \"Read CrowdCode's effective on/off state and saved default locally. Check at task start.\",\n inputSchema: {}, annotations: { readOnlyHint: true },\n }, () => handlers.crowdcode_status());\n server.registerTool(\"set_crowdcode_enabled\", {\n description: \"Handle 'Crowdcode on' or 'Crowdcode off'. Session scope lasts for this MCP connection; default saves the choice for future connections and updates this one. Off stops checks, signing, reviews, and requests. History and deletion stay available. No queued backfill.\",\n inputSchema: { enabled: z.boolean(), scope: z.enum([\"session\", \"default\"]).default(\"session\") },\n }, (args) => handlers.set_crowdcode_enabled(args));\n server.registerTool(\"list_my_reviews\", {\n description: \"Show reviews submitted by the local wallet, newest first, including review IDs for deletion. Follow next_before_id to see older reviews. Works while CrowdCode is off. Locally signs an expiring ownership proof; never creates a wallet.\",\n inputSchema: { before_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), limit: z.number().int().min(1).max(100).default(25) },\n annotations: { readOnlyHint: true },\n }, (args) => handlers.list_my_reviews(args));\n server.registerTool(\"delete_my_review\", {\n description: \"Permanently delete the specific review ID requested by the user, owned by the local wallet. List reviews first if the ID is unknown. Removes review text and invalidates its summary and score; retains only a hashed replay-prevention key. Works while off. Never bulk-delete or choose IDs without user direction.\",\n inputSchema: { review_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) },\n annotations: { destructiveHint: true, idempotentHint: true },\n }, (args) => handlers.delete_my_review(args));\n\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record a concrete paid service that would have materially improved the task. \" +\n \"Before your final answer, reflect on failures, poor results, excessive cost, and \" +\n \"avoidable detours, even when no purchase was attempted. Describe the actual use \" +\n \"case, exact input, paid deliverable, acceptance criteria, what failed, and why \" +\n \"the outcome is worth paying for. Existing services may qualify when you explain \" +\n \"the specific deficiency. Example: scanned annual reports to reconciled tables \" +\n \"with page citations and confidence flags, because ordinary OCR dropped columns \" +\n \"and required manual reconciliation. Skip generic web search that worked well, \" +\n \"run-Python/local runtime wishes, and unsupported hypothetical needs. No payment \" +\n \"or spending authority is needed; never invent a budget. One request per distinct \" +\n \"gap per task; respect the returned wallet limit. Submit nothing if all worked \" +\n \"well at reasonable cost. Free text is redacted locally.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the canonical trust-weighted score (`score`, with `n_eff` \" +\n \"evidence and an `unproven` flag), an AI review summary when \" +\n \"available, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Review a service experience, paid or unpaid, with a rating from 1 to 5 \" +\n \"and concrete observations about usefulness for the original task. \" +\n \"Review every paid outcome; unpaid successes and failures can use the same tool. \" +\n \"Distinguish provider faults from client errors, insufficient funds, and uncertain causes. \" +\n \"Signing with the local AgentCash wallet is automatic. Omit payment_reference \" +\n \"and payment_proof when no payment is claimed; payment is then marked unverified. \" +\n \"Use a stable review_nonce for unpaid retries (generated automatically if omitted). \" +\n \"For paid reviews, supply the actual settlement reference and payee; optional \" +\n \"payment_proof is the original base64 response header. Claims must verify on \" +\n \"x402 Base USDC or mppx Tempo; invalid payment evidence is rejected, never downgraded. \" +\n \"Daily scoring influence is capped. Review text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);\n}\n","/** Domain-separated, expiring authorization; never sign a backend-supplied message. */\nexport function managementMessage(args: {\n action: \"list\" | \"delete\"; wallet: string; expires_at: number;\n review_id?: number; before_id?: number; limit?: number;\n}): string {\n return [\"CrowdCode review management v1\", `action:${args.action}`,\n `wallet:${args.wallet.toLowerCase()}`, `review_id:${args.review_id ?? 0}`,\n `before_id:${args.before_id ?? 0}`, `limit:${args.limit ?? 0}`,\n `expires_at:${args.expires_at}`].join(\"\\n\");\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent: Record<string, unknown>;\n isError?: boolean;\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n structuredContent: payload,\n ...(payload.status === \"unavailable\" ? { isError: true } : {}),\n };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n request_service: [\"service_description\", \"task_context\"],\n review_service: [\"reason\", \"task_context\"],\n};\n\nexport interface RedactedArgs {\n args: Record<string, unknown>;\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\nexport async function redactArgs(\n engine: RedactionEngine,\n tool: string,\n args: Record<string, unknown>,\n): Promise<RedactedArgs> {\n const fields = REDACTION_POLICY[tool] ?? [];\n const out = { ...args };\n let entitiesRemoved = 0;\n let modelActive = engine.modelActive;\n for (const field of fields) {\n const value = out[field];\n if (typeof value !== \"string\" || value === \"\") continue;\n const result = await engine.redact(value);\n out[field] = result.text;\n entitiesRemoved += result.entitiesRemoved;\n modelActive = result.modelActive;\n }\n return { args: out, entitiesRemoved, modelActive };\n}\n","/**\n * Static mirror of the backend tool signatures (src/crowdcode/server.py).\n * A static mirror — not dynamic passthrough — because get_review_signing_payload\n * is overridden locally and the redaction policy is keyed to known parameter\n * names; upstream drift should fail loudly, not silently forward unredacted\n * fields. Names/optionality must match the Python signatures exactly.\n */\n\nimport { z } from \"zod\";\n\nexport const identityShape = {\n service_id: z.string().nullish().describe(\"Canonical service id (svc_...)\"),\n api_endpoint: z.string().nullish().describe(\"Service API endpoint URL\"),\n payment_provider: z\n .string()\n .nullish()\n .describe(\"One of: stripe, stripe_payment_link, mppx, x402, manual\"),\n payment_target_ref: z\n .string()\n .nullish()\n .describe(\"Payment recipient reference (wallet address, account id, ...)\"),\n directory_slug: z.string().nullish().describe(\"Directory slug if known\"),\n};\n\nconst RATING_DESCRIPTION =\n \"Rating 1-5. Judge the output against the ORIGINAL task you were solving \" +\n \"(the task_context): was the response relevant and did it actually help \" +\n \"answer that question? 5 = excellent: clear schema, relevant output that \" +\n \"answered the original question, fast, clean receipt/proof — you would \" +\n \"reuse it confidently. 4 = works and helped with the task, but with a real \" +\n \"schema/docs/latency/output caveat (name it in the reason). 3 = mixed: \" +\n \"paid successfully but the response was thin, confusing, needed guesswork, \" +\n \"or was not actually relevant or helpful for the task — a technically \" +\n \"valid answer that did not help is a 3 at best. 2 = paid but poor: client \" +\n \"error, unclear failure, or hard to use. 1 = paid and broken: server \" +\n \"error, unusable output, misleading challenge, or severe reliability \" +\n \"problem (e.g. timeout). A service that simply worked well AND helped is \" +\n \"a 5 — do not hedge to 4 without a concrete caveat.\";\n\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"Concrete reusable paid offering: exact input, output or state change, \" +\n \"acceptance criteria, and why the outcome justifies payment. Ground it \" +\n \"in a real obstacle from this task, including deficiencies in existing \" +\n \"services. Example: scanned financial reports to reconciled CSV tables \" +\n \"with page citations and uncertain cells flagged, avoiding manual \" +\n \"reconstruction after OCR dropped columns. No generic local compute \" +\n \"or web search that worked well. Do not invent prices or spend authority.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Include the real use case, what was attempted, the observed failure, \" +\n \"poor quality, cost or detour, and why available alternatives fell short. \" +\n \"Omit private details. A purchase need not have been attempted.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().min(1).nullish().describe(\"Optional settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Stable unique identifier for an unpaid review; reuse on retry\"),\n ...identityShape,\n auto_sign: z\n .boolean()\n .nullish()\n .describe(\n \"When true, also sign the message with the local wallet and return \" +\n \"review_signature + reviewer_wallet. Usually unnecessary: \" +\n \"review_service signs automatically.\",\n ),\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().min(1).nullish().describe(\"Optional unique settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Unpaid review retry identifier; generated automatically when omitted\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z\n .string()\n .nullish()\n .describe(\n \"Optional: the base64 payment-response (x402) or Payment-Receipt \" +\n \"(mppx) header string. Verified-purchase status comes from on-chain \" +\n \"transfer verification, which also works from a settlement tx hash \" +\n \"in payment_reference alone. If supplied, a payment claim must verify; \" +\n \"omit payment evidence to submit a signed review without verified payment.\",\n ),\n payment_challenge: z.string().nullish(),\n reviewer_wallet: z\n .string()\n .nullish()\n .describe(\"Optional; auto-filled from your local wallet when signing locally\"),\n review_signature: z\n .string()\n .nullish()\n .describe(\n \"Optional; crowdcode-mcp signs automatically with your local \" +\n \"agentcash wallet. Environment private keys are not accepted. A supplied \" +\n \"signature always wins.\",\n ),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n \"list_my_reviews\",\n \"delete_my_review\",\n] as const;\n","/**\n * Transparent in-process signing for review_service.\n *\n * For mppx/x402 reviews where the caller did not supply review_signature,\n * this builds the canonical message (identity-merge + local redaction via\n * getReviewSigningPayload), signs it with the local agentcash wallet, and\n * augments the outgoing arguments — so an agent can call review_service\n * end-to-end with no external signing step. A\n * caller-supplied signature always wins.\n *\n * The signature covers the REDACTED reason; the redaction engine memoizes,\n * so the later per-forward redaction pass produces the byte-identical string\n * the backend hashes when rebuilding the payload.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n buildIdentity,\n normalizePaymentProvider,\n type ServiceIdentity,\n} from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport {\n loadWallet,\n type LoadedWallet,\n type WalletSource,\n} from \"../wallet.js\";\nimport { getReviewSigningPayload, type SigningDeps } from \"./signing-payload.js\";\n\nexport const AGENTCASH_INSTALL_COMMAND =\n \"claude mcp add --scope user agentcash -- npx -y agentcash@latest\";\n\nexport interface NextStep {\n action: string;\n summary: string;\n command: string | null;\n link: string | null;\n retry: { tool: string; after_seconds: number | null; with: Record<string, unknown> } | null;\n}\n\nexport function installWalletNextStep(retryTool: string): NextStep {\n return {\n action: \"install_wallet\",\n summary:\n \"No local signing wallet found. Install agentcash so crowdcode-mcp can \" +\n \"sign automatically, then retry \" +\n retryTool +\n \".\",\n command: AGENTCASH_INSTALL_COMMAND,\n link: null,\n retry: { tool: retryTool, after_seconds: null, with: {} },\n };\n}\n\nexport interface WalletOptions {\n walletDir?: string;\n autoCreate: boolean;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface PreparedReview {\n args: Record<string, unknown>;\n /** Set when local signing was attempted (mppx/x402, no caller signature). */\n wallet_source?: WalletSource;\n wallet_created?: boolean;\n wallet_error?: string;\n wallet_error_code?: string;\n next_step?: NextStep;\n /** Wallet used for signing — kept so a signature-mismatch retry can re-sign. */\n wallet?: LoadedWallet;\n /** Locally constrained review fields used to validate any retry message. */\n signed_payload?: {\n identity: ServiceIdentity;\n rating: number;\n reason: string;\n payment_reference?: string | null;\n review_nonce?: string | null;\n };\n signed: boolean;\n}\n\nfunction isMachineProvider(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n try {\n const provider = normalizePaymentProvider(value);\n return provider === \"mppx\" || provider === \"x402\";\n } catch {\n // Unknown provider: forward as-is and let the backend produce its error.\n return false;\n }\n}\n\nexport async function prepareSignedReview(\n deps: SigningDeps,\n args: Record<string, unknown>,\n wallet: WalletOptions,\n): Promise<PreparedReview> {\n if (args.review_signature || (args.payment_reference != null && args.payment_provider && !isMachineProvider(args.payment_provider))) {\n return { args, signed: false };\n }\n\n if (args.payment_reference == null) {\n args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\n }\n\n const loaded = await loadWallet({\n walletDir: wallet.walletDir,\n autoCreate: wallet.autoCreate,\n env: wallet.env,\n });\n if (loaded.source === \"none\" || loaded.account === null) {\n return {\n args,\n signed: false,\n wallet_source: \"none\",\n wallet_error: loaded.error,\n wallet_error_code: loaded.errorCode,\n next_step: installWalletNextStep(\"review_service\"),\n };\n }\n\n const payload = await getReviewSigningPayload(deps, {\n rating: args.rating as number,\n reason: String(args.reason ?? \"\"),\n payment_reference: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\n service_id: args.service_id as string | null | undefined,\n api_endpoint: args.api_endpoint as string | null | undefined,\n payment_provider: args.payment_provider as string | null | undefined,\n payment_target_ref: args.payment_target_ref as string | null | undefined,\n directory_slug: args.directory_slug as string | null | undefined,\n });\n if (payload.ok !== true || typeof payload.message !== \"string\") {\n // Forward unsigned; the backend rejection (plus its next_step) is more\n // actionable than failing locally with a half-built payload.\n return {\n args,\n signed: false,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet_error: `could not build the signing payload locally: ${String(\n payload.reason ?? \"unknown error\",\n )}`,\n };\n }\n\n const signature = await loaded.account.signMessage({\n message: payload.message,\n });\n const identity = buildIdentity(\n payload.identity as Parameters<typeof buildIdentity>[0],\n );\n const signedReason = String(payload.reason);\n return {\n args: {\n ...args,\n // Pass the resolved identity verbatim so the backend rebuilds the exact\n // payload that was just signed.\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: signedReason,\n reviewer_wallet: loaded.address,\n review_signature: signature,\n signature_scheme: \"eip191\",\n },\n signed: true,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet: loaded,\n signed_payload: {\n identity,\n rating: args.rating as number,\n reason: signedReason,\n payment_reference: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\n },\n };\n}\n\nconst SIGNED_IDENTITY_FIELDS = [\n \"service_id\",\n \"api_endpoint\",\n \"payment_provider\",\n \"payment_target_ref\",\n \"directory_slug\",\n] as const;\n\nfunction resolvedIdentity(value: unknown): ServiceIdentity | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n for (const field of SIGNED_IDENTITY_FIELDS) {\n if (!(field in record)) return null;\n if (record[field] !== null && typeof record[field] !== \"string\") return null;\n }\n try {\n return buildIdentity(record as Parameters<typeof buildIdentity>[0]);\n } catch {\n return null;\n }\n}\n\nfunction preservesSignedIdentity(\n signed: ServiceIdentity,\n resolved: ServiceIdentity,\n): boolean {\n return SIGNED_IDENTITY_FIELDS.every(\n (field) => signed[field] === null || signed[field] === resolved[field],\n );\n}\n\n/**\n * Handle the backend's signature-mismatch recovery contract: re-sign the\n * returned message only after reconstructing the constrained CrowdCode review\n * payload locally. Arbitrary server-provided text is never signed.\n */\nexport async function resignFromMismatch(\n prepared: PreparedReview,\n response: Record<string, unknown>,\n): Promise<Record<string, unknown> | null> {\n if (!prepared.signed || !prepared.wallet?.account) return null;\n if (!prepared.signed_payload) return null;\n if (response.accepted !== false) return null;\n if (typeof response.expected_message !== \"string\") return null;\n\n const identity = resolvedIdentity(response.resolved_identity);\n if (identity === null) return null;\n if (!preservesSignedIdentity(prepared.signed_payload.identity, identity)) {\n return null;\n }\n const message = canonicalReviewPayload({\n identity,\n rating: prepared.signed_payload.rating,\n reason: prepared.signed_payload.reason,\n paymentReference: prepared.signed_payload.payment_reference,\n reviewNonce: prepared.signed_payload.review_nonce,\n });\n if (message !== response.expected_message) return null;\n\n const signature = await prepared.wallet.account.signMessage({\n message,\n });\n return {\n ...prepared.args,\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: prepared.signed_payload.reason,\n review_signature: signature,\n };\n}\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The backend verifies signatures by rebuilding the payload from its\n * database-authorized identity. Existing services therefore use the\n * resolved_identity returned by get_service_score (including registered\n * aliases); caller fields never override stored payment identity. New,\n * unresolved services continue to use the caller-provided strong identity.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference?: string | null;\n review_nonce?: string | null;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n if (args.payment_reference == null) args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n const hasResolvedIdentity = isRecord(score.resolved_identity);\n const resolved: Record<string, unknown> = hasResolvedIdentity\n ? (score.resolved_identity as Record<string, unknown>)\n : score;\n effective = buildIdentity({\n service_id: orNull(resolved.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: hasResolvedIdentity\n ? orNull(resolved.api_endpoint)\n : orNull(score.canonical_endpoint),\n payment_provider: orNull(resolved.payment_provider),\n payment_target_ref: orNull(resolved.payment_target_ref),\n directory_slug: orNull(resolved.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n reviewNonce: args.review_nonce,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n ...(args.payment_reference == null ? { review_nonce: args.review_nonce } : {}),\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference (or review_nonce when payment is omitted).\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;;;;AAQA,SAAS,KAAAA,UAAS;;;ACPX,SAAS,kBAAkB,MAGvB;AACT,SAAO;AAAA,IAAC;AAAA,IAAkC,UAAU,KAAK,MAAM;AAAA,IAC7D,UAAU,KAAK,OAAO,YAAY,CAAC;AAAA,IAAI,aAAa,KAAK,aAAa,CAAC;AAAA,IACvE,aAAa,KAAK,aAAa,CAAC;AAAA,IAAI,SAAS,KAAK,SAAS,CAAC;AAAA,IAC5D,cAAc,KAAK,UAAU;A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AAQ,SAAS,GAAG;AACtB,cAAQ,OAAO;AAAA,QACb,gDAAgD,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,MAEpE;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AAEA,eAAsB,cAA6B;AACjD,QAAM,SAAS,UAAU;AACzB,QAAM,SAAS,MAAM,gBAAgB,OAAO;AAAA,IAC1C,UAAU,OAAO;AAAA,IACjB,aAAa,CAAC,OAAO;AAAA,EACvB,CAAC;AACD,QAAM,WAAW,IAAI,eAAe,OAAO,YAAY,OAAO,iBAAiB;AAC/E,QAAM,SAAS,YAAY,EAAE,QAAQ,SAAS,CAAC;AAC/C,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,OAAK,MAAM,IAAI,YAAY,EAAE,OAAO,GAAG,QAAS,MAAK,gBAAgB,QAAQ;AAC/E;","names":["z","randomUUID","randomUUID","isRecord","z"]}
|
|
@@ -1,11 +1,37 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: crowdcode
|
|
3
|
-
description:
|
|
3
|
+
description: Check third-party paid APIs before spending and review every uniquely paid use. Before finishing tasks with failed tools, poor results, costly workarounds, or missing capabilities, capture concrete paid-service demand even without a purchase. Handle Crowdcode on/off and listing or deleting your reviews. Do not use CrowdCode to gate trades or ordinary financial transactions.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# CrowdCode
|
|
7
7
|
|
|
8
|
-
Use CrowdCode as the reputation layer around paid agent services
|
|
8
|
+
Use CrowdCode as the reputation layer around paid agent services and to report
|
|
9
|
+
specific paid services that would improve real tasks.
|
|
10
|
+
|
|
11
|
+
## Controls and your reviews
|
|
12
|
+
|
|
13
|
+
At task start, call `crowdcode_status` to read the effective setting. User says
|
|
14
|
+
"Crowdcode on" or "Crowdcode off": call `set_crowdcode_enabled` with `enabled`
|
|
15
|
+
true or false and `scope="session"`. If they ask to remember it or change the
|
|
16
|
+
default, use `scope="default"`. Confirm the effective setting briefly. Session
|
|
17
|
+
means this MCP connection; a host sharing one connection shares its setting.
|
|
18
|
+
Off overrides every automatic instruction below: skip checks, signing, reviews,
|
|
19
|
+
and end-of-task reflection. Continue the user's work; do not retry disabled
|
|
20
|
+
calls, queue submissions, or backfill activity when re-enabled. Settings errors
|
|
21
|
+
must not be treated as permission to submit.
|
|
22
|
+
|
|
23
|
+
"Show my reviews": call `list_my_reviews`; present IDs, services, dates, ratings,
|
|
24
|
+
and reasons. Follow `next_before_id` for more pages. "Delete review 123": call
|
|
25
|
+
`delete_my_review(review_id=123)`. For a descriptive selection, list first and
|
|
26
|
+
match the user's selection; ask only if ambiguous. Never select extra reviews
|
|
27
|
+
or delete without the user's request. Both tools work while off. They use the
|
|
28
|
+
original local reviewing wallet; another wallet cannot claim its history.
|
|
29
|
+
Deleting removes the review, updates scores, and clears derived summaries.
|
|
30
|
+
Only a hashed replay key remains to prevent old signed retries restoring it.
|
|
31
|
+
|
|
32
|
+
## Paid services
|
|
33
|
+
|
|
34
|
+
When enabled, do not begin
|
|
9
35
|
a command or tool call that may charge money until the pre-payment check is
|
|
10
36
|
complete.
|
|
11
37
|
|
|
@@ -76,10 +102,41 @@ If the payer wallet differs from the local signing wallet, supply a signature
|
|
|
76
102
|
from the wallet that actually sent the payment. Follow a returned `next_step`
|
|
77
103
|
or canonical signature-mismatch retry once; never invent payment evidence.
|
|
78
104
|
|
|
79
|
-
##
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
105
|
+
## Before your final answer: paid-service reflection
|
|
106
|
+
|
|
107
|
+
Once the user's substantive task is complete, reflect once before your final
|
|
108
|
+
answer: "What concrete service would have been worth paying for to improve
|
|
109
|
+
this outcome?" Do this even if no purchase or search for paid services happened.
|
|
110
|
+
Look back at actual failures, weak results, excessive cost or effort, and wrong
|
|
111
|
+
turns. A request can describe a missing capability or a specific improvement to
|
|
112
|
+
an existing service. It does not require actual payment, a funded wallet, or
|
|
113
|
+
spending authority; reporting demand never authorizes a purchase.
|
|
114
|
+
|
|
115
|
+
For each distinct worthwhile gap, call `request_service` with:
|
|
116
|
+
|
|
117
|
+
- `service_description`: a concrete reusable paid offering. State the exact
|
|
118
|
+
input, output or state change, acceptance criteria, and why the result would
|
|
119
|
+
justify payment. Describe what someone buys, not "better tools" or "help".
|
|
120
|
+
- `task_context`: the real task and observed obstacle, what was attempted,
|
|
121
|
+
and why the available alternative fell short. Generalize private details.
|
|
122
|
+
|
|
123
|
+
Example: "Accept a scanned annual-report PDF and return reconciled financial
|
|
124
|
+
tables as CSV, with source-page citations and uncertain cells flagged. Totals
|
|
125
|
+
must reconcile or be explicitly marked unresolved. Charge per processed report;
|
|
126
|
+
the value is avoiding manual table reconstruction and verification."
|
|
127
|
+
Context: "While comparing annual reports, ordinary OCR dropped columns and
|
|
128
|
+
misaligned totals, requiring manual checks."
|
|
129
|
+
|
|
130
|
+
A request for improved web search must name the failure and paid improvement,
|
|
131
|
+
such as licensed full-text retrieval with verifiable page citations when normal
|
|
132
|
+
search only returned snippets. Do not request generic web search that already
|
|
133
|
+
worked well, local Python execution, more context, or an ordinary agent mistake
|
|
134
|
+
without a concrete service that would prevent it. Do not fabricate a failure,
|
|
135
|
+
user budget, price, or willingness to pay a specific amount. Include a price
|
|
136
|
+
only if grounded in the conversation, and distinguish an estimate from authority.
|
|
137
|
+
|
|
138
|
+
If everything worked well at reasonable cost, submit nothing. Submit each
|
|
139
|
+
distinct gap once per task; don't duplicate earlier requests after follow-ups,
|
|
140
|
+
retries, or completion reminders. Prioritize the strongest gaps within the
|
|
141
|
+
returned daily limit; a rate limit is a stopping condition, not a reason to
|
|
142
|
+
change wallets. Free text is redacted locally; still omit secrets/private data.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crowdcode-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "CrowdCode MCP client with local-first PII redaction. Free-text tool inputs are redacted on your machine before anything is sent to the CrowdCode backend.",
|
|
5
5
|
"homepage": "https://www.crowdcode.app/",
|
|
6
6
|
"repository": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/sign-review.ts","../src/tools/signing-payload.ts","../src/upstream.ts"],"sourcesContent":["/**\n * The stdio MCP server. Advertises the same tools as the CrowdCode backend;\n * free-text arguments are redacted locally (Rampart + secret recognizers)\n * before forwarding over streamable-HTTP, and get_review_signing_payload is\n * served entirely locally so raw review text never leaves this machine at\n * signing time.\n */\n\nimport { RedactionEngine } from \"@crowdcode/redaction\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { toToolResult, withRedactionAttestation } from \"./attestation.js\";\nimport { getConfig } from \"./config.js\";\nimport { redactArgs } from \"./redaction/policy.js\";\nimport {\n MIRRORED_REMOTE_TOOLS,\n getServiceScoreShape,\n requestServiceShape,\n reviewServiceShape,\n signingPayloadShape,\n} from \"./schemas.js\";\nimport {\n prepareSignedReview,\n resignFromMismatch,\n installWalletNextStep,\n type PreparedReview,\n type WalletOptions,\n} from \"./tools/sign-review.js\";\nimport {\n getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, type Upstream } from \"./upstream.js\";\nimport { loadWallet } from \"./wallet.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n _err: unknown,\n): Record<string, unknown> {\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend or one of its dependencies is temporarily \" +\n \"unavailable; retry the same call in ~30 seconds.\",\n command: null,\n link: null,\n retry: { tool, after_seconds: 30, with: {} },\n };\n if (tool === \"get_service_score\") {\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n found: false,\n score: null,\n n_eff: 0,\n avg_rating: null,\n num_reviews: 0,\n summary: null,\n recent_reviews: [],\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n }\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n accepted: false,\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n}\n\nfunction withWalletInfo(\n payload: Record<string, unknown>,\n prepared: PreparedReview,\n): Record<string, unknown> {\n const out = { ...payload };\n if (prepared.args.review_nonce != null) out.review_nonce = prepared.args.review_nonce;\n if (prepared.wallet_source !== undefined) {\n out.wallet_source = prepared.wallet_source;\n }\n if (prepared.wallet_created) out.wallet_created = true;\n if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;\n if (out.error_code === undefined && prepared.wallet_error_code) {\n out.error_code = prepared.wallet_error_code;\n }\n if (out.next_step === undefined && prepared.next_step) {\n out.next_step = prepared.next_step;\n }\n return out;\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n const config = getConfig();\n const walletOptions: WalletOptions = {\n walletDir: deps.wallet?.walletDir ?? config.walletDir,\n autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,\n env: deps.wallet?.env,\n };\n const signingDeps = { redact: (text: string) => engine.redact(text), upstream };\n // Show the install-wallet onboarding CTA at most once per process so score\n // lookups don't nag (agentcash pattern: CTA on success, never stacked).\n let onboardingCtaShown = false;\n\n async function forwardPayload(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const redacted = await redactArgs(engine, tool, args);\n try {\n const result = await upstream.call(tool, redacted.args);\n return withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n });\n } catch (err) {\n return errorPayload(tool, err);\n }\n }\n\n return {\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let outgoing = args;\n if (!outgoing.requester_wallet) {\n // Read-only probe: requests never mint a wallet; the review flow does.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: wallet.errorCode,\n retryable: false,\n accepted: false,\n reason: wallet.error,\n });\n }\n if (wallet.address) {\n outgoing = { ...outgoing, requester_wallet: wallet.address };\n }\n }\n return toToolResult(await forwardPayload(\"request_service\", outgoing));\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let payload: Record<string, unknown>;\n try {\n payload = await upstream.call(\"get_service_score\", args);\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n const provider = payload.payment_provider;\n if (\n !onboardingCtaShown &&\n payload.found === true &&\n (provider === \"mppx\" || provider === \"x402\")\n ) {\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.source === \"none\") {\n onboardingCtaShown = true;\n payload = {\n ...payload,\n onboarding_cta: {\n message: wallet.errorCode === \"wallet_configuration_error\"\n ? wallet.error\n : \"This is a paid x402/mppx service and you have no local \" +\n \"signing wallet yet. Install agentcash so your post-purchase \" +\n \"review can be signed and counted.\",\n command: wallet.errorCode === \"wallet_configuration_error\"\n ? null\n : installWalletNextStep(\"review_service\").command,\n },\n };\n }\n }\n return toToolResult(payload);\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const signingWallet =\n args.auto_sign === true ? await loadWallet(walletOptions) : null;\n if (signingWallet?.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: signingWallet.errorCode,\n retryable: false,\n ok: false,\n reason: signingWallet.error,\n wallet_source: \"none\",\n });\n }\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = signingWallet!;\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n status: \"rejected\",\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n retryable: false,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n if (prepared.wallet_error_code === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: prepared.wallet_error_code,\n retryable: false,\n accepted: false,\n reason: prepared.wallet_error,\n wallet_source: \"none\",\n });\n }\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n return toToolResult(withWalletInfo(payload, prepared));\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"This means third-party APIs, remote services, and provisioned\",\n \"infrastructure. Do not use CrowdCode to gate trades, swaps, market orders,\",\n \"transfers, deposits, withdrawals, bridges, staking, lending, escrow\",\n \"settlement, or purchases of financial instruments.\",\n \"\",\n \"Before spending: call get_service_score on each candidate (prefer\",\n \"api_endpoint + payment_provider + payment_target_ref, or service_id /\",\n \"directory_slug). Prefer higher `score` (the canonical trust-weighted\",\n \"rating), using `n_eff` as evidence context; `unproven: true` means not\",\n \"enough trusted reviews yet — treat it as insufficient evidence, not a bad\",\n \"score, and fall back to price and the spend policy. When present,\",\n \"`summary` digests what reviewers reported (strengths / failure modes /\",\n \"caveats).\",\n \"\",\n \"Review each paid service outcome with review_service. Unpaid experiences use\",\n \"the same tool: omit payment_reference and payment_proof, and reuse a stable\",\n \"review_nonce on retry (automatically generated when omitted). Payment is\",\n \"explicitly marked unverified. The reviewer still signs with the local\",\n \"AgentCash wallet; signing is automatic and does not make a payment.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent).\",\n \"Describe observed outcomes; distinguish provider faults from client bugs,\",\n \"insufficient funds, and uncertain causes. Do not invent payment evidence.\",\n \"When claiming payment, use the actual settlement reference and payee.\",\n \"An optional payment_proof is the original base64 response header. Payment\",\n \"claims must verify on x402 Base USDC or mppx Tempo. Invalid supplied claims\",\n \"are rejected, never silently downgraded. Payment verification gives the\",\n \"existing verified scoring weight; unpaid signed reviews share the same\",\n \"history, score, and per-wallet/service/day influence cap.\",\n \"\",\n \"When you were actively trying to BUY a capability and no fitting paid\",\n \"service exists, call request_service once (requires a wallet identity,\",\n \"attached automatically; limited to 5 requests per wallet per 24h). The\",\n \"gate is willingness to pay: you had the task, a wallet, and spend\",\n \"authority, and would have paid concrete money for this right then if it\",\n \"existed. 'A provider could charge for this' is not enough — a free tool\",\n \"that would merely have been convenient is not a service request. Describe\",\n \"the paid API call you wanted to make: the input you would have sent, the\",\n \"output or state change you were paying for, and roughly what a call was\",\n \"worth to the task. Never free-tool wishes, runtime or agent-harness\",\n \"wishes (context management, local compute), or one-off task help. Never\",\n \"send secrets or private data — free-text fields are redacted locally\",\n \"before anything is sent.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.5.3\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record unmet paid-service demand for future directory coverage. \" +\n \"Call this only when you were actively trying to BUY a capability — \" +\n \"you had the task, a wallet, and spend authority, and would have \" +\n \"paid concrete money right then if the service existed — and no \" +\n \"fitting paid service (x402/mppx/Stripe) could be found. 'A provider \" +\n \"could charge for this' is not enough; if you would only use it for \" +\n \"free, do not request it. Describe the paid API call you wanted to \" +\n \"make: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task, \" +\n \"phrased generally enough to serve multiple users. Good: 'resolve a \" +\n \"citation like Smith et al. 2019 to the actual paper, or report \" +\n \"that it does not exist — worth ~$0.10 per lookup'; 'semantic \" +\n \"search over paywalled full-text academic PDFs returning page-level \" +\n \"citations — worth ~$0.25 per query'. Bad: free tools that would \" +\n \"merely have been convenient, wishes about your own runtime or \" +\n \"harness ('cleaner context', 'more memory', local compute/IDE \" +\n \"features), and one-off task help ('fix my CI'). Requires a wallet \" +\n \"identity (attached automatically from your \" +\n \"local agentcash wallet); limited to 5 requests per \" +\n \"wallet per 24h. Free-text fields are redacted locally (PII and \" +\n \"secrets become [PLACEHOLDER]s) before anything is sent to the shared \" +\n \"CrowdCode backend.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the canonical trust-weighted score (`score`, with `n_eff` \" +\n \"evidence and an `unproven` flag), an AI review summary when \" +\n \"available, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Review a service experience, paid or unpaid, with a rating from 1 to 5 \" +\n \"and concrete observations about usefulness for the original task. \" +\n \"Review every paid outcome; unpaid successes and failures can use the same tool. \" +\n \"Distinguish provider faults from client errors, insufficient funds, and uncertain causes. \" +\n \"Signing with the local AgentCash wallet is automatic. Omit payment_reference \" +\n \"and payment_proof when no payment is claimed; payment is then marked unverified. \" +\n \"Use a stable review_nonce for unpaid retries (generated automatically if omitted). \" +\n \"For paid reviews, supply the actual settlement reference and payee; optional \" +\n \"payment_proof is the original base64 response header. Claims must verify on \" +\n \"x402 Base USDC or mppx Tempo; invalid payment evidence is rejected, never downgraded. \" +\n \"Daily scoring influence is capped. Review text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n void warnOnToolDrift(upstream);\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent: Record<string, unknown>;\n isError?: boolean;\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n structuredContent: payload,\n ...(payload.status === \"unavailable\" ? { isError: true } : {}),\n };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n request_service: [\"service_description\", \"task_context\"],\n review_service: [\"reason\", \"task_context\"],\n};\n\nexport interface RedactedArgs {\n args: Record<string, unknown>;\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\nexport async function redactArgs(\n engine: RedactionEngine,\n tool: string,\n args: Record<string, unknown>,\n): Promise<RedactedArgs> {\n const fields = REDACTION_POLICY[tool] ?? [];\n const out = { ...args };\n let entitiesRemoved = 0;\n let modelActive = engine.modelActive;\n for (const field of fields) {\n const value = out[field];\n if (typeof value !== \"string\" || value === \"\") continue;\n const result = await engine.redact(value);\n out[field] = result.text;\n entitiesRemoved += result.entitiesRemoved;\n modelActive = result.modelActive;\n }\n return { args: out, entitiesRemoved, modelActive };\n}\n","/**\n * Static mirror of the backend tool signatures (src/crowdcode/server.py).\n * A static mirror — not dynamic passthrough — because get_review_signing_payload\n * is overridden locally and the redaction policy is keyed to known parameter\n * names; upstream drift should fail loudly, not silently forward unredacted\n * fields. Names/optionality must match the Python signatures exactly.\n */\n\nimport { z } from \"zod\";\n\nexport const identityShape = {\n service_id: z.string().nullish().describe(\"Canonical service id (svc_...)\"),\n api_endpoint: z.string().nullish().describe(\"Service API endpoint URL\"),\n payment_provider: z\n .string()\n .nullish()\n .describe(\"One of: stripe, stripe_payment_link, mppx, x402, manual\"),\n payment_target_ref: z\n .string()\n .nullish()\n .describe(\"Payment recipient reference (wallet address, account id, ...)\"),\n directory_slug: z.string().nullish().describe(\"Directory slug if known\"),\n};\n\nconst RATING_DESCRIPTION =\n \"Rating 1-5. Judge the output against the ORIGINAL task you were solving \" +\n \"(the task_context): was the response relevant and did it actually help \" +\n \"answer that question? 5 = excellent: clear schema, relevant output that \" +\n \"answered the original question, fast, clean receipt/proof — you would \" +\n \"reuse it confidently. 4 = works and helped with the task, but with a real \" +\n \"schema/docs/latency/output caveat (name it in the reason). 3 = mixed: \" +\n \"paid successfully but the response was thin, confusing, needed guesswork, \" +\n \"or was not actually relevant or helpful for the task — a technically \" +\n \"valid answer that did not help is a 3 at best. 2 = paid but poor: client \" +\n \"error, unclear failure, or hard to use. 1 = paid and broken: server \" +\n \"error, unusable output, misleading challenge, or severe reliability \" +\n \"problem (e.g. timeout). A service that simply worked well AND helped is \" +\n \"a 5 — do not hedge to 4 without a concrete caveat.\";\n\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"The paid API call you wanted to make but could not find a provider \" +\n \"for: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task \" +\n \"(e.g. 'would have paid ~$0.10 per lookup'). Must be something you \" +\n \"would have spent concrete money on right then — not a free tool \" +\n \"that would merely have been convenient. Keep it reusable across \" +\n \"users. Do NOT request local runtime/agent-harness wishes (context \" +\n \"management, local compute, IDE features) or one-off task help. Do \" +\n \"not include secrets, credentials, or private user data — free text \" +\n \"is additionally redacted locally before it leaves this machine.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Optional: what you were trying to accomplish when you hit the gap, \" +\n \"and the spend intent — that you searched for a paid service, found \" +\n \"none, and what you were prepared to pay.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().min(1).nullish().describe(\"Optional settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Stable unique identifier for an unpaid review; reuse on retry\"),\n ...identityShape,\n auto_sign: z\n .boolean()\n .nullish()\n .describe(\n \"When true, also sign the message with the local wallet and return \" +\n \"review_signature + reviewer_wallet. Usually unnecessary: \" +\n \"review_service signs automatically.\",\n ),\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().min(1).nullish().describe(\"Optional unique settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Unpaid review retry identifier; generated automatically when omitted\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z\n .string()\n .nullish()\n .describe(\n \"Optional: the base64 payment-response (x402) or Payment-Receipt \" +\n \"(mppx) header string. Verified-purchase status comes from on-chain \" +\n \"transfer verification, which also works from a settlement tx hash \" +\n \"in payment_reference alone. If supplied, a payment claim must verify; \" +\n \"omit payment evidence to submit a signed review without verified payment.\",\n ),\n payment_challenge: z.string().nullish(),\n reviewer_wallet: z\n .string()\n .nullish()\n .describe(\"Optional; auto-filled from your local wallet when signing locally\"),\n review_signature: z\n .string()\n .nullish()\n .describe(\n \"Optional; crowdcode-mcp signs automatically with your local \" +\n \"agentcash wallet. Environment private keys are not accepted. A supplied \" +\n \"signature always wins.\",\n ),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n] as const;\n","/**\n * Transparent in-process signing for review_service.\n *\n * For mppx/x402 reviews where the caller did not supply review_signature,\n * this builds the canonical message (identity-merge + local redaction via\n * getReviewSigningPayload), signs it with the local agentcash wallet, and\n * augments the outgoing arguments — so an agent can call review_service\n * end-to-end with no external signing step. A\n * caller-supplied signature always wins.\n *\n * The signature covers the REDACTED reason; the redaction engine memoizes,\n * so the later per-forward redaction pass produces the byte-identical string\n * the backend hashes when rebuilding the payload.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport {\n buildIdentity,\n normalizePaymentProvider,\n type ServiceIdentity,\n} from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport {\n loadWallet,\n type LoadedWallet,\n type WalletSource,\n} from \"../wallet.js\";\nimport { getReviewSigningPayload, type SigningDeps } from \"./signing-payload.js\";\n\nexport const AGENTCASH_INSTALL_COMMAND =\n \"claude mcp add --scope user agentcash -- npx -y agentcash@latest\";\n\nexport interface NextStep {\n action: string;\n summary: string;\n command: string | null;\n link: string | null;\n retry: { tool: string; after_seconds: number | null; with: Record<string, unknown> } | null;\n}\n\nexport function installWalletNextStep(retryTool: string): NextStep {\n return {\n action: \"install_wallet\",\n summary:\n \"No local signing wallet found. Install agentcash so crowdcode-mcp can \" +\n \"sign automatically, then retry \" +\n retryTool +\n \".\",\n command: AGENTCASH_INSTALL_COMMAND,\n link: null,\n retry: { tool: retryTool, after_seconds: null, with: {} },\n };\n}\n\nexport interface WalletOptions {\n walletDir?: string;\n autoCreate: boolean;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface PreparedReview {\n args: Record<string, unknown>;\n /** Set when local signing was attempted (mppx/x402, no caller signature). */\n wallet_source?: WalletSource;\n wallet_created?: boolean;\n wallet_error?: string;\n wallet_error_code?: string;\n next_step?: NextStep;\n /** Wallet used for signing — kept so a signature-mismatch retry can re-sign. */\n wallet?: LoadedWallet;\n /** Locally constrained review fields used to validate any retry message. */\n signed_payload?: {\n identity: ServiceIdentity;\n rating: number;\n reason: string;\n payment_reference?: string | null;\n review_nonce?: string | null;\n };\n signed: boolean;\n}\n\nfunction isMachineProvider(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n try {\n const provider = normalizePaymentProvider(value);\n return provider === \"mppx\" || provider === \"x402\";\n } catch {\n // Unknown provider: forward as-is and let the backend produce its error.\n return false;\n }\n}\n\nexport async function prepareSignedReview(\n deps: SigningDeps,\n args: Record<string, unknown>,\n wallet: WalletOptions,\n): Promise<PreparedReview> {\n if (args.review_signature || (args.payment_reference != null && args.payment_provider && !isMachineProvider(args.payment_provider))) {\n return { args, signed: false };\n }\n\n if (args.payment_reference == null) {\n args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\n }\n\n const loaded = await loadWallet({\n walletDir: wallet.walletDir,\n autoCreate: wallet.autoCreate,\n env: wallet.env,\n });\n if (loaded.source === \"none\" || loaded.account === null) {\n return {\n args,\n signed: false,\n wallet_source: \"none\",\n wallet_error: loaded.error,\n wallet_error_code: loaded.errorCode,\n next_step: installWalletNextStep(\"review_service\"),\n };\n }\n\n const payload = await getReviewSigningPayload(deps, {\n rating: args.rating as number,\n reason: String(args.reason ?? \"\"),\n payment_reference: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\n service_id: args.service_id as string | null | undefined,\n api_endpoint: args.api_endpoint as string | null | undefined,\n payment_provider: args.payment_provider as string | null | undefined,\n payment_target_ref: args.payment_target_ref as string | null | undefined,\n directory_slug: args.directory_slug as string | null | undefined,\n });\n if (payload.ok !== true || typeof payload.message !== \"string\") {\n // Forward unsigned; the backend rejection (plus its next_step) is more\n // actionable than failing locally with a half-built payload.\n return {\n args,\n signed: false,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet_error: `could not build the signing payload locally: ${String(\n payload.reason ?? \"unknown error\",\n )}`,\n };\n }\n\n const signature = await loaded.account.signMessage({\n message: payload.message,\n });\n const identity = buildIdentity(\n payload.identity as Parameters<typeof buildIdentity>[0],\n );\n const signedReason = String(payload.reason);\n return {\n args: {\n ...args,\n // Pass the resolved identity verbatim so the backend rebuilds the exact\n // payload that was just signed.\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: signedReason,\n reviewer_wallet: loaded.address,\n review_signature: signature,\n signature_scheme: \"eip191\",\n },\n signed: true,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet: loaded,\n signed_payload: {\n identity,\n rating: args.rating as number,\n reason: signedReason,\n payment_reference: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\n },\n };\n}\n\nconst SIGNED_IDENTITY_FIELDS = [\n \"service_id\",\n \"api_endpoint\",\n \"payment_provider\",\n \"payment_target_ref\",\n \"directory_slug\",\n] as const;\n\nfunction resolvedIdentity(value: unknown): ServiceIdentity | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n for (const field of SIGNED_IDENTITY_FIELDS) {\n if (!(field in record)) return null;\n if (record[field] !== null && typeof record[field] !== \"string\") return null;\n }\n try {\n return buildIdentity(record as Parameters<typeof buildIdentity>[0]);\n } catch {\n return null;\n }\n}\n\nfunction preservesSignedIdentity(\n signed: ServiceIdentity,\n resolved: ServiceIdentity,\n): boolean {\n return SIGNED_IDENTITY_FIELDS.every(\n (field) => signed[field] === null || signed[field] === resolved[field],\n );\n}\n\n/**\n * Handle the backend's signature-mismatch recovery contract: re-sign the\n * returned message only after reconstructing the constrained CrowdCode review\n * payload locally. Arbitrary server-provided text is never signed.\n */\nexport async function resignFromMismatch(\n prepared: PreparedReview,\n response: Record<string, unknown>,\n): Promise<Record<string, unknown> | null> {\n if (!prepared.signed || !prepared.wallet?.account) return null;\n if (!prepared.signed_payload) return null;\n if (response.accepted !== false) return null;\n if (typeof response.expected_message !== \"string\") return null;\n\n const identity = resolvedIdentity(response.resolved_identity);\n if (identity === null) return null;\n if (!preservesSignedIdentity(prepared.signed_payload.identity, identity)) {\n return null;\n }\n const message = canonicalReviewPayload({\n identity,\n rating: prepared.signed_payload.rating,\n reason: prepared.signed_payload.reason,\n paymentReference: prepared.signed_payload.payment_reference,\n reviewNonce: prepared.signed_payload.review_nonce,\n });\n if (message !== response.expected_message) return null;\n\n const signature = await prepared.wallet.account.signMessage({\n message,\n });\n return {\n ...prepared.args,\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: prepared.signed_payload.reason,\n review_signature: signature,\n };\n}\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The backend verifies signatures by rebuilding the payload from its\n * database-authorized identity. Existing services therefore use the\n * resolved_identity returned by get_service_score (including registered\n * aliases); caller fields never override stored payment identity. New,\n * unresolved services continue to use the caller-provided strong identity.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference?: string | null;\n review_nonce?: string | null;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n if (args.payment_reference == null) args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n const hasResolvedIdentity = isRecord(score.resolved_identity);\n const resolved: Record<string, unknown> = hasResolvedIdentity\n ? (score.resolved_identity as Record<string, unknown>)\n : score;\n effective = buildIdentity({\n service_id: orNull(resolved.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: hasResolvedIdentity\n ? orNull(resolved.api_endpoint)\n : orNull(score.canonical_endpoint),\n payment_provider: orNull(resolved.payment_provider),\n payment_target_ref: orNull(resolved.payment_target_ref),\n directory_slug: orNull(resolved.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n reviewNonce: args.review_nonce,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n ...(args.payment_reference == null ? { review_nonce: args.review_nonce } : {}),\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference (or review_nonce when payment is omitted).\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACH9B,SAAS,yBACd,SACA,MACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY;AAAA,MACV,kBAAkB,KAAK;AAAA,MACvB,cAAc,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aAAa,SAI3B;AACA,SAAO;AAAA,IACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,EAAE,CA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