@dcp-ai/create-langchain 2.0.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/bin.js ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @dcp-ai/create-langchain — scaffolds a DCP-governed LangChain project.
4
+ *
5
+ * Usage:
6
+ * npm create @dcp-ai/langchain my-app
7
+ * npx @dcp-ai/create-langchain my-app
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const TEMPLATE_NAME = 'langchain';
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ const TEMPLATE_DIR = path.join(__dirname, 'template');
16
+
17
+ function die(msg) {
18
+ console.error(`\x1b[31m✗\x1b[0m ${msg}`);
19
+ process.exit(1);
20
+ }
21
+
22
+ function copyRecursive(src, dest) {
23
+ const stat = fs.statSync(src);
24
+ if (stat.isDirectory()) {
25
+ fs.mkdirSync(dest, { recursive: true });
26
+ for (const entry of fs.readdirSync(src)) {
27
+ copyRecursive(path.join(src, entry), path.join(dest, entry));
28
+ }
29
+ } else {
30
+ fs.copyFileSync(src, dest);
31
+ }
32
+ }
33
+
34
+ const target = process.argv[2];
35
+ if (!target) {
36
+ console.log(`Usage: npm create @dcp-ai/${TEMPLATE_NAME} <directory>`);
37
+ process.exit(0);
38
+ }
39
+
40
+ const dest = path.resolve(process.cwd(), target);
41
+ if (fs.existsSync(dest) && fs.readdirSync(dest).length > 0) {
42
+ die(`Target directory "${target}" already exists and is not empty.`);
43
+ }
44
+
45
+ if (!fs.existsSync(TEMPLATE_DIR)) {
46
+ die(`Template directory not found at ${TEMPLATE_DIR}. Reinstall the package.`);
47
+ }
48
+
49
+ console.log(`\x1b[36m→\x1b[0m Scaffolding DCP-AI ${TEMPLATE_NAME} template into ${dest}`);
50
+ copyRecursive(TEMPLATE_DIR, dest);
51
+
52
+ console.log(`\x1b[32m✓\x1b[0m Done.\n`);
53
+ console.log(`Next steps:\n`);
54
+ console.log(` cd ${target}`);
55
+ console.log(` npm install`);
56
+ console.log(` # follow the README for API keys and run instructions\n`);
57
+ console.log(`Docs: https://docs.dcp-ai.org/quickstart/QUICKSTART_LANGCHAIN/`);
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@dcp-ai/create-langchain",
3
+ "version": "2.0.0",
4
+ "description": "Scaffold a DCP-AI governed LangChain agent project",
5
+ "type": "module",
6
+ "bin": {
7
+ "create-dcp-langchain": "./bin.js"
8
+ },
9
+ "files": ["bin.js", "template"],
10
+ "keywords": ["dcp", "langchain", "agent", "ai", "template", "scaffold"],
11
+ "license": "Apache-2.0",
12
+ "author": "DCP-AI Contributors",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/dcp-ai-protocol/dcp-ai",
16
+ "directory": "packages/create-langchain"
17
+ },
18
+ "homepage": "https://dcp-ai.org",
19
+ "bugs": {
20
+ "url": "https://github.com/dcp-ai-protocol/dcp-ai/issues"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ }
28
+ }
@@ -0,0 +1,33 @@
1
+ # DCP-AI + LangChain Template
2
+
3
+ Get your LangChain agent digital citizenship in 3 steps.
4
+
5
+ ## Quick Start
6
+
7
+ 1. Initialize DCP identity:
8
+ ```bash
9
+ npx @dcp-ai/cli init
10
+ ```
11
+
12
+ 2. Install dependencies:
13
+ ```bash
14
+ npm install
15
+ ```
16
+
17
+ 3. Run your agent:
18
+ ```bash
19
+ node index.js
20
+ ```
21
+
22
+ ## What this template does
23
+
24
+ - Creates a LangChain agent with DCP digital citizenship
25
+ - Every action is declared as an Intent
26
+ - Every response is audited
27
+ - The agent carries a verifiable Citizenship Bundle
28
+
29
+ ## Files
30
+
31
+ - `index.js` — LangChain agent with DCP integration
32
+ - `.dcp/config.json` — DCP configuration (generated by init)
33
+ - `package.json` — Dependencies
@@ -0,0 +1,233 @@
1
+ /**
2
+ * DCP-AI + LangChain Template
3
+ *
4
+ * Demonstrates how a LangChain agent obtains digital citizenship
5
+ * under the DCP v2.0 protocol. Every LLM call is wrapped in the
6
+ * Intent → PolicyDecision → Action → AuditEntry → Bundle lifecycle.
7
+ */
8
+
9
+ import crypto from "node:crypto";
10
+ import { ChatOpenAI } from "@langchain/openai";
11
+ import { HumanMessage } from "@langchain/core/messages";
12
+
13
+ // ─── Step 1: Load DCP configuration and generate keys ────────────────────────
14
+ //
15
+ // In production, `npx @dcp-ai/cli init` writes a .dcp/config.json with your
16
+ // owner details and jurisdiction. Here we bootstrap a minimal config in-memory.
17
+
18
+ const sessionNonce = crypto.randomBytes(32).toString("hex");
19
+ const now = new Date().toISOString();
20
+ const humanId = `rpr:${crypto.randomUUID()}`;
21
+ const agentId = `agent:${crypto.randomUUID()}`;
22
+
23
+ // Ed25519 classical key (in production, use @dcp-ai/sdk's registerDefaultProviders)
24
+ const classicalKid = crypto.randomBytes(16).toString("hex");
25
+ const pqKid = crypto.randomBytes(16).toString("hex");
26
+
27
+ const keyEntries = [
28
+ { kid: classicalKid, alg: "ed25519", public_key_b64: "«generated»", created_at: now, expires_at: null, status: "active" },
29
+ { kid: pqKid, alg: "ml-dsa-65", public_key_b64: "«generated»", created_at: now, expires_at: null, status: "active" },
30
+ ];
31
+
32
+ console.log("🔑 DCP identity created");
33
+ console.log(` Agent: ${agentId}`);
34
+ console.log(` Human: ${humanId}`);
35
+ console.log(` Session: ${sessionNonce.slice(0, 16)}…\n`);
36
+
37
+ // ─── Step 2: Create ResponsiblePrincipalRecord and AgentPassport ─────────────────────
38
+ //
39
+ // The RPR ties the agent to a legally-responsible human.
40
+ // The AgentPassport declares what the agent is allowed to do.
41
+
42
+ const responsiblePrincipalRecord = {
43
+ dcp_version: "2.0",
44
+ human_id: humanId,
45
+ session_nonce: sessionNonce,
46
+ legal_name: "Ada Lovelace",
47
+ entity_type: "natural_person",
48
+ jurisdiction: "US",
49
+ liability_mode: "owner_responsible",
50
+ override_rights: true,
51
+ issued_at: now,
52
+ expires_at: null,
53
+ contact: "ada@example.com",
54
+ binding_keys: keyEntries,
55
+ };
56
+
57
+ const agentPassport = {
58
+ dcp_version: "2.0",
59
+ agent_id: agentId,
60
+ session_nonce: sessionNonce,
61
+ keys: keyEntries,
62
+ principal_binding_reference: humanId,
63
+ capabilities: ["browse", "api_call"],
64
+ risk_tier: "low",
65
+ created_at: now,
66
+ status: "active",
67
+ };
68
+
69
+ console.log("📋 ResponsiblePrincipalRecord created — agent bound to Ada Lovelace (US)");
70
+ console.log("🛂 AgentPassport created — capabilities: browse, api_call\n");
71
+
72
+ // ─── Step 3: Declare an Intent before calling the LLM ────────────────────────
73
+ //
74
+ // DCP-02 requires that every sensitive action starts with an Intent declaration.
75
+ // The policy engine evaluates the intent and returns approve / escalate / block.
76
+
77
+ const intentId = `intent:${crypto.randomUUID()}`;
78
+
79
+ const intent = {
80
+ dcp_version: "2.0",
81
+ intent_id: intentId,
82
+ session_nonce: sessionNonce,
83
+ agent_id: agentId,
84
+ human_id: humanId,
85
+ timestamp: now,
86
+ action_type: "api_call",
87
+ target: {
88
+ channel: "api",
89
+ domain: "api.openai.com",
90
+ },
91
+ data_classes: ["none"],
92
+ estimated_impact: "low",
93
+ requires_consent: false,
94
+ };
95
+
96
+ console.log(`📝 Intent declared: ${intentId}`);
97
+
98
+ // ─── Step 4: Get a PolicyDecision ────────────────────────────────────────────
99
+ //
100
+ // A local or remote policy engine evaluates the intent against the agent's
101
+ // risk tier, capabilities, and data classification. Risk scores are 0-1000
102
+ // (millirisk — no floating point).
103
+
104
+ const policyDecision = {
105
+ dcp_version: "2.0",
106
+ intent_id: intentId,
107
+ session_nonce: sessionNonce,
108
+ decision: "approve",
109
+ risk_score: 50,
110
+ reasons: ["Low-impact API call to known domain, within agent capabilities"],
111
+ required_confirmation: null,
112
+ applied_policy_hash: `sha256:${crypto.createHash("sha256").update("default-policy-v2").digest("hex")}`,
113
+ timestamp: now,
114
+ };
115
+
116
+ console.log(`✅ Policy decision: ${policyDecision.decision} (risk: ${policyDecision.risk_score}/1000)\n`);
117
+
118
+ // ─── Step 5: Execute the action (LangChain LLM call) ────────────────────────
119
+ //
120
+ // Only proceed if the policy decision is "approve". If "escalate", the agent
121
+ // must wait for human confirmation. If "block", the action is forbidden.
122
+
123
+ let outcome = "error";
124
+
125
+ if (policyDecision.decision === "approve") {
126
+ console.log("🤖 Calling LangChain agent…\n");
127
+
128
+ try {
129
+ const model = new ChatOpenAI({ modelName: "gpt-4o-mini", temperature: 0 });
130
+ const response = await model.invoke([
131
+ new HumanMessage("Summarize the DCP protocol in one sentence."),
132
+ ]);
133
+ console.log(` Response: ${response.content}\n`);
134
+ outcome = "success";
135
+ } catch (err) {
136
+ console.log(` (Skipping actual LLM call — set OPENAI_API_KEY to run live)`);
137
+ console.log(` Simulated response: "DCP gives AI agents verifiable digital citizenship."\n`);
138
+ outcome = "success";
139
+ }
140
+ } else {
141
+ console.log(`⛔ Action blocked by policy: ${policyDecision.reasons.join(", ")}`);
142
+ }
143
+
144
+ // ─── Step 6: Create AuditEntries for the action ──────────────────────────────
145
+ //
146
+ // DCP-03 requires a tamper-evident audit trail. Each entry references the
147
+ // previous entry's hash (hash chain) and the intent it fulfills.
148
+
149
+ const auditId = `audit:${crypto.randomUUID()}`;
150
+ const intentHash = hashPayload(intent);
151
+
152
+ const auditEntry = {
153
+ dcp_version: "2.0",
154
+ audit_id: auditId,
155
+ session_nonce: sessionNonce,
156
+ prev_hash: "sha256:0000000000000000000000000000000000000000000000000000000000000000",
157
+ hash_alg: "sha256",
158
+ timestamp: new Date().toISOString(),
159
+ agent_id: agentId,
160
+ human_id: humanId,
161
+ intent_id: intentId,
162
+ intent_hash: intentHash,
163
+ policy_decision: "approved",
164
+ outcome,
165
+ evidence: {
166
+ tool: "langchain.ChatOpenAI",
167
+ result_ref: "gpt-4o-mini-response",
168
+ evidence_hash: `sha256:${crypto.createHash("sha256").update(outcome).digest("hex")}`,
169
+ },
170
+ pq_checkpoint_ref: null,
171
+ };
172
+
173
+ console.log(`📒 Audit entry recorded: ${auditId}`);
174
+
175
+ // ─── Step 7: Build and sign the CitizenshipBundle ────────────────────────────
176
+ //
177
+ // The bundle binds together: RPR + Passport + Intent + PolicyDecision + AuditEntries.
178
+ // A manifest captures hashes of all artifacts plus the audit Merkle root.
179
+ // The bundle is composite-signed (Ed25519 + ML-DSA-65) for post-quantum safety.
180
+
181
+ function canonicalize(obj) {
182
+ if (obj === null || typeof obj !== "object") return JSON.stringify(obj);
183
+ if (Array.isArray(obj)) return "[" + obj.map(canonicalize).join(",") + "]";
184
+ const sorted = Object.keys(obj).sort();
185
+ return "{" + sorted.map(k => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") + "}";
186
+ }
187
+
188
+ function hashPayload(payload) {
189
+ const data = typeof payload === "string" ? payload : canonicalize(payload);
190
+ return `sha256:${crypto.createHash("sha256").update(data).digest("hex")}`;
191
+ }
192
+
193
+ const manifest = {
194
+ session_nonce: sessionNonce,
195
+ rpr_hash: hashPayload(responsiblePrincipalRecord),
196
+ passport_hash: hashPayload(agentPassport),
197
+ intent_hash: hashPayload(intent),
198
+ policy_hash: hashPayload(policyDecision),
199
+ audit_merkle_root: hashPayload(auditEntry),
200
+ audit_count: 1,
201
+ };
202
+
203
+ const citizenshipBundle = {
204
+ dcp_bundle_version: "2.0",
205
+ manifest,
206
+ responsible_principal_record: { payload: responsiblePrincipalRecord, payload_hash: manifest.rpr_hash, composite_sig: { classical: { alg: "ed25519", kid: classicalKid, sig_b64: "«sig»" }, pq: { alg: "ml-dsa-65", kid: pqKid, sig_b64: "«sig»" }, binding: "pq_over_classical" } },
207
+ agent_passport: { payload: agentPassport, payload_hash: manifest.passport_hash, composite_sig: { classical: { alg: "ed25519", kid: classicalKid, sig_b64: "«sig»" }, pq: { alg: "ml-dsa-65", kid: pqKid, sig_b64: "«sig»" }, binding: "pq_over_classical" } },
208
+ intent: { payload: intent, payload_hash: manifest.intent_hash, composite_sig: { classical: { alg: "ed25519", kid: classicalKid, sig_b64: "«sig»" }, pq: { alg: "ml-dsa-65", kid: pqKid, sig_b64: "«sig»" }, binding: "pq_over_classical" } },
209
+ policy_decision: { payload: policyDecision, payload_hash: manifest.policy_hash, composite_sig: { classical: { alg: "ed25519", kid: classicalKid, sig_b64: "«sig»" }, pq: { alg: "ml-dsa-65", kid: pqKid, sig_b64: "«sig»" }, binding: "pq_over_classical" } },
210
+ audit_entries: [auditEntry],
211
+ };
212
+
213
+ const signedBundle = {
214
+ bundle: citizenshipBundle,
215
+ signature: {
216
+ hash_alg: "sha256",
217
+ created_at: new Date().toISOString(),
218
+ signer: { type: "human", id: humanId, kids: [classicalKid, pqKid] },
219
+ manifest_hash: hashPayload(manifest),
220
+ composite_sig: {
221
+ classical: { alg: "ed25519", kid: classicalKid, sig_b64: "«bundle-sig»" },
222
+ pq: { alg: "ml-dsa-65", kid: pqKid, sig_b64: "«bundle-sig»" },
223
+ binding: "pq_over_classical",
224
+ },
225
+ },
226
+ };
227
+
228
+ console.log("\n🏛️ Citizenship Bundle signed");
229
+ console.log(` Bundle version: ${citizenshipBundle.dcp_bundle_version}`);
230
+ console.log(` Audit entries: ${citizenshipBundle.audit_entries.length}`);
231
+ console.log(` Signer: ${signedBundle.signature.signer.id}`);
232
+ console.log(` Binding: ${signedBundle.signature.composite_sig.binding}`);
233
+ console.log("\n✅ LangChain agent completed with full DCP digital citizenship.\n");
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "dcp-langchain-template",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "scripts": { "start": "node index.js" },
6
+ "dependencies": {
7
+ "langchain": "^0.3.0",
8
+ "@langchain/openai": "^0.3.0"
9
+ }
10
+ }