@backwrite/sdk 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -23
- package/dist/agents.d.ts +207 -0
- package/dist/agents.d.ts.map +1 -0
- package/dist/agents.js +340 -0
- package/dist/agents.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +43 -3
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/services.d.ts +9 -8
- package/dist/services.d.ts.map +1 -1
- package/dist/services.js +28 -29
- package/dist/services.js.map +1 -1
- package/package.json +20 -2
- package/src/agents.ts +476 -0
- package/src/client.ts +47 -3
- package/src/index.ts +1 -0
- package/src/services.ts +28 -29
package/src/agents.ts
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
//! Agentic State Management & Agent Plugins 1.0.0 primitives for @backwrite/sdk v0.3.0.
|
|
2
|
+
//!
|
|
3
|
+
//! - `backwrite.workspaces`: Provision isolated Agent Workspaces pairing Git worktrees
|
|
4
|
+
//! with disposable Copy-on-Write PostgreSQL 18 branches.
|
|
5
|
+
//! - `backwrite.agents`: Stream agent thoughts/tool logs over Backwrite Realtime / NATS
|
|
6
|
+
//! JetStream and coordinate parallel agents with Valkey-backed Agent Lockfiles.
|
|
7
|
+
//! - `backwrite.plugins`: Programmatically export Agent Plugins 1.0.0 bundles
|
|
8
|
+
//! (`plugin.json`, `mcp.json`, live `schema.json`, and `skills/*/SKILL.md`).
|
|
9
|
+
|
|
10
|
+
import type { BackwriteClient } from "./client.js";
|
|
11
|
+
import type { ScopeOptions } from "./services.js";
|
|
12
|
+
|
|
13
|
+
function slugify(input: string): string {
|
|
14
|
+
return (
|
|
15
|
+
String(input || "agent-workspace")
|
|
16
|
+
.toLowerCase()
|
|
17
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
18
|
+
.replace(/^-+|-+$/g, "")
|
|
19
|
+
.slice(0, 40) || "agent-workspace"
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function requireProject(client: BackwriteClient, override?: string): string {
|
|
24
|
+
const id = override || client.projectId;
|
|
25
|
+
if (!id) {
|
|
26
|
+
throw new Error("Backwrite SDK: projectId is required (set on client options or method options).");
|
|
27
|
+
}
|
|
28
|
+
return id;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function requireBranch(client: BackwriteClient, override?: string): string {
|
|
32
|
+
const id = override || client.branchId;
|
|
33
|
+
if (!id) {
|
|
34
|
+
throw new Error("Backwrite SDK: branchId is required (set on client options or method options).");
|
|
35
|
+
}
|
|
36
|
+
return id;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ── Agent Workspace ──────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
export interface CreateWorkspaceOptions {
|
|
42
|
+
/** Task or agent name slug (default: generated unique agent workspace name). */
|
|
43
|
+
name?: string;
|
|
44
|
+
/** Git base branch to branch the worktree from (default: "main"). */
|
|
45
|
+
baseBranch?: string;
|
|
46
|
+
/** Provision a disposable PostgreSQL 18 CoW branch (default: true). */
|
|
47
|
+
isolatedDb?: boolean;
|
|
48
|
+
/** Include Git worktree coordinates & commands (default: true). */
|
|
49
|
+
gitWorktree?: boolean;
|
|
50
|
+
/** Copy-on-Write creation mode (default: "schema-only"). */
|
|
51
|
+
mode?: "schema-only" | "full-copy";
|
|
52
|
+
/** Target Backwrite Project ID (defaults to client.projectId). */
|
|
53
|
+
projectId?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface AgentWorkspaceInfo {
|
|
57
|
+
workspaceId: string;
|
|
58
|
+
projectId: string;
|
|
59
|
+
branchId: string;
|
|
60
|
+
operationId?: string;
|
|
61
|
+
gitBranch: string;
|
|
62
|
+
worktreePath: string;
|
|
63
|
+
gitWorktreeCommand: string;
|
|
64
|
+
cleanupCommand: string;
|
|
65
|
+
envTemplate: Record<string, string>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Unified handle tying a local Git worktree specification to an isolated
|
|
70
|
+
* Backwrite Copy-on-Write PostgreSQL 18 branch, lockfile namespace, and event stream.
|
|
71
|
+
*/
|
|
72
|
+
export class AgentWorkspace {
|
|
73
|
+
readonly workspaceId: string;
|
|
74
|
+
readonly projectId: string;
|
|
75
|
+
readonly branchId: string;
|
|
76
|
+
readonly operationId?: string;
|
|
77
|
+
readonly gitBranch: string;
|
|
78
|
+
readonly worktreePath: string;
|
|
79
|
+
readonly gitWorktreeCommand: string;
|
|
80
|
+
readonly cleanupCommand: string;
|
|
81
|
+
readonly envTemplate: Record<string, string>;
|
|
82
|
+
|
|
83
|
+
constructor(
|
|
84
|
+
private readonly client: BackwriteClient,
|
|
85
|
+
info: AgentWorkspaceInfo,
|
|
86
|
+
) {
|
|
87
|
+
this.workspaceId = info.workspaceId;
|
|
88
|
+
this.projectId = info.projectId;
|
|
89
|
+
this.branchId = info.branchId;
|
|
90
|
+
this.operationId = info.operationId;
|
|
91
|
+
this.gitBranch = info.gitBranch;
|
|
92
|
+
this.worktreePath = info.worktreePath;
|
|
93
|
+
this.gitWorktreeCommand = info.gitWorktreeCommand;
|
|
94
|
+
this.cleanupCommand = info.cleanupCommand;
|
|
95
|
+
this.envTemplate = info.envTemplate;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Execute SQL scoped strictly to this workspace's isolated CoW branch. */
|
|
99
|
+
async query(sql: string) {
|
|
100
|
+
return this.client.query(this.projectId, sql, { branchId: this.branchId });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Introspect this workspace's isolated branch schema. */
|
|
104
|
+
async getSchema() {
|
|
105
|
+
return this.client.getSchema(this.projectId, { branchId: this.branchId });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Acquire a distributed file lock so parallel agents do not edit the same file. */
|
|
109
|
+
async acquireLock(filePath: string, ttlSeconds = 600) {
|
|
110
|
+
return this.client.agents.locks.acquire(filePath, {
|
|
111
|
+
agentId: this.workspaceId,
|
|
112
|
+
branchId: this.branchId,
|
|
113
|
+
ttlSeconds,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Release a previously acquired file lock. */
|
|
118
|
+
async releaseLock(filePath: string) {
|
|
119
|
+
return this.client.agents.locks.release(filePath, {
|
|
120
|
+
agentId: this.workspaceId,
|
|
121
|
+
branchId: this.branchId,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Emit a structured status/log event for this agent workspace over Realtime / NATS. */
|
|
126
|
+
async emit(event: string, message: string, metadata: Record<string, unknown> = {}) {
|
|
127
|
+
return this.client.agents.emit(this.workspaceId, event, message, {
|
|
128
|
+
branchId: this.branchId,
|
|
129
|
+
metadata,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Tear down the disposable PostgreSQL 18 branch associated with this workspace. */
|
|
134
|
+
async destroy() {
|
|
135
|
+
if (!this.branchId) return { deleted: false };
|
|
136
|
+
return this.client.branches.delete(this.branchId);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export class AgentWorkspacesService {
|
|
141
|
+
constructor(private readonly client: BackwriteClient) {}
|
|
142
|
+
|
|
143
|
+
async create(options: CreateWorkspaceOptions = {}): Promise<AgentWorkspace> {
|
|
144
|
+
const projectId = requireProject(this.client, options.projectId);
|
|
145
|
+
const slug = slugify(options.name || `task-${Date.now().toString(36)}`);
|
|
146
|
+
const workspaceId = `agent-${slug}-${Date.now().toString(36).slice(-4)}`;
|
|
147
|
+
const baseBranch = options.baseBranch || "main";
|
|
148
|
+
const gitBranch = `agent/${slug}`;
|
|
149
|
+
const worktreePath = `.backwrite/worktrees/${workspaceId}`;
|
|
150
|
+
|
|
151
|
+
let branchId = this.client.branchId || "";
|
|
152
|
+
let operationId: string | undefined;
|
|
153
|
+
|
|
154
|
+
if (options.isolatedDb !== false) {
|
|
155
|
+
const created = (await this.client.request(
|
|
156
|
+
"POST",
|
|
157
|
+
`/v1/projects/${encodeURIComponent(projectId)}/branches`,
|
|
158
|
+
{
|
|
159
|
+
body: {
|
|
160
|
+
name: workspaceId,
|
|
161
|
+
branch_type: "preview",
|
|
162
|
+
mode: options.mode || "schema-only",
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
)) as { branch_id?: string; id?: string; operation_id?: string };
|
|
166
|
+
branchId = created.branch_id || created.id || branchId;
|
|
167
|
+
operationId = created.operation_id;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const useWorktree = options.gitWorktree !== false;
|
|
171
|
+
return new AgentWorkspace(this.client, {
|
|
172
|
+
workspaceId,
|
|
173
|
+
projectId,
|
|
174
|
+
branchId,
|
|
175
|
+
operationId,
|
|
176
|
+
gitBranch,
|
|
177
|
+
worktreePath,
|
|
178
|
+
gitWorktreeCommand: useWorktree
|
|
179
|
+
? `git worktree add -b ${gitBranch} ${worktreePath} ${baseBranch}`
|
|
180
|
+
: "",
|
|
181
|
+
cleanupCommand: useWorktree
|
|
182
|
+
? `git worktree remove ${worktreePath} && git branch -d ${gitBranch}`
|
|
183
|
+
: "",
|
|
184
|
+
envTemplate: {
|
|
185
|
+
BACKWRITE_PROJECT_ID: projectId,
|
|
186
|
+
BACKWRITE_BRANCH_ID: branchId,
|
|
187
|
+
DATABASE_URL: "postgresql://<ROLE>:<PASSWORD>@pooler.backwrite.dev:6543/<DB>?sslmode=require",
|
|
188
|
+
DIRECT_URL: "postgresql://<ROLE>:<PASSWORD>@db.backwrite.dev:5432/<DB>?sslmode=require",
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async list(scope: ScopeOptions = {}) {
|
|
194
|
+
const projectId = requireProject(this.client, scope.projectId);
|
|
195
|
+
return this.client.branches.list(projectId);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async destroy(branchId: string) {
|
|
199
|
+
return this.client.branches.delete(branchId);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ── Distributed Agent Lockfiles & Realtime Event Streaming ───────────────────
|
|
204
|
+
|
|
205
|
+
export interface AgentLockResult {
|
|
206
|
+
filePath: string;
|
|
207
|
+
acquired: boolean;
|
|
208
|
+
contested: boolean;
|
|
209
|
+
heldBy?: string;
|
|
210
|
+
since?: string;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export class AgentLocksService {
|
|
214
|
+
constructor(private readonly client: BackwriteClient) {}
|
|
215
|
+
|
|
216
|
+
private lockKey(filePath: string): string {
|
|
217
|
+
const normalized = String(filePath || "").replace(/^\/+/, "");
|
|
218
|
+
if (!normalized || normalized.includes("..")) {
|
|
219
|
+
throw new Error(`Backwrite SDK: invalid lockfile path '${filePath}'`);
|
|
220
|
+
}
|
|
221
|
+
return `bw:lock:${encodeURIComponent(normalized)}`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async check(filePath: string, opts: { branchId?: string } = {}): Promise<AgentLockResult> {
|
|
225
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
226
|
+
const key = this.lockKey(filePath);
|
|
227
|
+
try {
|
|
228
|
+
const entry = (await this.client.cache.get(key, branchId)) as { value?: string };
|
|
229
|
+
if (entry?.value) {
|
|
230
|
+
const parsed = typeof entry.value === "string" ? JSON.parse(entry.value) : entry.value;
|
|
231
|
+
return {
|
|
232
|
+
filePath,
|
|
233
|
+
acquired: false,
|
|
234
|
+
contested: true,
|
|
235
|
+
heldBy: parsed.agent_id,
|
|
236
|
+
since: parsed.acquired_at,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
} catch {
|
|
240
|
+
// Cache miss means unlocked
|
|
241
|
+
}
|
|
242
|
+
return { filePath, acquired: false, contested: false };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async acquire(
|
|
246
|
+
filePath: string,
|
|
247
|
+
opts: { agentId: string; branchId?: string; ttlSeconds?: number },
|
|
248
|
+
): Promise<AgentLockResult> {
|
|
249
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
250
|
+
const existing = await this.check(filePath, { branchId });
|
|
251
|
+
if (existing.contested && existing.heldBy && existing.heldBy !== opts.agentId) {
|
|
252
|
+
return existing;
|
|
253
|
+
}
|
|
254
|
+
const now = new Date().toISOString();
|
|
255
|
+
await this.client.cache.set(
|
|
256
|
+
this.lockKey(filePath),
|
|
257
|
+
JSON.stringify({ agent_id: opts.agentId, file_path: filePath, acquired_at: now }),
|
|
258
|
+
opts.ttlSeconds ?? 600,
|
|
259
|
+
branchId,
|
|
260
|
+
);
|
|
261
|
+
return { filePath, acquired: true, contested: false, heldBy: opts.agentId, since: now };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async release(filePath: string, opts: { agentId?: string; branchId?: string } = {}) {
|
|
265
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
266
|
+
await this.client.cache.del(this.lockKey(filePath), branchId).catch(() => ({}));
|
|
267
|
+
return { filePath, released: true, agentId: opts.agentId };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export interface AgentEvent {
|
|
272
|
+
agentId: string;
|
|
273
|
+
event: string;
|
|
274
|
+
message: string;
|
|
275
|
+
metadata?: Record<string, unknown>;
|
|
276
|
+
ts: string;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export class AgentsService {
|
|
280
|
+
readonly locks: AgentLocksService;
|
|
281
|
+
|
|
282
|
+
constructor(private readonly client: BackwriteClient) {
|
|
283
|
+
this.locks = new AgentLocksService(client);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Publish a structured agent event over Backwrite Realtime / NATS JetStream. */
|
|
287
|
+
async emit(
|
|
288
|
+
agentId: string,
|
|
289
|
+
event: string,
|
|
290
|
+
message: string,
|
|
291
|
+
opts: { branchId?: string; metadata?: Record<string, unknown> } = {},
|
|
292
|
+
) {
|
|
293
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
294
|
+
return this.client.realtime.broadcast(
|
|
295
|
+
`agent:${agentId}`,
|
|
296
|
+
event,
|
|
297
|
+
{
|
|
298
|
+
agent_id: agentId,
|
|
299
|
+
message,
|
|
300
|
+
metadata: opts.metadata || {},
|
|
301
|
+
ts: new Date().toISOString(),
|
|
302
|
+
},
|
|
303
|
+
branchId,
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Subscribe to live agent events over Backwrite Realtime WebSocket (when available)
|
|
309
|
+
* using a short-lived signed WS ticket. Returns an unsubscribe handle.
|
|
310
|
+
*/
|
|
311
|
+
async subscribe(
|
|
312
|
+
agentId: string,
|
|
313
|
+
onEvent: (ev: AgentEvent) => void,
|
|
314
|
+
opts: { branchId?: string; onError?: (err: unknown) => void } = {},
|
|
315
|
+
): Promise<{ channel: string; ticket: unknown; unsubscribe: () => void }> {
|
|
316
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
317
|
+
const channel = `agent:${agentId}`;
|
|
318
|
+
const ticket = (await this.client.realtime.createTicket(branchId)) as {
|
|
319
|
+
ws_url?: string;
|
|
320
|
+
url?: string;
|
|
321
|
+
ticket?: string;
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
let ws: WebSocket | null = null;
|
|
325
|
+
const wsUrl = ticket?.ws_url || ticket?.url;
|
|
326
|
+
if (wsUrl && typeof globalThis.WebSocket === "function") {
|
|
327
|
+
try {
|
|
328
|
+
const finalUrl = ticket?.ticket
|
|
329
|
+
? `${wsUrl}${wsUrl.includes("?") ? "&" : "?"}ticket=${encodeURIComponent(ticket.ticket)}`
|
|
330
|
+
: wsUrl;
|
|
331
|
+
ws = new globalThis.WebSocket(finalUrl);
|
|
332
|
+
ws.onmessage = (msg) => {
|
|
333
|
+
try {
|
|
334
|
+
const parsed = JSON.parse(String(msg.data));
|
|
335
|
+
const payload = parsed.payload || parsed;
|
|
336
|
+
onEvent({
|
|
337
|
+
agentId: payload.agent_id || agentId,
|
|
338
|
+
event: parsed.event || payload.event || "message",
|
|
339
|
+
message: payload.message || JSON.stringify(payload),
|
|
340
|
+
metadata: payload.metadata,
|
|
341
|
+
ts: payload.ts || new Date().toISOString(),
|
|
342
|
+
});
|
|
343
|
+
} catch {
|
|
344
|
+
// Ignore non-JSON heartbeat frames
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
ws.onerror = (err) => opts.onError?.(err);
|
|
348
|
+
} catch (err) {
|
|
349
|
+
opts.onError?.(err);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
channel,
|
|
355
|
+
ticket,
|
|
356
|
+
unsubscribe: () => {
|
|
357
|
+
try {
|
|
358
|
+
ws?.close();
|
|
359
|
+
} catch {
|
|
360
|
+
// Safe cleanup
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ── Agent Plugins 1.0.0 Programmatic Generator ───────────────────────────────
|
|
368
|
+
|
|
369
|
+
export interface ExportPluginOptions {
|
|
370
|
+
/** Plugin name (e.g. "MySaaS-Agent-Core"). */
|
|
371
|
+
name: string;
|
|
372
|
+
/** Optional description for plugin.json. */
|
|
373
|
+
description?: string;
|
|
374
|
+
/** Embed live relational schema from Backwrite into schema.json (default: true). */
|
|
375
|
+
includeSchema?: boolean;
|
|
376
|
+
/** Skill names to generate under skills/<name>/SKILL.md. */
|
|
377
|
+
generateSkills?: string[];
|
|
378
|
+
/** Override projectId / branchId. */
|
|
379
|
+
projectId?: string;
|
|
380
|
+
branchId?: string;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export interface ExportedAgentPlugin {
|
|
384
|
+
standard: "1.0.0";
|
|
385
|
+
name: string;
|
|
386
|
+
/** Map of relative file paths (`plugin.json`, `mcp.json`, `skills/.../SKILL.md`) to UTF-8 content. */
|
|
387
|
+
files: Record<string, string>;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
export class PluginsService {
|
|
391
|
+
constructor(private readonly client: BackwriteClient) {}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Generate a complete Agent Plugins 1.0.0 bundle (pure data — zero fs dependency,
|
|
395
|
+
* works identically in Node.js, Edge runtimes, and browsers).
|
|
396
|
+
*/
|
|
397
|
+
async export(options: ExportPluginOptions): Promise<ExportedAgentPlugin> {
|
|
398
|
+
const safeName = slugify(options.name);
|
|
399
|
+
const projectId = options.projectId || this.client.projectId || "";
|
|
400
|
+
const branchId = options.branchId || this.client.branchId || "";
|
|
401
|
+
const skills =
|
|
402
|
+
options.generateSkills && options.generateSkills.length > 0
|
|
403
|
+
? options.generateSkills
|
|
404
|
+
: ["bw-migrations", "bw-deploy", "database-troubleshooting", "api-generation"];
|
|
405
|
+
|
|
406
|
+
let schemaSnapshot: unknown = undefined;
|
|
407
|
+
if (options.includeSchema !== false && projectId) {
|
|
408
|
+
schemaSnapshot = await this.client
|
|
409
|
+
.getSchema(projectId, branchId ? { branchId } : {})
|
|
410
|
+
.catch(() => undefined);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const files: Record<string, string> = {
|
|
414
|
+
"plugin.json": JSON.stringify(
|
|
415
|
+
{
|
|
416
|
+
schemaVersion: "1.0.0",
|
|
417
|
+
name: safeName,
|
|
418
|
+
version: "1.0.0",
|
|
419
|
+
description:
|
|
420
|
+
options.description ||
|
|
421
|
+
`Backwrite Agent Plugin for ${options.name} — CoW PostgreSQL 18 branching, 36 MCP tools, and Agent Skills.`,
|
|
422
|
+
mcpConfig: "./mcp.json",
|
|
423
|
+
skillsDir: "./skills",
|
|
424
|
+
backwrite: {
|
|
425
|
+
projectIdEnv: "BACKWRITE_PROJECT_ID",
|
|
426
|
+
branchIdEnv: "BACKWRITE_BRANCH_ID",
|
|
427
|
+
},
|
|
428
|
+
},
|
|
429
|
+
null,
|
|
430
|
+
2,
|
|
431
|
+
),
|
|
432
|
+
"mcp.json": JSON.stringify(
|
|
433
|
+
{
|
|
434
|
+
mcpServers: {
|
|
435
|
+
backwrite: {
|
|
436
|
+
command: "npx",
|
|
437
|
+
args: ["-y", "@backwrite/mcp@0.3.0"],
|
|
438
|
+
env: {
|
|
439
|
+
BACKWRITE_URL: "https://api.backwrite.dev",
|
|
440
|
+
BACKWRITE_SERVICE_KEY: "${BACKWRITE_SERVICE_KEY}",
|
|
441
|
+
BACKWRITE_PROJECT_ID: "${BACKWRITE_PROJECT_ID}",
|
|
442
|
+
BACKWRITE_BRANCH_ID: "${BACKWRITE_BRANCH_ID}",
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
},
|
|
446
|
+
},
|
|
447
|
+
null,
|
|
448
|
+
2,
|
|
449
|
+
),
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
if (schemaSnapshot !== undefined) {
|
|
453
|
+
files["schema.json"] = JSON.stringify(schemaSnapshot, null, 2);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const templates: Record<string, string> = {
|
|
457
|
+
"bw-migrations": `---\nname: bw-migrations\ndescription: Run schema migrations safely on isolated Backwrite PostgreSQL 18 CoW branches.\n---\n\n# Safe Migrations SOP\n\n1. Always call \`backwrite_spawn_worktree\` before editing migrations.\n2. Acquire file locks via \`backwrite_workspace_lock\` to avoid parallel agent conflicts.\n3. Validate DDL with \`backwrite_sync_schema(run_advisors=true)\` and fix RLS/index findings.\n4. Hand off via \`bw review <agent-id>\` for human merge approval.\n`,
|
|
458
|
+
"bw-deploy": `---\nname: bw-deploy\ndescription: Pre-deploy verification for PgBouncer pooling, Advisors, and PITR snapshots.\n---\n\n# Deploy Readiness SOP\n\n1. Read \`backwrite://architecture/topology\` and \`backwrite://advisors/findings\`.\n2. Take a pre-deploy snapshot via \`backwrite_create_snapshot\`.\n3. Verify application connections point to \`pooler.backwrite.dev:6543?sslmode=require\`.\n`,
|
|
459
|
+
"database-troubleshooting": `---\nname: database-troubleshooting\ndescription: Debug query plans, locks, and schema anomalies without touching production.\n---\n\n# Database Troubleshooting SOP\n\n1. Fork an isolated branch with \`backwrite_spawn_worktree\`.\n2. Inspect \`backwrite://advisors/findings\` and run \`EXPLAIN (ANALYZE, BUFFERS)\` on the disposable branch.\n3. If credentials or business rules are ambiguous, pause via \`backwrite_elicit_context\`.\n`,
|
|
460
|
+
"api-generation": `---\nname: api-generation\ndescription: Generate typed TypeScript, Drizzle, or Prisma models from the live Backwrite schema.\n---\n\n# API & Schema Type Generation SOP\n\n1. Read \`backwrite://schema/current\` or call \`backwrite_generate_types\`.\n2. Always load credentials and project/branch IDs from environment variables (\`BACKWRITE_SERVICE_KEY\`, \`BACKWRITE_PROJECT_ID\`, \`BACKWRITE_BRANCH_ID\`).\n`,
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
for (const s of skills) {
|
|
464
|
+
const k = slugify(s);
|
|
465
|
+
files[`skills/${k}/SKILL.md`] =
|
|
466
|
+
templates[k] ||
|
|
467
|
+
`---\nname: ${k}\ndescription: Backwrite Agent Skill (${k}).\n---\n\n# ${k}\n\nProvision a disposable Copy-on-Write branch via \`backwrite_spawn_worktree\`, coordinate edits with \`backwrite_workspace_lock\`, and verify via \`backwrite_sync_schema\`.\n`;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return {
|
|
471
|
+
standard: "1.0.0",
|
|
472
|
+
name: safeName,
|
|
473
|
+
files,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
}
|
package/src/client.ts
CHANGED
|
@@ -80,6 +80,11 @@ import {
|
|
|
80
80
|
OrgsService,
|
|
81
81
|
ProjectsService,
|
|
82
82
|
} from "./services.js";
|
|
83
|
+
import {
|
|
84
|
+
AgentWorkspacesService,
|
|
85
|
+
AgentsService,
|
|
86
|
+
PluginsService,
|
|
87
|
+
} from "./agents.js";
|
|
83
88
|
|
|
84
89
|
export interface BackwriteClientOptions {
|
|
85
90
|
/** Base URL of the gateway, e.g. `https://api.backwrite.dev`. */
|
|
@@ -111,8 +116,31 @@ function isBinaryBody(body: unknown): body is ArrayBuffer | Uint8Array {
|
|
|
111
116
|
return body instanceof ArrayBuffer || body instanceof Uint8Array;
|
|
112
117
|
}
|
|
113
118
|
|
|
119
|
+
function validateBaseUrl(raw: string): string {
|
|
120
|
+
let u: URL;
|
|
121
|
+
try {
|
|
122
|
+
u = new URL(raw);
|
|
123
|
+
} catch {
|
|
124
|
+
throw new Error(`BackwriteClient: invalid baseUrl '${raw}'`);
|
|
125
|
+
}
|
|
126
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") {
|
|
127
|
+
throw new Error(`BackwriteClient: unsupported baseUrl protocol '${u.protocol}'`);
|
|
128
|
+
}
|
|
129
|
+
if (u.username || u.password || /[\r\n\0]/.test(raw)) {
|
|
130
|
+
throw new Error("BackwriteClient: embedded credentials or control characters in baseUrl are forbidden");
|
|
131
|
+
}
|
|
132
|
+
return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
114
135
|
function buildUrl(baseUrl: string, path: string, query: Record<string, QueryValue>): URL {
|
|
115
|
-
|
|
136
|
+
if (!path.startsWith("/") || path.startsWith("//") || path.includes("..") || /[\r\n\0]/.test(path)) {
|
|
137
|
+
throw new Error(`BackwriteClient: invalid request path '${path}'`);
|
|
138
|
+
}
|
|
139
|
+
const base = new URL(baseUrl);
|
|
140
|
+
const url = new URL(`${baseUrl}${path}`);
|
|
141
|
+
if (url.origin !== base.origin) {
|
|
142
|
+
throw new Error("BackwriteClient: request path attempted cross-origin redirect");
|
|
143
|
+
}
|
|
116
144
|
for (const [key, value] of Object.entries(query)) {
|
|
117
145
|
url.searchParams.set(key, String(value));
|
|
118
146
|
}
|
|
@@ -147,10 +175,16 @@ export class BackwriteClient {
|
|
|
147
175
|
readonly advisors: AdvisorsService;
|
|
148
176
|
readonly orgs: OrgsService;
|
|
149
177
|
readonly projects: ProjectsService;
|
|
178
|
+
readonly workspaces: AgentWorkspacesService;
|
|
179
|
+
readonly agents: AgentsService;
|
|
180
|
+
readonly plugins: PluginsService;
|
|
150
181
|
|
|
151
182
|
constructor(options: BackwriteClientOptions = {}) {
|
|
152
183
|
const resolvedBase = options.baseUrl ?? "https://api.backwrite.dev";
|
|
153
|
-
this.baseUrl = resolvedBase
|
|
184
|
+
this.baseUrl = validateBaseUrl(resolvedBase);
|
|
185
|
+
if (options.apiKey && /[\r\n\0]/.test(options.apiKey)) {
|
|
186
|
+
throw new Error("BackwriteClient: apiKey contains illegal control characters");
|
|
187
|
+
}
|
|
154
188
|
this.apiKey = options.apiKey;
|
|
155
189
|
this.projectId = options.projectId;
|
|
156
190
|
this.branchId = options.branchId;
|
|
@@ -169,6 +203,9 @@ export class BackwriteClient {
|
|
|
169
203
|
this.advisors = new AdvisorsService(this);
|
|
170
204
|
this.orgs = new OrgsService(this);
|
|
171
205
|
this.projects = new ProjectsService(this);
|
|
206
|
+
this.workspaces = new AgentWorkspacesService(this);
|
|
207
|
+
this.agents = new AgentsService(this);
|
|
208
|
+
this.plugins = new PluginsService(this);
|
|
172
209
|
}
|
|
173
210
|
|
|
174
211
|
/**
|
|
@@ -191,7 +228,14 @@ export class BackwriteClient {
|
|
|
191
228
|
headers["apikey"] = this.apiKey;
|
|
192
229
|
}
|
|
193
230
|
}
|
|
194
|
-
if (options.idempotencyKey)
|
|
231
|
+
if (options.idempotencyKey) {
|
|
232
|
+
headers["idempotency-key"] = options.idempotencyKey;
|
|
233
|
+
} else if (method !== "GET") {
|
|
234
|
+
headers["idempotency-key"] =
|
|
235
|
+
typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
|
|
236
|
+
? `bwsdk_${crypto.randomUUID()}`
|
|
237
|
+
: `bwsdk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`;
|
|
238
|
+
}
|
|
195
239
|
|
|
196
240
|
let payload: BodyInit | undefined;
|
|
197
241
|
if (options.body !== undefined) {
|
package/src/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ export { BackwriteClient, BackwriteApiError };
|
|
|
14
14
|
export type { RequestOptions, BackwriteClientOptions };
|
|
15
15
|
export { operations, OPERATION_META };
|
|
16
16
|
export * from "./services.js";
|
|
17
|
+
export * from "./agents.js";
|
|
17
18
|
|
|
18
19
|
type RequestLike = (
|
|
19
20
|
method: "GET" | "PUT" | "POST" | "DELETE" | "PATCH",
|