crowdcode-mcp 0.12.0 → 0.13.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.
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ /**
3
+ * CrowdCode Stop hook (Claude Code and Codex), installed by
4
+ * `crowdcode-mcp install`.
5
+ *
6
+ * It reads the local transcript the host passes as `transcript_path` (no
7
+ * network) and asks for a reflection only when the turn earned one:
8
+ * - a paid call (by its payment receipt) that was not rated afterwards,
9
+ * - a failed tool call, or
10
+ * - at least 8 tool calls.
11
+ * Otherwise it stays silent. It blocks at most once per stop
12
+ * (`stop_hook_active`) and fails open on anything unexpected.
13
+ */
14
+
15
+ const fs = require("node:fs");
16
+ const os = require("node:os");
17
+ const path = require("node:path");
18
+
19
+ const MANY_TOOL_CALLS = 8;
20
+ const TAIL_BYTES = 4 * 1024 * 1024;
21
+ const REVIEW_TOOL_RE = /crowdcode.*review_service$/i;
22
+ const CROWDCODE_TOOL_RE = /^mcp__(plugin_)?crowdcode/i;
23
+
24
+ function disabled() {
25
+ const dir = process.env.CROWDCODE_HOME || path.join(os.homedir(), ".crowdcode");
26
+ const file = process.env.CROWDCODE_CONFIG_PATH || path.join(dir, "preferences.json");
27
+ try { return JSON.parse(fs.readFileSync(file, "utf8")).enabled === false; } catch { return false; }
28
+ }
29
+
30
+ function tailLines(file) {
31
+ const fd = fs.openSync(file, "r");
32
+ try {
33
+ const size = fs.fstatSync(fd).size;
34
+ const length = Math.min(size, TAIL_BYTES);
35
+ const buffer = Buffer.alloc(length);
36
+ fs.readSync(fd, buffer, 0, length, size - length);
37
+ const lines = buffer.toString("utf8").split("\n");
38
+ if (length < size) lines.shift(); // a partial first line
39
+ const parsed = [];
40
+ for (const line of lines) {
41
+ if (!line.trim()) continue;
42
+ try { parsed.push(JSON.parse(line)); } catch { /* skip */ }
43
+ }
44
+ return parsed;
45
+ } finally { fs.closeSync(fd); }
46
+ }
47
+
48
+ /**
49
+ * The current turn as a flat list of steps:
50
+ * {kind: "call", id, name} | {kind: "result", id, output, failed}
51
+ * Claude Code: `user`/`assistant` lines with tool_use and tool_result blocks.
52
+ * Codex: `response_item` lines with function_call(_output) payloads.
53
+ */
54
+ function currentTurn(entries) {
55
+ let start = 0;
56
+ entries.forEach((entry, index) => {
57
+ if (isUserPrompt(entry)) start = index + 1;
58
+ });
59
+ const steps = [];
60
+ for (const entry of entries.slice(start)) {
61
+ const message = entry && entry.message;
62
+ if (message && Array.isArray(message.content)) {
63
+ for (const block of message.content) {
64
+ if (!block || typeof block !== "object") continue;
65
+ if (block.type === "tool_use") steps.push({ kind: "call", id: block.id, name: String(block.name || "") });
66
+ else if (block.type === "tool_result") steps.push({ kind: "result", id: block.tool_use_id, output: block.content, failed: block.is_error === true });
67
+ }
68
+ continue;
69
+ }
70
+ const payload = entry && entry.type === "response_item" ? entry.payload : null;
71
+ if (!payload) continue;
72
+ if (payload.type === "function_call" || payload.type === "custom_tool_call" || payload.type === "mcp_tool_call") {
73
+ steps.push({ kind: "call", id: payload.call_id, name: String(payload.name || "") });
74
+ } else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output" || payload.type === "mcp_tool_call_output") {
75
+ const output = payload.output;
76
+ const text = typeof output === "string" ? output : JSON.stringify(output ?? "");
77
+ const failed = /"exit_code"\s*:\s*[1-9]/.test(text) || /"is_?error"\s*:\s*true/i.test(text) ||
78
+ /"success"\s*:\s*false/.test(text) || (output && typeof output === "object" && output.success === false);
79
+ steps.push({ kind: "result", id: payload.call_id, output, failed: Boolean(failed) });
80
+ }
81
+ }
82
+ return steps;
83
+ }
84
+
85
+ function isUserPrompt(entry) {
86
+ if (!entry || entry.isMeta) return false;
87
+ if (entry.type === "user" && entry.message) {
88
+ const content = entry.message.content;
89
+ if (typeof content === "string") return true;
90
+ return Array.isArray(content) && content.length > 0 && !content.some(block => block && block.type === "tool_result");
91
+ }
92
+ if (entry.type === "event_msg" && entry.payload && entry.payload.type === "user_message") return true;
93
+ return false;
94
+ }
95
+
96
+ function assess(steps, findReceipt) {
97
+ const names = new Map();
98
+ let calls = 0;
99
+ let failed = 0;
100
+ let unrated = 0;
101
+ for (const step of steps) {
102
+ if (step.kind === "call") {
103
+ calls += 1;
104
+ names.set(step.id, step.name);
105
+ if (REVIEW_TOOL_RE.test(step.name) && unrated > 0) unrated -= 1;
106
+ continue;
107
+ }
108
+ if (step.failed) failed += 1;
109
+ const name = names.get(step.id) || "";
110
+ if (!CROWDCODE_TOOL_RE.test(name) && findReceipt(step.output)) unrated += 1;
111
+ }
112
+ return { calls, failed, unrated };
113
+ }
114
+
115
+ function reasonFor(stats) {
116
+ const parts = [
117
+ "CrowdCode check (once): read crowdcode_status. If it is off or unavailable, or this turn only managed CrowdCode settings or reviews, finish now without reflecting or submitting anything.",
118
+ ];
119
+ if (stats.unrated > 0) {
120
+ parts.push(`You paid for ${stats.unrated === 1 ? "a service call" : `${stats.unrated} service calls`} this turn without rating ${stats.unrated === 1 ? "it" : "them"}: rate each with review_service in one line (rating 1-5 and one sentence on what came back). Community reviews are published as unweighted evidence.`);
121
+ }
122
+ parts.push(
123
+ "Then reflect once on what a service could have changed in this task, in two kinds. gap: a step that failed, was poor, slow or costly. leverage: a service that, at a fair price, would have let you deliver a much better result or something you could not do at all: act (book, call, buy, file, send), reach data you could not (licensed, real-time, behind the user's own login with consent), persist (monitor, alert, retry over days) or verify (an authoritative or human check).",
124
+ "For each worthwhile one, call request_service with kind, input, output, problem, builds_on (what it could be built from today: an official API, a licensed dataset, existing paid services, a human-ops team), unlocks (what you could then have done for the user), frequency (one_off, per_task_like_this or recurring) and price_per_call (price the outcome's value). Describe a reusable service, never this task's answer restated; never invent a budget or repeat a request. If nothing qualifies, submit nothing. Then finish; do not reopen the user's task.",
125
+ );
126
+ return parts.join(" ");
127
+ }
128
+
129
+ function decide(event, findReceipt) {
130
+ if (!event || event.hook_event_name !== "Stop" || event.stop_hook_active) return null;
131
+ if (Array.isArray(event.background_tasks) && event.background_tasks.length) return null;
132
+ if (typeof event.transcript_path !== "string" || !event.transcript_path) return null;
133
+ const stats = assess(currentTurn(tailLines(event.transcript_path)), findReceipt);
134
+ if (stats.unrated === 0 && stats.failed === 0 && stats.calls < MANY_TOOL_CALLS) return null;
135
+ return { decision: "block", reason: reasonFor(stats) };
136
+ }
137
+
138
+ if (require.main === module) {
139
+ const chunks = [];
140
+ process.stdin.on("data", chunk => chunks.push(chunk));
141
+ process.stdin.on("end", () => {
142
+ try {
143
+ if (disabled()) return;
144
+ const { findReceipt } = require("./receipts.cjs");
145
+ const decision = decide(JSON.parse(Buffer.concat(chunks).toString("utf8")), findReceipt);
146
+ if (decision) process.stdout.write(JSON.stringify(decision));
147
+ } catch { /* a broken optional reminder must never trap the user */ }
148
+ });
149
+ process.stdin.on("error", () => {});
150
+ }
151
+
152
+ module.exports = { decide, currentTurn, assess, reasonFor };
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * CrowdCode PostToolUse hook (Claude Code and Codex), installed by
4
+ * `crowdcode-mcp install`.
5
+ *
6
+ * When any MCP tool's output carries an x402 or MPP payment receipt, append
7
+ * one line of metadata to ~/.crowdcode/pending.jsonl:
8
+ * {endpoint, method, network, payment_reference, amount_atomic, status,
9
+ * response_bytes, observed_at, payer, tool}
10
+ * The endpoint loses its query string; nothing from the request or the
11
+ * response body is written. The crowdcode-mcp server signs and submits the
12
+ * line as an observation (packages/mcp/src/observations.ts).
13
+ *
14
+ * No network, no output, always exit 0: a broken hook must never interrupt
15
+ * the user's session. `crowdcode-mcp off` stops recording.
16
+ */
17
+
18
+ const fs = require("node:fs");
19
+ const os = require("node:os");
20
+ const path = require("node:path");
21
+
22
+ function crowdcodeDir() {
23
+ return process.env.CROWDCODE_HOME || path.join(os.homedir(), ".crowdcode");
24
+ }
25
+
26
+ function disabled() {
27
+ const file = process.env.CROWDCODE_CONFIG_PATH || path.join(crowdcodeDir(), "preferences.json");
28
+ try { return JSON.parse(fs.readFileSync(file, "utf8")).enabled === false; } catch { return false; }
29
+ }
30
+
31
+ function record(raw) {
32
+ const receipts = require("./receipts.cjs");
33
+ if (!receipts.mayHoldReceipt(raw)) return null;
34
+ const event = JSON.parse(raw);
35
+ if (event.hook_event_name && event.hook_event_name !== "PostToolUse") return null;
36
+ const tool = typeof event.tool_name === "string" ? event.tool_name : "";
37
+ // CrowdCode's own tools echo payment evidence; they never make a payment.
38
+ if (!tool.startsWith("mcp__") || /^mcp__(plugin_)?crowdcode/i.test(tool)) return null;
39
+ const receipt = receipts.findReceipt(event.tool_response);
40
+ if (!receipt) return null;
41
+ const endpoint = receipts.endpointOf(event.tool_input);
42
+ if (!endpoint) return null;
43
+ const response = typeof event.tool_response === "string" ? event.tool_response : JSON.stringify(event.tool_response ?? "");
44
+ return {
45
+ endpoint,
46
+ method: receipts.methodOf(event.tool_input),
47
+ network: receipt.network,
48
+ payment_reference: receipt.reference,
49
+ amount_atomic: receipts.priceToAtomic(receipt.price),
50
+ status: receipt.status,
51
+ response_bytes: Buffer.byteLength(response, "utf8"),
52
+ observed_at: new Date().toISOString(),
53
+ payer: receipt.payer,
54
+ tool,
55
+ };
56
+ }
57
+
58
+ function main(raw) {
59
+ if (disabled()) return;
60
+ const line = record(raw);
61
+ if (!line) return;
62
+ const dir = crowdcodeDir();
63
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
64
+ fs.appendFileSync(path.join(dir, "pending.jsonl"), JSON.stringify(line) + "\n", { mode: 0o600 });
65
+ }
66
+
67
+ if (require.main === module) {
68
+ const chunks = [];
69
+ process.stdin.on("data", chunk => chunks.push(chunk));
70
+ process.stdin.on("end", () => {
71
+ try { main(Buffer.concat(chunks).toString("utf8")); } catch { /* never break the session */ }
72
+ });
73
+ process.stdin.on("error", () => {});
74
+ }
75
+
76
+ module.exports = { record, main };
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * CrowdCode: recognize a paid call in any tool's output by its payment
4
+ * receipt, never by the tool's name. Shared by the PostToolUse hook (which
5
+ * records the call) and the Stop hook (which asks for a rating).
6
+ *
7
+ * - x402: the `PAYMENT-RESPONSE` / `X-PAYMENT-RESPONSE` header, base64 JSON
8
+ * `{success, transaction, network, payer}`.
9
+ * - MPP: the `Payment-Receipt` header, base64url JSON
10
+ * `{method, reference, status, timestamp}`.
11
+ * - AgentCash also summarizes either one as `paymentInfo`
12
+ * `{protocol, network, price, payment: {success, transactionHash}}`.
13
+ *
14
+ * Only metadata is extracted: where the call went, which settlement paid for
15
+ * it, and how big the answer was. Never the request or the response.
16
+ * Self-contained: Node built-ins only, no network.
17
+ */
18
+
19
+ const MAX_DEPTH = 8;
20
+ const MAX_STRINGS = 400;
21
+ const TX_RE = /^0x[0-9a-fA-F]{64}$/;
22
+ const SOLANA_SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{64,90}$/;
23
+ const HEADER_TEXT_RE = /(x-payment-response|payment-response|payment-receipt)["'\s]*[:=]\s*["']?([A-Za-z0-9+/_-]{20,}={0,2})/gi;
24
+
25
+ function decodeJson(value) {
26
+ if (typeof value !== "string") return null;
27
+ const text = value.trim();
28
+ if (!/^[A-Za-z0-9+/_-]+={0,2}$/.test(text)) return null;
29
+ try {
30
+ const parsed = JSON.parse(Buffer.from(text.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
31
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
32
+ } catch { return null; }
33
+ }
34
+
35
+ function normalizeNetwork(value) {
36
+ const text = String(value || "").trim().toLowerCase();
37
+ if (!text) return null;
38
+ if (text === "base" || text === "eip155:8453" || text === "8453") return "base";
39
+ if (text === "tempo" || text === "eip155:4217" || text === "4217") return "tempo";
40
+ if (text === "solana" || text.startsWith("solana:5eykt4u")) return "solana";
41
+ return text;
42
+ }
43
+
44
+ function fromX402(settle) {
45
+ if (!settle || settle.success === false) return null;
46
+ const reference = settle.transaction || settle.transactionHash || settle.txHash;
47
+ if (typeof reference !== "string") return null;
48
+ return { protocol: "x402", network: normalizeNetwork(settle.network) || "base", reference: reference.trim(),
49
+ payer: typeof settle.payer === "string" ? settle.payer : null };
50
+ }
51
+
52
+ function fromMpp(receipt) {
53
+ if (!receipt || (receipt.status && receipt.status !== "success")) return null;
54
+ const reference = receipt.reference || receipt.txHash || receipt.transactionHash;
55
+ if (typeof reference !== "string") return null;
56
+ return { protocol: "mpp", network: "tempo", reference: reference.trim(), payer: null };
57
+ }
58
+
59
+ function fromPaymentInfo(info) {
60
+ if (!info || typeof info !== "object") return null;
61
+ const payment = info.payment;
62
+ if (!payment || payment.success === false || typeof payment.transactionHash !== "string") return null;
63
+ return { protocol: info.protocol === "mpp" ? "mpp" : "x402", network: normalizeNetwork(info.network) || "base",
64
+ reference: payment.transactionHash.trim(), payer: null, price: info.price };
65
+ }
66
+
67
+ function validReference(found) {
68
+ return found && (TX_RE.test(found.reference) || (found.network === "solana" && SOLANA_SIG_RE.test(found.reference)));
69
+ }
70
+
71
+ /** Every string and object in a tool result, including JSON nested in text blocks. */
72
+ function walk(value, visit, depth = 0, budget = { strings: 0 }) {
73
+ if (depth > MAX_DEPTH || value === null || value === undefined) return;
74
+ if (typeof value === "string") {
75
+ if (++budget.strings > MAX_STRINGS) return;
76
+ visit(value, null);
77
+ const text = value.trim();
78
+ if ((text.startsWith("{") || text.startsWith("[")) && text.length < 2_000_000) {
79
+ try { walk(JSON.parse(text), visit, depth + 1, budget); } catch { /* plain text */ }
80
+ }
81
+ return;
82
+ }
83
+ if (Array.isArray(value)) { for (const item of value) walk(item, visit, depth + 1, budget); return; }
84
+ if (typeof value === "object") {
85
+ visit(null, value);
86
+ for (const key of Object.keys(value)) walk(value[key], visit, depth + 1, budget);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * The payment receipt in one tool result, or null.
92
+ * Returns {protocol, network, reference, payer, price?, status}.
93
+ */
94
+ function findReceipt(toolResponse) {
95
+ let found = null;
96
+ let price;
97
+ let status = null;
98
+ walk(toolResponse, (text, object) => {
99
+ if (object) {
100
+ // AgentCash spreads its paymentInfo into the result metadata.
101
+ if ((object.protocol === "x402" || object.protocol === "mpp") && object.payment) {
102
+ const info = fromPaymentInfo(object);
103
+ if (info && info.price !== undefined) price = info.price;
104
+ if (!found && info) found = info;
105
+ }
106
+ for (const [key, value] of Object.entries(object)) {
107
+ const name = key.toLowerCase();
108
+ if (!found && (name === "payment-response" || name === "x-payment-response")) found = fromX402(decodeJson(value));
109
+ else if (!found && name === "payment-receipt") found = fromMpp(decodeJson(value));
110
+ else if (name === "paymentinfo") {
111
+ const info = fromPaymentInfo(value);
112
+ if (info && info.price !== undefined) price = info.price;
113
+ if (!found && info) found = info;
114
+ } else if ((name === "status" || name === "statuscode" || name === "http_status") &&
115
+ Number.isInteger(value) && value >= 100 && value <= 599 && status === null) status = value;
116
+ }
117
+ return;
118
+ }
119
+ if (!found && text && /payment-(response|receipt)/i.test(text)) {
120
+ HEADER_TEXT_RE.lastIndex = 0;
121
+ let match;
122
+ while (!found && (match = HEADER_TEXT_RE.exec(text))) {
123
+ const decoded = decodeJson(match[2]);
124
+ found = match[1].toLowerCase() === "payment-receipt" ? fromMpp(decoded) : fromX402(decoded);
125
+ }
126
+ }
127
+ });
128
+ if (!validReference(found)) return null;
129
+ if (price !== undefined && found.price === undefined) found.price = price;
130
+ found.status = status;
131
+ return found;
132
+ }
133
+
134
+ /** USD like "$0.01" or 0.01 to USDC atomic units (6 decimals), or null. */
135
+ function priceToAtomic(price) {
136
+ const text = typeof price === "number" ? String(price) : typeof price === "string" ? price.replace(/[$,\s]/g, "") : "";
137
+ if (!/^\d+(\.\d+)?$/.test(text)) return null;
138
+ const atomic = Math.round(Number(text) * 1e6);
139
+ return Number.isSafeInteger(atomic) && atomic >= 0 ? atomic : null;
140
+ }
141
+
142
+ /** The endpoint a tool called, without query or fragment (they can hold the request). */
143
+ function endpointOf(toolInput) {
144
+ if (!toolInput || typeof toolInput !== "object") return null;
145
+ for (const key of ["url", "endpoint", "resource", "uri", "api_endpoint"]) {
146
+ const value = toolInput[key];
147
+ if (typeof value !== "string") continue;
148
+ try {
149
+ const url = new URL(value.trim());
150
+ if (url.protocol !== "https:") return null;
151
+ return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, "") || "/"}`;
152
+ } catch { return null; }
153
+ }
154
+ return null;
155
+ }
156
+
157
+ function methodOf(toolInput) {
158
+ const method = toolInput && typeof toolInput.method === "string" ? toolInput.method.trim().toUpperCase() : "";
159
+ return /^[A-Z]{3,7}$/.test(method) ? method : null;
160
+ }
161
+
162
+ /** Cheap pre-check on the raw hook input, before any parsing. */
163
+ function mayHoldReceipt(raw) {
164
+ return /payment-(response|receipt)|paymentInfo|transactionHash/i.test(raw);
165
+ }
166
+
167
+ module.exports = { findReceipt, priceToAtomic, endpointOf, methodOf, mayHoldReceipt, decodeJson };
@@ -0,0 +1,24 @@
1
+ import {
2
+ MESSAGE_HEADER,
3
+ OBSERVATION_DISCLOSURE,
4
+ OBSERVATION_FIELDS,
5
+ buildSubmission,
6
+ crowdcodeDir,
7
+ flushPending,
8
+ observationMessage,
9
+ observationsUrl,
10
+ toRecord
11
+ } from "./chunk-QKICGYZG.js";
12
+ import "./chunk-2Y65AAP3.js";
13
+ export {
14
+ MESSAGE_HEADER,
15
+ OBSERVATION_DISCLOSURE,
16
+ OBSERVATION_FIELDS,
17
+ buildSubmission,
18
+ crowdcodeDir,
19
+ flushPending,
20
+ observationMessage,
21
+ observationsUrl,
22
+ toRecord
23
+ };
24
+ //# sourceMappingURL=observations-HIXF7KW5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}