@chaoschain/sdk 0.2.3 → 0.3.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/CHANGELOG.md CHANGED
@@ -5,6 +5,41 @@ All notable changes to the ChaosChain TypeScript SDK will be documented in this
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.3.0] - 2026-03-20
9
+
10
+ ### Added
11
+
12
+ - **Session SDK** (`src/session/`): `SessionClient` and `Session` classes for Engineering Studio session ingestion
13
+ - `session.start()` — Create a new coding session
14
+ - `session.log()` — Log events with automatic parent chaining
15
+ - `session.step()` — Convenience wrapper mapping friendly names to canonical event types
16
+ - `session.complete()` — Complete session and get `workflow_id` + `data_hash`
17
+ - Automatic `parent_event_id` chaining across sequential `log()` calls
18
+ - `step()` helper maps friendly names (`planning`, `implementing`, `testing`, `debugging`, `completing`) to canonical event types
19
+ - E2E smoke test script at `scripts/test-session-e2e.ts` for validating against live gateway
20
+ - Session SDK accessible via `sdk.session` when gateway is configured
21
+ - **Verifier Agent Support**: Complete PoA (Proof-of-Agency) scoring utilities for verifier agents
22
+ - `verifyWorkEvidence()` — Validate evidence DAG and extract deterministic signals
23
+ - `extractAgencySignals()` — Extract initiative, collaboration, reasoning signals from evidence
24
+ - `composeScoreVector()` — Compose final score vector with verifier judgment (compliance/efficiency required)
25
+ - `composeScoreVectorWithDefaults()` — Compose scores with fallback defaults
26
+ - `GatewayClient.getPendingWork()` — Discover pending work for a studio
27
+ - `GatewayClient.getWorkEvidence()` — Fetch full evidence graph for work submission
28
+ - Types: `AgencySignals`, `VerifierAssessment`, `WorkVerificationResult`, `EngineeringStudioPolicy`, `WorkMandate`
29
+ - **Verifier Integration Guide** documentation with complete step-by-step workflow
30
+
31
+ ### Changed
32
+
33
+ - **Gateway is now always configured by default**: SDK automatically creates a `GatewayClient` pointing to `https://gateway.chaoscha.in` when no `gatewayConfig` or `gatewayUrl` is provided. This is a **breaking change** for code that expected `sdk.gateway` to be `null` when not explicitly configured.
34
+ - Gateway client initialization log now shows the resolved base URL
35
+ - Updated README with comprehensive verifier agent integration examples and 3-layer PoA scoring architecture
36
+
37
+ ### Fixed
38
+
39
+ - `randomUUID()` now uses `node:crypto` import for Node.js compatibility
40
+ - **Treasury address correction**: Fixed incorrect treasury address for `base-sepolia` network in `X402PaymentManager` (changed from `0x8004AA63c570c570eBF15376c0dB199918BFe9Fb` to `0x20E7B2A2c8969725b88Dd3EF3a11Bc3353C83F70`)
41
+ - TypeScript unused parameter warning in `computeComplianceSignal()` (renamed `observed` to `_observed`)
42
+
8
43
  ## [0.2.0] - Unreleased
9
44
 
10
45
  ### Added
package/README.md CHANGED
@@ -11,6 +11,7 @@ The ChaosChain TypeScript SDK enables developers to build autonomous AI agents w
11
11
  - **ERC-8004 v1.0** ✅ **100% compliant** - on-chain identity, validation and reputation
12
12
  - **ChaosChain Studios** - Multi-agent collaboration with reputation and rewards
13
13
  - **Gateway Integration** - Workflow orchestration, crash recovery, and XMTP messaging
14
+ - **Engineering Studio Sessions** - Capture agent work sessions with automatic Evidence DAG construction
14
15
  - **x402 payments** using Coinbase's HTTP 402 protocol
15
16
  - **Pluggable storage** - IPFS, Pinata, Irys, 0G Storage
16
17
  - **Type-safe** - Full TypeScript support with exported types
@@ -51,28 +52,121 @@ Storage backends are optional and intended for development/testing. In productio
51
52
  - **Missing RPC URL** → set `rpcUrl` explicitly (recommended for production).
52
53
  - **Using Gateway without config** → pass `gatewayConfig` or `gatewayUrl` to the constructor.
53
54
 
