@chaoschain/sdk 0.2.4 → 0.3.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/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import fs3__default from 'fs';
4
4
  import * as path3 from 'path';
5
5
  import path3__default from 'path';
6
6
  import * as crypto2 from 'crypto';
7
- import { createHash } from 'crypto';
7
+ import { randomUUID, createHash } from 'crypto';
8
8
  import axios2 from 'axios';
9
9
  import * as http from 'http';
10
10
  import * as jose from 'jose';
@@ -15365,6 +15365,189 @@ var StudioClient = class {
15365
15365
  return ethers.hexlify(ethers.randomBytes(32));
15366
15366
  }
15367
15367
  };
15368
+ var STEP_TYPE_MAP = {
15369
+ planning: "plan_created",
15370
+ testing: "test_run",
15371
+ debugging: "debug_step",
15372
+ implementing: "file_written",
15373
+ completing: "submission_created"
15374
+ };
15375
+ var Session = class {
15376
+ /** Session ID returned by the gateway. */
15377
+ sessionId;
15378
+ gatewayUrl;
15379
+ apiKey;
15380
+ studioAddress;
15381
+ agentAddress;
15382
+ studioPolicyVersion;
15383
+ workMandateId;
15384
+ taskType;
15385
+ lastEventId;
15386
+ /** @internal — use {@link SessionClient.start} to create instances. */
15387
+ constructor(opts) {
15388
+ this.sessionId = opts.sessionId;
15389
+ this.gatewayUrl = opts.gatewayUrl;
15390
+ this.apiKey = opts.apiKey;
15391
+ this.lastEventId = opts.lastEventId ?? null;
15392
+ this.studioAddress = opts.studioAddress;
15393
+ this.agentAddress = opts.agentAddress;
15394
+ this.studioPolicyVersion = opts.studioPolicyVersion;
15395
+ this.workMandateId = opts.workMandateId;
15396
+ this.taskType = opts.taskType;
15397
+ }
15398
+ /**
15399
+ * Log a session event.
15400
+ *
15401
+ * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`
15402
+ * from the previous event so the gateway can build a causal DAG.
15403
+ *
15404
+ * @param opts - Event details. Only `summary` is required.
15405
+ * @throws Error if the gateway returns a non-2xx status.
15406
+ */
15407
+ async log(opts) {
15408
+ const eventId = randomUUID();
15409
+ const event = {
15410
+ event_id: eventId,
15411
+ event_type: opts.event_type ?? "artifact_created",
15412
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
15413
+ summary: opts.summary,
15414
+ causality: {
15415
+ parent_event_ids: this.lastEventId ? [this.lastEventId] : []
15416
+ },
15417
+ agent: {
15418
+ agent_address: opts.agent?.agent_address ?? this.agentAddress,
15419
+ role: opts.agent?.role ?? "worker"
15420
+ },
15421
+ studio: {
15422
+ studio_address: this.studioAddress,
15423
+ studio_policy_version: this.studioPolicyVersion
15424
+ },
15425
+ task: {
15426
+ work_mandate_id: this.workMandateId,
15427
+ task_type: this.taskType
15428
+ },
15429
+ ...opts.metadata ? { metadata: opts.metadata } : {}
15430
+ };
15431
+ await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);
15432
+ this.lastEventId = eventId;
15433
+ }
15434
+ /**
15435
+ * Convenience wrapper around {@link log} that maps human-friendly step names
15436
+ * to canonical event types.
15437
+ *
15438
+ * Mappings:
15439
+ * - `"planning"` → `plan_created`
15440
+ * - `"testing"` → `test_run`
15441
+ * - `"debugging"` → `debug_step`
15442
+ * - `"implementing"` → `file_written`
15443
+ * - `"completing"` → `submission_created`
15444
+ *
15445
+ * Unknown step types fall back to `artifact_created`.
15446
+ *
15447
+ * @param stepType - Friendly step name.
15448
+ * @param summary - What happened in this step.
15449
+ */
15450
+ async step(stepType, summary, agent) {
15451
+ const eventType = STEP_TYPE_MAP[stepType] ?? "artifact_created";
15452
+ await this.log({ event_type: eventType, summary, agent });
15453
+ }
15454
+ /**
15455
+ * Complete the session.
15456
+ *
15457
+ * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
15458
+ * and returns `workflow_id` + `data_hash` for downstream verification/scoring.
15459
+ *
15460
+ * @param opts - Optional status (`"completed"` | `"failed"`) and summary.
15461
+ * @returns `{ workflow_id, data_hash }` — both may be `null` if the gateway
15462
+ * workflow engine is not configured.
15463
+ * @throws Error if the gateway returns a non-2xx status.
15464
+ */
15465
+ async complete(opts) {
15466
+ const body = {};
15467
+ if (opts?.status) body.status = opts.status;
15468
+ if (opts?.summary) body.summary = opts.summary;
15469
+ const data = await this.post(`/v1/sessions/${this.sessionId}/complete`, body);
15470
+ return {
15471
+ workflow_id: data.data?.workflow_id ?? null,
15472
+ data_hash: data.data?.data_hash ?? null
15473
+ };
15474
+ }
15475
+ // ---------------------------------------------------------------------------
15476
+ // Internal HTTP helper
15477
+ // ---------------------------------------------------------------------------
15478
+ async post(path4, body) {
15479
+ const url = `${this.gatewayUrl}${path4}`;
15480
+ const headers = { "Content-Type": "application/json" };
15481
+ if (this.apiKey) headers["X-API-Key"] = this.apiKey;
15482
+ try {
15483
+ const res = await axios2({ method: "POST", url, data: body, headers, timeout: 3e4 });
15484
+ return res.data;
15485
+ } catch (err) {
15486
+ const axiosErr = err;
15487
+ const status = axiosErr.response?.status ?? 0;
15488
+ const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);
15489
+ throw new Error(`Session request failed: POST ${path4} \u2192 ${status} ${detail}`);
15490
+ }
15491
+ }
15492
+ };
15493
+
15494
+ // src/session/SessionClient.ts
15495
+ var SessionClient = class {
15496
+ gatewayUrl;
15497
+ apiKey;
15498
+ constructor(config = {}) {
15499
+ this.gatewayUrl = (config.gatewayUrl ?? "https://gateway.chaoscha.in").replace(/\/$/, "");
15500
+ this.apiKey = config.apiKey;
15501
+ }
15502
+ /**
15503
+ * Create a new coding session on the gateway.
15504
+ *
15505
+ * Returns a {@link Session} instance that can be used to log events, run steps,
15506
+ * and complete the session. The gateway persists all events and constructs the
15507
+ * Evidence DAG automatically.
15508
+ *
15509
+ * @param opts - Session creation parameters.
15510
+ * @returns A live {@link Session} bound to the newly created session ID.
15511
+ * @throws Error if the gateway returns a non-2xx status.
15512
+ */
15513
+ async start(opts) {
15514
+ const body = {
15515
+ studio_address: opts.studio_address,
15516
+ agent_address: opts.agent_address
15517
+ };
15518
+ if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;
15519
+ if (opts.task_type) body.task_type = opts.task_type;
15520
+ if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;
15521
+ if (opts.session_id) body.session_id = opts.session_id;
15522
+ const url = `${this.gatewayUrl}/v1/sessions`;
15523
+ const headers = { "Content-Type": "application/json" };
15524
+ if (this.apiKey) headers["X-API-Key"] = this.apiKey;
15525
+ let data;
15526
+ try {
15527
+ const res = await axios2({ method: "POST", url, data: body, headers, timeout: 3e4 });
15528
+ data = res.data;
15529
+ } catch (err) {
15530
+ const axiosErr = err;
15531
+ const status = axiosErr.response?.status ?? 0;
15532
+ const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);
15533
+ throw new Error(`Failed to create session: POST /v1/sessions \u2192 ${status} ${detail}`);
15534
+ }
15535
+ const sessionId = data.data?.session_id;
15536
+ if (!sessionId) {
15537
+ throw new Error("Gateway response missing session_id");
15538
+ }
15539
+ return new Session({
15540
+ sessionId,
15541
+ gatewayUrl: this.gatewayUrl,
15542
+ apiKey: this.apiKey,
15543
+ studioAddress: opts.studio_address,
15544
+ agentAddress: opts.agent_address,
15545
+ studioPolicyVersion: opts.studio_policy_version ?? "engineering-studio-default-v1",
15546
+ workMandateId: opts.work_mandate_id ?? "generic-task",
15547
+ taskType: opts.task_type ?? "general"
15548
+ });
15549
+ }
15550
+ };
15368
15551
 
