@chaoschain/sdk 0.2.4 → 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/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,186 @@ 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: { agent_address: this.agentAddress, role: "worker" },
15418
+ studio: {
15419
+ studio_address: this.studioAddress,
15420
+ studio_policy_version: this.studioPolicyVersion
15421
+ },
15422
+ task: {
15423
+ work_mandate_id: this.workMandateId,
15424
+ task_type: this.taskType
15425
+ },
15426
+ ...opts.metadata ? { metadata: opts.metadata } : {}
15427
+ };
15428
+ await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);
15429
+ this.lastEventId = eventId;
15430
+ }
15431
+ /**
15432
+ * Convenience wrapper around {@link log} that maps human-friendly step names
15433
+ * to canonical event types.
15434
+ *
15435
+ * Mappings:
15436
+ * - `"planning"` → `plan_created`
15437
+ * - `"testing"` → `test_run`
15438
+ * - `"debugging"` → `debug_step`
15439
+ * - `"implementing"` → `file_written`
15440
+ * - `"completing"` → `submission_created`
15441
+ *
15442
+ * Unknown step types fall back to `artifact_created`.
15443
+ *
15444
+ * @param stepType - Friendly step name.
15445
+ * @param summary - What happened in this step.
15446
+ */
15447
+ async step(stepType, summary) {
15448
+ const eventType = STEP_TYPE_MAP[stepType] ?? "artifact_created";
15449
+ await this.log({ event_type: eventType, summary });
15450
+ }
15451
+ /**
15452
+ * Complete the session.
15453
+ *
15454
+ * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
15455
+ * and returns `workflow_id` + `data_hash` for downstream verification/scoring.
15456
+ *
15457
+ * @param opts - Optional status (`"completed"` | `"failed"`) and summary.
15458
+ * @returns `{ workflow_id, data_hash }` — both may be `null` if the gateway
15459
+ * workflow engine is not configured.
15460
+ * @throws Error if the gateway returns a non-2xx status.
15461
+ */
15462
+ async complete(opts) {
15463
+ const body = {};
15464
+ if (opts?.status) body.status = opts.status;
15465
+ if (opts?.summary) body.summary = opts.summary;
15466
+ const data = await this.post(`/v1/sessions/${this.sessionId}/complete`, body);
15467
+ return {
15468
+ workflow_id: data.data?.workflow_id ?? null,
15469
+ data_hash: data.data?.data_hash ?? null
15470
+ };
15471
+ }
15472
+ // ---------------------------------------------------------------------------
15473
+ // Internal HTTP helper
15474
+ // ---------------------------------------------------------------------------
15475
+ async post(path4, body) {
15476
+ const url = `${this.gatewayUrl}${path4}`;
15477
+ const headers = { "Content-Type": "application/json" };
15478
+ if (this.apiKey) headers["X-API-Key"] = this.apiKey;
15479
+ try {
15480
+ const res = await axios2({ method: "POST", url, data: body, headers, timeout: 3e4 });
15481
+ return res.data;
15482
+ } catch (err) {
15483
+ const axiosErr = err;
15484
+ const status = axiosErr.response?.status ?? 0;
15485
+ const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);
15486
+ throw new Error(`Session request failed: POST ${path4} \u2192 ${status} ${detail}`);
15487
+ }
15488
+ }
15489
+ };
15490
+
15491
+ // src/session/SessionClient.ts
15492
+ var SessionClient = class {
15493
+ gatewayUrl;
15494
+ apiKey;
15495
+ constructor(config = {}) {
15496
+ this.gatewayUrl = (config.gatewayUrl ?? "https://gateway.chaoscha.in").replace(/\/$/, "");
15497
+ this.apiKey = config.apiKey;
15498
+ }
15499
+ /**
15500
+ * Create a new coding session on the gateway.
15501
+ *
15502
+ * Returns a {@link Session} instance that can be used to log events, run steps,
15503
+ * and complete the session. The gateway persists all events and constructs the
15504
+ * Evidence DAG automatically.
15505
+ *
15506
+ * @param opts - Session creation parameters.
15507
+ * @returns A live {@link Session} bound to the newly created session ID.
15508
+ * @throws Error if the gateway returns a non-2xx status.
15509
+ */
15510
+ async start(opts) {
15511
+ const body = {
15512
+ studio_address: opts.studio_address,
15513
+ agent_address: opts.agent_address
15514
+ };
15515
+ if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;
15516
+ if (opts.task_type) body.task_type = opts.task_type;
15517
+ if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;
15518
+ if (opts.session_id) body.session_id = opts.session_id;
15519
+ const url = `${this.gatewayUrl}/v1/sessions`;
15520
+ const headers = { "Content-Type": "application/json" };
15521
+ if (this.apiKey) headers["X-API-Key"] = this.apiKey;
15522
+ let data;
15523
+ try {
15524
+ const res = await axios2({ method: "POST", url, data: body, headers, timeout: 3e4 });
15525
+ data = res.data;
15526
+ } catch (err) {
15527
+ const axiosErr = err;
15528
+ const status = axiosErr.response?.status ?? 0;
15529
+ const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);
15530
+ throw new Error(`Failed to create session: POST /v1/sessions \u2192 ${status} ${detail}`);
15531
+ }
15532
+ const sessionId = data.data?.session_id;
15533
+ if (!sessionId) {
15534
+ throw new Error("Gateway response missing session_id");
15535
+ }
15536
+ return new Session({
15537
+ sessionId,
15538
+ gatewayUrl: this.gatewayUrl,
15539
+ apiKey: this.apiKey,
15540
+ studioAddress: opts.studio_address,
15541
+ agentAddress: opts.agent_address,
15542
+ studioPolicyVersion: opts.studio_policy_version ?? "engineering-studio-default-v1",
15543
+ workMandateId: opts.work_mandate_id ?? "generic-task",
15544
+ taskType: opts.task_type ?? "general"
15545
+ });
15546
+ }
15547
+ };
15368
15548
 