55
+ ## Engineering Studio — Session SDK
56
+
57
+ The Session SDK enables AI agents to capture their work sessions without manually constructing event schemas or DAGs. Sessions automatically build a verifiable Evidence DAG that produces trust profiles for reputation and scoring.
58
+
59
+ **Quick Start:**
60
+
61
+ ```typescript
62
+ import { SessionClient } from '@chaoschain/sdk';
63
+
64
+ const client = new SessionClient({
65
+ gatewayUrl: 'https://gateway.chaoscha.in',
66
+ apiKey: process.env.CHAOSCHAIN_API_KEY,
67
+ });
68
+
69
+ // 1. Start a session
70
+ const session = await client.start({
71
+ studio_address: '0xFA0795fD5D7F58eCAa7Eae35Ad9cB8AED9424Dd0',
72
+ agent_address: '0x9B4Cef62a0ce1671ccFEFA6a6D8cBFa165c49831',
73
+ task_type: 'feature',
74
+ });
75
+
76
+ // 2. Log events (automatic parent chaining)
77
+ await session.log({ summary: 'Planning cache layer implementation' });
78
+
79
+ // 3. Use step() for common workflows
80
+ await session.step('implementing', 'Added CacheService class');
81
+ await session.step('testing', 'All 47 tests pass');
82
+
83
+ // 4. Complete and get workflow_id + data_hash
84
+ const { workflow_id, data_hash } = await session.complete();
85
+ ```
86
+
87
+ **step() Mappings:**
88
+
89
+ | Friendly Name | Canonical Event Type |
90
+ |--------------|---------------------|
91
+ | `planning` | `plan_created` |
92
+ | `implementing`| `file_written` |
93
+ | `testing` | `test_run` |
94
+ | `debugging` | `debug_step` |
95
+ | `completing` | `submission_created`|
96
+
97
+ **View Your Session:**
98
+
99
+ After completing a session, view it in the browser:
100
+
101
+ ```
102
+ https://gateway.chaoscha.in/v1/sessions/{session_id}/viewer
103
+ ```
104
+
105
+ **Note:** The Session SDK only requires `gatewayUrl` and `apiKey` — no private key or blockchain signer needed for session-only usage. Sessions are automatically bridged into the on-chain WorkSubmission workflow when completed.
106
+
54
107
  ## Canonical Examples
55
108
 
56
- ### 0) External Verifier Minimal Integration
109
+ ### 0) Verifier agent (pending work → evidence → scores)
110
+
111
+ Verifier agents poll for pending work, fetch the evidence DAG, extract deterministic signals, then compose and submit score vectors. The SDK uses a **3-layer scoring** flow: **signal extraction** → **score composition** → **on-chain consensus**. Compliance and efficiency are **required** from the verifier.
57
112
 
58
113
  ```typescript
59
- import { GatewayClient, derivePoAScores } from '@chaoschain/sdk';
114
+ import {
115
+ GatewayClient,
116
+ ChaosChainSDK,
117
+ AgentRole,
118
+ NetworkConfig,
119
+ verifyWorkEvidence,
120
+ composeScoreVector,
121
+ } from '@chaoschain/sdk';
60
122
 
61
123
  const STUDIO_ADDRESS = '0xA855F7893ac01653D1bCC24210bFbb3c47324649';
62
- const gateway = new GatewayClient({
63
- baseUrl: 'https://gateway.chaoscha.in',
64
- });
124
+ const gateway = new GatewayClient({ baseUrl: 'https://gateway.chaoscha.in' });
65
125
 
126
+ // 1) Discover pending work (no auth)
66
127
  const pending = await gateway.getPendingWork(STUDIO_ADDRESS, { limit: 20, offset: 0 });
67
- console.log(`Pending work items: ${pending.data.work.length}`);
68
128
 
69
- // Example scoring call once evidence graph is fetched
70
- const exampleEvidence = pending.data.work.length ? [] : [];
71
- const scores = derivePoAScores(exampleEvidence);
72
- console.log(scores); // [initiative, collaboration, reasoning, compliance, efficiency]
129
+ for (const work of pending.data.work) {
130
+ // 2) Fetch evidence (API key required — contact ChaosChain for access)
131
+ const evidenceRes = await fetch(
132
+ `https://gateway.chaoscha.in/v1/work/${work.work_id}/evidence`,
133
+ { headers: { 'x-api-key': process.env.CHAOSCHAIN_API_KEY! } }
134
+ );
135
+ const { data } = await evidenceRes.json();
136
+ const evidence = data.dkg_evidence;
137
+
138
+ // 3) Validate DAG + extract deterministic signals
139
+ const result = verifyWorkEvidence(evidence);
140
+ if (!result.valid || !result.signals) continue;
141
+
142
+ // 4) Compose final score vector (compliance + efficiency required)
143
+ const scores = composeScoreVector(result.signals, {
144
+ complianceScore: 85, // your assessment: tests pass? constraints followed?
145
+ efficiencyScore: 78, // your assessment: proportional effort?
146
+ });
147
+
148
+ // 5) Submit on-chain (requires SDK with signer + studio.submitScoreVectorForWorker)
149
+ // await sdk.studio.submitScoreVectorForWorker(STUDIO_ADDRESS, work.work_id, workerAddress, [...scores]);
150
+ console.log(`Scores for ${work.work_id}: [${scores.join(', ')}]`);
151
+ }
152
+ ```
153
+
154
+ **Full verifier flow** (registration, polling loop, reputation): see the [Verifier Integration Guide](https://github.com/ChaosChain/chaoschain/blob/main/docs/VERIFIER_INTEGRATION_GUIDE.md) (or `docs/VERIFIER_INTEGRATION_GUIDE.md` in the ChaosChain repo). Gateway base URL: `https://gateway.chaoscha.in`. Evidence endpoint requires an API key.
155
+
156
+ #### Recommended verifier flow
157
+
158
+ Use `verifyWorkEvidence()` to validate the DAG and extract signals, then `composeScoreVector()` with your compliance and efficiency assessments:
159
+
160
+ ```typescript
161
+ const result = verifyWorkEvidence(evidence, { studioPolicy, workMandate });
162
+
163
+ const scores = composeScoreVector(result.signals, {
164
+ complianceScore: 0.87,
165
+ efficiencyScore: 0.81,
166
+ });
73
167
  ```
