crowdcode-mcp 0.11.0 → 0.12.1
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 +12 -7
- package/dist/{chunk-M37QDGMY.js → chunk-2Y65AAP3.js} +3 -21
- package/dist/chunk-2Y65AAP3.js.map +1 -0
- package/dist/chunk-CF6JGOQF.js +26 -0
- package/dist/chunk-CF6JGOQF.js.map +1 -0
- package/dist/chunk-QKICGYZG.js +184 -0
- package/dist/chunk-QKICGYZG.js.map +1 -0
- package/dist/cli.js +116 -41
- package/dist/cli.js.map +1 -1
- package/dist/hooks/completion.cjs +152 -0
- package/dist/hooks/paid-call.cjs +76 -0
- package/dist/hooks/receipts.cjs +167 -0
- package/dist/observations-HIXF7KW5.js +24 -0
- package/dist/observations-HIXF7KW5.js.map +1 -0
- package/dist/{server-LCPX3I3T.js → server-AMGZRDBF.js} +86 -48
- package/dist/server-AMGZRDBF.js.map +1 -0
- package/dist/skills/crowdcode/SKILL.md +87 -49
- package/package.json +1 -1
- package/dist/chunk-M37QDGMY.js.map +0 -1
- package/dist/server-LCPX3I3T.js.map +0 -1
package/README.md
CHANGED
|
@@ -58,9 +58,9 @@ Identify the service by `api_endpoint` + `payment_provider` +
|
|
|
58
58
|
"n_eff": 5.8,
|
|
59
59
|
"unproven": false,
|
|
60
60
|
"summary": {
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
"
|
|
61
|
+
"pros": ["Consistently relevant review comments."],
|
|
62
|
+
"cons": [],
|
|
63
|
+
"watch_out": ["Slower on large diffs."]
|
|
64
64
|
},
|
|
65
65
|
"avg_rating": 4.5,
|
|
66
66
|
"num_reviews": 7
|
|
@@ -73,7 +73,9 @@ fresh and adversarial wallets count for nothing no matter how many of them
|
|
|
73
73
|
exist. `n_eff` says how much trusted evidence backs the score, and
|
|
74
74
|
`unproven: true` means there isn't enough of it yet — read that as *insufficient
|
|
75
75
|
evidence*, not as a bad service, and fall back to price and your spend policy.
|
|
76
|
-
`summary` digests what reviewers actually reported
|
|
76
|
+
`summary` digests what reviewers actually reported as pros, cons and things to
|
|
77
|
+
watch out for. Individual reviews are private: CrowdCode stores them but never
|
|
78
|
+
returns their text.
|
|
77
79
|
|
|
78
80
|
The algorithm is public: [docs/SCORING.md][scoring].
|
|
79
81
|
|
|
@@ -125,9 +127,12 @@ proofs from the *actual payment*, not from a directory listing:
|
|
|
125
127
|
### `request_service` — record unmet paid demand
|
|
126
128
|
|
|
127
129
|
Before the final answer, reflect on actual obstacles that a concrete paid
|
|
128
|
-
service could have solved
|
|
129
|
-
|
|
130
|
-
|
|
130
|
+
service could have solved, and describe the service in four required fields:
|
|
131
|
+
`input` (the clear input the user will give), `output` (the exact output they
|
|
132
|
+
want), `problem` (what it solves) and `price_per_call` (what you would pay per
|
|
133
|
+
call, in USD). A specific improvement to an inadequate existing service
|
|
134
|
+
qualifies; an attempted purchase is not required. Requests stay private;
|
|
135
|
+
CrowdCode publishes only aggregated, generalized proposals.
|
|
131
136
|
|
|
132
137
|
### `get_review_signing_payload` — usually unnecessary
|
|
133
138
|
|
|
@@ -190,30 +190,12 @@ async function loadSolanaWallet(walletDir) {
|
|
|
190
190
|
};
|
|
191
191
|
}
|
|
192
192
|
|
|
193
|
-
// src/config.ts
|
|
194
|
-
import { homedir as homedir2 } from "os";
|
|
195
|
-
import { join as join2 } from "path";
|
|
196
|
-
var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes"]);
|
|
197
|
-
function getConfig(env = process.env) {
|
|
198
|
-
return {
|
|
199
|
-
backendUrl: env.CROWDCODE_BACKEND_URL ?? "https://crowdcode-backend.onrender.com/mcp",
|
|
200
|
-
cacheDir: env.CROWDCODE_CACHE_DIR ?? join2(homedir2(), ".cache", "crowdcode-mcp"),
|
|
201
|
-
disableModel: TRUTHY.has((env.CROWDCODE_DISABLE_MODEL ?? "").toLowerCase()),
|
|
202
|
-
upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 15e3),
|
|
203
|
-
// Signing wallet shared with agentcash (~/.agentcash/wallet.json).
|
|
204
|
-
walletDir: env.CROWDCODE_WALLET_DIR ?? defaultWalletDir(),
|
|
205
|
-
walletAutoCreate: !TRUTHY.has(
|
|
206
|
-
(env.CROWDCODE_DISABLE_WALLET_CREATE ?? "").toLowerCase()
|
|
207
|
-
)
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
|
|
211
193
|
export {
|
|
212
194
|
isSolanaSignature,
|
|
213
195
|
solanaReferenceSignature,
|
|
214
196
|
payerLinkMessage,
|
|
197
|
+
defaultWalletDir,
|
|
215
198
|
loadWallet,
|
|
216
|
-
loadSolanaWallet
|
|
217
|
-
getConfig
|
|
199
|
+
loadSolanaWallet
|
|
218
200
|
};
|
|
219
|
-
//# sourceMappingURL=chunk-
|
|
201
|
+
//# sourceMappingURL=chunk-2Y65AAP3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wallet.ts","../src/canonical/solana.ts"],"sourcesContent":["/**\n * Local signing wallet, shared with agentcash.\n *\n * Reads (and lazily creates) the same wallet file agentcash uses —\n * ~/.agentcash/wallet.json — so reviews are signed by the identical identity\n * that pays for x402/mppx services. Private keys supplied through environment\n * variables are deliberately unsupported: the agent gets addresses and\n * canonical review signatures, never a key-ingestion API.\n * 1. An existing file is zod-validated and its address cross-checked\n * against the key; an unreadable or invalid file is NEVER overwritten.\n * 2. A missing file is created on demand (opt-out via\n * CROWDCODE_DISABLE_WALLET_CREATE) with agentcash's exact shape and\n * 0600 permissions, so a later agentcash install picks up the same\n * wallet.\n */\n\nimport { createPrivateKey, createPublicKey, sign as cryptoSign } from \"node:crypto\";\nimport { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n generatePrivateKey,\n privateKeyToAccount,\n type PrivateKeyAccount,\n} from \"viem/accounts\";\nimport { getAddress } from \"viem/utils\";\nimport { z } from \"zod\";\nimport { base58Decode, base58Encode } from \"./canonical/solana.js\";\n\nexport type WalletSource = \"agentcash\" | \"none\";\n\nexport interface LoadedWallet {\n source: WalletSource;\n account: PrivateKeyAccount | null;\n address: string | null;\n error?: string;\n errorCode?: string;\n created?: boolean;\n}\n\nexport interface LoadWalletOptions {\n env?: NodeJS.ProcessEnv;\n walletDir?: string;\n autoCreate?: boolean;\n}\n\nconst PRIVATE_KEY_RE = /^0x[a-fA-F0-9]{64}$/;\n\n// Same shape agentcash's storedWalletSchema validates (src/wallet/evm.ts).\nconst storedWalletSchema = z.object({\n privateKey: z.string().regex(PRIVATE_KEY_RE),\n address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),\n createdAt: z.string(),\n});\n\nexport function defaultWalletDir(): string {\n return join(homedir(), \".agentcash\");\n}\n\nlet memo: LoadedWallet | null = null;\n\n/** Test hook: clear the process-level memo. */\nexport function resetWalletCache(): void {\n memo = null;\n}\n\nexport async function loadWallet(\n opts: LoadWalletOptions = {},\n): Promise<LoadedWallet> {\n const isDefault = opts.env === undefined && opts.walletDir === undefined;\n if (isDefault && memo) return memo;\n\n const result = await load(\n opts.env ?? process.env,\n opts.walletDir ?? defaultWalletDir(),\n opts.autoCreate ?? false,\n );\n // Memoize only usable wallets: a \"none\" result must stay retryable (a later\n // call with autoCreate, or after the user installs agentcash, should see\n // the new state). `created` is dropped from the memo so only the call that\n // actually wrote the file reports it.\n if (isDefault && result.source !== \"none\") {\n memo = { ...result, created: undefined };\n }\n return result;\n}\n\nasync function load(\n env: NodeJS.ProcessEnv,\n dir: string,\n autoCreate: boolean,\n): Promise<LoadedWallet> {\n if (Object.prototype.hasOwnProperty.call(env, \"X402_PRIVATE_KEY\")) {\n return none(\n \"X402_PRIVATE_KEY is no longer supported; remove it from the CrowdCode \" +\n \"process and use the local agentcash wallet file instead\",\n \"wallet_configuration_error\",\n );\n }\n\n const file = join(dir, \"wallet.json\");\n let raw: string | null = null;\n try {\n raw = await readFile(file, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n return none(`wallet file is unreadable: ${(err as Error).message}`);\n }\n }\n\n if (raw !== null) {\n return parseStored(raw, file);\n }\n\n if (!autoCreate) {\n return none();\n }\n\n const privateKey = generatePrivateKey();\n const account = privateKeyToAccount(privateKey);\n const stored = {\n privateKey,\n address: account.address,\n createdAt: new Date().toISOString(),\n };\n try {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n // \"wx\" fails on a concurrently created file instead of clobbering it.\n await writeFile(file, JSON.stringify(stored, null, 2), {\n mode: 0o600,\n flag: \"wx\",\n });\n await chmod(file, 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n try {\n return parseStored(await readFile(file, \"utf8\"), file);\n } catch (readErr) {\n return none(`wallet file is unreadable: ${(readErr as Error).message}`);\n }\n }\n return none(`could not create wallet file: ${(err as Error).message}`);\n }\n return { source: \"agentcash\", account, address: account.address, created: true };\n}\n\nfunction parseStored(raw: string, file: string): LoadedWallet {\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n return none(`wallet file is not valid JSON: ${file} — fix or remove it`);\n }\n const parsed = storedWalletSchema.safeParse(parsedJson);\n if (!parsed.success) {\n return none(\n `wallet file does not match the agentcash wallet shape: ${file} — ` +\n \"fix or remove it\",\n );\n }\n const account = privateKeyToAccount(parsed.data.privateKey as `0x${string}`);\n // Defense against a swapped/corrupted file: the stored address must be the\n // one the stored key derives.\n if (getAddress(account.address) !== getAddress(parsed.data.address)) {\n return none(\n `wallet file address does not match its private key: ${file} — ` +\n \"fix or remove it\",\n );\n }\n return { source: \"agentcash\", account, address: getAddress(parsed.data.address) };\n}\n\nfunction none(error?: string, errorCode?: string): LoadedWallet {\n return { source: \"none\", account: null, address: null, error, errorCode };\n}\n\n/**\n * agentcash's Solana wallet, ~/.agentcash/solana-wallet.json (agentcash\n * src/wallet/svm.ts): `{ privateKey: base58(32-byte ed25519 seed), address,\n * createdAt }`. agentcash pays x402 Solana with this key, so it can sign the\n * payer link that makes a Solana review verified. Read-only: CrowdCode never\n * creates a Solana key, and a missing or invalid file just means reviews go\n * out without payer_signature.\n */\nexport interface SolanaWallet {\n address: string;\n /** ed25519 over the UTF-8 bytes of `message`; base58 signature. */\n sign(message: string): string;\n}\n\nconst solanaWalletSchema = z.object({\n privateKey: z.string().regex(/^[1-9A-HJ-NP-Za-km-z]+$/),\n address: z.string(),\n createdAt: z.string().optional(),\n});\n\n// PKCS#8 DER prefix for a raw 32-byte Ed25519 seed (RFC 8410).\nconst ED25519_PKCS8_PREFIX = Buffer.from(\"302e020100300506032b657004220420\", \"hex\");\n\nexport async function loadSolanaWallet(walletDir?: string): Promise<SolanaWallet | null> {\n let raw: string;\n try {\n raw = await readFile(join(walletDir ?? defaultWalletDir(), \"solana-wallet.json\"), \"utf8\");\n } catch {\n return null;\n }\n let parsed: z.infer<typeof solanaWalletSchema>;\n try {\n parsed = solanaWalletSchema.parse(JSON.parse(raw));\n } catch {\n return null;\n }\n const secret = base58Decode(parsed.privateKey);\n // agentcash stores the 32-byte seed; Solana CLI keypairs are seed + pubkey.\n if (secret === null || (secret.length !== 32 && secret.length !== 64)) return null;\n const key = createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(secret.subarray(0, 32))]),\n format: \"der\",\n type: \"pkcs8\",\n });\n const jwk = createPublicKey(key).export({ format: \"jwk\" });\n const address = base58Encode(Buffer.from(String(jwk.x), \"base64url\"));\n // Same defense as the EVM file: the stored address must derive from the key.\n if (address !== parsed.address.trim()) return null;\n if (secret.length === 64 && base58Encode(secret.subarray(32)) !== address) return null;\n return {\n address,\n sign: (message) => base58Encode(cryptoSign(null, Buffer.from(message, \"utf8\"), key)),\n };\n}\n","/**\n * Solana pieces of the review contract (mirrors src/crowdcode/solana.py and\n * payer_link_message in src/crowdcode/payments.py; spec/CANONICAL_PAYLOAD.md).\n *\n * Solana identifiers are case-sensitive base58 and are never lowercased.\n */\n\nimport { createHash } from \"node:crypto\";\n\nconst ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nconst BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;\n\nexport function base58Decode(value: string): Uint8Array | null {\n if (typeof value !== \"string\" || !BASE58_RE.test(value)) return null;\n let n = 0n;\n for (const char of value) n = n * 58n + BigInt(ALPHABET.indexOf(char));\n const body: number[] = [];\n while (n > 0n) {\n body.unshift(Number(n & 0xffn));\n n >>= 8n;\n }\n const zeros = value.length - value.replace(/^1+/, \"\").length;\n return Uint8Array.from([...new Array<number>(zeros).fill(0), ...body]);\n}\n\nexport function base58Encode(bytes: Uint8Array): string {\n let n = 0n;\n for (const byte of bytes) n = (n << 8n) | BigInt(byte);\n let out = \"\";\n while (n > 0n) {\n out = ALPHABET[Number(n % 58n)] + out;\n n /= 58n;\n }\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n return \"1\".repeat(zeros) + out;\n}\n\nfunction decodesTo(value: unknown, size: number): boolean {\n if (typeof value !== \"string\") return false;\n return base58Decode(value.trim())?.length === size;\n}\n\n/** A base58 32-byte public key. */\nexport const isSolanaAddress = (value: unknown): boolean => decodesTo(value, 32);\n/** A base58 64-byte ed25519 signature (also a Solana transaction id). */\nexport const isSolanaSignature = (value: unknown): boolean => decodesTo(value, 64);\n\n/**\n * The transaction signature named by `x402:solana:<sig>` (prefix\n * case-insensitive) or a bare base58 signature; null otherwise.\n */\nexport function solanaReferenceSignature(reference: unknown): string | null {\n if (typeof reference !== \"string\") return null;\n let cleaned = reference.trim();\n if (cleaned.slice(0, 12).toLowerCase() === \"x402:solana:\") cleaned = cleaned.slice(12);\n return isSolanaSignature(cleaned) ? cleaned : null;\n}\n\nexport const PAYER_LINK_MESSAGE_HEADER = \"CrowdCode review payer link v1\";\n\n/**\n * The text a Solana payer signs (ed25519 over its raw UTF-8 bytes; the\n * signature is sent base58 as `payer_signature`) to link its payment to a\n * review. It commits to the exact canonical review payload the reviewer\n * signed and to the reviewer's EVM wallet.\n */\nexport function payerLinkMessage(reviewerWallet: string, payload: string): string {\n return [\n PAYER_LINK_MESSAGE_HEADER,\n `reviewer_wallet:${reviewerWallet.trim().toLowerCase()}`,\n `payload_sha256:${createHash(\"sha256\").update(payload, \"utf8\").digest(\"hex\")}`,\n ].join(\"\\n\");\n}\n"],"mappings":";AAgBA,SAAS,kBAAkB,iBAAiB,QAAQ,kBAAkB;AACtE,SAAS,OAAO,OAAO,UAAU,iBAAiB;AAClD,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB;AAC3B,SAAS,SAAS;;;ACnBlB,SAAS,kBAAkB;AAE3B,IAAM,WAAW;AACjB,IAAM,YAAY;AAEX,SAAS,aAAa,OAAkC;AAC7D,MAAI,OAAO,UAAU,YAAY,CAAC,UAAU,KAAK,KAAK,EAAG,QAAO;AAChE,MAAI,IAAI;AACR,aAAW,QAAQ,MAAO,KAAI,IAAI,MAAM,OAAO,SAAS,QAAQ,IAAI,CAAC;AACrE,QAAM,OAAiB,CAAC;AACxB,SAAO,IAAI,IAAI;AACb,SAAK,QAAQ,OAAO,IAAI,KAAK,CAAC;AAC9B,UAAM;AAAA,EACR;AACA,QAAM,QAAQ,MAAM,SAAS,MAAM,QAAQ,OAAO,EAAE,EAAE;AACtD,SAAO,WAAW,KAAK,CAAC,GAAG,IAAI,MAAc,KAAK,EAAE,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC;AACvE;AAEO,SAAS,aAAa,OAA2B;AACtD,MAAI,IAAI;AACR,aAAW,QAAQ,MAAO,KAAK,KAAK,KAAM,OAAO,IAAI;AACrD,MAAI,MAAM;AACV,SAAO,IAAI,IAAI;AACb,UAAM,SAAS,OAAO,IAAI,GAAG,CAAC,IAAI;AAClC,SAAK;AAAA,EACP;AACA,MAAI,QAAQ;AACZ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CAAC;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,SAAS,aAAa,OAAO,UAAU;AAE7C,MAAI,WAAW,QAAS,OAAO,WAAW,MAAM,OAAO,WAAW,GAAK,QAAO;AAC9E,QAAM,MAAM,iBAAiB;AAAA,IAC3B,KAAK,OAAO,OAAO,CAAC,sBAAsB,OAAO,KAAK,OAAO,SAAS,GAAG,EAAE,CAAC,CAAC,CAAC;AAAA,IAC9E,QAAQ;AAAA,IACR,MAAM;AAAA,EACR,CAAC;AACD,QAAM,MAAM,gBAAgB,GAAG,EAAE,OAAO,EAAE,QAAQ,MAAM,CAAC;AACzD,QAAM,UAAU,aAAa,OAAO,KAAK,OAAO,IAAI,CAAC,GAAG,WAAW,CAAC;AAEpE,MAAI,YAAY,OAAO,QAAQ,KAAK,EAAG,QAAO;AAC9C,MAAI,OAAO,WAAW,MAAM,aAAa,OAAO,SAAS,EAAE,CAAC,MAAM,QAAS,QAAO;AAClF,SAAO;AAAA,IACL;AAAA,IACA,MAAM,CAAC,YAAY,aAAa,WAAW,MAAM,OAAO,KAAK,SAAS,MAAM,GAAG,GAAG,CAAC;AAAA,EACrF;AACF;","names":[]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import {
|
|
2
|
+
defaultWalletDir
|
|
3
|
+
} from "./chunk-2Y65AAP3.js";
|
|
4
|
+
|
|
5
|
+
// src/config.ts
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { join } from "path";
|
|
8
|
+
var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes"]);
|
|
9
|
+
function getConfig(env = process.env) {
|
|
10
|
+
return {
|
|
11
|
+
backendUrl: env.CROWDCODE_BACKEND_URL ?? "https://crowdcode-backend.onrender.com/mcp",
|
|
12
|
+
cacheDir: env.CROWDCODE_CACHE_DIR ?? join(homedir(), ".cache", "crowdcode-mcp"),
|
|
13
|
+
disableModel: TRUTHY.has((env.CROWDCODE_DISABLE_MODEL ?? "").toLowerCase()),
|
|
14
|
+
upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 15e3),
|
|
15
|
+
// Signing wallet shared with agentcash (~/.agentcash/wallet.json).
|
|
16
|
+
walletDir: env.CROWDCODE_WALLET_DIR ?? defaultWalletDir(),
|
|
17
|
+
walletAutoCreate: !TRUTHY.has(
|
|
18
|
+
(env.CROWDCODE_DISABLE_WALLET_CREATE ?? "").toLowerCase()
|
|
19
|
+
)
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export {
|
|
24
|
+
getConfig
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=chunk-CF6JGOQF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { defaultWalletDir } from \"./wallet.js\";\n\nexport interface Config {\n backendUrl: string;\n cacheDir: string;\n disableModel: boolean;\n upstreamTimeoutMs: number;\n walletDir: string;\n walletAutoCreate: boolean;\n}\n\nconst TRUTHY = new Set([\"1\", \"true\", \"yes\"]);\n\nexport function getConfig(env: NodeJS.ProcessEnv = process.env): Config {\n return {\n backendUrl:\n env.CROWDCODE_BACKEND_URL ?? \"https://crowdcode-backend.onrender.com/mcp\",\n cacheDir: env.CROWDCODE_CACHE_DIR ?? join(homedir(), \".cache\", \"crowdcode-mcp\"),\n disableModel: TRUTHY.has((env.CROWDCODE_DISABLE_MODEL ?? \"\").toLowerCase()),\n upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 15_000),\n // Signing wallet shared with agentcash (~/.agentcash/wallet.json).\n walletDir: env.CROWDCODE_WALLET_DIR ?? defaultWalletDir(),\n walletAutoCreate: !TRUTHY.has(\n (env.CROWDCODE_DISABLE_WALLET_CREATE ?? \"\").toLowerCase(),\n ),\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AAYrB,IAAM,SAAS,oBAAI,IAAI,CAAC,KAAK,QAAQ,KAAK,CAAC;AAEpC,SAAS,UAAU,MAAyB,QAAQ,KAAa;AACtE,SAAO;AAAA,IACL,YACE,IAAI,yBAAyB;AAAA,IAC/B,UAAU,IAAI,uBAAuB,KAAK,QAAQ,GAAG,UAAU,eAAe;AAAA,IAC9E,cAAc,OAAO,KAAK,IAAI,2BAA2B,IAAI,YAAY,CAAC;AAAA,IAC1E,mBAAmB,OAAO,IAAI,iCAAiC,IAAM;AAAA;AAAA,IAErE,WAAW,IAAI,wBAAwB,iBAAiB;AAAA,IACxD,kBAAkB,CAAC,OAAO;AAAA,OACvB,IAAI,mCAAmC,IAAI,YAAY;AAAA,IAC1D;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import {
|
|
2
|
+
loadSolanaWallet,
|
|
3
|
+
loadWallet
|
|
4
|
+
} from "./chunk-2Y65AAP3.js";
|
|
5
|
+
|
|
6
|
+
// src/observations.ts
|
|
7
|
+
import { randomUUID } from "crypto";
|
|
8
|
+
import { appendFile, mkdir, readdir, readFile, rename, rm, stat } from "fs/promises";
|
|
9
|
+
import { homedir } from "os";
|
|
10
|
+
import { join } from "path";
|
|
11
|
+
var OBSERVATION_FIELDS = [
|
|
12
|
+
"endpoint",
|
|
13
|
+
"method",
|
|
14
|
+
"network",
|
|
15
|
+
"payment_reference",
|
|
16
|
+
"amount_atomic",
|
|
17
|
+
"status",
|
|
18
|
+
"response_bytes",
|
|
19
|
+
"observed_at"
|
|
20
|
+
];
|
|
21
|
+
var MESSAGE_HEADER = "CrowdCode observation v1";
|
|
22
|
+
var MAX_ATTEMPTS = 20;
|
|
23
|
+
var MAX_AGE_MS = 6 * 24 * 3600 * 1e3;
|
|
24
|
+
var STALE_CLAIM_MS = 5 * 60 * 1e3;
|
|
25
|
+
var REQUEST_TIMEOUT_MS = 15e3;
|
|
26
|
+
function observationMessage(record) {
|
|
27
|
+
return [MESSAGE_HEADER, ...OBSERVATION_FIELDS.map((key) => `${key}:${record[key] ?? ""}`)].join("\n");
|
|
28
|
+
}
|
|
29
|
+
function crowdcodeDir(env = process.env) {
|
|
30
|
+
return env.CROWDCODE_HOME ?? join(homedir(), ".crowdcode");
|
|
31
|
+
}
|
|
32
|
+
function observationsUrl(backendUrl, env = process.env) {
|
|
33
|
+
if (env.CROWDCODE_OBSERVATIONS_URL) return env.CROWDCODE_OBSERVATIONS_URL;
|
|
34
|
+
const url = new URL(backendUrl);
|
|
35
|
+
url.pathname = url.pathname.replace(/\/mcp\/?$/, "") + "/api/observations";
|
|
36
|
+
url.pathname = url.pathname.replace(/\/{2,}/g, "/");
|
|
37
|
+
return url.toString();
|
|
38
|
+
}
|
|
39
|
+
function toRecord(line) {
|
|
40
|
+
return Object.fromEntries(OBSERVATION_FIELDS.map((key) => [key, line[key] ?? null]));
|
|
41
|
+
}
|
|
42
|
+
async function buildSubmission(line, wallet, solana) {
|
|
43
|
+
if (!wallet.account || !wallet.address) return null;
|
|
44
|
+
const record = toRecord(line);
|
|
45
|
+
const message = observationMessage(record);
|
|
46
|
+
const body = { observation: record, signature: await wallet.account.signMessage({ message }) };
|
|
47
|
+
if (record.network === "solana") {
|
|
48
|
+
if (!solana || line.payer && line.payer !== solana.address) return null;
|
|
49
|
+
body.payer_wallet = solana.address;
|
|
50
|
+
body.payer_signature = solana.sign(message);
|
|
51
|
+
} else if (line.payer && line.payer.toLowerCase() !== wallet.address.toLowerCase()) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return body;
|
|
55
|
+
}
|
|
56
|
+
async function submit(body, deps) {
|
|
57
|
+
const doFetch = deps.fetch ?? fetch;
|
|
58
|
+
let response;
|
|
59
|
+
try {
|
|
60
|
+
response = await doFetch(deps.url, {
|
|
61
|
+
method: "POST",
|
|
62
|
+
headers: { "content-type": "application/json" },
|
|
63
|
+
body: JSON.stringify(body),
|
|
64
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
65
|
+
});
|
|
66
|
+
} catch {
|
|
67
|
+
return "retry";
|
|
68
|
+
}
|
|
69
|
+
let payload = {};
|
|
70
|
+
try {
|
|
71
|
+
payload = await response.json();
|
|
72
|
+
} catch {
|
|
73
|
+
}
|
|
74
|
+
if (response.ok && payload.accepted === true) return payload.duplicate === true ? "duplicate" : "sent";
|
|
75
|
+
if (response.status >= 500 || response.status === 429 || payload.retryable === true) return "retry";
|
|
76
|
+
deps.log?.(`crowdcode-mcp: observation not accepted (${String(payload.error_code ?? response.status)})`);
|
|
77
|
+
return "dropped";
|
|
78
|
+
}
|
|
79
|
+
function parseLines(text) {
|
|
80
|
+
const lines = [];
|
|
81
|
+
for (const raw of text.split("\n")) {
|
|
82
|
+
if (!raw.trim()) continue;
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(raw);
|
|
85
|
+
if (parsed && typeof parsed.endpoint === "string" && typeof parsed.payment_reference === "string") lines.push(parsed);
|
|
86
|
+
} catch {
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return lines;
|
|
90
|
+
}
|
|
91
|
+
async function recoverStale(dir, now) {
|
|
92
|
+
let names;
|
|
93
|
+
try {
|
|
94
|
+
names = await readdir(dir);
|
|
95
|
+
} catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
for (const name of names) {
|
|
99
|
+
if (!name.startsWith("pending.jsonl.") || !name.endsWith(".sending")) continue;
|
|
100
|
+
const file = join(dir, name);
|
|
101
|
+
try {
|
|
102
|
+
if (now - (await stat(file)).mtimeMs < STALE_CLAIM_MS) continue;
|
|
103
|
+
await appendFile(join(dir, "pending.jsonl"), await readFile(file, "utf8"), { mode: 384 });
|
|
104
|
+
await rm(file, { force: true });
|
|
105
|
+
} catch {
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
var flushing = null;
|
|
110
|
+
function flushPending(deps) {
|
|
111
|
+
if (flushing) return flushing;
|
|
112
|
+
flushing = flushOnce(deps).finally(() => {
|
|
113
|
+
flushing = null;
|
|
114
|
+
});
|
|
115
|
+
return flushing;
|
|
116
|
+
}
|
|
117
|
+
async function flushOnce(deps) {
|
|
118
|
+
const result = { sent: 0, duplicate: 0, retry: 0, dropped: 0 };
|
|
119
|
+
if (deps.enabled && !await deps.enabled()) return result;
|
|
120
|
+
const dir = deps.dir ?? crowdcodeDir();
|
|
121
|
+
const now = deps.now?.() ?? Date.now();
|
|
122
|
+
await recoverStale(dir, now);
|
|
123
|
+
const pending = join(dir, "pending.jsonl");
|
|
124
|
+
const claim = join(dir, `pending.jsonl.${process.pid}-${randomUUID()}.sending`);
|
|
125
|
+
try {
|
|
126
|
+
await rename(pending, claim);
|
|
127
|
+
} catch {
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
131
|
+
const lines = parseLines(await readFile(claim, "utf8"));
|
|
132
|
+
const wallet = await loadWallet({ walletDir: deps.walletDir, autoCreate: false });
|
|
133
|
+
const solana = lines.some((line) => line.network === "solana") ? await loadSolanaWallet(deps.walletDir) : null;
|
|
134
|
+
const requeue = [];
|
|
135
|
+
const seen = /* @__PURE__ */ new Set();
|
|
136
|
+
for (const line of lines) {
|
|
137
|
+
if (seen.has(line.payment_reference)) continue;
|
|
138
|
+
seen.add(line.payment_reference);
|
|
139
|
+
const age = now - Date.parse(line.observed_at);
|
|
140
|
+
if (!(age < MAX_AGE_MS) || (line.attempts ?? 0) >= MAX_ATTEMPTS) {
|
|
141
|
+
result.dropped += 1;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const body = await buildSubmission(line, wallet, solana);
|
|
145
|
+
if (body === null) {
|
|
146
|
+
result.dropped += 1;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const verdict = await submit(body, deps);
|
|
150
|
+
result[verdict] += 1;
|
|
151
|
+
if (verdict === "retry") requeue.push({ ...line, attempts: (line.attempts ?? 0) + 1 });
|
|
152
|
+
}
|
|
153
|
+
if (requeue.length) {
|
|
154
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
155
|
+
await appendFile(pending, requeue.map((line) => JSON.stringify(line) + "\n").join(""), { mode: 384 });
|
|
156
|
+
}
|
|
157
|
+
await rm(claim, { force: true });
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
var OBSERVATION_DISCLOSURE = [
|
|
161
|
+
"Paid-call records (on by default; `crowdcode-mcp off` stops them):",
|
|
162
|
+
" When an MCP tool such as AgentCash pays for an x402 or MPP call, a local hook",
|
|
163
|
+
" writes one line to ~/.crowdcode/pending.jsonl. crowdcode-mcp signs it with your",
|
|
164
|
+
" local wallet and sends exactly these fields to CrowdCode:",
|
|
165
|
+
" endpoint (no query string), method, network, payment_reference (the settlement",
|
|
166
|
+
" transaction), amount_atomic, status (HTTP), response_bytes, observed_at",
|
|
167
|
+
" Never the request, the response, your prompt or any file. CrowdCode checks the",
|
|
168
|
+
' payment on-chain and counts it as "someone else paid and it answered"; it is',
|
|
169
|
+
" never a rating. The Stop hook reads the local transcript only to decide whether",
|
|
170
|
+
" to ask for a reflection, and sends nothing."
|
|
171
|
+
].join("\n");
|
|
172
|
+
|
|
173
|
+
export {
|
|
174
|
+
OBSERVATION_FIELDS,
|
|
175
|
+
MESSAGE_HEADER,
|
|
176
|
+
observationMessage,
|
|
177
|
+
crowdcodeDir,
|
|
178
|
+
observationsUrl,
|
|
179
|
+
toRecord,
|
|
180
|
+
buildSubmission,
|
|
181
|
+
flushPending,
|
|
182
|
+
OBSERVATION_DISCLOSURE
|
|
183
|
+
};
|
|
184
|
+
//# sourceMappingURL=chunk-QKICGYZG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/observations.ts"],"sourcesContent":["/**\n * Paid-call observations (C5): sign and submit what the PostToolUse hook\n * recorded in ~/.crowdcode/pending.jsonl.\n *\n * The hook writes metadata only and never touches the network. This module\n * runs inside the crowdcode-mcp server (every 15 s while it is connected) and\n * through `crowdcode-mcp flush`. For each pending line it sends exactly the\n * eight OBSERVATION_FIELDS, signed by the local wallet that paid, to\n * `POST /api/observations`. Nothing else leaves the machine: no request, no\n * response, no tool name, no query string.\n *\n * `crowdcode-mcp off` (the saved default) stops both recording and sending.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { appendFile, mkdir, readdir, readFile, rename, rm, stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { loadSolanaWallet, loadWallet, type LoadedWallet, type SolanaWallet } from \"./wallet.js\";\n\nexport const OBSERVATION_FIELDS = [\n \"endpoint\",\n \"method\",\n \"network\",\n \"payment_reference\",\n \"amount_atomic\",\n \"status\",\n \"response_bytes\",\n \"observed_at\",\n] as const;\n\nexport type ObservationRecord = {\n endpoint: string;\n method: string | null;\n network: string;\n payment_reference: string;\n amount_atomic: number | null;\n status: number | null;\n response_bytes: number | null;\n observed_at: string;\n};\n\n/** One line of pending.jsonl: the record plus local-only bookkeeping. */\nexport interface PendingLine extends ObservationRecord {\n payer?: string | null;\n tool?: string;\n attempts?: number;\n}\n\nexport const MESSAGE_HEADER = \"CrowdCode observation v1\";\nconst MAX_ATTEMPTS = 20;\nconst MAX_AGE_MS = 6 * 24 * 3600 * 1000;\nconst STALE_CLAIM_MS = 5 * 60 * 1000;\nconst REQUEST_TIMEOUT_MS = 15_000;\n\n/** Exactly the text the backend verifies (crowdcode.observations.observation_message). */\nexport function observationMessage(record: ObservationRecord): string {\n return [MESSAGE_HEADER, ...OBSERVATION_FIELDS.map((key) => `${key}:${record[key] ?? \"\"}`)].join(\"\\n\");\n}\n\nexport function crowdcodeDir(env: NodeJS.ProcessEnv = process.env): string {\n return env.CROWDCODE_HOME ?? join(homedir(), \".crowdcode\");\n}\n\nexport function observationsUrl(backendUrl: string, env: NodeJS.ProcessEnv = process.env): string {\n if (env.CROWDCODE_OBSERVATIONS_URL) return env.CROWDCODE_OBSERVATIONS_URL;\n const url = new URL(backendUrl);\n url.pathname = url.pathname.replace(/\\/mcp\\/?$/, \"\") + \"/api/observations\";\n url.pathname = url.pathname.replace(/\\/{2,}/g, \"/\");\n return url.toString();\n}\n\n/** Only the eight contract fields, in order, whatever else the line holds. */\nexport function toRecord(line: PendingLine): ObservationRecord {\n return Object.fromEntries(OBSERVATION_FIELDS.map((key) => [key, line[key] ?? null])) as ObservationRecord;\n}\n\nexport interface SubmitBody {\n observation: ObservationRecord;\n signature: string;\n payer_wallet?: string;\n payer_signature?: string;\n}\n\nexport interface FlushDeps {\n dir?: string;\n url: string;\n walletDir?: string;\n fetch?: typeof fetch;\n enabled?: () => Promise<boolean>;\n now?: () => number;\n log?: (message: string) => void;\n}\n\nexport interface FlushResult {\n sent: number;\n duplicate: number;\n retry: number;\n dropped: number;\n}\n\ntype Verdict = \"sent\" | \"duplicate\" | \"retry\" | \"dropped\";\n\nexport async function buildSubmission(\n line: PendingLine,\n wallet: LoadedWallet,\n solana: SolanaWallet | null,\n): Promise<SubmitBody | null> {\n if (!wallet.account || !wallet.address) return null;\n const record = toRecord(line);\n const message = observationMessage(record);\n const body: SubmitBody = { observation: record, signature: await wallet.account.signMessage({ message }) };\n if (record.network === \"solana\") {\n // The Solana payer links the payment; only the local agentcash key can.\n if (!solana || (line.payer && line.payer !== solana.address)) return null;\n body.payer_wallet = solana.address;\n body.payer_signature = solana.sign(message);\n } else if (line.payer && line.payer.toLowerCase() !== wallet.address.toLowerCase()) {\n return null; // paid by some other wallet: this machine cannot vouch for it\n }\n return body;\n}\n\nasync function submit(body: SubmitBody, deps: FlushDeps): Promise<Verdict> {\n const doFetch = deps.fetch ?? fetch;\n let response: Response;\n try {\n response = await doFetch(deps.url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch {\n return \"retry\";\n }\n let payload: Record<string, unknown> = {};\n try { payload = (await response.json()) as Record<string, unknown>; } catch { /* empty */ }\n if (response.ok && payload.accepted === true) return payload.duplicate === true ? \"duplicate\" : \"sent\";\n if (response.status >= 500 || response.status === 429 || payload.retryable === true) return \"retry\";\n deps.log?.(`crowdcode-mcp: observation not accepted (${String(payload.error_code ?? response.status)})`);\n return \"dropped\";\n}\n\nfunction parseLines(text: string): PendingLine[] {\n const lines: PendingLine[] = [];\n for (const raw of text.split(\"\\n\")) {\n if (!raw.trim()) continue;\n try {\n const parsed = JSON.parse(raw) as PendingLine;\n if (parsed && typeof parsed.endpoint === \"string\" && typeof parsed.payment_reference === \"string\") lines.push(parsed);\n } catch { /* a torn line is skipped */ }\n }\n return lines;\n}\n\n/** Return orphaned claims (a process that died mid-flush) to the queue. */\nasync function recoverStale(dir: string, now: number): Promise<void> {\n let names: string[];\n try { names = await readdir(dir); } catch { return; }\n for (const name of names) {\n if (!name.startsWith(\"pending.jsonl.\") || !name.endsWith(\".sending\")) continue;\n const file = join(dir, name);\n try {\n if (now - (await stat(file)).mtimeMs < STALE_CLAIM_MS) continue;\n await appendFile(join(dir, \"pending.jsonl\"), await readFile(file, \"utf8\"), { mode: 0o600 });\n await rm(file, { force: true });\n } catch { /* another process got it */ }\n }\n}\n\nlet flushing: Promise<FlushResult> | null = null;\n\n/** Submit everything pending once. Concurrent calls in one process share a run. */\nexport function flushPending(deps: FlushDeps): Promise<FlushResult> {\n if (flushing) return flushing;\n flushing = flushOnce(deps).finally(() => { flushing = null; });\n return flushing;\n}\n\nasync function flushOnce(deps: FlushDeps): Promise<FlushResult> {\n const result: FlushResult = { sent: 0, duplicate: 0, retry: 0, dropped: 0 };\n if (deps.enabled && !(await deps.enabled())) return result;\n const dir = deps.dir ?? crowdcodeDir();\n const now = deps.now?.() ?? Date.now();\n await recoverStale(dir, now);\n const pending = join(dir, \"pending.jsonl\");\n const claim = join(dir, `pending.jsonl.${process.pid}-${randomUUID()}.sending`);\n // The rename is the lock: the hook keeps appending to a fresh pending.jsonl,\n // and two servers never submit the same line.\n try { await rename(pending, claim); } catch { return result; }\n // A hook that opened the old file just before the rename finishes its write.\n await new Promise((resolve) => setTimeout(resolve, 50));\n const lines = parseLines(await readFile(claim, \"utf8\"));\n const wallet = await loadWallet({ walletDir: deps.walletDir, autoCreate: false });\n const solana = lines.some((line) => line.network === \"solana\") ? await loadSolanaWallet(deps.walletDir) : null;\n const requeue: PendingLine[] = [];\n const seen = new Set<string>();\n for (const line of lines) {\n if (seen.has(line.payment_reference)) continue;\n seen.add(line.payment_reference);\n const age = now - Date.parse(line.observed_at);\n if (!(age < MAX_AGE_MS) || (line.attempts ?? 0) >= MAX_ATTEMPTS) { result.dropped += 1; continue; }\n const body = await buildSubmission(line, wallet, solana);\n if (body === null) { result.dropped += 1; continue; }\n const verdict = await submit(body, deps);\n result[verdict] += 1;\n if (verdict === \"retry\") requeue.push({ ...line, attempts: (line.attempts ?? 0) + 1 });\n }\n if (requeue.length) {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n await appendFile(pending, requeue.map((line) => JSON.stringify(line) + \"\\n\").join(\"\"), { mode: 0o600 });\n }\n await rm(claim, { force: true });\n return result;\n}\n\n/** What `crowdcode-mcp install` prints before turning observations on. */\nexport const OBSERVATION_DISCLOSURE = [\n \"Paid-call records (on by default; `crowdcode-mcp off` stops them):\",\n \" When an MCP tool such as AgentCash pays for an x402 or MPP call, a local hook\",\n \" writes one line to ~/.crowdcode/pending.jsonl. crowdcode-mcp signs it with your\",\n \" local wallet and sends exactly these fields to CrowdCode:\",\n \" endpoint (no query string), method, network, payment_reference (the settlement\",\n \" transaction), amount_atomic, status (HTTP), response_bytes, observed_at\",\n \" Never the request, the response, your prompt or any file. CrowdCode checks the\",\n \" payment on-chain and counts it as \\\"someone else paid and it answered\\\"; it is\",\n \" never a rating. The Stop hook reads the local transcript only to decide whether\",\n \" to ask for a reflection, and sends nothing.\",\n].join(\"\\n\");\n"],"mappings":";;;;;;AAcA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,OAA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,EACA;AAAA,EACA;AACF,EAAE,KAAK,IAAI;","names":[]}
|
package/dist/cli.js
CHANGED
|
@@ -1,30 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
getConfig
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-CF6JGOQF.js";
|
|
5
|
+
import "./chunk-2Y65AAP3.js";
|
|
5
6
|
|
|
6
7
|
// src/cli.ts
|
|
7
8
|
import { rm as rm2, stat as stat2 } from "fs/promises";
|
|
8
9
|
import { createInterface } from "readline/promises";
|
|
9
10
|
|
|
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
|
-
|
|
28
11
|
// src/installer.ts
|
|
29
12
|
import { createHash } from "crypto";
|
|
30
13
|
import {
|
|
@@ -300,22 +283,87 @@ function mergeJsonMcpConfig(content, path = "config.json") {
|
|
|
300
283
|
return `${JSON.stringify(config, null, 2)}
|
|
301
284
|
`;
|
|
302
285
|
}
|
|
303
|
-
|
|
286
|
+
var HOOK_FILES = ["receipts.cjs", "paid-call.cjs", "completion.cjs"];
|
|
287
|
+
async function bundledHook(packageRoot, name) {
|
|
288
|
+
const packaged = await readOptional(join(packageRoot, "dist", "hooks", name));
|
|
289
|
+
if (packaged !== null) return packaged;
|
|
290
|
+
return readFile(join(packageRoot, "hooks", name), "utf8");
|
|
291
|
+
}
|
|
292
|
+
function hooksDir(homeDir) {
|
|
293
|
+
return join(homeDir, ".crowdcode", "hooks");
|
|
294
|
+
}
|
|
295
|
+
async function installHookFiles(env) {
|
|
296
|
+
for (const name of HOOK_FILES) {
|
|
297
|
+
const path = join(hooksDir(env.homeDir), name);
|
|
298
|
+
const content = await bundledHook(env.packageRoot, name);
|
|
299
|
+
if (content !== await readOptional(path)) await atomicWrite(path, content);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function claudeHook(path) {
|
|
303
|
+
return { type: "command", command: "node", args: [path], timeout: 5 };
|
|
304
|
+
}
|
|
305
|
+
function codexHook(path, platform) {
|
|
306
|
+
return { type: "command", command: codexCommand(path, platform), timeout: 5 };
|
|
307
|
+
}
|
|
308
|
+
function codexCommand(path, platform) {
|
|
309
|
+
return platform === "win32" ? `node "${path}"` : `node '${path.replace(/'/g, "'\\''")}'`;
|
|
310
|
+
}
|
|
311
|
+
function isOurHook(hook, path) {
|
|
312
|
+
if (!hook || hook.type !== "command") return false;
|
|
313
|
+
if (hook.command === "node" && Array.isArray(hook.args)) return hook.args.length === 1 && hook.args[0] === path;
|
|
314
|
+
return typeof hook.command === "string" && ["darwin", "linux", "win32"].some((platform) => hook.command === codexCommand(path, platform));
|
|
315
|
+
}
|
|
316
|
+
function mergeHookEvent(hookMap, event, path, hook, matcher) {
|
|
317
|
+
const current = hookMap[event] ?? [];
|
|
318
|
+
if (!Array.isArray(current)) throw new Error(`Invalid ${event} hooks settings`);
|
|
319
|
+
const kept = current.filter((entry) => !(Array.isArray(entry?.hooks) && entry.hooks.some((h) => isOurHook(h, path))));
|
|
320
|
+
const ours = { ...matcher ? { matcher } : {}, hooks: [hook] };
|
|
321
|
+
const existing = current.find((entry) => Array.isArray(entry?.hooks) && entry.hooks.some((h) => isOurHook(h, path)));
|
|
322
|
+
hookMap[event] = existing && JSON.stringify(existing) === JSON.stringify(ours) ? current : [...kept, ours];
|
|
323
|
+
}
|
|
324
|
+
function hookMapOf(settings, path) {
|
|
325
|
+
const hooks = settings.hooks ?? {};
|
|
326
|
+
if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) throw new Error(`Invalid hooks settings in ${path}`);
|
|
327
|
+
return hooks;
|
|
328
|
+
}
|
|
329
|
+
async function installClaudeHooks(env) {
|
|
304
330
|
const settingsPath = join(env.homeDir, ".claude", "settings.json");
|
|
305
331
|
const settings = parseJsonConfig(await readOptional(settingsPath) ?? "{}", settingsPath);
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
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 }] }];
|
|
332
|
+
const hookMap = hookMapOf(settings, settingsPath);
|
|
333
|
+
const dir = hooksDir(env.homeDir);
|
|
334
|
+
mergeHookEvent(hookMap, "PostToolUse", join(dir, "paid-call.cjs"), claudeHook(join(dir, "paid-call.cjs")), "mcp__.*");
|
|
335
|
+
mergeHookEvent(hookMap, "Stop", join(dir, "completion.cjs"), claudeHook(join(dir, "completion.cjs")));
|
|
314
336
|
settings.hooks = hookMap;
|
|
315
|
-
await atomicWrite(hookPath, COMPLETION_HOOK);
|
|
316
337
|
const next = JSON.stringify(settings, null, 2) + "\n";
|
|
317
338
|
if (next !== await readOptional(settingsPath)) await atomicWrite(settingsPath, next);
|
|
318
339
|
}
|
|
340
|
+
function codexHooksPath(input = {}) {
|
|
341
|
+
const env = resolvedEnvironment(input);
|
|
342
|
+
return join(env.env.CODEX_HOME ?? join(env.homeDir, ".codex"), "hooks.json");
|
|
343
|
+
}
|
|
344
|
+
async function installCodexHooks(env) {
|
|
345
|
+
const path = codexHooksPath(env);
|
|
346
|
+
const settings = parseJsonConfig(await readOptional(path) ?? "{}", path);
|
|
347
|
+
const hookMap = hookMapOf(settings, path);
|
|
348
|
+
const dir = hooksDir(env.homeDir);
|
|
349
|
+
mergeHookEvent(hookMap, "PostToolUse", join(dir, "paid-call.cjs"), codexHook(join(dir, "paid-call.cjs"), env.platform), "mcp__.*");
|
|
350
|
+
mergeHookEvent(hookMap, "Stop", join(dir, "completion.cjs"), codexHook(join(dir, "completion.cjs"), env.platform));
|
|
351
|
+
settings.hooks = hookMap;
|
|
352
|
+
const next = JSON.stringify(settings, null, 2) + "\n";
|
|
353
|
+
if (next !== await readOptional(path)) await atomicWrite(path, next);
|
|
354
|
+
}
|
|
355
|
+
async function hooksCurrent(env, settingsPath) {
|
|
356
|
+
try {
|
|
357
|
+
for (const name of HOOK_FILES) {
|
|
358
|
+
if (await readOptional(join(hooksDir(env.homeDir), name)) !== await bundledHook(env.packageRoot, name)) return false;
|
|
359
|
+
}
|
|
360
|
+
const settings = JSON.parse(await readOptional(settingsPath) ?? "{}");
|
|
361
|
+
const has = (event, file) => Array.isArray(settings.hooks?.[event]) && settings.hooks[event].some((entry) => Array.isArray(entry?.hooks) && entry.hooks.some((hook) => isOurHook(hook, join(hooksDir(env.homeDir), file))));
|
|
362
|
+
return has("PostToolUse", "paid-call.cjs") && has("Stop", "completion.cjs");
|
|
363
|
+
} catch {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
319
367
|
async function configureClient(client, env) {
|
|
320
368
|
const path = getClientConfigPath(client, env);
|
|
321
369
|
const current = await readOptional(path) ?? "";
|
|
@@ -343,8 +391,10 @@ async function installForClients(clients, input = {}) {
|
|
|
343
391
|
let claudeMode = null;
|
|
344
392
|
if (clients.includes("claude-code")) {
|
|
345
393
|
claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);
|
|
346
|
-
await installCompletionHook(env);
|
|
347
394
|
}
|
|
395
|
+
if (clients.includes("claude-code") || clients.includes("codex")) await installHookFiles(env);
|
|
396
|
+
if (clients.includes("claude-code")) await installClaudeHooks(env);
|
|
397
|
+
if (clients.includes("codex")) await installCodexHooks(env);
|
|
348
398
|
const results = [];
|
|
349
399
|
for (const client of clients) {
|
|
350
400
|
const configPath = await configureClient(client, env);
|
|
@@ -399,13 +449,7 @@ async function doctorClients(clients = CORE_CLIENTS, input = {}) {
|
|
|
399
449
|
if (client === "claude-code") {
|
|
400
450
|
const skillPath = claudeCodeSkillDir(env.homeDir);
|
|
401
451
|
const skillCurrent = await readOptional(join(skillPath, "SKILL.md")) === expectedSkill;
|
|
402
|
-
|
|
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
|
-
}
|
|
452
|
+
const completionHookCurrent = await hooksCurrent(env, join(env.homeDir, ".claude", "settings.json"));
|
|
409
453
|
results.push({
|
|
410
454
|
client,
|
|
411
455
|
configPath,
|
|
@@ -413,7 +457,7 @@ async function doctorClients(clients = CORE_CLIENTS, input = {}) {
|
|
|
413
457
|
skillPath,
|
|
414
458
|
skillCurrent,
|
|
415
459
|
completionHookCurrent,
|
|
416
|
-
...!completionHookCurrent ? { detail: "Re-run install --client claude-code to refresh the
|
|
460
|
+
...!completionHookCurrent ? { detail: "Re-run install --client claude-code to refresh the CrowdCode hooks." } : {}
|
|
417
461
|
});
|
|
418
462
|
} else if (client === "claude-desktop") {
|
|
419
463
|
results.push({
|
|
@@ -424,6 +468,17 @@ async function doctorClients(clients = CORE_CLIENTS, input = {}) {
|
|
|
424
468
|
skillCurrent: mcpConfigured,
|
|
425
469
|
detail: "Claude Desktop uses CrowdCode's MCP initialization instructions."
|
|
426
470
|
});
|
|
471
|
+
} else if (client === "codex") {
|
|
472
|
+
const completionHookCurrent = await hooksCurrent(env, codexHooksPath(env));
|
|
473
|
+
results.push({
|
|
474
|
+
client,
|
|
475
|
+
configPath,
|
|
476
|
+
mcpConfigured,
|
|
477
|
+
skillPath: canonicalPath,
|
|
478
|
+
skillCurrent: canonicalCurrent,
|
|
479
|
+
completionHookCurrent,
|
|
480
|
+
...!completionHookCurrent ? { detail: "Re-run install --client codex to refresh the CrowdCode hooks." } : {}
|
|
481
|
+
});
|
|
427
482
|
} else {
|
|
428
483
|
results.push({
|
|
429
484
|
client,
|
|
@@ -576,6 +631,12 @@ async function runInstall(args) {
|
|
|
576
631
|
` ${result.client}: MCP ${result.configPath}; skill ${result.skillPath} (${result.skillMode})`
|
|
577
632
|
);
|
|
578
633
|
}
|
|
634
|
+
if (clients.includes("claude-code") || clients.includes("codex")) {
|
|
635
|
+
const { OBSERVATION_DISCLOSURE } = await import("./observations-HIXF7KW5.js");
|
|
636
|
+
console.error("");
|
|
637
|
+
console.error(OBSERVATION_DISCLOSURE);
|
|
638
|
+
console.error("");
|
|
639
|
+
}
|
|
579
640
|
console.error("Restart these clients so they reload the CrowdCode skill and MCP server.");
|
|
580
641
|
}
|
|
581
642
|
async function runDoctor(args) {
|
|
@@ -598,10 +659,12 @@ async function runDoctor(args) {
|
|
|
598
659
|
}
|
|
599
660
|
function printHelp() {
|
|
600
661
|
console.error(
|
|
601
|
-
`usage: crowdcode-mcp [serve|on|off|status|install|doctor|check <text>|clear-cache]
|
|
662
|
+
`usage: crowdcode-mcp [serve|on|off|status|flush|install|doctor|check <text>|clear-cache]
|
|
602
663
|
serve start the stdio MCP server (default)
|
|
603
|
-
on/off save CrowdCode default (active session overrides take precedence)
|
|
664
|
+
on/off save CrowdCode default (active session overrides take precedence);
|
|
665
|
+
off also stops paid-call records
|
|
604
666
|
status show the saved default for new connections
|
|
667
|
+
flush submit pending paid-call records now (signed metadata only)
|
|
605
668
|
install install the CrowdCode skill and MCP config
|
|
606
669
|
[--client <client>] [--all-detected] [--yes]
|
|
607
670
|
doctor verify skill and MCP config [--client <client>] [--all-detected]
|
|
@@ -616,7 +679,7 @@ async function main() {
|
|
|
616
679
|
case void 0:
|
|
617
680
|
case "serve": {
|
|
618
681
|
routeStdoutToStderr();
|
|
619
|
-
const { startServer } = await import("./server-
|
|
682
|
+
const { startServer } = await import("./server-AMGZRDBF.js");
|
|
620
683
|
await startServer();
|
|
621
684
|
break;
|
|
622
685
|
}
|
|
@@ -629,6 +692,18 @@ async function main() {
|
|
|
629
692
|
console.log(JSON.stringify(state));
|
|
630
693
|
break;
|
|
631
694
|
}
|
|
695
|
+
case "flush": {
|
|
696
|
+
const { flushPending, observationsUrl } = await import("./observations-HIXF7KW5.js");
|
|
697
|
+
const { Preferences } = await import("./preferences-JBW45B4W.js");
|
|
698
|
+
const preferences = new Preferences();
|
|
699
|
+
const result = await flushPending({
|
|
700
|
+
url: observationsUrl(getConfig().backendUrl),
|
|
701
|
+
enabled: async () => (await preferences.status()).enabled,
|
|
702
|
+
log: (message) => console.error(message)
|
|
703
|
+
});
|
|
704
|
+
console.log(JSON.stringify(result));
|
|
705
|
+
break;
|
|
706
|
+
}
|
|
632
707
|
case "check":
|
|
633
708
|
await runCheck(rest.length > 0 ? rest.join(" ") : void 0);
|
|
634
709
|
break;
|