15369
15549
  // src/ChaosChainSDK.ts
15370
15550
  var ChaosChainSDK = class _ChaosChainSDK {
@@ -15382,8 +15562,10 @@ var ChaosChainSDK = class _ChaosChainSDK {
15382
15562
  a2aX402Extension;
15383
15563
  processIntegrity;
15384
15564
  mandateManager;
15385
- // Gateway client for workflow submission (optional)
15386
- gateway = null;
15565
+ // Gateway client for workflow submission (always initialized)
15566
+ gateway;
15567
+ /** Session client for Engineering Studio session management. */
15568
+ session;
15387
15569
  // Studio client for direct on-chain operations
15388
15570
  studio;
15389
15571
  // Configuration
@@ -15548,7 +15730,10 @@ var ChaosChainSDK = class _ChaosChainSDK {
15548
15730
  const gatewayConfig = config.gatewayConfig ?? (config.gatewayUrl ? { gatewayUrl: config.gatewayUrl } : {});
15549
15731
  this.gateway = new GatewayClient(gatewayConfig);
15550
15732
  const gatewayBaseUrl = gatewayConfig.baseUrl ?? gatewayConfig.gatewayUrl ?? "https://gateway.chaoscha.in";
15551
- console.log(`\u{1F310} Gateway client initialized: ${gatewayBaseUrl}`);
15733
+ this.session = new SessionClient({
15734
+ gatewayUrl: gatewayBaseUrl,
15735
+ apiKey: gatewayConfig.auth?.apiKey
15736
+ });
15552
15737
  this.studio = new StudioClient({
15553
15738
  provider: this.provider,
15554
15739
  signer: this.walletManager.getWallet(),
@@ -15561,16 +15746,6 @@ var ChaosChainSDK = class _ChaosChainSDK {
15561
15746
  );
15562
15747
  _ChaosChainSDK.warnedStudioClientProduction = true;
15563
15748
  }
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
15749
  }
15575
15750
  // ============================================================================
15576
15751
  // ERC-8004 Identity Methods
@@ -15979,7 +16154,7 @@ var ChaosChainSDK = class _ChaosChainSDK {
15979
16154
  * Get SDK version
15980
16155
  */
15981
16156
  getVersion() {
15982
- return "0.2.4";
16157
+ return "0.3.0";
15983
16158
  }
15984
16159
  /**
15985
16160
  * Get SDK capabilities summary
@@ -16009,9 +16184,11 @@ var ChaosChainSDK = class _ChaosChainSDK {
16009
16184
  }
16010
16185
  /**
16011
16186
  * Check if Gateway is configured.
16187
+ * Always returns true in v0.3.0+. Gateway is always initialized pointing to
16188
+ * https://gateway.chaoscha.in unless overridden via gatewayConfig.
16012
16189
  */
16013
16190
  isGatewayEnabled() {
16014
- return this.gateway !== null;
16191
+ return true;
16015
16192
  }
16016
16193
  /**
16017
16194
  * Get Gateway client instance.
@@ -16775,7 +16952,7 @@ function verifyWorkEvidence(evidence, context) {
16775
16952
  }
16776
16953
 
16777
16954
  // src/index.ts
16778
- var SDK_VERSION = "0.2.4";
16955
+ var SDK_VERSION = "0.3.0";
16779
16956
  var ERC8004_VERSION = "1.0";
16780
16957
  var X402_VERSION = "1.0";
16781
16958
  var src_default = ChaosChainSDK;
@@ -16801,6 +16978,6 @@ mime-types/index.js:
16801
16978
  *)
16802
16979
  */
16803
16980
 
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 };
16981
+ 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
16982
  //# sourceMappingURL=index.js.map
16806
16983
  //# sourceMappingURL=index.js.map