@chaoschain/sdk 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +102 -12
- package/dist/{IPFSLocal-B4hnMEfS.d.ts → IPFSLocal-B_Sgmd_Q.d.ts} +1 -1
- package/dist/{IPFSLocal-zRj6kG8e.d.cts → IPFSLocal-DjFddwHD.d.cts} +1 -1
- package/dist/gateway/index.cjs +591 -0
- package/dist/gateway/index.cjs.map +1 -0
- package/dist/gateway/index.d.cts +3 -0
- package/dist/gateway/index.d.ts +3 -0
- package/dist/gateway/index.js +581 -0
- package/dist/gateway/index.js.map +1 -0
- package/dist/index-CL0fidQs.d.ts +223 -0
- package/dist/index-iUO5l1VD.d.cts +223 -0
- package/dist/index.cjs +8 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -382
- package/dist/index.d.ts +9 -382
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/providers/compute/index.d.cts +1 -1
- package/dist/providers/compute/index.d.ts +1 -1
- package/dist/providers/storage/index.d.cts +2 -2
- package/dist/providers/storage/index.d.ts +2 -2
- package/dist/session/index.cjs +196 -0
- package/dist/session/index.cjs.map +1 -0
- package/dist/session/index.d.cts +169 -0
- package/dist/session/index.d.ts +169 -0
- package/dist/session/index.js +189 -0
- package/dist/session/index.js.map +1 -0
- package/dist/{types-BBVtx_jV.d.cts → types-C0Ay90UI.d.cts} +1 -1
- package/dist/{types-BBVtx_jV.d.ts → types-C0Ay90UI.d.ts} +1 -1
- package/package.json +11 -1
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import axios from 'axios';
|
|
3
|
+
|
|
4
|
+
// src/session/Session.ts
|
|
5
|
+
var STEP_TYPE_MAP = {
|
|
6
|
+
planning: "plan_created",
|
|
7
|
+
testing: "test_run",
|
|
8
|
+
debugging: "debug_step",
|
|
9
|
+
implementing: "file_written",
|
|
10
|
+
completing: "submission_created"
|
|
11
|
+
};
|
|
12
|
+
var Session = class {
|
|
13
|
+
/** Session ID returned by the gateway. */
|
|
14
|
+
sessionId;
|
|
15
|
+
gatewayUrl;
|
|
16
|
+
apiKey;
|
|
17
|
+
studioAddress;
|
|
18
|
+
agentAddress;
|
|
19
|
+
studioPolicyVersion;
|
|
20
|
+
workMandateId;
|
|
21
|
+
taskType;
|
|
22
|
+
lastEventId;
|
|
23
|
+
/** @internal — use {@link SessionClient.start} to create instances. */
|
|
24
|
+
constructor(opts) {
|
|
25
|
+
this.sessionId = opts.sessionId;
|
|
26
|
+
this.gatewayUrl = opts.gatewayUrl;
|
|
27
|
+
this.apiKey = opts.apiKey;
|
|
28
|
+
this.lastEventId = opts.lastEventId ?? null;
|
|
29
|
+
this.studioAddress = opts.studioAddress;
|
|
30
|
+
this.agentAddress = opts.agentAddress;
|
|
31
|
+
this.studioPolicyVersion = opts.studioPolicyVersion;
|
|
32
|
+
this.workMandateId = opts.workMandateId;
|
|
33
|
+
this.taskType = opts.taskType;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Log a session event.
|
|
37
|
+
*
|
|
38
|
+
* Automatically generates `event_id`, `timestamp`, and chains `parent_event_ids`
|
|
39
|
+
* from the previous event so the gateway can build a causal DAG.
|
|
40
|
+
*
|
|
41
|
+
* @param opts - Event details. Only `summary` is required.
|
|
42
|
+
* @throws Error if the gateway returns a non-2xx status.
|
|
43
|
+
*/
|
|
44
|
+
async log(opts) {
|
|
45
|
+
const eventId = randomUUID();
|
|
46
|
+
const event = {
|
|
47
|
+
event_id: eventId,
|
|
48
|
+
event_type: opts.event_type ?? "artifact_created",
|
|
49
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
50
|
+
summary: opts.summary,
|
|
51
|
+
causality: {
|
|
52
|
+
parent_event_ids: this.lastEventId ? [this.lastEventId] : []
|
|
53
|
+
},
|
|
54
|
+
agent: {
|
|
55
|
+
agent_address: opts.agent?.agent_address ?? this.agentAddress,
|
|
56
|
+
role: opts.agent?.role ?? "worker"
|
|
57
|
+
},
|
|
58
|
+
studio: {
|
|
59
|
+
studio_address: this.studioAddress,
|
|
60
|
+
studio_policy_version: this.studioPolicyVersion
|
|
61
|
+
},
|
|
62
|
+
task: {
|
|
63
|
+
work_mandate_id: this.workMandateId,
|
|
64
|
+
task_type: this.taskType
|
|
65
|
+
},
|
|
66
|
+
...opts.metadata ? { metadata: opts.metadata } : {}
|
|
67
|
+
};
|
|
68
|
+
await this.post(`/v1/sessions/${this.sessionId}/events`, [event]);
|
|
69
|
+
this.lastEventId = eventId;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Convenience wrapper around {@link log} that maps human-friendly step names
|
|
73
|
+
* to canonical event types.
|
|
74
|
+
*
|
|
75
|
+
* Mappings:
|
|
76
|
+
* - `"planning"` → `plan_created`
|
|
77
|
+
* - `"testing"` → `test_run`
|
|
78
|
+
* - `"debugging"` → `debug_step`
|
|
79
|
+
* - `"implementing"` → `file_written`
|
|
80
|
+
* - `"completing"` → `submission_created`
|
|
81
|
+
*
|
|
82
|
+
* Unknown step types fall back to `artifact_created`.
|
|
83
|
+
*
|
|
84
|
+
* @param stepType - Friendly step name.
|
|
85
|
+
* @param summary - What happened in this step.
|
|
86
|
+
*/
|
|
87
|
+
async step(stepType, summary, agent) {
|
|
88
|
+
const eventType = STEP_TYPE_MAP[stepType] ?? "artifact_created";
|
|
89
|
+
await this.log({ event_type: eventType, summary, agent });
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Complete the session.
|
|
93
|
+
*
|
|
94
|
+
* Triggers the on-chain WorkSubmission workflow (if the gateway is configured for it)
|
|
95
|
+
* and returns `workflow_id` + `data_hash` for downstream verification/scoring.
|
|
96
|
+
*
|
|
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.
|
|
100
|
+
* @throws Error if the gateway returns a non-2xx status.
|
|
101
|
+
*/
|
|
102
|
+
async complete(opts) {
|
|
103
|
+
const body = {};
|
|
104
|
+
if (opts?.status) body.status = opts.status;
|
|
105
|
+
if (opts?.summary) body.summary = opts.summary;
|
|
106
|
+
const data = await this.post(`/v1/sessions/${this.sessionId}/complete`, body);
|
|
107
|
+
return {
|
|
108
|
+
workflow_id: data.data?.workflow_id ?? null,
|
|
109
|
+
data_hash: data.data?.data_hash ?? null
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
// Internal HTTP helper
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
async post(path, body) {
|
|
116
|
+
const url = `${this.gatewayUrl}${path}`;
|
|
117
|
+
const headers = { "Content-Type": "application/json" };
|
|
118
|
+
if (this.apiKey) headers["X-API-Key"] = this.apiKey;
|
|
119
|
+
try {
|
|
120
|
+
const res = await axios({ method: "POST", url, data: body, headers, timeout: 3e4 });
|
|
121
|
+
return res.data;
|
|
122
|
+
} catch (err) {
|
|
123
|
+
const axiosErr = err;
|
|
124
|
+
const status = axiosErr.response?.status ?? 0;
|
|
125
|
+
const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);
|
|
126
|
+
throw new Error(`Session request failed: POST ${path} \u2192 ${status} ${detail}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
var SessionClient = class {
|
|
131
|
+
gatewayUrl;
|
|
132
|
+
apiKey;
|
|
133
|
+
constructor(config = {}) {
|
|
134
|
+
this.gatewayUrl = (config.gatewayUrl ?? "https://gateway.chaoscha.in").replace(/\/$/, "");
|
|
135
|
+
this.apiKey = config.apiKey;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Create a new coding session on the gateway.
|
|
139
|
+
*
|
|
140
|
+
* Returns a {@link Session} instance that can be used to log events, run steps,
|
|
141
|
+
* and complete the session. The gateway persists all events and constructs the
|
|
142
|
+
* Evidence DAG automatically.
|
|
143
|
+
*
|
|
144
|
+
* @param opts - Session creation parameters.
|
|
145
|
+
* @returns A live {@link Session} bound to the newly created session ID.
|
|
146
|
+
* @throws Error if the gateway returns a non-2xx status.
|
|
147
|
+
*/
|
|
148
|
+
async start(opts) {
|
|
149
|
+
const body = {
|
|
150
|
+
studio_address: opts.studio_address,
|
|
151
|
+
agent_address: opts.agent_address
|
|
152
|
+
};
|
|
153
|
+
if (opts.work_mandate_id) body.work_mandate_id = opts.work_mandate_id;
|
|
154
|
+
if (opts.task_type) body.task_type = opts.task_type;
|
|
155
|
+
if (opts.studio_policy_version) body.studio_policy_version = opts.studio_policy_version;
|
|
156
|
+
if (opts.session_id) body.session_id = opts.session_id;
|
|
157
|
+
const url = `${this.gatewayUrl}/v1/sessions`;
|
|
158
|
+
const headers = { "Content-Type": "application/json" };
|
|
159
|
+
if (this.apiKey) headers["X-API-Key"] = this.apiKey;
|
|
160
|
+
let data;
|
|
161
|
+
try {
|
|
162
|
+
const res = await axios({ method: "POST", url, data: body, headers, timeout: 3e4 });
|
|
163
|
+
data = res.data;
|
|
164
|
+
} catch (err) {
|
|
165
|
+
const axiosErr = err;
|
|
166
|
+
const status = axiosErr.response?.status ?? 0;
|
|
167
|
+
const detail = JSON.stringify(axiosErr.response?.data ?? axiosErr.message);
|
|
168
|
+
throw new Error(`Failed to create session: POST /v1/sessions \u2192 ${status} ${detail}`);
|
|
169
|
+
}
|
|
170
|
+
const sessionId = data.data?.session_id;
|
|
171
|
+
if (!sessionId) {
|
|
172
|
+
throw new Error("Gateway response missing session_id");
|
|
173
|
+
}
|
|
174
|
+
return new Session({
|
|
175
|
+
sessionId,
|
|
176
|
+
gatewayUrl: this.gatewayUrl,
|
|
177
|
+
apiKey: this.apiKey,
|
|
178
|
+
studioAddress: opts.studio_address,
|
|
179
|
+
agentAddress: opts.agent_address,
|
|
180
|
+
studioPolicyVersion: opts.studio_policy_version ?? "engineering-studio-default-v1",
|
|
181
|
+
workMandateId: opts.work_mandate_id ?? "generic-task",
|
|
182
|
+
taskType: opts.task_type ?? "general"
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
export { Session, SessionClient };
|
|
188
|
+
//# sourceMappingURL=index.js.map
|
|
189
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/session/Session.ts","../../src/session/SessionClient.ts"],"names":["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,IAAA,IAAA,CAAK,WAAA,GAAc,KAAK,WAAA,IAAe,IAAA;AACvC,IAAA,IAAA,CAAK,gBAAgB,IAAA,CAAK,aAAA;AAC1B,IAAA,IAAA,CAAK,eAAe,IAAA,CAAK,YAAA;AACzB,IAAA,IAAA,CAAK,sBAAsB,IAAA,CAAK,mBAAA;AAChC,IAAA,IAAA,CAAK,gBAAgB,IAAA,CAAK,aAAA;AAC1B,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AAAA,EACvB;AAAA;AAAA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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"]}
|
|
@@ -785,4 +785,4 @@ interface DKGNodeData {
|
|
|
785
785
|
canonicalHash?: string;
|
|
786
786
|
}
|
|
787
787
|
|
|
788
|
-
export { type
|
|
788
|
+
export { type GatewayHealthResponse as $, AgentRole as A, composeScoreVector as B, type ComputeProvider as C, type DKGNodeData as D, composeScoreVectorWithDefaults as E, type FeedbackParams as F, type GatewayClientConfig as G, rangeFit as H, type IntegrityProof as I, type EvidencePackage as J, type WorkEvidenceVerificationResult as K, type WorkVerificationResult as L, type AgencySignals as M, NetworkConfig as N, type VerifierAssessment as O, PaymentMethod as P, type DemoAssessment as Q, type ScoreRange as R, type StorageProvider as S, type TEEAttestation as T, type UploadOptions as U, type ValidationRequestParams as V, type WalletConfig as W, type X402PaymentParams as X, type EngineeringStudioPolicy as Y, type WorkMandate as Z, type SignalExtractionContext as _, type UploadResult as a, type NetworkInfo as b, type ContractAddresses as c, type ChaosChainSDKConfig as d, type AgentMetadata as e, type AgentRegistration as f, type WorkflowStatus as g, ScoreSubmissionMode as h, type FeedbackRecord as i, type ValidationRequest as j, type X402Payment as k, type TransactionResult as l, ValidationStatus as m, WorkflowType as n, WorkflowState as o, type WorkflowProgress as p, type WorkflowError as q, type PendingWorkItem as r, type PendingWorkResponse as s, type WorkEvidenceResponse as t, type XMTPMessageData as u, computeDepth as v, derivePoAScores as w, validateEvidenceGraph as x, verifyWorkEvidence as y, extractAgencySignals as z };
|
|
@@ -785,4 +785,4 @@ interface DKGNodeData {
|
|
|
785
785
|
canonicalHash?: string;
|
|
786
786
|
}
|
|
787
787
|
|
|
788
|
-
export { type
|
|
788
|
+
export { type GatewayHealthResponse as $, AgentRole as A, composeScoreVector as B, type ComputeProvider as C, type DKGNodeData as D, composeScoreVectorWithDefaults as E, type FeedbackParams as F, type GatewayClientConfig as G, rangeFit as H, type IntegrityProof as I, type EvidencePackage as J, type WorkEvidenceVerificationResult as K, type WorkVerificationResult as L, type AgencySignals as M, NetworkConfig as N, type VerifierAssessment as O, PaymentMethod as P, type DemoAssessment as Q, type ScoreRange as R, type StorageProvider as S, type TEEAttestation as T, type UploadOptions as U, type ValidationRequestParams as V, type WalletConfig as W, type X402PaymentParams as X, type EngineeringStudioPolicy as Y, type WorkMandate as Z, type SignalExtractionContext as _, type UploadResult as a, type NetworkInfo as b, type ContractAddresses as c, type ChaosChainSDKConfig as d, type AgentMetadata as e, type AgentRegistration as f, type WorkflowStatus as g, ScoreSubmissionMode as h, type FeedbackRecord as i, type ValidationRequest as j, type X402Payment as k, type TransactionResult as l, ValidationStatus as m, WorkflowType as n, WorkflowState as o, type WorkflowProgress as p, type WorkflowError as q, type PendingWorkItem as r, type PendingWorkResponse as s, type WorkEvidenceResponse as t, type XMTPMessageData as u, computeDepth as v, derivePoAScores as w, validateEvidenceGraph as x, verifyWorkEvidence as y, extractAgencySignals as z };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chaoschain/sdk",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "TypeScript SDK for building verifiable AI agents on ChaosChain",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -12,6 +12,16 @@
|
|
|
12
12
|
"import": "./dist/index.js",
|
|
13
13
|
"require": "./dist/index.cjs"
|
|
14
14
|
},
|
|
15
|
+
"./session": {
|
|
16
|
+
"types": "./dist/session/index.d.ts",
|
|
17
|
+
"import": "./dist/session/index.js",
|
|
18
|
+
"require": "./dist/session/index.cjs"
|
|
19
|
+
},
|
|
20
|
+
"./gateway": {
|
|
21
|
+
"types": "./dist/gateway/index.d.ts",
|
|
22
|
+
"import": "./dist/gateway/index.js",
|
|
23
|
+
"require": "./dist/gateway/index.cjs"
|
|
24
|
+
},
|
|
15
25
|
"./providers/storage": {
|
|
16
26
|
"types": "./dist/providers/storage/index.d.ts",
|
|
17
27
|
"import": "./dist/providers/storage/index.js",
|