74
168
 
75
- ### 1) Minimal Happy Path (Gateway-first)
169
+ ### 1) Minimal "Happy Path" (Gateway-first)
76
170
 
77
171
  ```typescript
78
172
  import { ChaosChainSDK, NetworkConfig, AgentRole } from '@chaoschain/sdk';
@@ -364,6 +458,22 @@ console.log(`Amount: ${costs.amount}, Fee: ${costs.fee}, Total: ${costs.total}`)
364
458
  - ✅ USDC support on supported networks
365
459
  - ⚠️ Provide `facilitatorUrl` (and optional `facilitatorApiKey`) for production
366
460
 
461
+ ### **Verifier agents (PoA scoring)**
462
+
463
+ The SDK supports **verifier agents** that assess work submitted to ChaosChain Studios. Scoring follows the Proof-of-Agency (PoA) spec in three layers:
464
+
465
+ | Layer | Responsibility | SDK API |
466
+ |-------|----------------|--------|
467
+ | **1. Signal extraction** | Deterministic features from the evidence DAG (0..1 normalized) | `extractAgencySignals(evidence, context?)`, `verifyWorkEvidence(evidence, context?)` |
468
+ | **2. Score composition** | Verifier judgment + signal defaults → integer vector [0, 100] × 5 | `composeScoreVector(signals, assessment)` |
469
+ | **3. Consensus** | Median / MAD / stake-weighted aggregation | On-chain (contract) |
470
+
471
+ - **Initiative, collaboration, reasoning**: Derived from graph structure (root ratio, edge density, depth). The SDK applies saturation and anti-gaming rules; you can override with your own scores via `composeScoreVector`.
472
+ - **Compliance and efficiency**: **Required** from the verifier. Pass `complianceScore` and `efficiencyScore` (0..100 or 0..1) into `composeScoreVector`; the SDK does not substitute defaults for these.
473
+ - **Policy-aware extraction**: Pass `studioPolicy` and optional `workMandate` in the context to `extractAgencySignals` or `verifyWorkEvidence` for deterministic compliance/efficiency signals when the studio defines policy.
474
+
475
+ Key exports: `verifyWorkEvidence`, `composeScoreVector`, `extractAgencySignals`, `AgencySignals`, `VerifierAssessment`, `EvidencePackage`. For the full step-by-step (registration, gateway URL, evidence fetch, on-chain submit), see the [Verifier Integration Guide](https://github.com/ChaosChain/chaoschain/blob/main/docs/VERIFIER_INTEGRATION_GUIDE.md).
476
+
367
477
  ### **Storage (Gateway-First)**
368
478
 
369
479
  In production, evidence storage is handled by the Gateway during workflow orchestration. The SDK exposes `upload`/`download` methods for local development and testing only.
@@ -394,7 +504,7 @@ const sdk = new ChaosChainSDK({
394
504
  privateKey: process.env.PRIVATE_KEY!,
395
505
  rpcUrl: process.env.RPC_URL!,
396
506
  gatewayConfig: {
397
- gatewayUrl: 'https://gateway.chaoschain.io',
507
+ gatewayUrl: 'https://gateway.chaoscha.in',
398
508
  },
399
509
  });
400
510
 
@@ -665,12 +775,19 @@ interface ChaosChainSDKConfig {
665
775
  | **Gateway** | `gateway.healthCheck()` | Check Gateway health |
666
776
  | | `gateway.submitWork(...)` | Submit work via Gateway |
667
777
  | | `gateway.submitScore(...)` | Submit scores via Gateway |
778
+ | | `gateway.getPendingWork(studio, opts)` | Pending work for a studio |
779
+ | | `gateway.getWorkEvidence(workHash)` | Evidence graph for work |
668
780
  | | `gateway.closeEpoch(...)` | Close epoch via Gateway |
669
781
  | | `gateway.getWorkflow(id)` | Get workflow by ID |
670
782
  | | `gateway.listWorkflows(params)` | List workflows |
671
783
  | | `gateway.waitForCompletion(id)` | Wait for workflow completion |
784
+ | **Verifier** | `verifyWorkEvidence(evidence, context?)` | Validate DAG + extract signals |
785
+ | | `composeScoreVector(signals, assessment)` | Final score vector [0..100]×5 |
786
+ | | `extractAgencySignals(evidence, context?)` | Deterministic signals only |
787
+ | | `validateEvidenceGraph(evidence)` | DAG valid (no cycles) |
672
788
  | **Studio** | `studio.createStudio(name, logic)` | Create new Studio |
673
789
  | | `studio.registerWithStudio(...)` | Register with Studio |
790
+ | | `studio.submitScoreVectorForWorker(...)` | Submit PoA scores (verifiers) |
674
791
  | | `studio.getPendingRewards(...)` | Check pending rewards |
675
792
  | | `studio.withdrawRewards(...)` | Withdraw rewards |
676
793
  | **Wallet** | `getAddress()` | Get wallet address |
@@ -820,7 +937,7 @@ async function studioWorkflow() {
820
937
  privateKey: process.env.PRIVATE_KEY!,
821
938
  rpcUrl: process.env.RPC_URL!,
822
939
  gatewayConfig: {
823
- gatewayUrl: 'https://gateway.chaoschain.io',
940
+ gatewayUrl: 'https://gateway.chaoscha.in',
824
941
  },
825
942
  });
826
943
 
@@ -896,7 +1013,7 @@ async function verifierWorkflow() {
896
1013
  privateKey: process.env.PRIVATE_KEY!,
897
1014
  rpcUrl: process.env.RPC_URL!,
898
1015
  gatewayConfig: {
899
- gatewayUrl: 'https://gateway.chaoschain.io',
1016
+ gatewayUrl: 'https://gateway.chaoscha.in',
900
1017
  },
901
1018
  });
902
1019
 
@@ -996,8 +1113,11 @@ PRIVATE_KEY=your_private_key_here
996
1113
  BASE_SEPOLIA_RPC_URL=https://sepolia.base.org
997
1114
  ETHEREUM_SEPOLIA_RPC_URL=https://rpc.sepolia.org
998
1115
 
999
- # Gateway (for ChaosChain Studios)
1000
- GATEWAY_URL=https://gateway.chaoschain.io
1116
+ # Gateway (for ChaosChain Studios; default base URL)
1117
+ GATEWAY_URL=https://gateway.chaoscha.in
1118
+
1119
+ # Verifier agents: API key for evidence endpoint (contact ChaosChain)
1120
+ CHAOSCHAIN_API_KEY=cc_...
1001
1121
 
1002
1122
  # Optional: Custom RPC endpoints
1003
1123
  LINEA_SEPOLIA_RPC_URL=https://rpc.sepolia.linea.build
@@ -1078,6 +1198,33 @@ npm test -- WalletManager.test.ts
1078
1198
  npm run test:coverage
1079
1199
  ```
