@slashfi/agents-sdk 0.20.0 → 0.22.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/src/pack.ts ADDED
@@ -0,0 +1,395 @@
1
+ /**
2
+ * ADK Pack
3
+ *
4
+ * Generates a publishable npm package from an agent.json file.
5
+ *
6
+ * Input: agent.json (SerializedAgentDefinition)
7
+ * Output: ready-to-publish directory with:
8
+ * - package.json
9
+ * - agent.json (copy)
10
+ * - meta.json (version metadata + diff)
11
+ * - index.js + index.d.ts (typed export)
12
+ */
13
+
14
+ import { spawnSync } from "node:child_process";
15
+ import { createHash } from "node:crypto";
16
+ import {
17
+ existsSync,
18
+ mkdirSync,
19
+ readFileSync,
20
+ writeFileSync,
21
+ } from "node:fs";
22
+ import { resolve } from "node:path";
23
+ import { parseJsonc } from "./jsonc.js";
24
+ import type { SerializedAgentDefinition } from "./serialized.js";
25
+
26
+ // ============================================
27
+ // Types
28
+ // ============================================
29
+
30
+ export interface PackOptions {
31
+ /** Path to agent.json */
32
+ agentFile: string;
33
+ /** Output directory (default: ./dist) */
34
+ outDir?: string;
35
+ /** npm scope (default: @agentdef) */
36
+ scope?: string;
37
+ /** Previous version's agent.json path for diff (optional) */
38
+ previousAgentFile?: string;
39
+ }
40
+
41
+ export interface PackResult {
42
+ packageDir: string;
43
+ packageName: string;
44
+ version: string;
45
+ hash: string;
46
+ meta: VersionMeta;
47
+ }
48
+
49
+ export interface VersionMeta {
50
+ hash: string;
51
+ serverVersion: string;
52
+ npmPackage?: string;
53
+ toolCount: number;
54
+ sizeBytes: number;
55
+ generatedAt: string;
56
+ sdkVersion: string;
57
+ changes?: VersionChanges;
58
+ }
59
+
60
+ export interface VersionChanges {
61
+ previousHash?: string;
62
+ toolsAdded: string[];
63
+ toolsRemoved: string[];
64
+ toolsModified: string[];
65
+ schemaChanges: string[];
66
+ }
67
+
68
+ // ============================================
69
+ // Hash
70
+ // ============================================
71
+
72
+ function contentHash(content: string): string {
73
+ return createHash("sha256").update(content).digest("hex").slice(0, 8);
74
+ }
75
+
76
+ // ============================================
77
+ // Diff
78
+ // ============================================
79
+
80
+ function diffDefinitions(
81
+ current: SerializedAgentDefinition,
82
+ previous: SerializedAgentDefinition,
83
+ previousRawContent: string,
84
+ ): VersionChanges {
85
+ const prevToolNames = new Set(previous.tools.map((t) => t.name));
86
+ const currToolNames = new Set(current.tools.map((t) => t.name));
87
+
88
+ const toolsAdded = current.tools
89
+ .filter((t) => !prevToolNames.has(t.name))
90
+ .map((t) => t.name);
91
+ const toolsRemoved = previous.tools
92
+ .filter((t) => !currToolNames.has(t.name))
93
+ .map((t) => t.name);
94
+
95
+ // Find modified tools (same name, different schema)
96
+ const toolsModified: string[] = [];
97
+ const schemaChanges: string[] = [];
98
+ const prevToolMap = new Map(previous.tools.map((t) => [t.name, t]));
99
+
100
+ for (const tool of current.tools) {
101
+ const prev = prevToolMap.get(tool.name);
102
+ if (!prev) continue;
103
+ const currSchema = JSON.stringify(tool.inputSchema);
104
+ const prevSchema = JSON.stringify(prev.inputSchema);
105
+ if (currSchema !== prevSchema) {
106
+ toolsModified.push(tool.name);
107
+ // Generate human-readable schema change description
108
+ const currProps = Object.keys(
109
+ ((tool.inputSchema as Record<string, unknown>).properties as Record<
110
+ string,
111
+ unknown
112
+ >) || {},
113
+ );
114
+ const prevProps = Object.keys(
115
+ ((prev.inputSchema as Record<string, unknown>).properties as Record<
116
+ string,
117
+ unknown
118
+ >) || {},
119
+ );
120
+ const added = currProps.filter((p) => !prevProps.includes(p));
121
+ const removed = prevProps.filter((p) => !currProps.includes(p));
122
+ if (added.length > 0) {
123
+ schemaChanges.push(
124
+ `${tool.name}: added properties: ${added.join(", ")}`,
125
+ );
126
+ }
127
+ if (removed.length > 0) {
128
+ schemaChanges.push(
129
+ `${tool.name}: removed properties: ${removed.join(", ")}`,
130
+ );
131
+ }
132
+ if (added.length === 0 && removed.length === 0) {
133
+ schemaChanges.push(`${tool.name}: schema modified`);
134
+ }
135
+ }
136
+ }
137
+
138
+ return {
139
+ previousHash: contentHash(previousRawContent),
140
+ toolsAdded,
141
+ toolsRemoved,
142
+ toolsModified,
143
+ schemaChanges,
144
+ };
145
+ }
146
+
147
+ // ============================================
148
+ // Pack
149
+ // ============================================
150
+
151
+ export function pack(options: PackOptions): PackResult {
152
+ const { agentFile, outDir = "./dist", scope = "@agentdef" } = options;
153
+
154
+ // Read agent.json
155
+ const agentPath = resolve(agentFile);
156
+ if (!existsSync(agentPath)) {
157
+ throw new Error(`agent.json not found: ${agentPath}`);
158
+ }
159
+ const agentContent = readFileSync(agentPath, "utf-8");
160
+ const definition = parseJsonc(agentContent) as SerializedAgentDefinition;
161
+
162
+ // Compute hash + version
163
+ const hash = contentHash(agentContent);
164
+ const version = `${definition.version || "1.0.0"}`;
165
+ const packageName = `${scope}/${definition.path}`;
166
+
167
+ // Create output directory
168
+ const packageDir = resolve(outDir, definition.path);
169
+ mkdirSync(packageDir, { recursive: true });
170
+
171
+ // Generate meta.json
172
+ const meta: VersionMeta = {
173
+ hash,
174
+ serverVersion:
175
+ definition.serverInfo?.version || definition.version || "1.0.0",
176
+ npmPackage: definition.serverSource,
177
+ toolCount: definition.tools.length,
178
+ sizeBytes: Buffer.byteLength(agentContent, "utf-8"),
179
+ generatedAt: definition.generatedAt || new Date().toISOString(),
180
+ sdkVersion: definition.sdkVersion || "0.21.0",
181
+ };
182
+
183
+ // Diff against previous if provided
184
+ if (options.previousAgentFile) {
185
+ const prevPath = resolve(options.previousAgentFile);
186
+ if (existsSync(prevPath)) {
187
+ const prevContent = readFileSync(prevPath, "utf-8");
188
+ const prevDef = parseJsonc(prevContent) as SerializedAgentDefinition;
189
+ meta.changes = diffDefinitions(definition, prevDef, prevContent);
190
+ }
191
+ }
192
+
193
+ // Write agent.json
194
+ writeFileSync(resolve(packageDir, "agent.json"), agentContent);
195
+
196
+ // Write meta.json
197
+ writeFileSync(
198
+ resolve(packageDir, "meta.json"),
199
+ `${JSON.stringify(meta, null, 2)}\n`,
200
+ );
201
+
202
+ // Write package.json
203
+ const pkg = {
204
+ name: packageName,
205
+ version,
206
+ description:
207
+ definition.description || `Agent definition for ${definition.name}`,
208
+ type: "module",
209
+ main: "index.js",
210
+ types: "index.d.ts",
211
+ exports: {
212
+ ".": {
213
+ import: "./index.js",
214
+ types: "./index.d.ts",
215
+ },
216
+ "./agent.json": "./agent.json",
217
+ "./meta.json": "./meta.json",
218
+ },
219
+ files: ["index.js", "index.d.ts", "agent.json", "meta.json"],
220
+ peerDependencies: {
221
+ "@slashfi/agents-sdk": ">=0.21.0",
222
+ },
223
+ keywords: ["agent", "mcp", "agentdef", definition.path],
224
+ license: "MIT",
225
+ repository: {
226
+ type: "git",
227
+ url: "https://github.com/slashfi/agents-sdk",
228
+ },
229
+ };
230
+ writeFileSync(
231
+ resolve(packageDir, "package.json"),
232
+ `${JSON.stringify(pkg, null, 2)}\n`,
233
+ );
234
+
235
+ // Write index.js
236
+ writeFileSync(
237
+ resolve(packageDir, "index.js"),
238
+ [
239
+ 'import { readFileSync } from "node:fs";',
240
+ 'import { fileURLToPath } from "node:url";',
241
+ 'import { dirname, resolve } from "node:path";',
242
+ "",
243
+ "const __dirname = dirname(fileURLToPath(import.meta.url));",
244
+ 'const definition = JSON.parse(readFileSync(resolve(__dirname, "agent.json"), "utf-8"));',
245
+ "export default definition;",
246
+ "export { definition };",
247
+ "",
248
+ ].join("\n"),
249
+ );
250
+
251
+ // Write index.d.ts
252
+ writeFileSync(
253
+ resolve(packageDir, "index.d.ts"),
254
+ [
255
+ 'import type { SerializedAgentDefinition } from "@slashfi/agents-sdk";',
256
+ "",
257
+ "declare const definition: SerializedAgentDefinition;",
258
+ "export default definition;",
259
+ "export { definition };",
260
+ "",
261
+ ].join("\n"),
262
+ );
263
+
264
+ return { packageDir, packageName, version, hash, meta };
265
+ }
266
+
267
+ // ============================================
268
+ // Publish
269
+ // ============================================
270
+
271
+ export interface PublishOptions extends PackOptions {
272
+ /** Dry run (don't actually publish) */
273
+ dryRun?: boolean;
274
+ /** npm tag (default: latest) */
275
+ tag?: string;
276
+ /** npm access level */
277
+ access?: "public" | "restricted";
278
+ /** npm registry URL */
279
+ registry?: string;
280
+ }
281
+
282
+ /**
283
+ * Compare semver: returns true if `a` is older than `b`.
284
+ */
285
+ function isOlderVersion(a: string, b: string): boolean {
286
+ const pa = a.split(".").map(Number);
287
+ const pb = b.split(".").map(Number);
288
+ for (let i = 0; i < 3; i++) {
289
+ if ((pa[i] || 0) < (pb[i] || 0)) return true;
290
+ if ((pa[i] || 0) > (pb[i] || 0)) return false;
291
+ }
292
+ return false; // equal
293
+ }
294
+
295
+ export function publish(options: PublishOptions): PackResult {
296
+ const result = pack(options);
297
+
298
+ // Check if this version already exists in the registry
299
+ const registryArgs = options.registry ? ["--registry", options.registry] : [];
300
+ const viewProc = spawnSync(
301
+ "npm",
302
+ ["view", `${result.packageName}`, "versions", "--json", ...registryArgs],
303
+ { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] },
304
+ );
305
+
306
+ if (viewProc.status === 0 && viewProc.stdout) {
307
+ try {
308
+ const raw = JSON.parse(viewProc.stdout);
309
+ const existing: string[] = Array.isArray(raw) ? raw : [raw];
310
+
311
+ // E409 prevention: version already exists
312
+ if (existing.includes(result.version)) {
313
+ const versions = existing.join(", ");
314
+ throw new Error(
315
+ `\x1b[31m\u2717 ${result.packageName}@${result.version} already exists in registry\x1b[0m\n\n Published versions: ${versions}\n Hint: bump the version in agent.json, or use --tag to publish a pre-release`,
316
+ );
317
+ }
318
+
319
+ // Out-of-order protection: warn if publishing older than latest
320
+ const latestViewProc = spawnSync(
321
+ "npm",
322
+ ["view", `${result.packageName}`, "dist-tags.latest", ...registryArgs],
323
+ { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] },
324
+ );
325
+ if (latestViewProc.status === 0 && latestViewProc.stdout) {
326
+ const latest = latestViewProc.stdout.trim();
327
+ if (latest && !options.tag && isOlderVersion(result.version, latest)) {
328
+ console.warn(
329
+ `\x1b[33m\u26A0 Warning: publishing ${result.version} which is older than latest (${latest})\x1b[0m`,
330
+ );
331
+ console.warn(
332
+ ` This will move the "latest" tag from ${latest} to ${result.version}.`,
333
+ );
334
+ console.warn(
335
+ " Use --tag <name> to publish without affecting latest.",
336
+ );
337
+ throw new Error(
338
+ `Refusing to clobber latest tag. Use --tag <name> to publish ${result.version} alongside ${latest}.`,
339
+ );
340
+ }
341
+ }
342
+ } catch (e) {
343
+ if (e instanceof Error && e.message.includes("already exists")) throw e;
344
+ if (e instanceof Error && e.message.includes("Refusing to clobber"))
345
+ throw e;
346
+ // JSON parse error or other issue — continue with publish
347
+ }
348
+ }
349
+
350
+ const npmArgs = ["publish", result.packageDir];
351
+ npmArgs.push("--access", options.access || "public");
352
+ if (options.tag) npmArgs.push("--tag", options.tag);
353
+ if (options.dryRun) npmArgs.push("--dry-run");
354
+ if (options.registry) npmArgs.push("--registry", options.registry);
355
+
356
+ console.log(
357
+ `Publishing ${result.packageName}@${result.version} (hash: ${result.hash})`,
358
+ );
359
+ const proc = spawnSync("npm", npmArgs, {
360
+ stdio: ["pipe", "pipe", "pipe"],
361
+ encoding: "utf-8",
362
+ });
363
+
364
+ if (proc.status !== 0) {
365
+ const stderr = proc.stderr || "";
366
+ // Extract npm log path for debug hint
367
+ const logMatch = stderr.match(/complete log[^:]*:\s*(.+\.log)/i);
368
+ const logHint = logMatch
369
+ ? `\n Debug: cat ${logMatch[1].trim()} | tail -40`
370
+ : "";
371
+ // Parse npm error for better messages
372
+ if (stderr.includes("E409") || stderr.includes("already present")) {
373
+ throw new Error(
374
+ `\x1b[31m\u2717 ${result.packageName}@${result.version} already exists in registry\x1b[0m\n\n` +
375
+ ` Hint: bump the version in agent.json, or use --tag to publish a pre-release${logHint}`,
376
+ );
377
+ }
378
+ if (stderr.includes("E401") || stderr.includes("authentication")) {
379
+ throw new Error(
380
+ `\x1b[31m\u2717 Authentication failed\x1b[0m\n\n Run: npm login --scope=@agentdef\n Or set NPM_TOKEN in your environment${logHint}`,
381
+ );
382
+ }
383
+ if (stderr.includes("E403") || stderr.includes("Forbidden")) {
384
+ throw new Error(
385
+ `\x1b[31m\u2717 Permission denied publishing ${result.packageName}\x1b[0m\n\n Make sure you have publish access to the @agentdef scope.\n Run: npm access ls-packages @agentdef${logHint}`,
386
+ );
387
+ }
388
+ // Fallback: show raw error
389
+ throw new Error(
390
+ `npm publish failed (exit ${proc.status}):${logHint}\n${stderr}`,
391
+ );
392
+ }
393
+
394
+ return result;
395
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Serialized Agent Definition
3
+ *
4
+ * Pure-data, JSON-serializable representation of an agent.
5
+ * No execute functions, no runtime hooks — just schemas and metadata.
6
+ *
7
+ * This is the universal IR:
8
+ * - Codegen produces it (MCP introspection → SerializedAgentDefinition)
9
+ * - Registry stores it (JSON in DB or filesystem)
10
+ * - API serves it (GET /agents/:name → SerializedAgentDefinition)
11
+ * - createClient() hydrates it (definition → typed proxy with real calls)
12
+ */
13
+
14
+ import type { JsonSchema, SecurityScheme } from "./types.js";
15
+
16
+ // ============================================
17
+ // Serialized Tool
18
+ // ============================================
19
+
20
+ export interface SerializedTool {
21
+ /** Tool name (unique within agent) */
22
+ name: string;
23
+ /** Short description for tool discovery */
24
+ description: string;
25
+ /** JSON Schema for input parameters */
26
+ inputSchema: JsonSchema;
27
+ /** JSON Schema for output (optional) */
28
+ outputSchema?: JsonSchema;
29
+ }
30
+
31
+ // ============================================
32
+ // Serialized Agent Definition
33
+ // ============================================
34
+
35
+ export interface SerializedAgentDefinition {
36
+ /** Agent path (e.g., 'notion', 'linear', 'github') */
37
+ path: string;
38
+ /** Human-readable name */
39
+ name: string;
40
+ /** Short description */
41
+ description: string;
42
+ /** Version of the definition */
43
+ version: string;
44
+ /** Visibility level */
45
+ visibility: "public" | "private";
46
+ /** Auth requirements */
47
+ auth?: SecurityScheme;
48
+ /** MCP server source command (e.g., 'npx @notionhq/notion-mcp-server') */
49
+ serverSource?: string;
50
+ /** Server info from MCP introspection */
51
+ serverInfo?: {
52
+ name: string;
53
+ version: string;
54
+ };
55
+ /** Tool definitions (schemas only, no execute) */
56
+ tools: SerializedTool[];
57
+ /** ISO timestamp of when this was generated */
58
+ generatedAt?: string;
59
+ /** SDK version used for codegen */
60
+ sdkVersion?: string;
61
+ }
62
+
63
+ // ============================================
64
+ // Serialization helpers
65
+ // ============================================
66
+
67
+ import type { AgentDefinition, ToolContext, ToolDefinition } from "./types.js";
68
+
69
+ /**
70
+ * Serialize an AgentDefinition to its pure-data representation.
71
+ * Strips execute functions, runtime hooks, listeners, etc.
72
+ */
73
+ export function serializeAgent(
74
+ agent: AgentDefinition,
75
+ meta?: { serverSource?: string; version?: string },
76
+ ): SerializedAgentDefinition {
77
+ return {
78
+ path: agent.path,
79
+ name: agent.config?.name ?? agent.path,
80
+ description: agent.config?.description ?? "",
81
+ version: meta?.version ?? "1.0.0",
82
+ visibility: (agent.visibility as "public" | "private") ?? "public",
83
+ auth: agent.config?.security,
84
+ serverSource: meta?.serverSource,
85
+ tools: agent.tools.map(serializeTool),
86
+ generatedAt: new Date().toISOString(),
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Serialize a single ToolDefinition to its pure-data representation.
92
+ */
93
+ export function serializeTool(
94
+ tool: ToolDefinition<ToolContext, unknown, unknown>,
95
+ ): SerializedTool {
96
+ return {
97
+ name: tool.name,
98
+ description: tool.description,
99
+ inputSchema: tool.inputSchema,
100
+ ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
101
+ };
102
+ }
package/dist/cli.d.ts DELETED
@@ -1,24 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * agents-sdk CLI
4
- *
5
- * Unified command-line interface for the agents SDK.
6
- *
7
- * Commands:
8
- * codegen - Generate agent definitions from an MCP server
9
- * use - Execute a tool on a codegenned agent
10
- *
11
- * @example
12
- * ```bash
13
- * # Generate from MCP server
14
- * agents-sdk codegen --server 'npx @mcp/notion' --name notion --out ./agents/@notion
15
- *
16
- * # Use a tool
17
- * agents-sdk use notion search_pages '{"query": "hello"}'
18
- *
19
- * # List tools on a codegenned agent
20
- * agents-sdk use notion --list
21
- * ```
22
- */
23
- export {};
24
- //# sourceMappingURL=cli.d.ts.map
package/dist/cli.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;GAoBG"}