@chaoschain/sdk 0.3.2 → 0.3.3

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.
@@ -18,10 +18,16 @@ var STEP_TYPE_MAP = {
18
18
  var Session = class {
19
19
  /** Session ID returned by the gateway. */
20
20
  sessionId;
21
- gatewayUrl;
22
- apiKey;
21
+ /** Epoch number returned by the gateway. */
22
+ epoch;
23
+ /** Studio contract address for this session. */
23
24
  studioAddress;
25
+ /** Default agent wallet address for this session. */
24
26
  agentAddress;
27
+ /** URL to view this session's Evidence DAG in the browser. */
28
+ viewerUrl;
29
+ gatewayUrl;
30
+ apiKey;
25
31
  studioPolicyVersion;
26
32
  workMandateId;
27
33
  taskType;
@@ -29,6 +35,8 @@ var Session = class {
29
35
  /** @internal — use {@link SessionClient.start} to create instances. */
30
36
  constructor(opts) {
31
37
  this.sessionId = opts.sessionId;
38
+ this.epoch = opts.epoch;
39
+ this.viewerUrl = `${opts.gatewayUrl}/v1/sessions/${opts.sessionId}/viewer`;
32
40
  this.gatewayUrl = opts.gatewayUrl;
33
41
  this.apiKey = opts.apiKey;
34
42
  this.lastEventId = opts.lastEventId ?? null;
@@ -44,7 +52,12 @@ var Session = class {
44
52
  * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`
45
53
  * from the previous event so the gateway can build a causal DAG.
46
54
  *
47
- * @param opts - Event details. Only `summary` is required.
55
+ * @param opts.summary - Human-readable description of what happened (required).
56
+ * @param opts.event_type - Canonical event type (default: `"artifact_created"`).
57
+ * @param opts.metadata - Arbitrary key-value metadata attached to the event.
58
+ * @param opts.agent - Override the session-level agent for this event.
59
+ * Pass `{ agent_address, role? }` to emit the event from a different agent.
60
+ * Valid roles: `"worker"`, `"verifier"`, `"collaborator"`. Defaults to `"worker"`.
48
61
  * @throws Error if the gateway returns a non-2xx status.
49
62
  */
50
63
  async log(opts) {
@@ -87,8 +100,9 @@ var Session = class {
87
100
  *
88
101
  * Unknown step types fall back to `artifact_created`.
89
102
  *
90
- * @param stepType - Friendly step name.
103
+ * @param stepType - Friendly step name (`"planning"`, `"implementing"`, `"testing"`, `"debugging"`, `"completing"`).
91
104
  * @param summary - What happened in this step.
105
+ * @param agent - Optional agent override for this event. Same as `log({ agent })`.
92
106
  */
93
107
  async step(stepType, summary, agent) {
94
108
  const eventType = STEP_TYPE_MAP[stepType] ?? "artifact_created";
@@ -98,11 +112,13 @@ var Session = class {
98
112
  * Complete the session.
99
113
  *
100
114
  * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
101
- * and returns `workflow_id` + `data_hash` for downstream verification/scoring.
115
+ * and returns the session result.
102
116
  *
103
- * @param opts - Optional status (`"completed"` | `"failed"`) and summary.
104
- * @returns `{ workflow_id, data_hash }` both may be `null` if the gateway
105
- * workflow engine is not configured.
117
+ * @param opts.status - `"completed"` or `"failed"` (default: `"completed"`).
118
+ * @param opts.summary - Human-readable summary of the session outcome.
119
+ * @returns `{ workflow_id, data_hash, epoch }` — `workflow_id` and `data_hash`
120
+ * may be `null` if the gateway workflow engine is not configured.
121
+ * `epoch` is the epoch this session belongs to.
106
122
  * @throws Error if the gateway returns a non-2xx status.
107
123
  */
108
124
  async complete(opts) {
@@ -112,7 +128,8 @@ var Session = class {
112
128
  const data = await this.post(`/v1/sessions/${this.sessionId}/complete`, body);
113
129
  return {
114
130
  workflow_id: data.data?.workflow_id ?? null,
115
- data_hash: data.data?.data_hash ?? null
131
+ data_hash: data.data?.data_hash ?? null,
132
+ epoch: data.data.epoch
116
133
  };
117
134
  }
118
135
  // ---------------------------------------------------------------------------
@@ -147,8 +164,16 @@ var SessionClient = class {
147
164
  * and complete the session. The gateway persists all events and constructs the
148
165
  * Evidence DAG automatically.
149
166
  *
150
- * @param opts - Session creation parameters.
151
- * @returns A live {@link Session} bound to the newly created session ID.
167
+ * The returned session exposes `session.sessionId`, `session.epoch`,
168
+ * `session.studioAddress`, and `session.agentAddress`.
169
+ *
170
+ * @param opts.studio_address - Studio contract address (required).
171
+ * @param opts.agent_address - Worker agent wallet address (required).
172
+ * @param opts.task_type - Task classification: `"feature"`, `"bugfix"`, `"refactor"`, etc. (default: `"general"`).
173
+ * @param opts.work_mandate_id - Work mandate identifier (default: `"generic-task"`).
174
+ * @param opts.studio_policy_version - Studio policy version (default: `"engineering-studio-default-v1"`).
175
+ * @param opts.session_id - Client-provided session ID. Server generates one if omitted.
176
+ * @returns A live {@link Session} bound to the newly created session ID and epoch.
152
177
  * @throws Error if the gateway returns a non-2xx status.
153
178
  */
154
179
  async start(opts) {
@@ -185,7 +210,8 @@ var SessionClient = class {
185
210
  agentAddress: opts.agent_address,
186
211
  studioPolicyVersion: opts.studio_policy_version ?? "engineering-studio-default-v1",
187
212
  workMandateId: opts.work_mandate_id ?? "generic-task",
188
- taskType: opts.task_type ?? "general"
213
+ taskType: opts.task_type ?? "general",
214
+ epoch: data.data.epoch
189
215
  });
190
216
  }
191
217
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/session/Session.ts","../../src/session/SessionClient.ts"],"names":["randomUUID","axios"],"mappings":";;;;;;;;;;AAqDA,IAAM,aAAA,GAAwC;AAAA,EAC5C,QAAA,EAAU,cAAA;AAAA,EACV,OAAA,EAAS,UAAA;AAAA,EACT,SAAA,EAAW,YAAA;AAAA,EACX,YAAA,EAAc,cAAA;AAAA,EACd,UAAA,EAAY;AACd,CAAA;AAMO,IAAM,UAAN,MAAc;AAAA;AAAA,EAEH,SAAA;AAAA,EAEC,UAAA;AAAA,EACA,MAAA;AAAA,EACA,aAAA;AAAA,EACA,YAAA;AAAA,EACA,mBAAA;AAAA,EACA,aAAA;AAAA,EACA,QAAA;AAAA,EACT,WAAA;AAAA;AAAA,EAGR,YAAY,IAAA,EAUT;AACD,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AACvB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IA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AK,IAAA,EAAM,UAAA;AAC7B,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,IACvD;AAEA,IAAA,OAAO,IAAI,OAAA,CAAQ;AAAA,MACjB,SAAA;AAAA,MACA,YAAY,IAAA,CAAK,UAAA;AAAA,MACjB,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,eAAe,IAAA,CAAK,cAAA;AAAA,MACpB,cAAc,IAAA,CAAK,aAAA;AAAA,MACnB,mBAAA,EAAqB,KAAK,qBAAA,IAAyB,+BAAA;AAAA,MACnD,aAAA,EAAe,KAAK,eAAA,IAAmB,cAAA;AAAA,MACvC,QAAA,EAAU,KAAK,SAAA,IAAa;AAAA,KAC7B,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/**\n * Session — high-level wrapper for ChaosChain Engineering Studio sessions.\n *\n * Agents use this class to log work events without constructing raw event schemas,\n * managing parent IDs, or thinking about DAGs. The gateway handles all of that.\n *\n * @example\n * ```ts\n * const session = await client.start({ studio_address: '0x...', agent_address: '0x...' });\n * await session.log({ summary: 'Planning cache layer implementation' });\n * await session.step('implementing', 'Added CacheService class');\n * await session.step('testing', 'All 47 tests pass');\n * const { workflow_id, data_hash } = await session.complete();\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport axios, { AxiosError } from 'axios';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Valid agent roles accepted by the gateway for session events. */\nexport type SessionAgentRole = 'worker' | 'verifier' | 'collaborator';\n\n/** Per-event agent override. */\nexport interface SessionAgentOverride {\n /** Wallet address of the agent emitting this event. */\n agent_address: string;\n /** Agent role (defaults to `\"worker\"`). Must be `worker`, `verifier`, or `collaborator`. */\n role?: SessionAgentRole;\n}\n\n/** Options for {@link Session.log}. */\nexport interface SessionLogOptions {\n /** Human-readable description of what happened. */\n summary: string;\n /** Canonical event type. Defaults to `\"artifact_created\"`. */\n event_type?: string;\n /** Arbitrary metadata attached to the event. */\n metadata?: Record<string, unknown>;\n /** Override the session-level agent for this event. */\n agent?: SessionAgentOverride;\n}\n\n/** Result returned by {@link Session.complete}. */\nexport interface SessionCompleteResult {\n workflow_id: string | null;\n data_hash: string | null;\n}\n\n/** Canonical event-type mappings for {@link Session.step}. */\nconst STEP_TYPE_MAP: Record<string, string> = {\n planning: 'plan_created',\n testing: 'test_run',\n debugging: 'debug_step',\n implementing: 'file_written',\n completing: 'submission_created',\n};\n\n// =============================================================================\n// Session\n// =============================================================================\n\nexport class Session {\n /** Session ID returned by the gateway. */\n public readonly sessionId: string;\n\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n private readonly studioAddress: string;\n private readonly agentAddress: string;\n private readonly studioPolicyVersion: string;\n private readonly workMandateId: string;\n private readonly taskType: string;\n private lastEventId: string | null;\n\n /** @internal — use {@link SessionClient.start} to create instances. */\n constructor(opts: {\n sessionId: string;\n gatewayUrl: string;\n apiKey?: string;\n lastEventId?: string | null;\n studioAddress: string;\n agentAddress: string;\n studioPolicyVersion: string;\n workMandateId: string;\n taskType: string;\n }) {\n this.sessionId = opts.sessionId;\n this.gatewayUrl = opts.gatewayUrl;\n this.apiKey = opts.apiKey;\n this.lastEventId = opts.lastEventId ?? null;\n this.studioAddress = opts.studioAddress;\n this.agentAddress = opts.agentAddress;\n this.studioPolicyVersion = opts.studioPolicyVersion;\n this.workMandateId = opts.workMandateId;\n this.taskType = opts.taskType;\n }\n\n /**\n * Log a session event.\n *\n * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`\n * from the previous event so the gateway can build a causal DAG.\n *\n * @param opts - Event details. Only `summary` is required.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async log(opts: SessionLogOptions): Promise<void> {\n const eventId = randomUUID();\n const event = {\n event_id: eventId,\n event_type: opts.event_type ?? 'artifact_created',\n timestamp: new Date().toISOString(),\n summary: opts.summary,\n causality: {\n parent_event_ids: this.lastEventId ? [this.lastEventId] : [],\n },\n agent: {\n agent_address: opts.agent?.agent_address ?? this.agentAddress,\n role: opts.agent?.role ?? 'worker',\n },\n studio: {\n studio_address: this.studioAddress,\n studio_policy_version: this.studioPolicyVersion,\n },\n task: {\n work_mandate_id: this.workMandateId,\n task_type: this.taskType,\n },\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n };\n\n await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);\n this.lastEventId = eventId;\n }\n\n /**\n * Convenience wrapper around {@link log} that maps human-friendly step names\n * to canonical event types.\n *\n * Mappings:\n * - `\"planning\"` → `plan_created`\n * - `\"testing\"` → `test_run`\n * - `\"debugging\"` → `debug_step`\n * - `\"implementing\"` → `file_written`\n * - `\"completing\"` → `submission_created`\n *\n * Unknown step types fall back to `artifact_created`.\n *\n * @param stepType - Friendly step name.\n * @param summary - What happened in this step.\n */\n async step(stepType: string, summary: string, agent?: SessionAgentOverride): Promise<void> {\n const eventType = STEP_TYPE_MAP[stepType] ?? 'artifact_created';\n await this.log({ event_type: eventType, summary, agent });\n }\n\n /**\n * Complete the session.\n *\n * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)\n * and returns `workflow_id` + `data_hash` for downstream verification/scoring.\n *\n * @param opts - Optional status (`\"completed\"` | `\"failed\"`) and summary.\n * @returns `{ workflow_id, data_hash }` — both may be `null` if the gateway\n * workflow engine is not configured.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async complete(\n opts?: { status?: 'completed' | 'failed'; summary?: string },\n ): Promise<SessionCompleteResult> {\n const body: Record<string, unknown> = {};\n if (opts?.status) body.status = opts.status;\n if (opts?.summary) body.summary = opts.summary;\n\n const data = await this.post<{\n data: { workflow_id: string | null; data_hash: string | null };\n }>(`/v1/sessions/${this.sessionId}/complete`, body);\n\n return {\n workflow_id: data.data?.workflow_id ?? null,\n data_hash: data.data?.data_hash ?? null,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internal HTTP helper\n // ---------------------------------------------------------------------------\n\n private async post<T = unknown>(path: string, body: unknown): Promise<T> {\n const url = `${this.gatewayUrl}${path}`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n return res.data as T;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Session request failed: POST ${path} → ${status} ${detail}`);\n }\n }\n}\n","/**\n * SessionClient — factory for creating ChaosChain Engineering Studio sessions.\n *\n * @example\n * ```ts\n * import { SessionClient } from '@chaoschain/sdk';\n *\n * const client = new SessionClient({ gatewayUrl: 'https://gateway.chaoscha.in', apiKey: 'cc_...' });\n * const session = await client.start({\n * studio_address: '0xFA0795fD5D7F58eCAa7Eae35Ad9cB8AED9424Dd0',\n * agent_address: '0x9B4Cef62a0ce1671ccFEFA6a6D8cBFa165c49831',\n * task_type: 'feature',\n * });\n *\n * await session.log({ summary: 'Started implementing cache layer' });\n * await session.step('testing', 'All tests pass');\n * const result = await session.complete();\n * ```\n */\n\nimport axios, { AxiosError } from 'axios';\nimport { Session } from './Session';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Configuration for {@link SessionClient}. */\nexport interface SessionClientConfig {\n /** Gateway base URL (default: `\"https://gateway.chaoscha.in\"`). */\n gatewayUrl?: string;\n /** API key sent as `X-API-Key` header. */\n apiKey?: string;\n}\n\n/** Options for {@link SessionClient.start}. */\nexport interface SessionStartOptions {\n /** Studio contract address (required). */\n studio_address: string;\n /** Worker agent wallet address (required). */\n agent_address: string;\n /** Work mandate ID (default: `\"generic-task\"`). */\n work_mandate_id?: string;\n /** Task classification (default: `\"general\"`). */\n task_type?: string;\n /** Studio policy version (default: `\"engineering-studio-default-v1\"`). */\n studio_policy_version?: string;\n /** Client-provided session ID. Server generates one if omitted. */\n session_id?: string;\n}\n\n// =============================================================================\n// SessionClient\n// =============================================================================\n\nexport class SessionClient {\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n\n constructor(config: SessionClientConfig = {}) {\n this.gatewayUrl = (config.gatewayUrl ?? 'https://gateway.chaoscha.in').replace(/\\/$/, '');\n this.apiKey = config.apiKey;\n }\n\n /**\n * Create a new coding session on the gateway.\n *\n * Returns a {@link Session} instance that can be used to log events, run steps,\n * and complete the session. The gateway persists all events and constructs the\n * Evidence DAG automatically.\n *\n * @param opts - Session creation parameters.\n * @returns A live {@link Session} bound to the newly created session ID.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async start(opts: SessionStartOptions): Promise<Session> {\n const body: Record<string, string> = {\n studio_address: opts.studio_address,\n agent_address: opts.agent_address,\n };\n if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;\n if (opts.task_type) body.task_type = opts.task_type;\n if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;\n if (opts.session_id) body.session_id = opts.session_id;\n\n const url = `${this.gatewayUrl}/v1/sessions`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n let data: { data: { session_id: string } };\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n data = res.data as typeof data;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Failed to create session: POST /v1/sessions → ${status} ${detail}`);\n }\n\n const sessionId = data.data?.session_id;\n if (!sessionId) {\n throw new Error('Gateway response missing session_id');\n }\n\n return new Session({\n sessionId,\n gatewayUrl: this.gatewayUrl,\n apiKey: this.apiKey,\n studioAddress: opts.studio_address,\n agentAddress: opts.agent_address,\n studioPolicyVersion: opts.studio_policy_version ?? 'engineering-studio-default-v1',\n workMandateId: opts.work_mandate_id ?? 'generic-task',\n taskType: opts.task_type ?? 'general',\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/session/Session.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e,IAAA,CAAK,cAAA;AAAA,MACpB,cAAc,IAAA,CAAK,aAAA;AAAA,MACnB,mBAAA,EAAqB,KAAK,qBAAA,IAAyB,+BAAA;AAAA,MACnD,aAAA,EAAe,KAAK,eAAA,IAAmB,cAAA;AAAA,MACvC,QAAA,EAAU,KAAK,SAAA,IAAa,SAAA;AAAA,MAC5B,KAAA,EAAO,KAAK,IAAA,CAAK;AAAA,KAClB,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/**\n * Session — high-level wrapper for ChaosChain Engineering Studio sessions.\n *\n * Agents use this class to log work events without constructing raw event schemas,\n * managing parent IDs, or thinking about DAGs. The gateway handles all of that.\n *\n * @example\n * ```ts\n * const session = await client.start({ studio_address: '0x...', agent_address: '0x...' });\n * await session.log({ summary: 'Planning cache layer implementation' });\n * await session.step('implementing', 'Added CacheService class');\n * await session.step('testing', 'All 47 tests pass');\n * const { workflow_id, data_hash } = await session.complete();\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport axios, { AxiosError } from 'axios';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Valid agent roles accepted by the gateway for session events. */\nexport type SessionAgentRole = 'worker' | 'verifier' | 'collaborator';\n\n/** Per-event agent override. */\nexport interface SessionAgentOverride {\n /** Wallet address of the agent emitting this event. */\n agent_address: string;\n /** Agent role (defaults to `\"worker\"`). Must be `worker`, `verifier`, or `collaborator`. */\n role?: SessionAgentRole;\n}\n\n/** Options for {@link Session.log}. */\nexport interface SessionLogOptions {\n /** Human-readable description of what happened. */\n summary: string;\n /** Canonical event type. Defaults to `\"artifact_created\"`. */\n event_type?: string;\n /** Arbitrary metadata attached to the event. */\n metadata?: Record<string, unknown>;\n /** Override the session-level agent for this event. */\n agent?: SessionAgentOverride;\n}\n\n/** Result returned by {@link Session.complete}. */\nexport interface SessionCompleteResult {\n workflow_id: string | null;\n data_hash: string | null;\n epoch: number;\n}\n\n/** Canonical event-type mappings for {@link Session.step}. */\nconst STEP_TYPE_MAP: Record<string, string> = {\n planning: 'plan_created',\n testing: 'test_run',\n debugging: 'debug_step',\n implementing: 'file_written',\n completing: 'submission_created',\n};\n\n// =============================================================================\n// Session\n// =============================================================================\n\nexport class Session {\n /** Session ID returned by the gateway. */\n public readonly sessionId: string;\n /** Epoch number returned by the gateway. */\n public readonly epoch: number;\n /** Studio contract address for this session. */\n public readonly studioAddress: string;\n /** Default agent wallet address for this session. */\n public readonly agentAddress: string;\n /** URL to view this session's Evidence DAG in the browser. */\n public readonly viewerUrl: string;\n\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n private readonly studioPolicyVersion: string;\n private readonly workMandateId: string;\n private readonly taskType: string;\n private lastEventId: string | null;\n\n /** @internal — use {@link SessionClient.start} to create instances. */\n constructor(opts: {\n sessionId: string;\n gatewayUrl: string;\n apiKey?: string;\n lastEventId?: string | null;\n studioAddress: string;\n agentAddress: string;\n studioPolicyVersion: string;\n workMandateId: string;\n taskType: string;\n epoch: number;\n }) {\n this.sessionId = opts.sessionId;\n this.epoch = opts.epoch;\n this.viewerUrl = `${opts.gatewayUrl}/v1/sessions/${opts.sessionId}/viewer`;\n this.gatewayUrl = opts.gatewayUrl;\n this.apiKey = opts.apiKey;\n this.lastEventId = opts.lastEventId ?? null;\n this.studioAddress = opts.studioAddress;\n this.agentAddress = opts.agentAddress;\n this.studioPolicyVersion = opts.studioPolicyVersion;\n this.workMandateId = opts.workMandateId;\n this.taskType = opts.taskType;\n }\n\n /**\n * Log a session event.\n *\n * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`\n * from the previous event so the gateway can build a causal DAG.\n *\n * @param opts.summary - Human-readable description of what happened (required).\n * @param opts.event_type - Canonical event type (default: `\"artifact_created\"`).\n * @param opts.metadata - Arbitrary key-value metadata attached to the event.\n * @param opts.agent - Override the session-level agent for this event.\n * Pass `{ agent_address, role? }` to emit the event from a different agent.\n * Valid roles: `\"worker\"`, `\"verifier\"`, `\"collaborator\"`. Defaults to `\"worker\"`.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async log(opts: SessionLogOptions): Promise<void> {\n const eventId = randomUUID();\n const event = {\n event_id: eventId,\n event_type: opts.event_type ?? 'artifact_created',\n timestamp: new Date().toISOString(),\n summary: opts.summary,\n causality: {\n parent_event_ids: this.lastEventId ? [this.lastEventId] : [],\n },\n agent: {\n agent_address: opts.agent?.agent_address ?? this.agentAddress,\n role: opts.agent?.role ?? 'worker',\n },\n studio: {\n studio_address: this.studioAddress,\n studio_policy_version: this.studioPolicyVersion,\n },\n task: {\n work_mandate_id: this.workMandateId,\n task_type: this.taskType,\n },\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n };\n\n await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);\n this.lastEventId = eventId;\n }\n\n /**\n * Convenience wrapper around {@link log} that maps human-friendly step names\n * to canonical event types.\n *\n * Mappings:\n * - `\"planning\"` → `plan_created`\n * - `\"testing\"` → `test_run`\n * - `\"debugging\"` → `debug_step`\n * - `\"implementing\"` → `file_written`\n * - `\"completing\"` → `submission_created`\n *\n * Unknown step types fall back to `artifact_created`.\n *\n * @param stepType - Friendly step name (`\"planning\"`, `\"implementing\"`, `\"testing\"`, `\"debugging\"`, `\"completing\"`).\n * @param summary - What happened in this step.\n * @param agent - Optional agent override for this event. Same as `log({ agent })`.\n */\n async step(stepType: string, summary: string, agent?: SessionAgentOverride): Promise<void> {\n const eventType = STEP_TYPE_MAP[stepType] ?? 'artifact_created';\n await this.log({ event_type: eventType, summary, agent });\n }\n\n /**\n * Complete the session.\n *\n * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)\n * and returns the session result.\n *\n * @param opts.status - `\"completed\"` or `\"failed\"` (default: `\"completed\"`).\n * @param opts.summary - Human-readable summary of the session outcome.\n * @returns `{ workflow_id, data_hash, epoch }` — `workflow_id` and `data_hash`\n * may be `null` if the gateway workflow engine is not configured.\n * `epoch` is the epoch this session belongs to.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async complete(\n opts?: { status?: 'completed' | 'failed'; summary?: string },\n ): Promise<SessionCompleteResult> {\n const body: Record<string, unknown> = {};\n if (opts?.status) body.status = opts.status;\n if (opts?.summary) body.summary = opts.summary;\n\n const data = await this.post<{\n data: { workflow_id: string | null; data_hash: string | null; epoch: number };\n }>(`/v1/sessions/${this.sessionId}/complete`, body);\n\n return {\n workflow_id: data.data?.workflow_id ?? null,\n data_hash: data.data?.data_hash ?? null,\n epoch: data.data.epoch,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internal HTTP helper\n // ---------------------------------------------------------------------------\n\n private async post<T = unknown>(path: string, body: unknown): Promise<T> {\n const url = `${this.gatewayUrl}${path}`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n return res.data as T;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Session request failed: POST ${path} → ${status} ${detail}`);\n }\n }\n}\n","/**\n * SessionClient — factory for creating ChaosChain Engineering Studio sessions.\n *\n * @example\n * ```ts\n * import { SessionClient } from '@chaoschain/sdk';\n *\n * const client = new SessionClient({ gatewayUrl: 'https://gateway.chaoscha.in', apiKey: 'cc_...' });\n * const session = await client.start({\n * studio_address: '0xFA0795fD5D7F58eCAa7Eae35Ad9cB8AED9424Dd0',\n * agent_address: '0x9B4Cef62a0ce1671ccFEFA6a6D8cBFa165c49831',\n * task_type: 'feature',\n * });\n *\n * await session.log({ summary: 'Started implementing cache layer' });\n * await session.step('testing', 'All tests pass');\n * const result = await session.complete();\n * ```\n */\n\nimport axios, { AxiosError } from 'axios';\nimport { Session } from './Session';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Configuration for {@link SessionClient}. */\nexport interface SessionClientConfig {\n /** Gateway base URL (default: `\"https://gateway.chaoscha.in\"`). */\n gatewayUrl?: string;\n /** API key sent as `X-API-Key` header. */\n apiKey?: string;\n}\n\n/** Options for {@link SessionClient.start}. */\nexport interface SessionStartOptions {\n /** Studio contract address (required). */\n studio_address: string;\n /** Worker agent wallet address (required). */\n agent_address: string;\n /** Work mandate ID (default: `\"generic-task\"`). */\n work_mandate_id?: string;\n /** Task classification (default: `\"general\"`). */\n task_type?: string;\n /** Studio policy version (default: `\"engineering-studio-default-v1\"`). */\n studio_policy_version?: string;\n /** Client-provided session ID. Server generates one if omitted. */\n session_id?: string;\n}\n\n// =============================================================================\n// SessionClient\n// =============================================================================\n\nexport class SessionClient {\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n\n constructor(config: SessionClientConfig = {}) {\n this.gatewayUrl = (config.gatewayUrl ?? 'https://gateway.chaoscha.in').replace(/\\/$/, '');\n this.apiKey = config.apiKey;\n }\n\n /**\n * Create a new coding session on the gateway.\n *\n * Returns a {@link Session} instance that can be used to log events, run steps,\n * and complete the session. The gateway persists all events and constructs the\n * Evidence DAG automatically.\n *\n * The returned session exposes `session.sessionId`, `session.epoch`,\n * `session.studioAddress`, and `session.agentAddress`.\n *\n * @param opts.studio_address - Studio contract address (required).\n * @param opts.agent_address - Worker agent wallet address (required).\n * @param opts.task_type - Task classification: `\"feature\"`, `\"bugfix\"`, `\"refactor\"`, etc. (default: `\"general\"`).\n * @param opts.work_mandate_id - Work mandate identifier (default: `\"generic-task\"`).\n * @param opts.studio_policy_version - Studio policy version (default: `\"engineering-studio-default-v1\"`).\n * @param opts.session_id - Client-provided session ID. Server generates one if omitted.\n * @returns A live {@link Session} bound to the newly created session ID and epoch.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async start(opts: SessionStartOptions): Promise<Session> {\n const body: Record<string, string> = {\n studio_address: opts.studio_address,\n agent_address: opts.agent_address,\n };\n if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;\n if (opts.task_type) body.task_type = opts.task_type;\n if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;\n if (opts.session_id) body.session_id = opts.session_id;\n\n const url = `${this.gatewayUrl}/v1/sessions`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n let data: { data: { session_id: string; epoch: number } };\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n data = res.data as typeof data;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Failed to create session: POST /v1/sessions → ${status} ${detail}`);\n }\n\n const sessionId = data.data?.session_id;\n if (!sessionId) {\n throw new Error('Gateway response missing session_id');\n }\n\n return new Session({\n sessionId,\n gatewayUrl: this.gatewayUrl,\n apiKey: this.apiKey,\n studioAddress: opts.studio_address,\n agentAddress: opts.agent_address,\n studioPolicyVersion: opts.studio_policy_version ?? 'engineering-studio-default-v1',\n workMandateId: opts.work_mandate_id ?? 'generic-task',\n taskType: opts.task_type ?? 'general',\n epoch: data.data.epoch,\n });\n }\n}\n"]}
@@ -37,14 +37,21 @@ interface SessionLogOptions {
37
37
  interface SessionCompleteResult {
38
38
  workflow_id: string | null;
39
39
  data_hash: string | null;
40
+ epoch: number;
40
41
  }
41
42
  declare class Session {
42
43
  /** Session ID returned by the gateway. */
43
44
  readonly sessionId: string;
45
+ /** Epoch number returned by the gateway. */
46
+ readonly epoch: number;
47
+ /** Studio contract address for this session. */
48
+ readonly studioAddress: string;
49
+ /** Default agent wallet address for this session. */
50
+ readonly agentAddress: string;
51
+ /** URL to view this session's Evidence DAG in the browser. */
52
+ readonly viewerUrl: string;
44
53
  private readonly gatewayUrl;
45
54
  private readonly apiKey;
46
- private readonly studioAddress;
47
- private readonly agentAddress;
48
55
  private readonly studioPolicyVersion;
49
56
  private readonly workMandateId;
50
57
  private readonly taskType;
@@ -60,6 +67,7 @@ declare class Session {
60
67
  studioPolicyVersion: string;
61
68
  workMandateId: string;
62
69
  taskType: string;
70
+ epoch: number;
63
71
  });
64
72
  /**
65
73
  * Log a session event.
@@ -67,7 +75,12 @@ declare class Session {
67
75
  * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`
68
76
  * from the previous event so the gateway can build a causal DAG.
69
77
  *
70
- * @param opts - Event details. Only `summary` is required.
78
+ * @param opts.summary - Human-readable description of what happened (required).
79
+ * @param opts.event_type - Canonical event type (default: `"artifact_created"`).
80
+ * @param opts.metadata - Arbitrary key-value metadata attached to the event.
81
+ * @param opts.agent - Override the session-level agent for this event.
82
+ * Pass `{ agent_address, role? }` to emit the event from a different agent.
83
+ * Valid roles: `"worker"`, `"verifier"`, `"collaborator"`. Defaults to `"worker"`.
71
84
  * @throws Error if the gateway returns a non-2xx status.
72
85
  */
73
86
  log(opts: SessionLogOptions): Promise<void>;
@@ -84,19 +97,22 @@ declare class Session {
84
97
  *
85
98
  * Unknown step types fall back to `artifact_created`.
86
99
  *
87
- * @param stepType - Friendly step name.
100
+ * @param stepType - Friendly step name (`"planning"`, `"implementing"`, `"testing"`, `"debugging"`, `"completing"`).
88
101
  * @param summary - What happened in this step.
102
+ * @param agent - Optional agent override for this event. Same as `log({ agent })`.
89
103
  */
90
104
  step(stepType: string, summary: string, agent?: SessionAgentOverride): Promise<void>;
91
105
  /**
92
106
  * Complete the session.
93
107
  *
94
108
  * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
95
- * and returns `workflow_id` + `data_hash` for downstream verification/scoring.
109
+ * and returns the session result.
96
110
  *
97
- * @param opts - Optional status (`"completed"` | `"failed"`) and summary.
98
- * @returns `{ workflow_id, data_hash }` both may be `null` if the gateway
99
- * workflow engine is not configured.
111
+ * @param opts.status - `"completed"` or `"failed"` (default: `"completed"`).
112
+ * @param opts.summary - Human-readable summary of the session outcome.
113
+ * @returns `{ workflow_id, data_hash, epoch }` — `workflow_id` and `data_hash`
114
+ * may be `null` if the gateway workflow engine is not configured.
115
+ * `epoch` is the epoch this session belongs to.
100
116
  * @throws Error if the gateway returns a non-2xx status.
101
117
  */
102
118
  complete(opts?: {
@@ -159,8 +175,16 @@ declare class SessionClient {
159
175
  * and complete the session. The gateway persists all events and constructs the
160
176
  * Evidence DAG automatically.
161
177
  *
162
- * @param opts - Session creation parameters.
163
- * @returns A live {@link Session} bound to the newly created session ID.
178
+ * The returned session exposes `session.sessionId`, `session.epoch`,
179
+ * `session.studioAddress`, and `session.agentAddress`.
180
+ *
181
+ * @param opts.studio_address - Studio contract address (required).
182
+ * @param opts.agent_address - Worker agent wallet address (required).
183
+ * @param opts.task_type - Task classification: `"feature"`, `"bugfix"`, `"refactor"`, etc. (default: `"general"`).
184
+ * @param opts.work_mandate_id - Work mandate identifier (default: `"generic-task"`).
185
+ * @param opts.studio_policy_version - Studio policy version (default: `"engineering-studio-default-v1"`).
186
+ * @param opts.session_id - Client-provided session ID. Server generates one if omitted.
187
+ * @returns A live {@link Session} bound to the newly created session ID and epoch.
164
188
  * @throws Error if the gateway returns a non-2xx status.
165
189
  */
166
190
  start(opts: SessionStartOptions): Promise<Session>;
@@ -37,14 +37,21 @@ interface SessionLogOptions {
37
37
  interface SessionCompleteResult {
38
38
  workflow_id: string | null;
39
39
  data_hash: string | null;
40
+ epoch: number;
40
41
  }
41
42
  declare class Session {
42
43
  /** Session ID returned by the gateway. */
43
44
  readonly sessionId: string;
45
+ /** Epoch number returned by the gateway. */
46
+ readonly epoch: number;
47
+ /** Studio contract address for this session. */
48
+ readonly studioAddress: string;
49
+ /** Default agent wallet address for this session. */
50
+ readonly agentAddress: string;
51
+ /** URL to view this session's Evidence DAG in the browser. */
52
+ readonly viewerUrl: string;
44
53
  private readonly gatewayUrl;
45
54
  private readonly apiKey;
46
- private readonly studioAddress;
47
- private readonly agentAddress;
48
55
  private readonly studioPolicyVersion;
49
56
  private readonly workMandateId;
50
57
  private readonly taskType;
@@ -60,6 +67,7 @@ declare class Session {
60
67
  studioPolicyVersion: string;
61
68
  workMandateId: string;
62
69
  taskType: string;
70
+ epoch: number;
63
71
  });
64
72
  /**
65
73
  * Log a session event.
@@ -67,7 +75,12 @@ declare class Session {
67
75
  * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`
68
76
  * from the previous event so the gateway can build a causal DAG.
69
77
  *
70
- * @param opts - Event details. Only `summary` is required.
78
+ * @param opts.summary - Human-readable description of what happened (required).
79
+ * @param opts.event_type - Canonical event type (default: `"artifact_created"`).
80
+ * @param opts.metadata - Arbitrary key-value metadata attached to the event.
81
+ * @param opts.agent - Override the session-level agent for this event.
82
+ * Pass `{ agent_address, role? }` to emit the event from a different agent.
83
+ * Valid roles: `"worker"`, `"verifier"`, `"collaborator"`. Defaults to `"worker"`.
71
84
  * @throws Error if the gateway returns a non-2xx status.
72
85
  */
73
86
  log(opts: SessionLogOptions): Promise<void>;
@@ -84,19 +97,22 @@ declare class Session {
84
97
  *
85
98
  * Unknown step types fall back to `artifact_created`.
86
99
  *
87
- * @param stepType - Friendly step name.
100
+ * @param stepType - Friendly step name (`"planning"`, `"implementing"`, `"testing"`, `"debugging"`, `"completing"`).
88
101
  * @param summary - What happened in this step.
102
+ * @param agent - Optional agent override for this event. Same as `log({ agent })`.
89
103
  */
90
104
  step(stepType: string, summary: string, agent?: SessionAgentOverride): Promise<void>;
91
105
  /**
92
106
  * Complete the session.
93
107
  *
94
108
  * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
95
- * and returns `workflow_id` + `data_hash` for downstream verification/scoring.
109
+ * and returns the session result.
96
110
  *
97
- * @param opts - Optional status (`"completed"` | `"failed"`) and summary.
98
- * @returns `{ workflow_id, data_hash }` both may be `null` if the gateway
99
- * workflow engine is not configured.
111
+ * @param opts.status - `"completed"` or `"failed"` (default: `"completed"`).
112
+ * @param opts.summary - Human-readable summary of the session outcome.
113
+ * @returns `{ workflow_id, data_hash, epoch }` — `workflow_id` and `data_hash`
114
+ * may be `null` if the gateway workflow engine is not configured.
115
+ * `epoch` is the epoch this session belongs to.
100
116
  * @throws Error if the gateway returns a non-2xx status.
101
117
  */
102
118
  complete(opts?: {
@@ -159,8 +175,16 @@ declare class SessionClient {
159
175
  * and complete the session. The gateway persists all events and constructs the
160
176
  * Evidence DAG automatically.
161
177
  *
162
- * @param opts - Session creation parameters.
163
- * @returns A live {@link Session} bound to the newly created session ID.
178
+ * The returned session exposes `session.sessionId`, `session.epoch`,
179
+ * `session.studioAddress`, and `session.agentAddress`.
180
+ *
181
+ * @param opts.studio_address - Studio contract address (required).
182
+ * @param opts.agent_address - Worker agent wallet address (required).
183
+ * @param opts.task_type - Task classification: `"feature"`, `"bugfix"`, `"refactor"`, etc. (default: `"general"`).
184
+ * @param opts.work_mandate_id - Work mandate identifier (default: `"generic-task"`).
185
+ * @param opts.studio_policy_version - Studio policy version (default: `"engineering-studio-default-v1"`).
186
+ * @param opts.session_id - Client-provided session ID. Server generates one if omitted.
187
+ * @returns A live {@link Session} bound to the newly created session ID and epoch.
164
188
  * @throws Error if the gateway returns a non-2xx status.
165
189
  */
166
190
  start(opts: SessionStartOptions): Promise<Session>;
@@ -12,10 +12,16 @@ var STEP_TYPE_MAP = {
12
12
  var Session = class {
13
13
  /** Session ID returned by the gateway. */
14
14
  sessionId;
15
- gatewayUrl;
16
- apiKey;
15
+ /** Epoch number returned by the gateway. */
16
+ epoch;
17
+ /** Studio contract address for this session. */
17
18
  studioAddress;
19
+ /** Default agent wallet address for this session. */
18
20
  agentAddress;
21
+ /** URL to view this session's Evidence DAG in the browser. */
22
+ viewerUrl;
23
+ gatewayUrl;
24
+ apiKey;
19
25
  studioPolicyVersion;
20
26
  workMandateId;
21
27
  taskType;
@@ -23,6 +29,8 @@ var Session = class {
23
29
  /** @internal — use {@link SessionClient.start} to create instances. */
24
30
  constructor(opts) {
25
31
  this.sessionId = opts.sessionId;
32
+ this.epoch = opts.epoch;
33
+ this.viewerUrl = `${opts.gatewayUrl}/v1/sessions/${opts.sessionId}/viewer`;
26
34
  this.gatewayUrl = opts.gatewayUrl;
27
35
  this.apiKey = opts.apiKey;
28
36
  this.lastEventId = opts.lastEventId ?? null;
@@ -38,7 +46,12 @@ var Session = class {
38
46
  * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`
39
47
  * from the previous event so the gateway can build a causal DAG.
40
48
  *
41
- * @param opts - Event details. Only `summary` is required.
49
+ * @param opts.summary - Human-readable description of what happened (required).
50
+ * @param opts.event_type - Canonical event type (default: `"artifact_created"`).
51
+ * @param opts.metadata - Arbitrary key-value metadata attached to the event.
52
+ * @param opts.agent - Override the session-level agent for this event.
53
+ * Pass `{ agent_address, role? }` to emit the event from a different agent.
54
+ * Valid roles: `"worker"`, `"verifier"`, `"collaborator"`. Defaults to `"worker"`.
42
55
  * @throws Error if the gateway returns a non-2xx status.
43
56
  */
44
57
  async log(opts) {
@@ -81,8 +94,9 @@ var Session = class {
81
94
  *
82
95
  * Unknown step types fall back to `artifact_created`.
83
96
  *
84
- * @param stepType - Friendly step name.
97
+ * @param stepType - Friendly step name (`"planning"`, `"implementing"`, `"testing"`, `"debugging"`, `"completing"`).
85
98
  * @param summary - What happened in this step.
99
+ * @param agent - Optional agent override for this event. Same as `log({ agent })`.
86
100
  */
87
101
  async step(stepType, summary, agent) {
88
102
  const eventType = STEP_TYPE_MAP[stepType] ?? "artifact_created";
@@ -92,11 +106,13 @@ var Session = class {
92
106
  * Complete the session.
93
107
  *
94
108
  * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
95
- * and returns `workflow_id` + `data_hash` for downstream verification/scoring.
109
+ * and returns the session result.
96
110
  *
97
- * @param opts - Optional status (`"completed"` | `"failed"`) and summary.
98
- * @returns `{ workflow_id, data_hash }` both may be `null` if the gateway
99
- * workflow engine is not configured.
111
+ * @param opts.status - `"completed"` or `"failed"` (default: `"completed"`).
112
+ * @param opts.summary - Human-readable summary of the session outcome.
113
+ * @returns `{ workflow_id, data_hash, epoch }` — `workflow_id` and `data_hash`
114
+ * may be `null` if the gateway workflow engine is not configured.
115
+ * `epoch` is the epoch this session belongs to.
100
116
  * @throws Error if the gateway returns a non-2xx status.
101
117
  */
102
118
  async complete(opts) {
@@ -106,7 +122,8 @@ var Session = class {
106
122
  const data = await this.post(`/v1/sessions/${this.sessionId}/complete`, body);
107
123
  return {
108
124
  workflow_id: data.data?.workflow_id ?? null,
109
- data_hash: data.data?.data_hash ?? null
125
+ data_hash: data.data?.data_hash ?? null,
126
+ epoch: data.data.epoch
110
127
  };
111
128
  }
112
129
  // ---------------------------------------------------------------------------
@@ -141,8 +158,16 @@ var SessionClient = class {
141
158
  * and complete the session. The gateway persists all events and constructs the
142
159
  * Evidence DAG automatically.
143
160
  *
144
- * @param opts - Session creation parameters.
145
- * @returns A live {@link Session} bound to the newly created session ID.
161
+ * The returned session exposes `session.sessionId`, `session.epoch`,
162
+ * `session.studioAddress`, and `session.agentAddress`.
163
+ *
164
+ * @param opts.studio_address - Studio contract address (required).
165
+ * @param opts.agent_address - Worker agent wallet address (required).
166
+ * @param opts.task_type - Task classification: `"feature"`, `"bugfix"`, `"refactor"`, etc. (default: `"general"`).
167
+ * @param opts.work_mandate_id - Work mandate identifier (default: `"generic-task"`).
168
+ * @param opts.studio_policy_version - Studio policy version (default: `"engineering-studio-default-v1"`).
169
+ * @param opts.session_id - Client-provided session ID. Server generates one if omitted.
170
+ * @returns A live {@link Session} bound to the newly created session ID and epoch.
146
171
  * @throws Error if the gateway returns a non-2xx status.
147
172
  */
148
173
  async start(opts) {
@@ -179,7 +204,8 @@ var SessionClient = class {
179
204
  agentAddress: opts.agent_address,
180
205
  studioPolicyVersion: opts.studio_policy_version ?? "engineering-studio-default-v1",
181
206
  workMandateId: opts.work_mandate_id ?? "generic-task",
182
- taskType: opts.task_type ?? "general"
207
+ taskType: opts.task_type ?? "general",
208
+ epoch: data.data.epoch
183
209
  });
184
210
  }
185
211
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/session/Session.ts","../../src/session/SessionClient.ts"],"names":["axios"],"mappings":";;;;AAqDA,IAAM,aAAA,GA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Q,MAAA,EAAQ,GAAA,EAAK,IAAA,EAAM,IAAA,EAAM,OAAA,EAAS,OAAA,EAAS,GAAA,EAAQ,CAAA;AACrF,MAAA,IAAA,GAAO,GAAA,CAAI,IAAA;AAAA,IACb,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,QAAA,GAAW,GAAA;AACjB,MAAA,MAAM,MAAA,GAAS,QAAA,CAAS,QAAA,EAAU,MAAA,IAAU,CAAA;AAC5C,MAAA,MAAM,SAAS,IAAA,CAAK,SAAA,CAAU,SAAS,QAAA,EAAU,IAAA,IAAQ,SAAS,OAAO,CAAA;AACzE,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mDAAA,EAAiD,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,CAAE,CAAA;AAAA,IACrF;AAEA,IAAA,MAAM,SAAA,GAAY,KAAK,IAAA,EAAM,UAAA;AAC7B,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,IACvD;AAEA,IAAA,OAAO,IAAI,OAAA,CAAQ;AAAA,MACjB,SAAA;AAAA,MACA,YAAY,IAAA,CAAK,UAAA;AAAA,MACjB,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,eAAe,IAAA,CAAK,cAAA;AAAA,MACpB,cAAc,IAAA,CAAK,aAAA;AAAA,MACnB,mBAAA,EAAqB,KAAK,qBAAA,IAAyB,+BAAA;AAAA,MACnD,aAAA,EAAe,KAAK,eAAA,IAAmB,cAAA;AAAA,MACvC,QAAA,EAAU,KAAK,SAAA,IAAa;AAAA,KAC7B,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/**\n * Session — high-level wrapper for ChaosChain Engineering Studio sessions.\n *\n * Agents use this class to log work events without constructing raw event schemas,\n * managing parent IDs, or thinking about DAGs. The gateway handles all of that.\n *\n * @example\n * ```ts\n * const session = await client.start({ studio_address: '0x...', agent_address: '0x...' });\n * await session.log({ summary: 'Planning cache layer implementation' });\n * await session.step('implementing', 'Added CacheService class');\n * await session.step('testing', 'All 47 tests pass');\n * const { workflow_id, data_hash } = await session.complete();\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport axios, { AxiosError } from 'axios';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Valid agent roles accepted by the gateway for session events. */\nexport type SessionAgentRole = 'worker' | 'verifier' | 'collaborator';\n\n/** Per-event agent override. */\nexport interface SessionAgentOverride {\n /** Wallet address of the agent emitting this event. */\n agent_address: string;\n /** Agent role (defaults to `\"worker\"`). Must be `worker`, `verifier`, or `collaborator`. */\n role?: SessionAgentRole;\n}\n\n/** Options for {@link Session.log}. */\nexport interface SessionLogOptions {\n /** Human-readable description of what happened. */\n summary: string;\n /** Canonical event type. Defaults to `\"artifact_created\"`. */\n event_type?: string;\n /** Arbitrary metadata attached to the event. */\n metadata?: Record<string, unknown>;\n /** Override the session-level agent for this event. */\n agent?: SessionAgentOverride;\n}\n\n/** Result returned by {@link Session.complete}. */\nexport interface SessionCompleteResult {\n workflow_id: string | null;\n data_hash: string | null;\n}\n\n/** Canonical event-type mappings for {@link Session.step}. */\nconst STEP_TYPE_MAP: Record<string, string> = {\n planning: 'plan_created',\n testing: 'test_run',\n debugging: 'debug_step',\n implementing: 'file_written',\n completing: 'submission_created',\n};\n\n// =============================================================================\n// Session\n// =============================================================================\n\nexport class Session {\n /** Session ID returned by the gateway. */\n public readonly sessionId: string;\n\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n private readonly studioAddress: string;\n private readonly agentAddress: string;\n private readonly studioPolicyVersion: string;\n private readonly workMandateId: string;\n private readonly taskType: string;\n private lastEventId: string | null;\n\n /** @internal — use {@link SessionClient.start} to create instances. */\n constructor(opts: {\n sessionId: string;\n gatewayUrl: string;\n apiKey?: string;\n lastEventId?: string | null;\n studioAddress: string;\n agentAddress: string;\n studioPolicyVersion: string;\n workMandateId: string;\n taskType: string;\n }) {\n this.sessionId = opts.sessionId;\n this.gatewayUrl = opts.gatewayUrl;\n this.apiKey = opts.apiKey;\n this.lastEventId = opts.lastEventId ?? null;\n this.studioAddress = opts.studioAddress;\n this.agentAddress = opts.agentAddress;\n this.studioPolicyVersion = opts.studioPolicyVersion;\n this.workMandateId = opts.workMandateId;\n this.taskType = opts.taskType;\n }\n\n /**\n * Log a session event.\n *\n * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`\n * from the previous event so the gateway can build a causal DAG.\n *\n * @param opts - Event details. Only `summary` is required.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async log(opts: SessionLogOptions): Promise<void> {\n const eventId = randomUUID();\n const event = {\n event_id: eventId,\n event_type: opts.event_type ?? 'artifact_created',\n timestamp: new Date().toISOString(),\n summary: opts.summary,\n causality: {\n parent_event_ids: this.lastEventId ? [this.lastEventId] : [],\n },\n agent: {\n agent_address: opts.agent?.agent_address ?? this.agentAddress,\n role: opts.agent?.role ?? 'worker',\n },\n studio: {\n studio_address: this.studioAddress,\n studio_policy_version: this.studioPolicyVersion,\n },\n task: {\n work_mandate_id: this.workMandateId,\n task_type: this.taskType,\n },\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n };\n\n await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);\n this.lastEventId = eventId;\n }\n\n /**\n * Convenience wrapper around {@link log} that maps human-friendly step names\n * to canonical event types.\n *\n * Mappings:\n * - `\"planning\"` → `plan_created`\n * - `\"testing\"` → `test_run`\n * - `\"debugging\"` → `debug_step`\n * - `\"implementing\"` → `file_written`\n * - `\"completing\"` → `submission_created`\n *\n * Unknown step types fall back to `artifact_created`.\n *\n * @param stepType - Friendly step name.\n * @param summary - What happened in this step.\n */\n async step(stepType: string, summary: string, agent?: SessionAgentOverride): Promise<void> {\n const eventType = STEP_TYPE_MAP[stepType] ?? 'artifact_created';\n await this.log({ event_type: eventType, summary, agent });\n }\n\n /**\n * Complete the session.\n *\n * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)\n * and returns `workflow_id` + `data_hash` for downstream verification/scoring.\n *\n * @param opts - Optional status (`\"completed\"` | `\"failed\"`) and summary.\n * @returns `{ workflow_id, data_hash }` — both may be `null` if the gateway\n * workflow engine is not configured.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async complete(\n opts?: { status?: 'completed' | 'failed'; summary?: string },\n ): Promise<SessionCompleteResult> {\n const body: Record<string, unknown> = {};\n if (opts?.status) body.status = opts.status;\n if (opts?.summary) body.summary = opts.summary;\n\n const data = await this.post<{\n data: { workflow_id: string | null; data_hash: string | null };\n }>(`/v1/sessions/${this.sessionId}/complete`, body);\n\n return {\n workflow_id: data.data?.workflow_id ?? null,\n data_hash: data.data?.data_hash ?? null,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internal HTTP helper\n // ---------------------------------------------------------------------------\n\n private async post<T = unknown>(path: string, body: unknown): Promise<T> {\n const url = `${this.gatewayUrl}${path}`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n return res.data as T;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Session request failed: POST ${path} → ${status} ${detail}`);\n }\n }\n}\n","/**\n * SessionClient — factory for creating ChaosChain Engineering Studio sessions.\n *\n * @example\n * ```ts\n * import { SessionClient } from '@chaoschain/sdk';\n *\n * const client = new SessionClient({ gatewayUrl: 'https://gateway.chaoscha.in', apiKey: 'cc_...' });\n * const session = await client.start({\n * studio_address: '0xFA0795fD5D7F58eCAa7Eae35Ad9cB8AED9424Dd0',\n * agent_address: '0x9B4Cef62a0ce1671ccFEFA6a6D8cBFa165c49831',\n * task_type: 'feature',\n * });\n *\n * await session.log({ summary: 'Started implementing cache layer' });\n * await session.step('testing', 'All tests pass');\n * const result = await session.complete();\n * ```\n */\n\nimport axios, { AxiosError } from 'axios';\nimport { Session } from './Session';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Configuration for {@link SessionClient}. */\nexport interface SessionClientConfig {\n /** Gateway base URL (default: `\"https://gateway.chaoscha.in\"`). */\n gatewayUrl?: string;\n /** API key sent as `X-API-Key` header. */\n apiKey?: string;\n}\n\n/** Options for {@link SessionClient.start}. */\nexport interface SessionStartOptions {\n /** Studio contract address (required). */\n studio_address: string;\n /** Worker agent wallet address (required). */\n agent_address: string;\n /** Work mandate ID (default: `\"generic-task\"`). */\n work_mandate_id?: string;\n /** Task classification (default: `\"general\"`). */\n task_type?: string;\n /** Studio policy version (default: `\"engineering-studio-default-v1\"`). */\n studio_policy_version?: string;\n /** Client-provided session ID. Server generates one if omitted. */\n session_id?: string;\n}\n\n// =============================================================================\n// SessionClient\n// =============================================================================\n\nexport class SessionClient {\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n\n constructor(config: SessionClientConfig = {}) {\n this.gatewayUrl = (config.gatewayUrl ?? 'https://gateway.chaoscha.in').replace(/\\/$/, '');\n this.apiKey = config.apiKey;\n }\n\n /**\n * Create a new coding session on the gateway.\n *\n * Returns a {@link Session} instance that can be used to log events, run steps,\n * and complete the session. The gateway persists all events and constructs the\n * Evidence DAG automatically.\n *\n * @param opts - Session creation parameters.\n * @returns A live {@link Session} bound to the newly created session ID.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async start(opts: SessionStartOptions): Promise<Session> {\n const body: Record<string, string> = {\n studio_address: opts.studio_address,\n agent_address: opts.agent_address,\n };\n if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;\n if (opts.task_type) body.task_type = opts.task_type;\n if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;\n if (opts.session_id) body.session_id = opts.session_id;\n\n const url = `${this.gatewayUrl}/v1/sessions`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n let data: { data: { session_id: string } };\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n data = res.data as typeof data;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Failed to create session: POST /v1/sessions → ${status} ${detail}`);\n }\n\n const sessionId = data.data?.session_id;\n if (!sessionId) {\n throw new Error('Gateway response missing session_id');\n }\n\n return new Session({\n sessionId,\n gatewayUrl: this.gatewayUrl,\n apiKey: this.apiKey,\n studioAddress: opts.studio_address,\n agentAddress: opts.agent_address,\n studioPolicyVersion: opts.studio_policy_version ?? 'engineering-studio-default-v1',\n workMandateId: opts.work_mandate_id ?? 'generic-task',\n taskType: opts.task_type ?? 'general',\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/session/Session.ts","../../src/session/SessionClient.ts"],"names":["axios"],"mappings":";;;;AAsDA,IAAM,aAAA,GAAwC;AAAA,EAC5C,QAAA,EAAU,cAAA;AAAA,EACV,OAAA,EAAS,UAAA;AAAA,EACT,SAAA,EAAW,YAAA;AAAA,EACX,YAAA,EAAc,cAAA;AAAA,EACd,UAAA,EAAY;AACd,CAAA;AAMO,IAAM,UAAN,MAAc;AAAA;AAAA,EAEH,SAAA;AAAA;AAAA,EAEA,KAAA;AAAA;AAAA,EAEA,aAAA;AAAA;AAAA,EAEA,YAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAEC,UAAA;AAAA,EACA,MAAA;AAAA,EACA,mBAAA;AAAA,EACA,aAAA;AAAA,EACA,QAAA;AAAA,EACT,WAAA;AAAA;AAAA,EAGR,YAAY,IAAA,EAWT;AACD,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,YAAY,CAAA,EAAG,IAAA,CAAK,UAAU,CAAA,aAAA,EAAgB,KAAK,SAAS,CAAA,OAAA,CAAA;A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5C,MAAA,MAAM,SAAS,IAAA,CAAK,SAAA,CAAU,SAAS,QAAA,EAAU,IAAA,IAAQ,SAAS,OAAO,CAAA;AACzE,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mDAAA,EAAiD,MAAM,CAAA,CAAA,EAAI,MAAM,CAAA,CAAE,CAAA;AAAA,IACrF;AAEA,IAAA,MAAM,SAAA,GAAY,KAAK,IAAA,EAAM,UAAA;AAC7B,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,IACvD;AAEA,IAAA,OAAO,IAAI,OAAA,CAAQ;AAAA,MACjB,SAAA;AAAA,MACA,YAAY,IAAA,CAAK,UAAA;AAAA,MACjB,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,eAAe,IAAA,CAAK,cAAA;AAAA,MACpB,cAAc,IAAA,CAAK,aAAA;AAAA,MACnB,mBAAA,EAAqB,KAAK,qBAAA,IAAyB,+BAAA;AAAA,MACnD,aAAA,EAAe,KAAK,eAAA,IAAmB,cAAA;AAAA,MACvC,QAAA,EAAU,KAAK,SAAA,IAAa,SAAA;AAAA,MAC5B,KAAA,EAAO,KAAK,IAAA,CAAK;AAAA,KAClB,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/**\n * Session — high-level wrapper for ChaosChain Engineering Studio sessions.\n *\n * Agents use this class to log work events without constructing raw event schemas,\n * managing parent IDs, or thinking about DAGs. The gateway handles all of that.\n *\n * @example\n * ```ts\n * const session = await client.start({ studio_address: '0x...', agent_address: '0x...' });\n * await session.log({ summary: 'Planning cache layer implementation' });\n * await session.step('implementing', 'Added CacheService class');\n * await session.step('testing', 'All 47 tests pass');\n * const { workflow_id, data_hash } = await session.complete();\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport axios, { AxiosError } from 'axios';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Valid agent roles accepted by the gateway for session events. */\nexport type SessionAgentRole = 'worker' | 'verifier' | 'collaborator';\n\n/** Per-event agent override. */\nexport interface SessionAgentOverride {\n /** Wallet address of the agent emitting this event. */\n agent_address: string;\n /** Agent role (defaults to `\"worker\"`). Must be `worker`, `verifier`, or `collaborator`. */\n role?: SessionAgentRole;\n}\n\n/** Options for {@link Session.log}. */\nexport interface SessionLogOptions {\n /** Human-readable description of what happened. */\n summary: string;\n /** Canonical event type. Defaults to `\"artifact_created\"`. */\n event_type?: string;\n /** Arbitrary metadata attached to the event. */\n metadata?: Record<string, unknown>;\n /** Override the session-level agent for this event. */\n agent?: SessionAgentOverride;\n}\n\n/** Result returned by {@link Session.complete}. */\nexport interface SessionCompleteResult {\n workflow_id: string | null;\n data_hash: string | null;\n epoch: number;\n}\n\n/** Canonical event-type mappings for {@link Session.step}. */\nconst STEP_TYPE_MAP: Record<string, string> = {\n planning: 'plan_created',\n testing: 'test_run',\n debugging: 'debug_step',\n implementing: 'file_written',\n completing: 'submission_created',\n};\n\n// =============================================================================\n// Session\n// =============================================================================\n\nexport class Session {\n /** Session ID returned by the gateway. */\n public readonly sessionId: string;\n /** Epoch number returned by the gateway. */\n public readonly epoch: number;\n /** Studio contract address for this session. */\n public readonly studioAddress: string;\n /** Default agent wallet address for this session. */\n public readonly agentAddress: string;\n /** URL to view this session's Evidence DAG in the browser. */\n public readonly viewerUrl: string;\n\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n private readonly studioPolicyVersion: string;\n private readonly workMandateId: string;\n private readonly taskType: string;\n private lastEventId: string | null;\n\n /** @internal — use {@link SessionClient.start} to create instances. */\n constructor(opts: {\n sessionId: string;\n gatewayUrl: string;\n apiKey?: string;\n lastEventId?: string | null;\n studioAddress: string;\n agentAddress: string;\n studioPolicyVersion: string;\n workMandateId: string;\n taskType: string;\n epoch: number;\n }) {\n this.sessionId = opts.sessionId;\n this.epoch = opts.epoch;\n this.viewerUrl = `${opts.gatewayUrl}/v1/sessions/${opts.sessionId}/viewer`;\n this.gatewayUrl = opts.gatewayUrl;\n this.apiKey = opts.apiKey;\n this.lastEventId = opts.lastEventId ?? null;\n this.studioAddress = opts.studioAddress;\n this.agentAddress = opts.agentAddress;\n this.studioPolicyVersion = opts.studioPolicyVersion;\n this.workMandateId = opts.workMandateId;\n this.taskType = opts.taskType;\n }\n\n /**\n * Log a session event.\n *\n * Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`\n * from the previous event so the gateway can build a causal DAG.\n *\n * @param opts.summary - Human-readable description of what happened (required).\n * @param opts.event_type - Canonical event type (default: `\"artifact_created\"`).\n * @param opts.metadata - Arbitrary key-value metadata attached to the event.\n * @param opts.agent - Override the session-level agent for this event.\n * Pass `{ agent_address, role? }` to emit the event from a different agent.\n * Valid roles: `\"worker\"`, `\"verifier\"`, `\"collaborator\"`. Defaults to `\"worker\"`.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async log(opts: SessionLogOptions): Promise<void> {\n const eventId = randomUUID();\n const event = {\n event_id: eventId,\n event_type: opts.event_type ?? 'artifact_created',\n timestamp: new Date().toISOString(),\n summary: opts.summary,\n causality: {\n parent_event_ids: this.lastEventId ? [this.lastEventId] : [],\n },\n agent: {\n agent_address: opts.agent?.agent_address ?? this.agentAddress,\n role: opts.agent?.role ?? 'worker',\n },\n studio: {\n studio_address: this.studioAddress,\n studio_policy_version: this.studioPolicyVersion,\n },\n task: {\n work_mandate_id: this.workMandateId,\n task_type: this.taskType,\n },\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n };\n\n await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);\n this.lastEventId = eventId;\n }\n\n /**\n * Convenience wrapper around {@link log} that maps human-friendly step names\n * to canonical event types.\n *\n * Mappings:\n * - `\"planning\"` → `plan_created`\n * - `\"testing\"` → `test_run`\n * - `\"debugging\"` → `debug_step`\n * - `\"implementing\"` → `file_written`\n * - `\"completing\"` → `submission_created`\n *\n * Unknown step types fall back to `artifact_created`.\n *\n * @param stepType - Friendly step name (`\"planning\"`, `\"implementing\"`, `\"testing\"`, `\"debugging\"`, `\"completing\"`).\n * @param summary - What happened in this step.\n * @param agent - Optional agent override for this event. Same as `log({ agent })`.\n */\n async step(stepType: string, summary: string, agent?: SessionAgentOverride): Promise<void> {\n const eventType = STEP_TYPE_MAP[stepType] ?? 'artifact_created';\n await this.log({ event_type: eventType, summary, agent });\n }\n\n /**\n * Complete the session.\n *\n * Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)\n * and returns the session result.\n *\n * @param opts.status - `\"completed\"` or `\"failed\"` (default: `\"completed\"`).\n * @param opts.summary - Human-readable summary of the session outcome.\n * @returns `{ workflow_id, data_hash, epoch }` — `workflow_id` and `data_hash`\n * may be `null` if the gateway workflow engine is not configured.\n * `epoch` is the epoch this session belongs to.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async complete(\n opts?: { status?: 'completed' | 'failed'; summary?: string },\n ): Promise<SessionCompleteResult> {\n const body: Record<string, unknown> = {};\n if (opts?.status) body.status = opts.status;\n if (opts?.summary) body.summary = opts.summary;\n\n const data = await this.post<{\n data: { workflow_id: string | null; data_hash: string | null; epoch: number };\n }>(`/v1/sessions/${this.sessionId}/complete`, body);\n\n return {\n workflow_id: data.data?.workflow_id ?? null,\n data_hash: data.data?.data_hash ?? null,\n epoch: data.data.epoch,\n };\n }\n\n // ---------------------------------------------------------------------------\n // Internal HTTP helper\n // ---------------------------------------------------------------------------\n\n private async post<T = unknown>(path: string, body: unknown): Promise<T> {\n const url = `${this.gatewayUrl}${path}`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n return res.data as T;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Session request failed: POST ${path} → ${status} ${detail}`);\n }\n }\n}\n","/**\n * SessionClient — factory for creating ChaosChain Engineering Studio sessions.\n *\n * @example\n * ```ts\n * import { SessionClient } from '@chaoschain/sdk';\n *\n * const client = new SessionClient({ gatewayUrl: 'https://gateway.chaoscha.in', apiKey: 'cc_...' });\n * const session = await client.start({\n * studio_address: '0xFA0795fD5D7F58eCAa7Eae35Ad9cB8AED9424Dd0',\n * agent_address: '0x9B4Cef62a0ce1671ccFEFA6a6D8cBFa165c49831',\n * task_type: 'feature',\n * });\n *\n * await session.log({ summary: 'Started implementing cache layer' });\n * await session.step('testing', 'All tests pass');\n * const result = await session.complete();\n * ```\n */\n\nimport axios, { AxiosError } from 'axios';\nimport { Session } from './Session';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Configuration for {@link SessionClient}. */\nexport interface SessionClientConfig {\n /** Gateway base URL (default: `\"https://gateway.chaoscha.in\"`). */\n gatewayUrl?: string;\n /** API key sent as `X-API-Key` header. */\n apiKey?: string;\n}\n\n/** Options for {@link SessionClient.start}. */\nexport interface SessionStartOptions {\n /** Studio contract address (required). */\n studio_address: string;\n /** Worker agent wallet address (required). */\n agent_address: string;\n /** Work mandate ID (default: `\"generic-task\"`). */\n work_mandate_id?: string;\n /** Task classification (default: `\"general\"`). */\n task_type?: string;\n /** Studio policy version (default: `\"engineering-studio-default-v1\"`). */\n studio_policy_version?: string;\n /** Client-provided session ID. Server generates one if omitted. */\n session_id?: string;\n}\n\n// =============================================================================\n// SessionClient\n// =============================================================================\n\nexport class SessionClient {\n private readonly gatewayUrl: string;\n private readonly apiKey: string | undefined;\n\n constructor(config: SessionClientConfig = {}) {\n this.gatewayUrl = (config.gatewayUrl ?? 'https://gateway.chaoscha.in').replace(/\\/$/, '');\n this.apiKey = config.apiKey;\n }\n\n /**\n * Create a new coding session on the gateway.\n *\n * Returns a {@link Session} instance that can be used to log events, run steps,\n * and complete the session. The gateway persists all events and constructs the\n * Evidence DAG automatically.\n *\n * The returned session exposes `session.sessionId`, `session.epoch`,\n * `session.studioAddress`, and `session.agentAddress`.\n *\n * @param opts.studio_address - Studio contract address (required).\n * @param opts.agent_address - Worker agent wallet address (required).\n * @param opts.task_type - Task classification: `\"feature\"`, `\"bugfix\"`, `\"refactor\"`, etc. (default: `\"general\"`).\n * @param opts.work_mandate_id - Work mandate identifier (default: `\"generic-task\"`).\n * @param opts.studio_policy_version - Studio policy version (default: `\"engineering-studio-default-v1\"`).\n * @param opts.session_id - Client-provided session ID. Server generates one if omitted.\n * @returns A live {@link Session} bound to the newly created session ID and epoch.\n * @throws Error if the gateway returns a non-2xx status.\n */\n async start(opts: SessionStartOptions): Promise<Session> {\n const body: Record<string, string> = {\n studio_address: opts.studio_address,\n agent_address: opts.agent_address,\n };\n if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;\n if (opts.task_type) body.task_type = opts.task_type;\n if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;\n if (opts.session_id) body.session_id = opts.session_id;\n\n const url = `${this.gatewayUrl}/v1/sessions`;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.apiKey) headers['X-API-Key'] = this.apiKey;\n\n let data: { data: { session_id: string; epoch: number } };\n try {\n const res = await axios({ method: 'POST', url, data: body, headers, timeout: 30_000 });\n data = res.data as typeof data;\n } catch (err) {\n const axiosErr = err as AxiosError;\n const status = axiosErr.response?.status ?? 0;\n const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);\n throw new Error(`Failed to create session: POST /v1/sessions → ${status} ${detail}`);\n }\n\n const sessionId = data.data?.session_id;\n if (!sessionId) {\n throw new Error('Gateway response missing session_id');\n }\n\n return new Session({\n sessionId,\n gatewayUrl: this.gatewayUrl,\n apiKey: this.apiKey,\n studioAddress: opts.studio_address,\n agentAddress: opts.agent_address,\n studioPolicyVersion: opts.studio_policy_version ?? 'engineering-studio-default-v1',\n workMandateId: opts.work_mandate_id ?? 'generic-task',\n taskType: opts.task_type ?? 'general',\n epoch: data.data.epoch,\n });\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaoschain/sdk",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "description": "TypeScript SDK for building verifiable AI agents on ChaosChain",
6
6
  "main": "./dist/index.cjs",