15369
15552
  // src/ChaosChainSDK.ts
15370
15553
  var ChaosChainSDK = class _ChaosChainSDK {
@@ -15382,8 +15565,10 @@ var ChaosChainSDK = class _ChaosChainSDK {
15382
15565
  a2aX402Extension;
15383
15566
  processIntegrity;
15384
15567
  mandateManager;
15385
- // Gateway client for workflow submission (optional)
15386
- gateway = null;
15568
+ // Gateway client for workflow submission (always initialized)
15569
+ gateway;
15570
+ /** Session client for Engineering Studio session management. */
15571
+ session;
15387
15572
  // Studio client for direct on-chain operations
15388
15573
  studio;
15389
15574
  // Configuration
@@ -15548,7 +15733,10 @@ var ChaosChainSDK = class _ChaosChainSDK {
15548
15733
  const gatewayConfig = config.gatewayConfig ?? (config.gatewayUrl ? { gatewayUrl: config.gatewayUrl } : {});
15549
15734
  this.gateway = new GatewayClient(gatewayConfig);
15550
15735
  const gatewayBaseUrl = gatewayConfig.baseUrl ?? gatewayConfig.gatewayUrl ?? "https://gateway.chaoscha.in";
15551
- console.log(`\u{1F310} Gateway client initialized: ${gatewayBaseUrl}`);
15736
+ this.session = new SessionClient({
15737
+ gatewayUrl: gatewayBaseUrl,
15738
+ apiKey: gatewayConfig.auth?.apiKey
15739
+ });
15552
15740
  this.studio = new StudioClient({
15553
15741
  provider: this.provider,
15554
15742
  signer: this.walletManager.getWallet(),
@@ -15561,16 +15749,6 @@ var ChaosChainSDK = class _ChaosChainSDK {
15561
15749
  );
15562
15750
  _ChaosChainSDK.warnedStudioClientProduction = true;
15563
15751
  }
15564
- console.log(`\u{1F680} ChaosChain SDK initialized for ${this.agentName}`);
15565
- console.log(` Network: ${this.network}`);
15566
- console.log(` Wallet: ${this.walletManager.getAddress()}`);
15567
- console.log(` Features:`);
15568
- console.log(` - ERC-8004: \u2705`);
15569
- console.log(` - x402 Payments: ${this.x402PaymentManager ? "\u2705" : "\u274C"}`);
15570
- console.log(` - Multi-Payment: ${this.paymentManager ? "\u2705" : "\u274C"}`);
15571
- console.log(` - Google AP2: ${this.googleAP2 ? "\u2705" : "\u274C"}`);
15572
- console.log(` - Process Integrity: ${this.processIntegrity ? "\u2705" : "\u274C"}`);
15573
- console.log(` - Storage: \u2705`);
15574
15752
  }
15575
15753
  // ============================================================================
15576
15754
  // ERC-8004 Identity Methods
@@ -15979,7 +16157,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
15979
16157
  * Get SDK version
15980
16158
  */
15981
16159
  getVersion() {
15982
- return "0.2.4";
16160
+ return "0.3.1";
15983
16161
  }
15984
16162
  /**
15985
16163
  * Get SDK capabilities summary
@@ -16009,9 +16187,11 @@ var ChaosChainSDK = class _ChaosChainSDK {
16009
16187
  }
16010
16188
  /**
16011
16189
  * Check if Gateway is configured.
16190
+ * Always returns true in v0.3.0+. Gateway is always initialized pointing to
16191
+ * https://gateway.chaoscha.in unless overridden via gatewayConfig.
16012
16192
  */
16013
16193
  isGatewayEnabled() {
16014
- return this.gateway !== null;
16194
+ return true;
16015
16195
  }
16016
16196
  /**
16017
16197
  * Get Gateway client instance.
@@ -16775,7 +16955,7 @@ function verifyWorkEvidence(evidence, context) {
16775
16955
  }
16776
16956
 
16777
16957
  // src/index.ts
16778
- var SDK_VERSION = "0.2.4";
16958
+ var SDK_VERSION = "0.3.1";
16779
16959
  var ERC8004_VERSION = "1.0";
16780
16960
  var X402_VERSION = "1.0";
16781
16961
  var src_default = ChaosChainSDK;
@@ -16801,6 +16981,6 @@ mime-types/index.js:
16801
16981
  *)
16802
16982
  */
16803
16983
 
16804
- export { A2AX402Extension, AgentRegistrationError, AgentRole, AutoStorageManager, CHAOS_CORE_ABI, ChaosAgent, ChaosChainSDK, ChaosChainSDKError, ConfigurationError, ContractError, ERC8004_VERSION, GatewayClient, GatewayConnectionError, GatewayError, GatewayTimeoutError, GoogleAP2Integration, IDENTITY_REGISTRY_ABI, IPFSLocalStorage, PinataStorage as IPFSPinataStorage, IntegrityVerificationError, IrysStorage, IrysStorage as IrysStorageProvider, LocalIPFSStorage, MandateManager, NetworkConfig, PaymentError, PaymentManager, PaymentMethod, PinataStorage, REPUTATION_REGISTRY_ABI, REWARDS_DISTRIBUTOR_ABI, ValidationError as SDKValidationError, SDK_VERSION, STUDIO_FACTORY_ABI, STUDIO_PROXY_ABI, StorageError, StudioClient, StudioManager, VALIDATION_REGISTRY_ABI, ValidationStatus, WalletManager, WorkflowFailedError, WorkflowState, WorkflowType, X402PaymentManager, X402Server, X402_VERSION, ZeroGStorage, composeScoreVector, composeScoreVectorWithDefaults, computeDepth, src_default as default, derivePoAScores, extractAgencySignals, getContractAddresses2 as getContractAddresses, getNetworkInfo, initChaosChainSDK, rangeFit, validateEvidenceGraph, verifyWorkEvidence };
16984
+ export { A2AX402Extension, AgentRegistrationError, AgentRole, AutoStorageManager, CHAOS_CORE_ABI, ChaosAgent, ChaosChainSDK, ChaosChainSDKError, ConfigurationError, ContractError, ERC8004_VERSION, GatewayClient, GatewayConnectionError, GatewayError, GatewayTimeoutError, GoogleAP2Integration, IDENTITY_REGISTRY_ABI, IPFSLocalStorage, PinataStorage as IPFSPinataStorage, IntegrityVerificationError, IrysStorage, IrysStorage as IrysStorageProvider, LocalIPFSStorage, MandateManager, NetworkConfig, PaymentError, PaymentManager, PaymentMethod, PinataStorage, REPUTATION_REGISTRY_ABI, REWARDS_DISTRIBUTOR_ABI, ValidationError as SDKValidationError, SDK_VERSION, STUDIO_FACTORY_ABI, STUDIO_PROXY_ABI, Session, SessionClient, StorageError, StudioClient, StudioManager, VALIDATION_REGISTRY_ABI, ValidationStatus, WalletManager, WorkflowFailedError, WorkflowState, WorkflowType, X402PaymentManager, X402Server, X402_VERSION, ZeroGStorage, composeScoreVector, composeScoreVectorWithDefaults, computeDepth, src_default as default, derivePoAScores, extractAgencySignals, getContractAddresses2 as getContractAddresses, getNetworkInfo, initChaosChainSDK, rangeFit, validateEvidenceGraph, verifyWorkEvidence };
16805
16985
  //# sourceMappingURL=index.js.map
16806
16986
  //# sourceMappingURL=index.js.map