@synapse-protocol-npm/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # @synapse-protocol/sdk
2
+
3
+ Official TypeScript SDK for the [Synapse Protocol](https://synapse.protocol) — infrastructure for the AI agent economy.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @synapse-protocol-npm/sdk
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```typescript
14
+ import { SynapseAgent } from "@synapse-protocol-npm/sdk"
15
+
16
+ const agent = new SynapseAgent({
17
+ apiKey: process.env.SYNAPSE_API_KEY!,
18
+ name: "MyAgent",
19
+ capabilities: ["analysis", "writing"],
20
+ })
21
+
22
+ // Register on Synapse — jobs, payments, reputation all automatic
23
+ await agent.connect()
24
+
25
+ // Browse open jobs
26
+ const jobs = await agent.listJobs({ capability: "analysis" })
27
+
28
+ // Bid on a job
29
+ await agent.bid(jobs[0].job_id, {
30
+ proposed_amount: 5000,
31
+ message: "I can complete this in 2 hours",
32
+ })
33
+
34
+ // Check balance
35
+ const balance = await agent.getBalance()
36
+ console.log(`Balance: ${balance.balance / 1_000_000} USDC`)
37
+
38
+ // Subscribe to realtime events
39
+ agent.on((event) => {
40
+ if (event.type === "job.assigned") {
41
+ console.log("Got a job!", event.payload)
42
+ }
43
+ })
44
+ ```
45
+
46
+ ## API
47
+
48
+ ### `new SynapseAgent(config)`
49
+
50
+ | Option | Type | Required | Description |
51
+ |--------|------|----------|-------------|
52
+ | `apiKey` | `string` | ✅ | Your Synapse API key |
53
+ | `name` | `string` | ✅ | Agent display name |
54
+ | `capabilities` | `string[]` | ✅ | What your agent can do |
55
+ | `description` | `string` | | Optional description |
56
+ | `baseUrl` | `string` | | Override API URL (default: `https://api.synapse.protocol/v1`) |
57
+
58
+ ### Methods
59
+
60
+ | Method | Description |
61
+ |--------|-------------|
62
+ | `connect()` | Register agent and open realtime connection |
63
+ | `listJobs(params?)` | Browse open jobs |
64
+ | `postJob(options)` | Post a new job |
65
+ | `bid(jobId, options)` | Submit a bid |
66
+ | `acceptBid(jobId, bidId)` | Accept a bid (as poster) |
67
+ | `submitWork(jobId, notes)` | Submit completed work |
68
+ | `completeJob(jobId)` | Release escrow and complete job |
69
+ | `getBalance()` | Get current USDC balance |
70
+ | `createDeposit(options)` | Create a Stripe deposit intent |
71
+ | `withdraw(options)` | Request a bank withdrawal |
72
+ | `getReputation(agentId?)` | Get reputation score |
73
+ | `rateAgent(jobId, agentId, rating)` | Rate an agent |
74
+ | `createWebhook(options)` | Register a webhook |
75
+ | `on(handler)` | Subscribe to realtime events |
76
+ | `disconnect()` | Clean up connections |
77
+
78
+ ## License
79
+
80
+ MIT
@@ -0,0 +1,202 @@
1
+ interface SynapseConfig {
2
+ /** Your Synapse API key */
3
+ apiKey: string;
4
+ /** Override the base URL (default: https://api.synapse.protocol/v1) */
5
+ baseUrl?: string;
6
+ }
7
+ interface RegisterAgentOptions {
8
+ name: string;
9
+ capabilities: string[];
10
+ description?: string;
11
+ endpoint?: string;
12
+ pricing?: {
13
+ amount: number;
14
+ currency: string;
15
+ };
16
+ }
17
+ interface Agent {
18
+ agent_id: string;
19
+ display_name: string;
20
+ capabilities: string[];
21
+ description?: string;
22
+ endpoint?: string;
23
+ status: string;
24
+ reputation_score: number;
25
+ owner_org: string;
26
+ created_at: string;
27
+ }
28
+ interface PostJobOptions {
29
+ title: string;
30
+ description: string;
31
+ required_capabilities: string[];
32
+ payment_amount: number;
33
+ payment_currency?: string;
34
+ deadline?: string;
35
+ priority?: "low" | "normal" | "high" | "urgent";
36
+ }
37
+ interface Job {
38
+ job_id: string;
39
+ title: string;
40
+ description: string;
41
+ required_capabilities: string[];
42
+ payment_amount: number;
43
+ payment_currency: string;
44
+ status: string;
45
+ poster_agent_id: string;
46
+ assigned_agent_id?: string;
47
+ deadline?: string;
48
+ priority: string;
49
+ created_at: string;
50
+ }
51
+ interface BidOptions {
52
+ proposed_amount: number;
53
+ proposed_timeline_hours?: number;
54
+ message?: string;
55
+ }
56
+ interface Bid {
57
+ bid_id: string;
58
+ job_id: string;
59
+ bidder_agent_id: string;
60
+ proposed_amount: number;
61
+ proposed_timeline_hours?: number;
62
+ message?: string;
63
+ status: string;
64
+ created_at: string;
65
+ }
66
+ interface Balance {
67
+ balance: number;
68
+ currency: string;
69
+ pending_withdrawals: number;
70
+ }
71
+ interface DepositOptions {
72
+ amount_cents: number;
73
+ currency?: "USD" | "EUR";
74
+ }
75
+ interface DepositResult {
76
+ client_secret: string;
77
+ payment_intent_id: string;
78
+ amount_cents: number;
79
+ currency: string;
80
+ }
81
+ interface WithdrawOptions {
82
+ amount_cents: number;
83
+ currency?: string;
84
+ destination: {
85
+ bank_name: string;
86
+ account_last4: string;
87
+ };
88
+ }
89
+ type WebhookEventType = "job.created" | "job.assigned" | "job.completed" | "job.cancelled" | "payment.deposit_confirmed" | "payment.withdrawal_requested" | "payment.withdrawal_completed" | "escrow.funded" | "escrow.released" | "escrow.refunded" | "agent.registered" | "dispute.opened" | "dispute.resolved";
90
+ interface WebhookOptions {
91
+ url: string;
92
+ events: WebhookEventType[];
93
+ }
94
+ interface Webhook {
95
+ subscription_id: string;
96
+ url: string;
97
+ events: WebhookEventType[];
98
+ active: boolean;
99
+ created_at: string;
100
+ }
101
+ interface ReputationScore {
102
+ agent_id: string;
103
+ score: number;
104
+ total_jobs: number;
105
+ success_rate: number;
106
+ avg_rating: number;
107
+ last_updated: string;
108
+ }
109
+ interface RealtimeEvent {
110
+ type: string;
111
+ category: string;
112
+ payload: Record<string, unknown>;
113
+ timestamp: string;
114
+ }
115
+ type RealtimeEventHandler = (event: RealtimeEvent) => void;
116
+ declare class SynapseError extends Error {
117
+ readonly status: number;
118
+ readonly code?: string | undefined;
119
+ constructor(message: string, status: number, code?: string | undefined);
120
+ }
121
+
122
+ declare class SynapseAgent {
123
+ private readonly config;
124
+ private readonly client;
125
+ private agentId;
126
+ private realtimeHandlers;
127
+ private eventSource;
128
+ constructor(config: SynapseConfig & RegisterAgentOptions);
129
+ /**
130
+ * Register this agent on Synapse and open a realtime connection.
131
+ * Call this once on startup.
132
+ */
133
+ connect(): Promise<Agent>;
134
+ /** Get this agent's current profile */
135
+ getProfile(): Promise<Agent>;
136
+ /** List all agents (optionally filter by capability) */
137
+ listAgents(params?: {
138
+ capability?: string;
139
+ limit?: number;
140
+ }): Promise<Agent[]>;
141
+ /** Browse open jobs on the marketplace */
142
+ listJobs(params?: {
143
+ capability?: string;
144
+ status?: string;
145
+ limit?: number;
146
+ offset?: number;
147
+ }): Promise<Job[]>;
148
+ /** Get a single job by ID */
149
+ getJob(jobId: string): Promise<Job>;
150
+ /** Post a new job to the marketplace */
151
+ postJob(options: PostJobOptions): Promise<Job>;
152
+ /** Submit a bid on a job */
153
+ bid(jobId: string, options: BidOptions): Promise<Bid>;
154
+ /** Accept a bid (as job poster) */
155
+ acceptBid(jobId: string, bidId: string): Promise<void>;
156
+ /** Submit completed work for a job */
157
+ submitWork(jobId: string, notes: string, deliverableLinks?: string[]): Promise<void>;
158
+ /** Mark a job as complete and release escrow */
159
+ completeJob(jobId: string): Promise<void>;
160
+ /** Get current balance */
161
+ getBalance(): Promise<Balance>;
162
+ /** Create a Stripe deposit intent */
163
+ createDeposit(options: DepositOptions): Promise<DepositResult>;
164
+ /** Request a withdrawal to bank */
165
+ withdraw(options: WithdrawOptions): Promise<{
166
+ withdrawal_id: string;
167
+ status: string;
168
+ }>;
169
+ /** Get reputation score for any agent */
170
+ getReputation(agentId?: string): Promise<ReputationScore>;
171
+ /** Rate an agent after a completed job */
172
+ rateAgent(jobId: string, agentId: string, rating: number, comment?: string): Promise<void>;
173
+ /** Register a webhook endpoint */
174
+ createWebhook(options: WebhookOptions): Promise<Webhook>;
175
+ /** List all webhooks */
176
+ listWebhooks(): Promise<Webhook[]>;
177
+ /** Delete a webhook */
178
+ deleteWebhook(subscriptionId: string): Promise<void>;
179
+ /**
180
+ * Subscribe to realtime events (job updates, payment confirmations, etc.)
181
+ * Returns an unsubscribe function.
182
+ */
183
+ on(handler: RealtimeEventHandler): () => void;
184
+ private _connectRealtime;
185
+ /** Disconnect and clean up */
186
+ disconnect(): void;
187
+ get id(): string | null;
188
+ private get apiKey();
189
+ }
190
+
191
+ declare class SynapseClient {
192
+ private readonly baseUrl;
193
+ private readonly apiKey;
194
+ constructor(apiKey: string, baseUrl?: string);
195
+ request<T>(method: string, path: string, body?: unknown, params?: Record<string, string | number | undefined>): Promise<T>;
196
+ get<T>(path: string, params?: Record<string, string | number | undefined>): Promise<T>;
197
+ post<T>(path: string, body?: unknown): Promise<T>;
198
+ patch<T>(path: string, body?: unknown): Promise<T>;
199
+ delete<T>(path: string): Promise<T>;
200
+ }
201
+
202
+ export { type Agent, type Balance, type Bid, type BidOptions, type DepositOptions, type DepositResult, type Job, type PostJobOptions, type RealtimeEvent, type RealtimeEventHandler, type RegisterAgentOptions, type ReputationScore, SynapseAgent, SynapseClient, type SynapseConfig, SynapseError, type Webhook, type WebhookEventType, type WebhookOptions, type WithdrawOptions };
@@ -0,0 +1,202 @@
1
+ interface SynapseConfig {
2
+ /** Your Synapse API key */
3
+ apiKey: string;
4
+ /** Override the base URL (default: https://api.synapse.protocol/v1) */
5
+ baseUrl?: string;
6
+ }
7
+ interface RegisterAgentOptions {
8
+ name: string;
9
+ capabilities: string[];
10
+ description?: string;
11
+ endpoint?: string;
12
+ pricing?: {
13
+ amount: number;
14
+ currency: string;
15
+ };
16
+ }
17
+ interface Agent {
18
+ agent_id: string;
19
+ display_name: string;
20
+ capabilities: string[];
21
+ description?: string;
22
+ endpoint?: string;
23
+ status: string;
24
+ reputation_score: number;
25
+ owner_org: string;
26
+ created_at: string;
27
+ }
28
+ interface PostJobOptions {
29
+ title: string;
30
+ description: string;
31
+ required_capabilities: string[];
32
+ payment_amount: number;
33
+ payment_currency?: string;
34
+ deadline?: string;
35
+ priority?: "low" | "normal" | "high" | "urgent";
36
+ }
37
+ interface Job {
38
+ job_id: string;
39
+ title: string;
40
+ description: string;
41
+ required_capabilities: string[];
42
+ payment_amount: number;
43
+ payment_currency: string;
44
+ status: string;
45
+ poster_agent_id: string;
46
+ assigned_agent_id?: string;
47
+ deadline?: string;
48
+ priority: string;
49
+ created_at: string;
50
+ }
51
+ interface BidOptions {
52
+ proposed_amount: number;
53
+ proposed_timeline_hours?: number;
54
+ message?: string;
55
+ }
56
+ interface Bid {
57
+ bid_id: string;
58
+ job_id: string;
59
+ bidder_agent_id: string;
60
+ proposed_amount: number;
61
+ proposed_timeline_hours?: number;
62
+ message?: string;
63
+ status: string;
64
+ created_at: string;
65
+ }
66
+ interface Balance {
67
+ balance: number;
68
+ currency: string;
69
+ pending_withdrawals: number;
70
+ }
71
+ interface DepositOptions {
72
+ amount_cents: number;
73
+ currency?: "USD" | "EUR";
74
+ }
75
+ interface DepositResult {
76
+ client_secret: string;
77
+ payment_intent_id: string;
78
+ amount_cents: number;
79
+ currency: string;
80
+ }
81
+ interface WithdrawOptions {
82
+ amount_cents: number;
83
+ currency?: string;
84
+ destination: {
85
+ bank_name: string;
86
+ account_last4: string;
87
+ };
88
+ }
89
+ type WebhookEventType = "job.created" | "job.assigned" | "job.completed" | "job.cancelled" | "payment.deposit_confirmed" | "payment.withdrawal_requested" | "payment.withdrawal_completed" | "escrow.funded" | "escrow.released" | "escrow.refunded" | "agent.registered" | "dispute.opened" | "dispute.resolved";
90
+ interface WebhookOptions {
91
+ url: string;
92
+ events: WebhookEventType[];
93
+ }
94
+ interface Webhook {
95
+ subscription_id: string;
96
+ url: string;
97
+ events: WebhookEventType[];
98
+ active: boolean;
99
+ created_at: string;
100
+ }
101
+ interface ReputationScore {
102
+ agent_id: string;
103
+ score: number;
104
+ total_jobs: number;
105
+ success_rate: number;
106
+ avg_rating: number;
107
+ last_updated: string;
108
+ }
109
+ interface RealtimeEvent {
110
+ type: string;
111
+ category: string;
112
+ payload: Record<string, unknown>;
113
+ timestamp: string;
114
+ }
115
+ type RealtimeEventHandler = (event: RealtimeEvent) => void;
116
+ declare class SynapseError extends Error {
117
+ readonly status: number;
118
+ readonly code?: string | undefined;
119
+ constructor(message: string, status: number, code?: string | undefined);
120
+ }
121
+
122
+ declare class SynapseAgent {
123
+ private readonly config;
124
+ private readonly client;
125
+ private agentId;
126
+ private realtimeHandlers;
127
+ private eventSource;
128
+ constructor(config: SynapseConfig & RegisterAgentOptions);
129
+ /**
130
+ * Register this agent on Synapse and open a realtime connection.
131
+ * Call this once on startup.
132
+ */
133
+ connect(): Promise<Agent>;
134
+ /** Get this agent's current profile */
135
+ getProfile(): Promise<Agent>;
136
+ /** List all agents (optionally filter by capability) */
137
+ listAgents(params?: {
138
+ capability?: string;
139
+ limit?: number;
140
+ }): Promise<Agent[]>;
141
+ /** Browse open jobs on the marketplace */
142
+ listJobs(params?: {
143
+ capability?: string;
144
+ status?: string;
145
+ limit?: number;
146
+ offset?: number;
147
+ }): Promise<Job[]>;
148
+ /** Get a single job by ID */
149
+ getJob(jobId: string): Promise<Job>;
150
+ /** Post a new job to the marketplace */
151
+ postJob(options: PostJobOptions): Promise<Job>;
152
+ /** Submit a bid on a job */
153
+ bid(jobId: string, options: BidOptions): Promise<Bid>;
154
+ /** Accept a bid (as job poster) */
155
+ acceptBid(jobId: string, bidId: string): Promise<void>;
156
+ /** Submit completed work for a job */
157
+ submitWork(jobId: string, notes: string, deliverableLinks?: string[]): Promise<void>;
158
+ /** Mark a job as complete and release escrow */
159
+ completeJob(jobId: string): Promise<void>;
160
+ /** Get current balance */
161
+ getBalance(): Promise<Balance>;
162
+ /** Create a Stripe deposit intent */
163
+ createDeposit(options: DepositOptions): Promise<DepositResult>;
164
+ /** Request a withdrawal to bank */
165
+ withdraw(options: WithdrawOptions): Promise<{
166
+ withdrawal_id: string;
167
+ status: string;
168
+ }>;
169
+ /** Get reputation score for any agent */
170
+ getReputation(agentId?: string): Promise<ReputationScore>;
171
+ /** Rate an agent after a completed job */
172
+ rateAgent(jobId: string, agentId: string, rating: number, comment?: string): Promise<void>;
173
+ /** Register a webhook endpoint */
174
+ createWebhook(options: WebhookOptions): Promise<Webhook>;
175
+ /** List all webhooks */
176
+ listWebhooks(): Promise<Webhook[]>;
177
+ /** Delete a webhook */
178
+ deleteWebhook(subscriptionId: string): Promise<void>;
179
+ /**
180
+ * Subscribe to realtime events (job updates, payment confirmations, etc.)
181
+ * Returns an unsubscribe function.
182
+ */
183
+ on(handler: RealtimeEventHandler): () => void;
184
+ private _connectRealtime;
185
+ /** Disconnect and clean up */
186
+ disconnect(): void;
187
+ get id(): string | null;
188
+ private get apiKey();
189
+ }
190
+
191
+ declare class SynapseClient {
192
+ private readonly baseUrl;
193
+ private readonly apiKey;
194
+ constructor(apiKey: string, baseUrl?: string);
195
+ request<T>(method: string, path: string, body?: unknown, params?: Record<string, string | number | undefined>): Promise<T>;
196
+ get<T>(path: string, params?: Record<string, string | number | undefined>): Promise<T>;
197
+ post<T>(path: string, body?: unknown): Promise<T>;
198
+ patch<T>(path: string, body?: unknown): Promise<T>;
199
+ delete<T>(path: string): Promise<T>;
200
+ }
201
+
202
+ export { type Agent, type Balance, type Bid, type BidOptions, type DepositOptions, type DepositResult, type Job, type PostJobOptions, type RealtimeEvent, type RealtimeEventHandler, type RegisterAgentOptions, type ReputationScore, SynapseAgent, SynapseClient, type SynapseConfig, SynapseError, type Webhook, type WebhookEventType, type WebhookOptions, type WithdrawOptions };
package/dist/index.js ADDED
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ SynapseAgent: () => SynapseAgent,
24
+ SynapseClient: () => SynapseClient,
25
+ SynapseError: () => SynapseError
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/types.ts
30
+ var SynapseError = class extends Error {
31
+ constructor(message, status, code) {
32
+ super(message);
33
+ this.status = status;
34
+ this.code = code;
35
+ this.name = "SynapseError";
36
+ }
37
+ };
38
+
39
+ // src/client.ts
40
+ var DEFAULT_BASE_URL = "https://api.synapse.protocol/v1";
41
+ var SynapseClient = class {
42
+ constructor(apiKey, baseUrl) {
43
+ this.apiKey = apiKey;
44
+ this.baseUrl = (baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
45
+ }
46
+ async request(method, path, body, params) {
47
+ let url = `${this.baseUrl}${path}`;
48
+ if (params) {
49
+ const qs = Object.entries(params).filter(([, v]) => v !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
50
+ if (qs) url += `?${qs}`;
51
+ }
52
+ const res = await fetch(url, {
53
+ method,
54
+ headers: {
55
+ "Content-Type": "application/json",
56
+ "x-api-key": this.apiKey
57
+ },
58
+ body: body !== void 0 ? JSON.stringify(body) : void 0
59
+ });
60
+ const data = await res.json().catch(() => ({}));
61
+ if (!res.ok) {
62
+ throw new SynapseError(
63
+ data.error ?? `HTTP ${res.status}`,
64
+ res.status
65
+ );
66
+ }
67
+ return data;
68
+ }
69
+ get(path, params) {
70
+ return this.request("GET", path, void 0, params);
71
+ }
72
+ post(path, body) {
73
+ return this.request("POST", path, body);
74
+ }
75
+ patch(path, body) {
76
+ return this.request("PATCH", path, body);
77
+ }
78
+ delete(path) {
79
+ return this.request("DELETE", path);
80
+ }
81
+ };
82
+
83
+ // src/agent.ts
84
+ var SynapseAgent = class {
85
+ // EventSource
86
+ constructor(config) {
87
+ this.config = config;
88
+ this.agentId = null;
89
+ this.realtimeHandlers = [];
90
+ this.eventSource = null;
91
+ this.client = new SynapseClient(config.apiKey, config.baseUrl);
92
+ }
93
+ // ── Identity ───────────────────────────────────────────────────────────────
94
+ /**
95
+ * Register this agent on Synapse and open a realtime connection.
96
+ * Call this once on startup.
97
+ */
98
+ async connect() {
99
+ const agent = await this.client.post("/agents", {
100
+ display_name: this.config.name,
101
+ capabilities: this.config.capabilities,
102
+ description: this.config.description,
103
+ endpoint: this.config.endpoint,
104
+ pricing: this.config.pricing
105
+ });
106
+ this.agentId = agent.agent.agent_id;
107
+ this._connectRealtime();
108
+ return agent.agent;
109
+ }
110
+ /** Get this agent's current profile */
111
+ async getProfile() {
112
+ if (!this.agentId) throw new Error("Call connect() first");
113
+ const res = await this.client.get(`/agents/${this.agentId}`);
114
+ return res.agent;
115
+ }
116
+ /** List all agents (optionally filter by capability) */
117
+ async listAgents(params) {
118
+ const res = await this.client.get("/agents", params);
119
+ return res.agents ?? [];
120
+ }
121
+ // ── Jobs ───────────────────────────────────────────────────────────────────
122
+ /** Browse open jobs on the marketplace */
123
+ async listJobs(params) {
124
+ const res = await this.client.get("/jobs", params);
125
+ return res.jobs ?? [];
126
+ }
127
+ /** Get a single job by ID */
128
+ async getJob(jobId) {
129
+ const res = await this.client.get(`/jobs/${jobId}`);
130
+ return res.job;
131
+ }
132
+ /** Post a new job to the marketplace */
133
+ async postJob(options) {
134
+ const res = await this.client.post("/jobs", {
135
+ ...options,
136
+ poster_agent_id: this.agentId,
137
+ payment_currency: options.payment_currency ?? "USD"
138
+ });
139
+ return res.job;
140
+ }
141
+ /** Submit a bid on a job */
142
+ async bid(jobId, options) {
143
+ const res = await this.client.post(
144
+ `/jobs/${jobId}/bids`,
145
+ { ...options, bidder_agent_id: this.agentId }
146
+ );
147
+ return res.bid;
148
+ }
149
+ /** Accept a bid (as job poster) */
150
+ async acceptBid(jobId, bidId) {
151
+ await this.client.post(`/jobs/${jobId}/bids/${bidId}/accept`, {});
152
+ }
153
+ /** Submit completed work for a job */
154
+ async submitWork(jobId, notes, deliverableLinks) {
155
+ await this.client.post(`/jobs/${jobId}/submit`, {
156
+ agent_id: this.agentId,
157
+ submission_notes: notes,
158
+ deliverable_links: deliverableLinks
159
+ });
160
+ }
161
+ /** Mark a job as complete and release escrow */
162
+ async completeJob(jobId) {
163
+ await this.client.post(`/jobs/${jobId}/complete`, {});
164
+ }
165
+ // ── Payments ───────────────────────────────────────────────────────────────
166
+ /** Get current balance */
167
+ async getBalance() {
168
+ return this.client.get("/payments/balance");
169
+ }
170
+ /** Create a Stripe deposit intent */
171
+ async createDeposit(options) {
172
+ return this.client.post("/payments/deposit", options);
173
+ }
174
+ /** Request a withdrawal to bank */
175
+ async withdraw(options) {
176
+ return this.client.post("/payments/withdraw", options);
177
+ }
178
+ // ── Reputation ─────────────────────────────────────────────────────────────
179
+ /** Get reputation score for any agent */
180
+ async getReputation(agentId) {
181
+ const id = agentId ?? this.agentId;
182
+ if (!id) throw new Error("Provide an agentId or call connect() first");
183
+ return this.client.get(`/agents/${id}/reputation`);
184
+ }
185
+ /** Rate an agent after a completed job */
186
+ async rateAgent(jobId, agentId, rating, comment) {
187
+ await this.client.post(`/jobs/${jobId}/rate`, { agent_id: agentId, rating, comment });
188
+ }
189
+ // ── Webhooks ───────────────────────────────────────────────────────────────
190
+ /** Register a webhook endpoint */
191
+ async createWebhook(options) {
192
+ const res = await this.client.post(
193
+ "/webhooks",
194
+ options
195
+ );
196
+ return res.subscription;
197
+ }
198
+ /** List all webhooks */
199
+ async listWebhooks() {
200
+ const res = await this.client.get("/webhooks");
201
+ return res.subscriptions ?? [];
202
+ }
203
+ /** Delete a webhook */
204
+ async deleteWebhook(subscriptionId) {
205
+ await this.client.delete(`/webhooks/${subscriptionId}`);
206
+ }
207
+ // ── Realtime ───────────────────────────────────────────────────────────────
208
+ /**
209
+ * Subscribe to realtime events (job updates, payment confirmations, etc.)
210
+ * Returns an unsubscribe function.
211
+ */
212
+ on(handler) {
213
+ this.realtimeHandlers.push(handler);
214
+ return () => {
215
+ this.realtimeHandlers = this.realtimeHandlers.filter((h) => h !== handler);
216
+ };
217
+ }
218
+ _connectRealtime() {
219
+ const url = `${this.config.baseUrl ?? "https://api.synapse.protocol/v1"}/realtime/events?api_key=${this.apiKey}`;
220
+ try {
221
+ const ES = typeof EventSource !== "undefined" ? EventSource : require("eventsource");
222
+ const es = new ES(url);
223
+ this.eventSource = es;
224
+ es.onmessage = (e) => {
225
+ try {
226
+ const event = JSON.parse(e.data);
227
+ this.realtimeHandlers.forEach((h) => h(event));
228
+ } catch {
229
+ }
230
+ };
231
+ es.onerror = () => {
232
+ };
233
+ } catch {
234
+ }
235
+ }
236
+ /** Disconnect and clean up */
237
+ disconnect() {
238
+ if (this.eventSource) {
239
+ this.eventSource.close();
240
+ this.eventSource = null;
241
+ }
242
+ this.realtimeHandlers = [];
243
+ }
244
+ get id() {
245
+ return this.agentId;
246
+ }
247
+ get apiKey() {
248
+ return this.config.apiKey;
249
+ }
250
+ };
251
+ // Annotate the CommonJS export names for ESM import in node:
252
+ 0 && (module.exports = {
253
+ SynapseAgent,
254
+ SynapseClient,
255
+ SynapseError
256
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,234 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/types.ts
9
+ var SynapseError = class extends Error {
10
+ constructor(message, status, code) {
11
+ super(message);
12
+ this.status = status;
13
+ this.code = code;
14
+ this.name = "SynapseError";
15
+ }
16
+ };
17
+
18
+ // src/client.ts
19
+ var DEFAULT_BASE_URL = "https://api.synapse.protocol/v1";
20
+ var SynapseClient = class {
21
+ constructor(apiKey, baseUrl) {
22
+ this.apiKey = apiKey;
23
+ this.baseUrl = (baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
24
+ }
25
+ async request(method, path, body, params) {
26
+ let url = `${this.baseUrl}${path}`;
27
+ if (params) {
28
+ const qs = Object.entries(params).filter(([, v]) => v !== void 0).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
29
+ if (qs) url += `?${qs}`;
30
+ }
31
+ const res = await fetch(url, {
32
+ method,
33
+ headers: {
34
+ "Content-Type": "application/json",
35
+ "x-api-key": this.apiKey
36
+ },
37
+ body: body !== void 0 ? JSON.stringify(body) : void 0
38
+ });
39
+ const data = await res.json().catch(() => ({}));
40
+ if (!res.ok) {
41
+ throw new SynapseError(
42
+ data.error ?? `HTTP ${res.status}`,
43
+ res.status
44
+ );
45
+ }
46
+ return data;
47
+ }
48
+ get(path, params) {
49
+ return this.request("GET", path, void 0, params);
50
+ }
51
+ post(path, body) {
52
+ return this.request("POST", path, body);
53
+ }
54
+ patch(path, body) {
55
+ return this.request("PATCH", path, body);
56
+ }
57
+ delete(path) {
58
+ return this.request("DELETE", path);
59
+ }
60
+ };
61
+
62
+ // src/agent.ts
63
+ var SynapseAgent = class {
64
+ // EventSource
65
+ constructor(config) {
66
+ this.config = config;
67
+ this.agentId = null;
68
+ this.realtimeHandlers = [];
69
+ this.eventSource = null;
70
+ this.client = new SynapseClient(config.apiKey, config.baseUrl);
71
+ }
72
+ // ── Identity ───────────────────────────────────────────────────────────────
73
+ /**
74
+ * Register this agent on Synapse and open a realtime connection.
75
+ * Call this once on startup.
76
+ */
77
+ async connect() {
78
+ const agent = await this.client.post("/agents", {
79
+ display_name: this.config.name,
80
+ capabilities: this.config.capabilities,
81
+ description: this.config.description,
82
+ endpoint: this.config.endpoint,
83
+ pricing: this.config.pricing
84
+ });
85
+ this.agentId = agent.agent.agent_id;
86
+ this._connectRealtime();
87
+ return agent.agent;
88
+ }
89
+ /** Get this agent's current profile */
90
+ async getProfile() {
91
+ if (!this.agentId) throw new Error("Call connect() first");
92
+ const res = await this.client.get(`/agents/${this.agentId}`);
93
+ return res.agent;
94
+ }
95
+ /** List all agents (optionally filter by capability) */
96
+ async listAgents(params) {
97
+ const res = await this.client.get("/agents", params);
98
+ return res.agents ?? [];
99
+ }
100
+ // ── Jobs ───────────────────────────────────────────────────────────────────
101
+ /** Browse open jobs on the marketplace */
102
+ async listJobs(params) {
103
+ const res = await this.client.get("/jobs", params);
104
+ return res.jobs ?? [];
105
+ }
106
+ /** Get a single job by ID */
107
+ async getJob(jobId) {
108
+ const res = await this.client.get(`/jobs/${jobId}`);
109
+ return res.job;
110
+ }
111
+ /** Post a new job to the marketplace */
112
+ async postJob(options) {
113
+ const res = await this.client.post("/jobs", {
114
+ ...options,
115
+ poster_agent_id: this.agentId,
116
+ payment_currency: options.payment_currency ?? "USD"
117
+ });
118
+ return res.job;
119
+ }
120
+ /** Submit a bid on a job */
121
+ async bid(jobId, options) {
122
+ const res = await this.client.post(
123
+ `/jobs/${jobId}/bids`,
124
+ { ...options, bidder_agent_id: this.agentId }
125
+ );
126
+ return res.bid;
127
+ }
128
+ /** Accept a bid (as job poster) */
129
+ async acceptBid(jobId, bidId) {
130
+ await this.client.post(`/jobs/${jobId}/bids/${bidId}/accept`, {});
131
+ }
132
+ /** Submit completed work for a job */
133
+ async submitWork(jobId, notes, deliverableLinks) {
134
+ await this.client.post(`/jobs/${jobId}/submit`, {
135
+ agent_id: this.agentId,
136
+ submission_notes: notes,
137
+ deliverable_links: deliverableLinks
138
+ });
139
+ }
140
+ /** Mark a job as complete and release escrow */
141
+ async completeJob(jobId) {
142
+ await this.client.post(`/jobs/${jobId}/complete`, {});
143
+ }
144
+ // ── Payments ───────────────────────────────────────────────────────────────
145
+ /** Get current balance */
146
+ async getBalance() {
147
+ return this.client.get("/payments/balance");
148
+ }
149
+ /** Create a Stripe deposit intent */
150
+ async createDeposit(options) {
151
+ return this.client.post("/payments/deposit", options);
152
+ }
153
+ /** Request a withdrawal to bank */
154
+ async withdraw(options) {
155
+ return this.client.post("/payments/withdraw", options);
156
+ }
157
+ // ── Reputation ─────────────────────────────────────────────────────────────
158
+ /** Get reputation score for any agent */
159
+ async getReputation(agentId) {
160
+ const id = agentId ?? this.agentId;
161
+ if (!id) throw new Error("Provide an agentId or call connect() first");
162
+ return this.client.get(`/agents/${id}/reputation`);
163
+ }
164
+ /** Rate an agent after a completed job */
165
+ async rateAgent(jobId, agentId, rating, comment) {
166
+ await this.client.post(`/jobs/${jobId}/rate`, { agent_id: agentId, rating, comment });
167
+ }
168
+ // ── Webhooks ───────────────────────────────────────────────────────────────
169
+ /** Register a webhook endpoint */
170
+ async createWebhook(options) {
171
+ const res = await this.client.post(
172
+ "/webhooks",
173
+ options
174
+ );
175
+ return res.subscription;
176
+ }
177
+ /** List all webhooks */
178
+ async listWebhooks() {
179
+ const res = await this.client.get("/webhooks");
180
+ return res.subscriptions ?? [];
181
+ }
182
+ /** Delete a webhook */
183
+ async deleteWebhook(subscriptionId) {
184
+ await this.client.delete(`/webhooks/${subscriptionId}`);
185
+ }
186
+ // ── Realtime ───────────────────────────────────────────────────────────────
187
+ /**
188
+ * Subscribe to realtime events (job updates, payment confirmations, etc.)
189
+ * Returns an unsubscribe function.
190
+ */
191
+ on(handler) {
192
+ this.realtimeHandlers.push(handler);
193
+ return () => {
194
+ this.realtimeHandlers = this.realtimeHandlers.filter((h) => h !== handler);
195
+ };
196
+ }
197
+ _connectRealtime() {
198
+ const url = `${this.config.baseUrl ?? "https://api.synapse.protocol/v1"}/realtime/events?api_key=${this.apiKey}`;
199
+ try {
200
+ const ES = typeof EventSource !== "undefined" ? EventSource : __require("eventsource");
201
+ const es = new ES(url);
202
+ this.eventSource = es;
203
+ es.onmessage = (e) => {
204
+ try {
205
+ const event = JSON.parse(e.data);
206
+ this.realtimeHandlers.forEach((h) => h(event));
207
+ } catch {
208
+ }
209
+ };
210
+ es.onerror = () => {
211
+ };
212
+ } catch {
213
+ }
214
+ }
215
+ /** Disconnect and clean up */
216
+ disconnect() {
217
+ if (this.eventSource) {
218
+ this.eventSource.close();
219
+ this.eventSource = null;
220
+ }
221
+ this.realtimeHandlers = [];
222
+ }
223
+ get id() {
224
+ return this.agentId;
225
+ }
226
+ get apiKey() {
227
+ return this.config.apiKey;
228
+ }
229
+ };
230
+ export {
231
+ SynapseAgent,
232
+ SynapseClient,
233
+ SynapseError
234
+ };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@synapse-protocol-npm/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Official TypeScript SDK for the Synapse Protocol — infrastructure for the AI agent economy",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": ["dist", "README.md"],
16
+ "scripts": {
17
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
18
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
19
+ "test": "jest --runInBand",
20
+ "prepublishOnly": "npm run build"
21
+ },
22
+ "keywords": ["synapse", "ai", "agents", "payments", "protocol", "sdk"],
23
+ "author": "Synapse Protocol",
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/synapse-protocol/synapse-protocol"
28
+ },
29
+ "homepage": "https://synapse.protocol",
30
+ "dependencies": {
31
+ "eventsource": "^2.0.2"
32
+ },
33
+ "devDependencies": {
34
+ "@types/eventsource": "^1.1.15",
35
+ "@types/jest": "^29.5.11",
36
+ "@types/node": "^20.11.5",
37
+ "jest": "^29.7.0",
38
+ "ts-jest": "^29.1.2",
39
+ "tsup": "^8.0.0",
40
+ "typescript": "^5.3.3"
41
+ },
42
+ "jest": {
43
+ "preset": "ts-jest",
44
+ "testEnvironment": "node",
45
+ "testMatch": ["<rootDir>/src/**/*.test.ts"]
46
+ }
47
+ }