@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/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# `@backwrite/sdk`
|
|
2
2
|
|
|
3
|
-
Official TypeScript/JavaScript
|
|
3
|
+
Official zero-dependency TypeScript/JavaScript SDK for [Backwrite](https://backwrite.dev) — PostgreSQL 18 Copy-on-Write branching, multi-tenant SQL, parallel AI Agent Workspaces, Agent Lockfiles, Realtime event streaming, and **Agent Plugins 1.0.0** generation.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -14,46 +14,72 @@ npm install @backwrite/sdk
|
|
|
14
14
|
|
|
15
15
|
## Quickstart
|
|
16
16
|
|
|
17
|
+
Always load API URLs, keys, project IDs, and branch IDs from environment variables — never hardcode live backend identifiers in source code.
|
|
18
|
+
|
|
17
19
|
```typescript
|
|
18
20
|
import { createClient } from "@backwrite/sdk";
|
|
19
21
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
url: "https://api.backwrite.dev",
|
|
22
|
+
const backwrite = createClient({
|
|
23
|
+
baseUrl: process.env.BACKWRITE_URL ?? "https://api.backwrite.dev",
|
|
23
24
|
apiKey: process.env.BACKWRITE_SERVICE_KEY!,
|
|
24
|
-
projectId:
|
|
25
|
-
branchId:
|
|
25
|
+
projectId: process.env.BACKWRITE_PROJECT_ID!,
|
|
26
|
+
branchId: process.env.BACKWRITE_BRANCH_ID,
|
|
26
27
|
});
|
|
27
28
|
|
|
28
|
-
// 1.
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
// 1. Run SQL on the active branch
|
|
30
|
+
const res = await backwrite.query(
|
|
31
|
+
process.env.BACKWRITE_PROJECT_ID!,
|
|
32
|
+
"SELECT id, email FROM users LIMIT 10"
|
|
32
33
|
);
|
|
33
34
|
|
|
34
|
-
// 2.
|
|
35
|
-
const
|
|
36
|
-
|
|
35
|
+
// 2. Provision an isolated Agent Workspace (Git worktree + disposable Postgres 18 branch)
|
|
36
|
+
const workspace = await backwrite.workspaces.create({
|
|
37
|
+
name: "auth-integration-tests",
|
|
38
|
+
baseBranch: "main",
|
|
39
|
+
isolatedDb: true,
|
|
40
|
+
gitWorktree: true,
|
|
41
|
+
});
|
|
42
|
+
console.log(workspace.gitWorktreeCommand, workspace.branchId);
|
|
43
|
+
|
|
44
|
+
// 3. Coordinate parallel agents with Valkey-backed Agent Lockfiles
|
|
45
|
+
const lock = await workspace.acquireLock("src/routes/auth.ts");
|
|
46
|
+
if (lock.contested) {
|
|
47
|
+
console.log(`Paused — contested by ${lock.heldBy}`);
|
|
48
|
+
}
|
|
37
49
|
|
|
38
|
-
//
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
metric: "cosine",
|
|
50
|
+
// 4. Stream live agent events over Backwrite Realtime / NATS JetStream
|
|
51
|
+
const sub = await backwrite.agents.subscribe(workspace.workspaceId, (ev) => {
|
|
52
|
+
console.log(`[${ev.event}] ${ev.message}`);
|
|
42
53
|
});
|
|
54
|
+
await workspace.emit("status", "Running auth migration tests");
|
|
55
|
+
|
|
56
|
+
// 5. Programmatically export an Agent Plugins 1.0.0 bundle
|
|
57
|
+
const plugin = await backwrite.plugins.export({
|
|
58
|
+
name: "MySaaS-Agent-Core",
|
|
59
|
+
includeSchema: true,
|
|
60
|
+
generateSkills: ["database-troubleshooting", "api-generation", "bw-migrations"],
|
|
61
|
+
});
|
|
62
|
+
// plugin.files contains plugin.json, mcp.json, schema.json, and skills/*/SKILL.md
|
|
43
63
|
```
|
|
44
64
|
|
|
45
65
|
---
|
|
46
66
|
|
|
47
|
-
##
|
|
67
|
+
## Capabilities
|
|
48
68
|
|
|
49
|
-
- **
|
|
50
|
-
- **
|
|
51
|
-
- **
|
|
52
|
-
- **
|
|
53
|
-
- **
|
|
69
|
+
- **SQL & Schema**: `backwrite.db`, `backwrite.query()`, `backwrite.getSchema()`
|
|
70
|
+
- **Agent Workspaces**: `backwrite.workspaces.create()` pairing Git worktrees with isolated CoW Postgres 18 branches
|
|
71
|
+
- **Agent Lockfiles**: `backwrite.agents.locks.acquire|release|check()` to prevent parallel agent merge conflicts
|
|
72
|
+
- **Realtime Agent Telemetry**: `backwrite.agents.emit()` & `backwrite.agents.subscribe()` over NATS JetStream / WebSockets
|
|
73
|
+
- **Agent Plugins 1.0.0**: `backwrite.plugins.export()` generating `plugin.json`, `mcp.json`, live `schema.json`, and `skills/*/SKILL.md`
|
|
74
|
+
- **Full Platform Surface**: `auth`, `branches`, `storage`, `cache`, `queues`, `vector`, `realtime`, `secrets`, `advisors`, `orgs`, `projects`
|
|
54
75
|
|
|
55
76
|
---
|
|
56
77
|
|
|
78
|
+
## Security & Permissions
|
|
79
|
+
|
|
80
|
+
- **Zero external runtime dependencies** and **zero shell or filesystem access**.
|
|
81
|
+
- **Scoped network access**: Uses standard `globalThis.fetch` strictly against your configured `baseUrl` (default `https://api.backwrite.dev`) with cross-origin SSRF guards, path validation, and CR/LF header-injection protection.
|
|
82
|
+
|
|
57
83
|
## License
|
|
58
84
|
|
|
59
85
|
Apache-2.0 © Backwrite
|
package/dist/agents.d.ts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import type { BackwriteClient } from "./client.js";
|
|
2
|
+
import type { ScopeOptions } from "./services.js";
|
|
3
|
+
export interface CreateWorkspaceOptions {
|
|
4
|
+
/** Task or agent name slug (default: generated unique agent workspace name). */
|
|
5
|
+
name?: string;
|
|
6
|
+
/** Git base branch to branch the worktree from (default: "main"). */
|
|
7
|
+
baseBranch?: string;
|
|
8
|
+
/** Provision a disposable PostgreSQL 18 CoW branch (default: true). */
|
|
9
|
+
isolatedDb?: boolean;
|
|
10
|
+
/** Include Git worktree coordinates & commands (default: true). */
|
|
11
|
+
gitWorktree?: boolean;
|
|
12
|
+
/** Copy-on-Write creation mode (default: "schema-only"). */
|
|
13
|
+
mode?: "schema-only" | "full-copy";
|
|
14
|
+
/** Target Backwrite Project ID (defaults to client.projectId). */
|
|
15
|
+
projectId?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface AgentWorkspaceInfo {
|
|
18
|
+
workspaceId: string;
|
|
19
|
+
projectId: string;
|
|
20
|
+
branchId: string;
|
|
21
|
+
operationId?: string;
|
|
22
|
+
gitBranch: string;
|
|
23
|
+
worktreePath: string;
|
|
24
|
+
gitWorktreeCommand: string;
|
|
25
|
+
cleanupCommand: string;
|
|
26
|
+
envTemplate: Record<string, string>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Unified handle tying a local Git worktree specification to an isolated
|
|
30
|
+
* Backwrite Copy-on-Write PostgreSQL 18 branch, lockfile namespace, and event stream.
|
|
31
|
+
*/
|
|
32
|
+
export declare class AgentWorkspace {
|
|
33
|
+
private readonly client;
|
|
34
|
+
readonly workspaceId: string;
|
|
35
|
+
readonly projectId: string;
|
|
36
|
+
readonly branchId: string;
|
|
37
|
+
readonly operationId?: string;
|
|
38
|
+
readonly gitBranch: string;
|
|
39
|
+
readonly worktreePath: string;
|
|
40
|
+
readonly gitWorktreeCommand: string;
|
|
41
|
+
readonly cleanupCommand: string;
|
|
42
|
+
readonly envTemplate: Record<string, string>;
|
|
43
|
+
constructor(client: BackwriteClient, info: AgentWorkspaceInfo);
|
|
44
|
+
/** Execute SQL scoped strictly to this workspace's isolated CoW branch. */
|
|
45
|
+
query(sql: string): Promise<{
|
|
46
|
+
success: boolean;
|
|
47
|
+
columns: string[];
|
|
48
|
+
rows: (string | null)[][];
|
|
49
|
+
summary: string;
|
|
50
|
+
execution_time_ms: number;
|
|
51
|
+
error?: string;
|
|
52
|
+
}>;
|
|
53
|
+
/** Introspect this workspace's isolated branch schema. */
|
|
54
|
+
getSchema(): Promise<{
|
|
55
|
+
branch_id: string;
|
|
56
|
+
database: string;
|
|
57
|
+
tables: Array<{
|
|
58
|
+
schema: string;
|
|
59
|
+
name: string;
|
|
60
|
+
type: string;
|
|
61
|
+
columns: Array<{
|
|
62
|
+
name: string;
|
|
63
|
+
data_type: string;
|
|
64
|
+
udt_name: string;
|
|
65
|
+
nullable: boolean;
|
|
66
|
+
default: string | null;
|
|
67
|
+
position: number;
|
|
68
|
+
is_pk: boolean;
|
|
69
|
+
is_unique: boolean;
|
|
70
|
+
}>;
|
|
71
|
+
primary_key: string[];
|
|
72
|
+
foreign_keys: Array<{
|
|
73
|
+
constraint_name: string;
|
|
74
|
+
column: string;
|
|
75
|
+
foreign_schema: string;
|
|
76
|
+
foreign_table: string;
|
|
77
|
+
foreign_column: string;
|
|
78
|
+
on_delete: string | null;
|
|
79
|
+
on_update: string | null;
|
|
80
|
+
}>;
|
|
81
|
+
indexes: Array<{
|
|
82
|
+
name: string;
|
|
83
|
+
definition: string;
|
|
84
|
+
is_primary: boolean;
|
|
85
|
+
is_unique: boolean;
|
|
86
|
+
}>;
|
|
87
|
+
policies: Array<{
|
|
88
|
+
name: string;
|
|
89
|
+
permissive: string;
|
|
90
|
+
roles: string[];
|
|
91
|
+
cmd: string;
|
|
92
|
+
qual: string;
|
|
93
|
+
with_check: string;
|
|
94
|
+
}>;
|
|
95
|
+
}>;
|
|
96
|
+
enums: Array<{
|
|
97
|
+
schema: string;
|
|
98
|
+
name: string;
|
|
99
|
+
values: string[];
|
|
100
|
+
}>;
|
|
101
|
+
}>;
|
|
102
|
+
/** Acquire a distributed file lock so parallel agents do not edit the same file. */
|
|
103
|
+
acquireLock(filePath: string, ttlSeconds?: number): Promise<AgentLockResult>;
|
|
104
|
+
/** Release a previously acquired file lock. */
|
|
105
|
+
releaseLock(filePath: string): Promise<{
|
|
106
|
+
filePath: string;
|
|
107
|
+
released: boolean;
|
|
108
|
+
agentId: string;
|
|
109
|
+
}>;
|
|
110
|
+
/** Emit a structured status/log event for this agent workspace over Realtime / NATS. */
|
|
111
|
+
emit(event: string, message: string, metadata?: Record<string, unknown>): Promise<unknown>;
|
|
112
|
+
/** Tear down the disposable PostgreSQL 18 branch associated with this workspace. */
|
|
113
|
+
destroy(): Promise<unknown>;
|
|
114
|
+
}
|
|
115
|
+
export declare class AgentWorkspacesService {
|
|
116
|
+
private readonly client;
|
|
117
|
+
constructor(client: BackwriteClient);
|
|
118
|
+
create(options?: CreateWorkspaceOptions): Promise<AgentWorkspace>;
|
|
119
|
+
list(scope?: ScopeOptions): Promise<unknown>;
|
|
120
|
+
destroy(branchId: string): Promise<unknown>;
|
|
121
|
+
}
|
|
122
|
+
export interface AgentLockResult {
|
|
123
|
+
filePath: string;
|
|
124
|
+
acquired: boolean;
|
|
125
|
+
contested: boolean;
|
|
126
|
+
heldBy?: string;
|
|
127
|
+
since?: string;
|
|
128
|
+
}
|
|
129
|
+
export declare class AgentLocksService {
|
|
130
|
+
private readonly client;
|
|
131
|
+
constructor(client: BackwriteClient);
|
|
132
|
+
private lockKey;
|
|
133
|
+
check(filePath: string, opts?: {
|
|
134
|
+
branchId?: string;
|
|
135
|
+
}): Promise<AgentLockResult>;
|
|
136
|
+
acquire(filePath: string, opts: {
|
|
137
|
+
agentId: string;
|
|
138
|
+
branchId?: string;
|
|
139
|
+
ttlSeconds?: number;
|
|
140
|
+
}): Promise<AgentLockResult>;
|
|
141
|
+
release(filePath: string, opts?: {
|
|
142
|
+
agentId?: string;
|
|
143
|
+
branchId?: string;
|
|
144
|
+
}): Promise<{
|
|
145
|
+
filePath: string;
|
|
146
|
+
released: boolean;
|
|
147
|
+
agentId: string;
|
|
148
|
+
}>;
|
|
149
|
+
}
|
|
150
|
+
export interface AgentEvent {
|
|
151
|
+
agentId: string;
|
|
152
|
+
event: string;
|
|
153
|
+
message: string;
|
|
154
|
+
metadata?: Record<string, unknown>;
|
|
155
|
+
ts: string;
|
|
156
|
+
}
|
|
157
|
+
export declare class AgentsService {
|
|
158
|
+
private readonly client;
|
|
159
|
+
readonly locks: AgentLocksService;
|
|
160
|
+
constructor(client: BackwriteClient);
|
|
161
|
+
/** Publish a structured agent event over Backwrite Realtime / NATS JetStream. */
|
|
162
|
+
emit(agentId: string, event: string, message: string, opts?: {
|
|
163
|
+
branchId?: string;
|
|
164
|
+
metadata?: Record<string, unknown>;
|
|
165
|
+
}): Promise<unknown>;
|
|
166
|
+
/**
|
|
167
|
+
* Subscribe to live agent events over Backwrite Realtime WebSocket (when available)
|
|
168
|
+
* using a short-lived signed WS ticket. Returns an unsubscribe handle.
|
|
169
|
+
*/
|
|
170
|
+
subscribe(agentId: string, onEvent: (ev: AgentEvent) => void, opts?: {
|
|
171
|
+
branchId?: string;
|
|
172
|
+
onError?: (err: unknown) => void;
|
|
173
|
+
}): Promise<{
|
|
174
|
+
channel: string;
|
|
175
|
+
ticket: unknown;
|
|
176
|
+
unsubscribe: () => void;
|
|
177
|
+
}>;
|
|
178
|
+
}
|
|
179
|
+
export interface ExportPluginOptions {
|
|
180
|
+
/** Plugin name (e.g. "MySaaS-Agent-Core"). */
|
|
181
|
+
name: string;
|
|
182
|
+
/** Optional description for plugin.json. */
|
|
183
|
+
description?: string;
|
|
184
|
+
/** Embed live relational schema from Backwrite into schema.json (default: true). */
|
|
185
|
+
includeSchema?: boolean;
|
|
186
|
+
/** Skill names to generate under skills/<name>/SKILL.md. */
|
|
187
|
+
generateSkills?: string[];
|
|
188
|
+
/** Override projectId / branchId. */
|
|
189
|
+
projectId?: string;
|
|
190
|
+
branchId?: string;
|
|
191
|
+
}
|
|
192
|
+
export interface ExportedAgentPlugin {
|
|
193
|
+
standard: "1.0.0";
|
|
194
|
+
name: string;
|
|
195
|
+
/** Map of relative file paths (`plugin.json`, `mcp.json`, `skills/.../SKILL.md`) to UTF-8 content. */
|
|
196
|
+
files: Record<string, string>;
|
|
197
|
+
}
|
|
198
|
+
export declare class PluginsService {
|
|
199
|
+
private readonly client;
|
|
200
|
+
constructor(client: BackwriteClient);
|
|
201
|
+
/**
|
|
202
|
+
* Generate a complete Agent Plugins 1.0.0 bundle (pure data — zero fs dependency,
|
|
203
|
+
* works identically in Node.js, Edge runtimes, and browsers).
|
|
204
|
+
*/
|
|
205
|
+
export(options: ExportPluginOptions): Promise<ExportedAgentPlugin>;
|
|
206
|
+
}
|
|
207
|
+
//# sourceMappingURL=agents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../src/agents.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AA8BlD,MAAM,WAAW,sBAAsB;IACrC,gFAAgF;IAChF,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qEAAqE;IACrE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uEAAuE;IACvE,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,mEAAmE;IACnE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,4DAA4D;IAC5D,IAAI,CAAC,EAAE,aAAa,GAAG,WAAW,CAAC;IACnC,kEAAkE;IAClE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,WA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AQ,CAAC,MAAM;gBAAN,MAAM,EAAE,eAAe;IAEpD;;;OAGG;IACG,MAAM,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;CA+EzE"}
|
package/dist/agents.js
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
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
|
+
function slugify(input) {
|
|
10
|
+
return (String(input || "agent-workspace")
|
|
11
|
+
.toLowerCase()
|
|
12
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
13
|
+
.replace(/^-+|-+$/g, "")
|
|
14
|
+
.slice(0, 40) || "agent-workspace");
|
|
15
|
+
}
|
|
16
|
+
function requireProject(client, override) {
|
|
17
|
+
const id = override || client.projectId;
|
|
18
|
+
if (!id) {
|
|
19
|
+
throw new Error("Backwrite SDK: projectId is required (set on client options or method options).");
|
|
20
|
+
}
|
|
21
|
+
return id;
|
|
22
|
+
}
|
|
23
|
+
function requireBranch(client, override) {
|
|
24
|
+
const id = override || client.branchId;
|
|
25
|
+
if (!id) {
|
|
26
|
+
throw new Error("Backwrite SDK: branchId is required (set on client options or method options).");
|
|
27
|
+
}
|
|
28
|
+
return id;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Unified handle tying a local Git worktree specification to an isolated
|
|
32
|
+
* Backwrite Copy-on-Write PostgreSQL 18 branch, lockfile namespace, and event stream.
|
|
33
|
+
*/
|
|
34
|
+
export class AgentWorkspace {
|
|
35
|
+
client;
|
|
36
|
+
workspaceId;
|
|
37
|
+
projectId;
|
|
38
|
+
branchId;
|
|
39
|
+
operationId;
|
|
40
|
+
gitBranch;
|
|
41
|
+
worktreePath;
|
|
42
|
+
gitWorktreeCommand;
|
|
43
|
+
cleanupCommand;
|
|
44
|
+
envTemplate;
|
|
45
|
+
constructor(client, info) {
|
|
46
|
+
this.client = client;
|
|
47
|
+
this.workspaceId = info.workspaceId;
|
|
48
|
+
this.projectId = info.projectId;
|
|
49
|
+
this.branchId = info.branchId;
|
|
50
|
+
this.operationId = info.operationId;
|
|
51
|
+
this.gitBranch = info.gitBranch;
|
|
52
|
+
this.worktreePath = info.worktreePath;
|
|
53
|
+
this.gitWorktreeCommand = info.gitWorktreeCommand;
|
|
54
|
+
this.cleanupCommand = info.cleanupCommand;
|
|
55
|
+
this.envTemplate = info.envTemplate;
|
|
56
|
+
}
|
|
57
|
+
/** Execute SQL scoped strictly to this workspace's isolated CoW branch. */
|
|
58
|
+
async query(sql) {
|
|
59
|
+
return this.client.query(this.projectId, sql, { branchId: this.branchId });
|
|
60
|
+
}
|
|
61
|
+
/** Introspect this workspace's isolated branch schema. */
|
|
62
|
+
async getSchema() {
|
|
63
|
+
return this.client.getSchema(this.projectId, { branchId: this.branchId });
|
|
64
|
+
}
|
|
65
|
+
/** Acquire a distributed file lock so parallel agents do not edit the same file. */
|
|
66
|
+
async acquireLock(filePath, ttlSeconds = 600) {
|
|
67
|
+
return this.client.agents.locks.acquire(filePath, {
|
|
68
|
+
agentId: this.workspaceId,
|
|
69
|
+
branchId: this.branchId,
|
|
70
|
+
ttlSeconds,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Release a previously acquired file lock. */
|
|
74
|
+
async releaseLock(filePath) {
|
|
75
|
+
return this.client.agents.locks.release(filePath, {
|
|
76
|
+
agentId: this.workspaceId,
|
|
77
|
+
branchId: this.branchId,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** Emit a structured status/log event for this agent workspace over Realtime / NATS. */
|
|
81
|
+
async emit(event, message, metadata = {}) {
|
|
82
|
+
return this.client.agents.emit(this.workspaceId, event, message, {
|
|
83
|
+
branchId: this.branchId,
|
|
84
|
+
metadata,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/** Tear down the disposable PostgreSQL 18 branch associated with this workspace. */
|
|
88
|
+
async destroy() {
|
|
89
|
+
if (!this.branchId)
|
|
90
|
+
return { deleted: false };
|
|
91
|
+
return this.client.branches.delete(this.branchId);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export class AgentWorkspacesService {
|
|
95
|
+
client;
|
|
96
|
+
constructor(client) {
|
|
97
|
+
this.client = client;
|
|
98
|
+
}
|
|
99
|
+
async create(options = {}) {
|
|
100
|
+
const projectId = requireProject(this.client, options.projectId);
|
|
101
|
+
const slug = slugify(options.name || `task-${Date.now().toString(36)}`);
|
|
102
|
+
const workspaceId = `agent-${slug}-${Date.now().toString(36).slice(-4)}`;
|
|
103
|
+
const baseBranch = options.baseBranch || "main";
|
|
104
|
+
const gitBranch = `agent/${slug}`;
|
|
105
|
+
const worktreePath = `.backwrite/worktrees/${workspaceId}`;
|
|
106
|
+
let branchId = this.client.branchId || "";
|
|
107
|
+
let operationId;
|
|
108
|
+
if (options.isolatedDb !== false) {
|
|
109
|
+
const created = (await this.client.request("POST", `/v1/projects/${encodeURIComponent(projectId)}/branches`, {
|
|
110
|
+
body: {
|
|
111
|
+
name: workspaceId,
|
|
112
|
+
branch_type: "preview",
|
|
113
|
+
mode: options.mode || "schema-only",
|
|
114
|
+
},
|
|
115
|
+
}));
|
|
116
|
+
branchId = created.branch_id || created.id || branchId;
|
|
117
|
+
operationId = created.operation_id;
|
|
118
|
+
}
|
|
119
|
+
const useWorktree = options.gitWorktree !== false;
|
|
120
|
+
return new AgentWorkspace(this.client, {
|
|
121
|
+
workspaceId,
|
|
122
|
+
projectId,
|
|
123
|
+
branchId,
|
|
124
|
+
operationId,
|
|
125
|
+
gitBranch,
|
|
126
|
+
worktreePath,
|
|
127
|
+
gitWorktreeCommand: useWorktree
|
|
128
|
+
? `git worktree add -b ${gitBranch} ${worktreePath} ${baseBranch}`
|
|
129
|
+
: "",
|
|
130
|
+
cleanupCommand: useWorktree
|
|
131
|
+
? `git worktree remove ${worktreePath} && git branch -d ${gitBranch}`
|
|
132
|
+
: "",
|
|
133
|
+
envTemplate: {
|
|
134
|
+
BACKWRITE_PROJECT_ID: projectId,
|
|
135
|
+
BACKWRITE_BRANCH_ID: branchId,
|
|
136
|
+
DATABASE_URL: "postgresql://<ROLE>:<PASSWORD>@pooler.backwrite.dev:6543/<DB>?sslmode=require",
|
|
137
|
+
DIRECT_URL: "postgresql://<ROLE>:<PASSWORD>@db.backwrite.dev:5432/<DB>?sslmode=require",
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
async list(scope = {}) {
|
|
142
|
+
const projectId = requireProject(this.client, scope.projectId);
|
|
143
|
+
return this.client.branches.list(projectId);
|
|
144
|
+
}
|
|
145
|
+
async destroy(branchId) {
|
|
146
|
+
return this.client.branches.delete(branchId);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export class AgentLocksService {
|
|
150
|
+
client;
|
|
151
|
+
constructor(client) {
|
|
152
|
+
this.client = client;
|
|
153
|
+
}
|
|
154
|
+
lockKey(filePath) {
|
|
155
|
+
const normalized = String(filePath || "").replace(/^\/+/, "");
|
|
156
|
+
if (!normalized || normalized.includes("..")) {
|
|
157
|
+
throw new Error(`Backwrite SDK: invalid lockfile path '${filePath}'`);
|
|
158
|
+
}
|
|
159
|
+
return `bw:lock:${encodeURIComponent(normalized)}`;
|
|
160
|
+
}
|
|
161
|
+
async check(filePath, opts = {}) {
|
|
162
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
163
|
+
const key = this.lockKey(filePath);
|
|
164
|
+
try {
|
|
165
|
+
const entry = (await this.client.cache.get(key, branchId));
|
|
166
|
+
if (entry?.value) {
|
|
167
|
+
const parsed = typeof entry.value === "string" ? JSON.parse(entry.value) : entry.value;
|
|
168
|
+
return {
|
|
169
|
+
filePath,
|
|
170
|
+
acquired: false,
|
|
171
|
+
contested: true,
|
|
172
|
+
heldBy: parsed.agent_id,
|
|
173
|
+
since: parsed.acquired_at,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
// Cache miss means unlocked
|
|
179
|
+
}
|
|
180
|
+
return { filePath, acquired: false, contested: false };
|
|
181
|
+
}
|
|
182
|
+
async acquire(filePath, opts) {
|
|
183
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
184
|
+
const existing = await this.check(filePath, { branchId });
|
|
185
|
+
if (existing.contested && existing.heldBy && existing.heldBy !== opts.agentId) {
|
|
186
|
+
return existing;
|
|
187
|
+
}
|
|
188
|
+
const now = new Date().toISOString();
|
|
189
|
+
await this.client.cache.set(this.lockKey(filePath), JSON.stringify({ agent_id: opts.agentId, file_path: filePath, acquired_at: now }), opts.ttlSeconds ?? 600, branchId);
|
|
190
|
+
return { filePath, acquired: true, contested: false, heldBy: opts.agentId, since: now };
|
|
191
|
+
}
|
|
192
|
+
async release(filePath, opts = {}) {
|
|
193
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
194
|
+
await this.client.cache.del(this.lockKey(filePath), branchId).catch(() => ({}));
|
|
195
|
+
return { filePath, released: true, agentId: opts.agentId };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
export class AgentsService {
|
|
199
|
+
client;
|
|
200
|
+
locks;
|
|
201
|
+
constructor(client) {
|
|
202
|
+
this.client = client;
|
|
203
|
+
this.locks = new AgentLocksService(client);
|
|
204
|
+
}
|
|
205
|
+
/** Publish a structured agent event over Backwrite Realtime / NATS JetStream. */
|
|
206
|
+
async emit(agentId, event, message, opts = {}) {
|
|
207
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
208
|
+
return this.client.realtime.broadcast(`agent:${agentId}`, event, {
|
|
209
|
+
agent_id: agentId,
|
|
210
|
+
message,
|
|
211
|
+
metadata: opts.metadata || {},
|
|
212
|
+
ts: new Date().toISOString(),
|
|
213
|
+
}, branchId);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Subscribe to live agent events over Backwrite Realtime WebSocket (when available)
|
|
217
|
+
* using a short-lived signed WS ticket. Returns an unsubscribe handle.
|
|
218
|
+
*/
|
|
219
|
+
async subscribe(agentId, onEvent, opts = {}) {
|
|
220
|
+
const branchId = requireBranch(this.client, opts.branchId);
|
|
221
|
+
const channel = `agent:${agentId}`;
|
|
222
|
+
const ticket = (await this.client.realtime.createTicket(branchId));
|
|
223
|
+
let ws = null;
|
|
224
|
+
const wsUrl = ticket?.ws_url || ticket?.url;
|
|
225
|
+
if (wsUrl && typeof globalThis.WebSocket === "function") {
|
|
226
|
+
try {
|
|
227
|
+
const finalUrl = ticket?.ticket
|
|
228
|
+
? `${wsUrl}${wsUrl.includes("?") ? "&" : "?"}ticket=${encodeURIComponent(ticket.ticket)}`
|
|
229
|
+
: wsUrl;
|
|
230
|
+
ws = new globalThis.WebSocket(finalUrl);
|
|
231
|
+
ws.onmessage = (msg) => {
|
|
232
|
+
try {
|
|
233
|
+
const parsed = JSON.parse(String(msg.data));
|
|
234
|
+
const payload = parsed.payload || parsed;
|
|
235
|
+
onEvent({
|
|
236
|
+
agentId: payload.agent_id || agentId,
|
|
237
|
+
event: parsed.event || payload.event || "message",
|
|
238
|
+
message: payload.message || JSON.stringify(payload),
|
|
239
|
+
metadata: payload.metadata,
|
|
240
|
+
ts: payload.ts || new Date().toISOString(),
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
// Ignore non-JSON heartbeat frames
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
ws.onerror = (err) => opts.onError?.(err);
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
opts.onError?.(err);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return {
|
|
254
|
+
channel,
|
|
255
|
+
ticket,
|
|
256
|
+
unsubscribe: () => {
|
|
257
|
+
try {
|
|
258
|
+
ws?.close();
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
// Safe cleanup
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
export class PluginsService {
|
|
268
|
+
client;
|
|
269
|
+
constructor(client) {
|
|
270
|
+
this.client = client;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Generate a complete Agent Plugins 1.0.0 bundle (pure data — zero fs dependency,
|
|
274
|
+
* works identically in Node.js, Edge runtimes, and browsers).
|
|
275
|
+
*/
|
|
276
|
+
async export(options) {
|
|
277
|
+
const safeName = slugify(options.name);
|
|
278
|
+
const projectId = options.projectId || this.client.projectId || "";
|
|
279
|
+
const branchId = options.branchId || this.client.branchId || "";
|
|
280
|
+
const skills = options.generateSkills && options.generateSkills.length > 0
|
|
281
|
+
? options.generateSkills
|
|
282
|
+
: ["bw-migrations", "bw-deploy", "database-troubleshooting", "api-generation"];
|
|
283
|
+
let schemaSnapshot = undefined;
|
|
284
|
+
if (options.includeSchema !== false && projectId) {
|
|
285
|
+
schemaSnapshot = await this.client
|
|
286
|
+
.getSchema(projectId, branchId ? { branchId } : {})
|
|
287
|
+
.catch(() => undefined);
|
|
288
|
+
}
|
|
289
|
+
const files = {
|
|
290
|
+
"plugin.json": JSON.stringify({
|
|
291
|
+
schemaVersion: "1.0.0",
|
|
292
|
+
name: safeName,
|
|
293
|
+
version: "1.0.0",
|
|
294
|
+
description: options.description ||
|
|
295
|
+
`Backwrite Agent Plugin for ${options.name} — CoW PostgreSQL 18 branching, 36 MCP tools, and Agent Skills.`,
|
|
296
|
+
mcpConfig: "./mcp.json",
|
|
297
|
+
skillsDir: "./skills",
|
|
298
|
+
backwrite: {
|
|
299
|
+
projectIdEnv: "BACKWRITE_PROJECT_ID",
|
|
300
|
+
branchIdEnv: "BACKWRITE_BRANCH_ID",
|
|
301
|
+
},
|
|
302
|
+
}, null, 2),
|
|
303
|
+
"mcp.json": JSON.stringify({
|
|
304
|
+
mcpServers: {
|
|
305
|
+
backwrite: {
|
|
306
|
+
command: "npx",
|
|
307
|
+
args: ["-y", "@backwrite/mcp@0.3.0"],
|
|
308
|
+
env: {
|
|
309
|
+
BACKWRITE_URL: "https://api.backwrite.dev",
|
|
310
|
+
BACKWRITE_SERVICE_KEY: "${BACKWRITE_SERVICE_KEY}",
|
|
311
|
+
BACKWRITE_PROJECT_ID: "${BACKWRITE_PROJECT_ID}",
|
|
312
|
+
BACKWRITE_BRANCH_ID: "${BACKWRITE_BRANCH_ID}",
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
}, null, 2),
|
|
317
|
+
};
|
|
318
|
+
if (schemaSnapshot !== undefined) {
|
|
319
|
+
files["schema.json"] = JSON.stringify(schemaSnapshot, null, 2);
|
|
320
|
+
}
|
|
321
|
+
const templates = {
|
|
322
|
+
"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`,
|
|
323
|
+
"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`,
|
|
324
|
+
"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`,
|
|
325
|
+
"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`,
|
|
326
|
+
};
|
|
327
|
+
for (const s of skills) {
|
|
328
|
+
const k = slugify(s);
|
|
329
|
+
files[`skills/${k}/SKILL.md`] =
|
|
330
|
+
templates[k] ||
|
|
331
|
+
`---\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`;
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
standard: "1.0.0",
|
|
335
|
+
name: safeName,
|
|
336
|
+
files,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
//# sourceMappingURL=agents.js.map
|