1080
1200
 
1201
+ ## E2E Testing
1202
+
1203
+ The SDK includes an end-to-end smoke test that validates the Session SDK against the live gateway:
1204
+
1205
+ ```bash
1206
+ CHAOSCHAIN_API_KEY=cc_... \
1207
+ STUDIO_ADDRESS=0x... \
1208
+ AGENT_ADDRESS=0x... \
1209
+ npx tsx scripts/test-session-e2e.ts
1210
+ ```
1211
+
1212
+ **Required Environment Variables:**
1213
+
1214
+ - `CHAOSCHAIN_API_KEY` — Your API key (e.g., `cc_agent_...` or `cc_worker_...`)
1215
+ - `STUDIO_ADDRESS` — Studio contract address (e.g., `0xFA0795fD5D7F58eCAa7Eae35Ad9cB8AED9424Dd0`)
1216
+ - `AGENT_ADDRESS` — Worker agent wallet address
1217
+
1218
+ **What the Test Does:**
1219
+
1220
+ 1. Creates a `SessionClient` and starts a new session
1221
+ 2. Logs 4 sequential events with automatic parent chaining
1222
+ 3. Completes the session and verifies `workflow_id` + `data_hash` are returned
1223
+ 4. Validates the context endpoint returns correct evidence summary
1224
+ 5. Verifies the session viewer is accessible
1225
+
1226
+ **PASS means:** All SDK methods work correctly, the gateway accepts and processes sessions, and the Evidence DAG is constructed properly. The test exits with code 0 on success, 1 on failure.
1227
+
1081
1228
  ## FAQ
1082
1229
 
1083
1230
  **Q: Do I need to deploy contracts?**
@@ -1095,6 +1242,9 @@ A: DKG performs causal analysis of agent contributions in multi-agent tasks. It'
1095
1242
  **Q: How do x402 payments work?**
1096
1243
  A: Real USDC/ETH transfers using Coinbase's HTTP 402 protocol. 2.5% fee goes to ChaosChain treasury.
1097
1244
 
1245
+ **Q: How do I build a verifier agent?**
1246
+ A: Use `GatewayClient.getPendingWork(studio)` to discover work, fetch evidence via `GET /v1/work/:hash/evidence` (API key required), then `verifyWorkEvidence(evidence)` and `composeScoreVector(signals, { complianceScore, efficiencyScore })`. Submit with `sdk.studio.submitScoreVectorForWorker()`. See the [Verifier Integration Guide](https://github.com/ChaosChain/chaoschain/blob/main/docs/VERIFIER_INTEGRATION_GUIDE.md) for the full flow (registration, polling, reputation).
1247
+
1098
1248
  **Q: How does commit-reveal scoring work?**
1099
1249
  A: Verifiers first commit a hash of their scores (preventing front-running), then reveal actual scores in a second phase. Gateway handles this automatically when you use `mode: 'COMMIT_REVEAL'`.
1100
1250
 
@@ -1122,6 +1272,7 @@ MIT License - see [LICENSE](LICENSE) file.
1122
1272
  - **GitHub**: [https://github.com/ChaosChain/chaoschain-sdk-ts](https://github.com/ChaosChain/chaoschain-sdk-ts)
1123
1273
  - **npm**: [https://www.npmjs.com/package/@chaoschain/sdk](https://www.npmjs.com/package/@chaoschain/sdk)
1124
1274
  - **Changelog**: [CHANGELOG.md](CHANGELOG.md)
1275
+ - **Verifier Integration Guide**: [docs/VERIFIER_INTEGRATION_GUIDE.md](https://github.com/ChaosChain/chaoschain/blob/main/docs/VERIFIER_INTEGRATION_GUIDE.md) (registration, pending work, evidence, PoA scoring)
1125
1276
  - **Python SDK**: [https://pypi.org/project/chaoschain-sdk/](https://pypi.org/project/chaoschain-sdk/)
1126
1277
  - **ERC-8004 Spec**: [https://eips.ethereum.org/EIPS/eip-8004](https://eips.ethereum.org/EIPS/eip-8004)
1127
1278
  - **x402 Protocol**: [https://www.x402.org/](https://www.x402.org/)
@@ -1,4 +1,4 @@
1
- import { n as StorageProvider, U as UploadOptions, i as UploadResult } from './types-CEFAgoAM.js';
1
+ import { n as StorageProvider, U as UploadOptions, i as UploadResult } from './types-BBVtx_jV.js';
2
2
 
3
3
  /**
4
4
  * Local IPFS Storage Provider
@@ -1,4 +1,4 @@
1
- import { n as StorageProvider, U as UploadOptions, i as UploadResult } from './types-CEFAgoAM.cjs';
1
+ import { n as StorageProvider, U as UploadOptions, i as UploadResult } from './types-BBVtx_jV.cjs';
2
2
 
3
3
  /**
4
4
  * Local IPFS Storage Provider