diff --git a/backend/__tests__/integration/self-serve-install.test.js b/backend/__tests__/integration/self-serve-install.test.js new file mode 100644 index 0000000000..555a3e199e --- /dev/null +++ b/backend/__tests__/integration/self-serve-install.test.js @@ -0,0 +1,204 @@ +/** + * ADR-006 Phase 1 — self-serve webhook install integration test. + * + * Walks the full self-serve flow: + * authed pod-member POSTs /install with runtimeType:'webhook' and NO + * pre-published manifest → backend synthesizes ephemeral AgentRegistry row + * → mints runtime token → token authorizes /events + posting messages + * → ephemeral row is excluded from marketplace catalog browse + * → non-webhook installs without manifest still 404. + */ + +const express = require('express'); +const request = require('supertest'); +const jwt = require('jsonwebtoken'); + +const { setupMongoDb, closeMongoDb } = require('../utils/testUtils'); + +const User = require('../../models/User'); +const Pod = require('../../models/Pod'); +const { AgentRegistry, AgentInstallation } = require('../../models/AgentRegistry'); + +const registryRoutes = require('../../routes/registry'); +const agentsRuntimeRoutes = require('../../routes/agentsRuntime'); + +const JWT_SECRET = 'test-jwt-secret-self-serve-install'; + +jest.setTimeout(60000); + +describe('ADR-006 self-serve webhook install', () => { + let app; + let podMember; + let outsider; + let memberToken; + let outsiderToken; + let pod; + + beforeAll(async () => { + process.env.JWT_SECRET = JWT_SECRET; + await setupMongoDb(); + + app = express(); + app.use(express.json()); + app.use('/api/registry', registryRoutes); + app.use('/api/agents/runtime', agentsRuntimeRoutes); + + podMember = await User.create({ + username: 'pod-member', + email: 'pod-member@test.com', + password: 'password123', + }); + outsider = await User.create({ + username: 'outsider', + email: 'outsider@test.com', + password: 'password123', + }); + memberToken = jwt.sign({ id: podMember._id.toString() }, JWT_SECRET); + outsiderToken = jwt.sign({ id: outsider._id.toString() }, JWT_SECRET); + + pod = await Pod.create({ + name: 'Self-Serve Test Pod', + type: 'chat', + createdBy: podMember._id, + members: [podMember._id], + }); + }); + + afterAll(async () => { + await closeMongoDb(); + }); + + beforeEach(async () => { + await AgentInstallation.deleteMany({}); + // Wipe both ephemeral self-serve rows AND any non-ephemeral fixtures + // created by individual tests, so order/parallelism doesn't leak. + await AgentRegistry.deleteMany({ agentName: { $regex: /^(public-|my-|outsider-|fallback-|collide|bad-|research-)/ } }); + await AgentRegistry.deleteMany({ ephemeral: true }); + }); + + it('installs a webhook agent with no published manifest and returns a runtime token', async () => { + const installRes = await request(app) + .post('/api/registry/install') + .set('Authorization', `Bearer ${memberToken}`) + .send({ + agentName: 'my-research-bot', + podId: pod._id.toString(), + displayName: 'My Research Bot', + version: '1.0.0', + config: { + runtime: { + runtimeType: 'webhook', + }, + }, + scopes: ['context:read', 'messages:write'], + }); + + expect(installRes.status).toBe(200); + expect(installRes.body.success).toBe(true); + expect(installRes.body.installation.agentName).toBe('my-research-bot'); + + // Synthesized registry row marked ephemeral, owned by installer. + const reg = await AgentRegistry.findOne({ agentName: 'my-research-bot' }); + expect(reg).toBeTruthy(); + expect(reg.ephemeral).toBe(true); + expect(reg.publisher.userId.toString()).toBe(podMember._id.toString()); + expect(reg.registry).toBe('private'); + + // Mint runtime token + verify it can poll events. + const tokenRes = await request(app) + .post(`/api/registry/pods/${pod._id}/agents/my-research-bot/runtime-tokens`) + .set('Authorization', `Bearer ${memberToken}`) + .send({ label: 'self-serve-test' }); + const runtimeToken = tokenRes.body.token; + expect(runtimeToken).toMatch(/^cm_agent_/); + + const eventsRes = await request(app) + .get('/api/agents/runtime/events') + .set('Authorization', `Bearer ${runtimeToken}`); + expect(eventsRes.status).toBe(200); + expect(Array.isArray(eventsRes.body.events)).toBe(true); + }); + + it('non-webhook installs without published manifest still 404', async () => { + const res = await request(app) + .post('/api/registry/install') + .set('Authorization', `Bearer ${memberToken}`) + .send({ + agentName: 'unknown-native-agent', + podId: pod._id.toString(), + config: { runtime: { runtimeType: 'native' } }, + scopes: ['context:read'], + }); + expect(res.status).toBe(404); + expect(res.body.error).toMatch(/not found in registry/i); + }); + + it('rejects malformed agentName with 400 (not 500 from schema validation)', async () => { + const res = await request(app) + .post('/api/registry/install') + .set('Authorization', `Bearer ${memberToken}`) + .send({ + agentName: 'has spaces', + podId: pod._id.toString(), + config: { runtime: { runtimeType: 'webhook' } }, + scopes: ['context:read'], + }); + expect(res.status).toBe(400); + expect(res.body.error).toMatch(/Invalid agentName/); + // No row should have been created on validation failure. + const reg = await AgentRegistry.findOne({ agentName: 'has spaces' }); + expect(reg).toBeNull(); + }); + + it('rejects self-serve install when caller is not a pod member', async () => { + const res = await request(app) + .post('/api/registry/install') + .set('Authorization', `Bearer ${outsiderToken}`) + .send({ + agentName: 'outsider-bot', + podId: pod._id.toString(), + config: { runtime: { runtimeType: 'webhook' } }, + scopes: ['context:read'], + }); + expect(res.status).toBe(403); + // No ephemeral row should have been created. + const reg = await AgentRegistry.findOne({ agentName: 'outsider-bot' }); + expect(reg).toBeNull(); + }); + + it('marketplace catalog excludes ephemeral self-serve agents', async () => { + // Create one published agent and one ephemeral via self-serve. + await AgentRegistry.create({ + agentName: 'public-marketplace-bot', + displayName: 'Public Bot', + description: 'Catalog-visible', + registry: 'commonly-community', + manifest: { + name: 'public-marketplace-bot', + version: '1.0.0', + capabilities: [], + context: { required: [] }, + runtime: { type: 'standalone', connection: 'rest' }, + }, + latestVersion: '1.0.0', + versions: [{ version: '1.0.0', publishedAt: new Date() }], + }); + await request(app) + .post('/api/registry/install') + .set('Authorization', `Bearer ${memberToken}`) + .send({ + agentName: 'my-private-webhook', + podId: pod._id.toString(), + config: { runtime: { runtimeType: 'webhook' } }, + scopes: ['context:read'], + }); + + const catalogRes = await request(app) + .get('/api/registry/agents') + .set('Authorization', `Bearer ${memberToken}`); + expect(catalogRes.status).toBe(200); + const names = (catalogRes.body.agents || []).map((a) => a.name); + expect(names).toContain('public-marketplace-bot'); + expect(names).not.toContain('my-private-webhook'); + }); +}); diff --git a/backend/models/AgentRegistry.ts b/backend/models/AgentRegistry.ts index da43f37a78..3f1ba59a38 100644 --- a/backend/models/AgentRegistry.ts +++ b/backend/models/AgentRegistry.ts @@ -64,6 +64,7 @@ export interface IAgentRegistry extends Document { }; status: RegistryStatus; iconUrl?: string; + ephemeral?: boolean; createdAt: Date; updatedAt: Date; } @@ -140,6 +141,11 @@ const AgentRegistrySchema = new Schema( }, status: { type: String, enum: ['active', 'deprecated', 'unpublished', 'pending-review'], default: 'active' }, iconUrl: String, + // ADR-006: self-serve webhook installs synthesize an ephemeral registry + // row owned by the installing user. Excluded from the marketplace catalog + // (search() filters by default), still resolvable by name for install/ + // uninstall flows. GC of orphan ephemerals is deferred (ADR-006 OQ #1). + ephemeral: { type: Boolean, default: false }, }, { timestamps: true }, ); @@ -156,7 +162,9 @@ AgentRegistrySchema.statics.search = function ( options: { limit?: number; offset?: number; category?: string | null; registry?: string | null; verified?: boolean | null } = {}, ) { const { limit = 20, offset = 0, category = null, registry = null, verified = null } = options; - const filter: Record = { status: 'active' }; + // Self-serve / ephemeral rows are private to their installer — never appear + // in marketplace browse. Direct getByName() lookup still resolves them. + const filter: Record = { status: 'active', ephemeral: { $ne: true } }; if (query) filter.$text = { $search: query }; if (category) filter.categories = category; if (registry) filter.registry = registry; diff --git a/backend/routes/registry/install.ts b/backend/routes/registry/install.ts index a49236e108..cfd5fee300 100644 --- a/backend/routes/registry/install.ts +++ b/backend/routes/registry/install.ts @@ -82,11 +82,6 @@ installRouter.post('/install', auth, async (req: any, res: any) => { return res.status(401).json({ error: 'Unauthorized' }); } - const agent = await AgentRegistry.getByName(agentName); - if (!agent) { - return res.status(404).json({ error: 'Agent not found in registry' }); - } - const pod = await Pod.findById(podId).lean(); if (!pod) { return res.status(404).json({ error: 'Pod not found' }); @@ -103,6 +98,65 @@ installRouter.post('/install', auth, async (req: any, res: any) => { return res.status(403).json({ error: 'You must be a member of this pod' }); } + let agent = await AgentRegistry.getByName(agentName); + + // ADR-006 §Self-serve install: when a pod member installs a webhook-typed + // agent that has no published manifest, synthesize an ephemeral registry + // row owned by them. Marketplace catalog excludes ephemeral rows; only + // direct getByName() resolves them. Membership check above is the gate. + if (!agent) { + const requestedRuntimeType = String( + (config && config.runtime && (config.runtime as any).runtimeType) || '', + ).toLowerCase(); + if (requestedRuntimeType !== 'webhook') { + return res.status(404).json({ error: 'Agent not found in registry' }); + } + // ADR-006 §invariant 7 — self-serve is pod-scope only. The route + // already requires `podId` (pod 404 above guards this), but the + // explicit check here keeps the invariant in source so a future + // refactor that adds instance/user/dm scope can't bypass it. + if (!podId) { + return res.status(400).json({ error: 'podId is required for self-serve install' }); + } + // The AgentRegistry schema enforces /^[a-z0-9-]+$/ at write time, so + // a malformed name would surface as a Mongoose 500. Reject upstream. + if (!/^[a-z0-9-]+$/.test(String(agentName).toLowerCase())) { + return res.status(400).json({ + error: 'Invalid agentName: must match /^[a-z0-9-]+$/', + }); + } + // manifest.runtime.type is the registry-level deployment shape + // (enum: 'standalone' | 'commonly-hosted' | 'hybrid'). Self-serve + // webhook agents run outside Commonly so they map to 'standalone'. + // The actual webhook routing is driven by config.runtime.runtimeType + // on the AgentInstallation, not on the registry manifest. + const synthManifest = { + name: String(agentName).toLowerCase(), + version: String(version || '1.0.0'), + description: String(displayName || agentName), + capabilities: [], + context: { required: [], optional: [] }, + runtime: { type: 'standalone', connection: 'rest' }, + }; + agent = await AgentRegistry.create({ + agentName: synthManifest.name, + displayName: String(displayName || agentName), + description: synthManifest.description, + manifest: synthManifest, + latestVersion: synthManifest.version, + versions: [{ version: synthManifest.version, manifest: synthManifest, publishedAt: new Date() }], + registry: 'private', + publisher: { userId, name: req.user?.username }, + ephemeral: true, + }); + console.log('[cap self-serve-install]', { + user: String(userId), + pod: String(podId), + agent: synthManifest.name, + runtime: 'webhook', + }); + } + let normalizedInstanceId; if (instanceId) { normalizedInstanceId = normalizeInstanceId(instanceId); diff --git a/backend/routes/registry/pod-agents.ts b/backend/routes/registry/pod-agents.ts index f091e7c806..62d8b2b6f4 100644 --- a/backend/routes/registry/pod-agents.ts +++ b/backend/routes/registry/pod-agents.ts @@ -81,6 +81,10 @@ podAgentsRouter.delete('/agents/:name/pods/:podId', auth, async (req: any, res: await AgentInstallation.uninstall(name, podId, instanceId); await AgentProfile.deleteOne({ agentId: buildAgentProfileId(name, instanceId), podId }); + // ADR-006 OQ #1: ephemeral self-serve registry rows whose only + // installation was just removed are leaked here. v1 punts; the GC + // janitor lands when orphan-row volume warrants it. + try { const resolvedType = AgentIdentityService.resolveAgentType(name); await AgentIdentityService.removeAgentFromPod( diff --git a/cli/__tests__/agent-init.test.mjs b/cli/__tests__/agent-init.test.mjs new file mode 100644 index 0000000000..df19356ded --- /dev/null +++ b/cli/__tests__/agent-init.test.mjs @@ -0,0 +1,147 @@ +/** + * agent-init.test.mjs — ADR-006 Phase 1 scaffolder. + * + * Drives `performInit` with a mocked CAP client and a temp `targetDir`, + * asserting: + * - SDK + bot.py are copied verbatim from examples/ + * - .commonly-env is written 0600 with the runtime token + * - install POSTed with runtimeType:'webhook' + * - clobber-protection refuses to overwrite any of the three files + * - unknown languages are rejected + */ + +import { jest } from '@jest/globals'; +import os from 'os'; +import path from 'path'; +import fs from 'fs'; + +import { performInit } from '../src/commands/agent.js'; + +const REPO_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..', '..'); +const SDK_FILE = path.join(REPO_ROOT, 'examples', 'sdk', 'python', 'commonly.py'); +const BOT_FILE = path.join(REPO_ROOT, 'examples', 'hello-world-python', 'bot.py'); + +const makeClient = ({ runtimeToken = 'cm_agent_init_test' } = {}) => { + const post = jest.fn(async (route, body) => { + if (route === '/api/registry/install') { + return { + installation: { + agentName: body.agentName, + instanceId: 'default', + podId: body.podId, + }, + runtimeToken, + }; + } + if (route.endsWith('/runtime-tokens')) { + return { token: runtimeToken }; + } + throw new Error(`unexpected POST ${route}`); + }); + return { post, get: jest.fn() }; +}; + +let tmp; + +beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-init-test-')); +}); +afterEach(() => { + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +describe('performInit (python)', () => { + test('copies SDK + template, mints token, writes .commonly-env', async () => { + const client = makeClient({ runtimeToken: 'cm_agent_xyz' }); + const result = await performInit({ + client, + language: 'python', + agentName: 'research-bot', + podId: 'pod-1', + targetDir: tmp, + }); + + // Files written + const sdkPath = path.join(tmp, 'commonly.py'); + const botPath = path.join(tmp, 'research-bot.py'); + const envPath = path.join(tmp, '.commonly-env'); + expect(fs.existsSync(sdkPath)).toBe(true); + expect(fs.existsSync(botPath)).toBe(true); + expect(fs.existsSync(envPath)).toBe(true); + + // SDK + bot are byte-for-byte copies of the canonical examples + expect(fs.readFileSync(sdkPath, 'utf8')).toBe(fs.readFileSync(SDK_FILE, 'utf8')); + expect(fs.readFileSync(botPath, 'utf8')).toBe(fs.readFileSync(BOT_FILE, 'utf8')); + + // Token file: KEY=VALUE format (sourceable + dotenv-friendly), mode 0600 + expect(fs.readFileSync(envPath, 'utf8')).toBe('COMMONLY_TOKEN=cm_agent_xyz\n'); + if (process.platform !== 'win32') { + const mode = fs.statSync(envPath).mode & 0o777; + expect(mode).toBe(0o600); + } + + // Install was issued with runtimeType:'webhook' (drives self-serve path) + expect(client.post).toHaveBeenCalledWith( + '/api/registry/install', + expect.objectContaining({ + agentName: 'research-bot', + podId: 'pod-1', + config: expect.objectContaining({ + runtime: expect.objectContaining({ runtimeType: 'webhook' }), + }), + }), + ); + + // Result object exposes the run hint for the CLI to print + expect(result.runtimeToken).toBe('cm_agent_xyz'); + expect(result.runHint).toContain('python3 research-bot.py'); + expect(result.files.env).toBe(envPath); + }); + + test('falls back to /runtime-tokens when install omits runtimeToken', async () => { + const client = { + post: jest.fn(async (route, body) => { + if (route === '/api/registry/install') { + return { installation: { agentName: body.agentName, instanceId: 'default' } }; + } + if (route.endsWith('/runtime-tokens')) { + return { token: 'cm_agent_from_tokens_route' }; + } + throw new Error(`unexpected POST ${route}`); + }), + get: jest.fn(), + }; + const res = await performInit({ + client, language: 'python', agentName: 'fallback-bot', + podId: 'pod-2', targetDir: tmp, + }); + expect(res.runtimeToken).toBe('cm_agent_from_tokens_route'); + expect(client.post).toHaveBeenCalledWith( + '/api/registry/pods/pod-2/agents/fallback-bot/runtime-tokens', {}, + ); + }); + + test('refuses to clobber an existing file in the target directory', async () => { + fs.writeFileSync(path.join(tmp, 'commonly.py'), '# user file', 'utf8'); + + const client = makeClient(); + await expect(performInit({ + client, language: 'python', agentName: 'collide', + podId: 'pod-1', targetDir: tmp, + })).rejects.toThrow(/Refusing to overwrite/); + // No install was issued — bail-before-write semantics. + expect(client.post).not.toHaveBeenCalled(); + // The pre-existing user file is untouched. + expect(fs.readFileSync(path.join(tmp, 'commonly.py'), 'utf8')).toBe('# user file'); + }); + + test('rejects unknown languages without writing anything', async () => { + const client = makeClient(); + await expect(performInit({ + client, language: 'rust', agentName: 'r', + podId: 'pod-1', targetDir: tmp, + })).rejects.toThrow(/Unsupported language "rust"/); + expect(fs.readdirSync(tmp)).toEqual([]); + expect(client.post).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/src/commands/agent.js b/cli/src/commands/agent.js index 74e3311a54..2d9d9143e8 100644 --- a/cli/src/commands/agent.js +++ b/cli/src/commands/agent.js @@ -5,14 +5,16 @@ * connect — local dev loop: poll events → forward to localhost * attach — wrap a local CLI as a Commonly agent (ADR-005) * run — poll events, spawn the wrapped CLI, post results (ADR-005) + * init — scaffold a webhook-SDK agent in the current dir (ADR-006) * list — list installed agents * logs — stream recent events for an agent * heartbeat — manually trigger an agent's heartbeat */ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs'; -import { join } from 'path'; +import { join, dirname, resolve as pathResolve } from 'path'; import { homedir, tmpdir } from 'os'; +import { fileURLToPath } from 'url'; import { createClient } from '../lib/api.js'; import { getToken, resolveInstanceUrl } from '../lib/config.js'; @@ -251,6 +253,117 @@ export const performRun = ({ return { stop: () => { running = false; } }; }; +// ── init: scaffold a webhook-SDK agent (ADR-006 §Scaffolding) ─────────────── + +const SUPPORTED_LANGUAGES = ['python']; + +// Resolve a repo-relative path from this module, regardless of where the CLI +// is invoked from. agent.js lives at cli/src/commands/agent.js → repo root is +// three levels up. The scaffolder copies the canonical SDK file from the repo +// into the user's cwd; ADR-006 §SDK lives = "live-copy, not dependency". +// +// Removal condition: ADR-006 §Migration path Phase 4 — when the CLI is +// published as `@commonly/cli` on npm, the example files won't sit at a +// repo-relative path; we'll need to bundle them into the package at build +// time and resolve via `import.meta.resolve` or a packaged-data lookup. +// Until that phase, repo-relative is the simplest correct answer. +const repoFile = (...parts) => pathResolve( + dirname(fileURLToPath(import.meta.url)), '..', '..', '..', ...parts, +); + +const SDK_SOURCES = { + python: { + sdkSrc: () => repoFile('examples', 'sdk', 'python', 'commonly.py'), + botSrc: () => repoFile('examples', 'hello-world-python', 'bot.py'), + sdkOut: 'commonly.py', + botOut: (name) => `${name}.py`, + runHint: (name) => `COMMONLY_TOKEN=$(cat .commonly-env) python3 ${name}.py`, + }, +}; + +/** + * Scaffold a webhook-SDK agent into `targetDir`. Pure core — the commander + * action wraps this with config loading, install + token-mint, and logging. + * + * Refuses to clobber any of the three output files. Self-serve install + * (ADR-006 §Self-serve install) makes publish unnecessary. + */ +export const performInit = async ({ + client, + language, + agentName, + podId, + displayName, + targetDir, +}) => { + const recipe = SDK_SOURCES[language]; + if (!recipe) { + throw new Error( + `Unsupported language "${language}". Supported: ${SUPPORTED_LANGUAGES.join(', ')}`, + ); + } + + const sdkOutPath = join(targetDir, recipe.sdkOut); + const botOutPath = join(targetDir, recipe.botOut(agentName)); + const tokenOutPath = join(targetDir, '.commonly-env'); + + for (const f of [sdkOutPath, botOutPath, tokenOutPath]) { + if (existsSync(f)) { + throw new Error(`Refusing to overwrite existing file: ${f}`); + } + } + + if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true }); + + // Copy the SDK file verbatim; copy the bot template byte-for-byte (the + // user renames their handler later — file name carries the agent name). + writeFileSync(sdkOutPath, readFileSync(recipe.sdkSrc(), 'utf8'), 'utf8'); + writeFileSync(botOutPath, readFileSync(recipe.botSrc(), 'utf8'), 'utf8'); + + // Self-serve install (ADR-006). No publish step; the backend synthesizes + // an ephemeral registry row when no manifest exists for this name. + const installResult = await client.post('/api/registry/install', { + agentName, + podId, + displayName: displayName || agentName, + version: '1.0.0', + config: { runtime: { runtimeType: 'webhook' } }, + scopes: ['context:read', 'messages:write', 'memory:read', 'memory:write'], + }); + const installation = installResult.installation || installResult; + const instanceId = installation.instanceId || 'default'; + + let runtimeToken = installResult.runtimeToken; + if (!runtimeToken) { + const tokenData = await client.post( + `/api/registry/pods/${podId}/agents/${agentName}/runtime-tokens`, {}, + ); + runtimeToken = tokenData.token; + } + if (!runtimeToken) { + throw new Error('Runtime token was not returned by install or tokens endpoint'); + } + + // .commonly-env uses KEY=VALUE format so `source .commonly-env`, dotenv, + // and standard env-loading tools work out of the box. Future keys (e.g. + // COMMONLY_BASE_URL) just append. Mode 0600 (POSIX) since the file holds + // a long-lived bearer token. + writeFileSync(tokenOutPath, `COMMONLY_TOKEN=${runtimeToken}\n`, + { encoding: 'utf8', mode: 0o600 }); + + return { + installation, + instanceId, + runtimeToken, + files: { + sdk: sdkOutPath, + bot: botOutPath, + env: tokenOutPath, + }, + runHint: recipe.runHint(agentName), + }; +}; + export const registerAgent = (program) => { const agent = program.command('agent').description('Manage agents'); @@ -483,6 +596,46 @@ export const registerAgent = (program) => { }); }); + // ── init (ADR-006) ──────────────────────────────────────────────────────── + agent + .command('init') + .description('Scaffold a webhook-SDK agent into the current directory') + .requiredOption('--language ', `One of: ${SUPPORTED_LANGUAGES.join(', ')}`) + .requiredOption('--name ', 'Agent name (e.g. research-bot)') + .requiredOption('--pod ', 'Pod ID to install into') + .option('--display ', 'Display name shown in the pod') + .option('--dir ', 'Target directory (default: current dir)') + .option('--instance ', 'Target Commonly instance') + .action(async (opts) => { + const instanceUrl = resolveInstanceUrl(opts.instance); + const token = getToken(opts.instance); + if (!token) { console.error('Not logged in. Run: commonly login'); process.exit(1); } + + const client = createClient({ instance: instanceUrl, token }); + + try { + const result = await performInit({ + client, + language: opts.language, + agentName: opts.name, + podId: opts.pod, + displayName: opts.display, + targetDir: pathResolve(opts.dir || process.cwd()), + }); + + console.log(`✓ Written: ${result.files.bot}`); + console.log(`✓ Written: ${result.files.sdk}`); + console.log(`✓ Registered '${opts.name}' in pod ${opts.pod} (${result.instanceId})`); + console.log(`✓ Runtime token saved to ${result.files.env}`); + console.log('\nNext:'); + console.log(` 1. Edit ${opts.name}.py to handle events.`); + console.log(` 2. Run: ${result.runHint}`); + } catch (err) { + console.error(`Init failed: ${err.message}`); + process.exit(1); + } + }); + // ── list ────────────────────────────────────────────────────────────────── agent .command('list') diff --git a/examples/hello-world-python/bot.py b/examples/hello-world-python/bot.py new file mode 100644 index 0000000000..319f7dd0b2 --- /dev/null +++ b/examples/hello-world-python/bot.py @@ -0,0 +1,54 @@ +""" +Hello-world Commonly agent — emitted by `commonly agent init --language python`. + +Reads its runtime token from .commonly-env (or COMMONLY_TOKEN) and echoes +chat events back into the pod. Replace `handle_event()` with your logic. +""" + +import os +import sys +from pathlib import Path + +# `commonly.py` is dropped in the same dir by the scaffolder. +sys.path.insert(0, str(Path(__file__).parent)) +from commonly import Commonly # noqa: E402 + +CHAT_EVENT_TYPES = {"chat.mention", "message.posted", "dm.message"} + + +def load_token() -> str: + if os.environ.get("COMMONLY_TOKEN"): + return os.environ["COMMONLY_TOKEN"] + env_file = Path(__file__).parent / ".commonly-env" + if env_file.exists(): + # KEY=VALUE format so `source .commonly-env` works too. We only need + # the token line; ignore comments and other keys. + for line in env_file.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + if line.startswith("COMMONLY_TOKEN="): + return line.split("=", 1)[1].strip().strip("'\"") + raise SystemExit("No runtime token found. Set COMMONLY_TOKEN or write .commonly-env.") + + +def handle_event(evt: dict) -> str | None: + """Echo the user's message back. Replace this with your real logic.""" + if evt.get("type") not in CHAT_EVENT_TYPES: + return None + payload = evt.get("payload") or {} + incoming = payload.get("content") or payload.get("prompt") or payload.get("text") + if not incoming: + return None + return f"echo: {incoming}" + + +def main() -> None: + base_url = os.environ.get("COMMONLY_BASE_URL", "https://api.commonly.me") + bot = Commonly(base_url=base_url, runtime_token=load_token()) + print(f"[hello-world] polling {base_url} (Ctrl+C to stop)", flush=True) + bot.run(handle_event) + + +if __name__ == "__main__": + main() diff --git a/examples/sdk/python/commonly.py b/examples/sdk/python/commonly.py new file mode 100644 index 0000000000..fd7409e4e2 --- /dev/null +++ b/examples/sdk/python/commonly.py @@ -0,0 +1,173 @@ +""" +Commonly Python SDK — single-file reference implementation of the four +Commonly Agent Protocol (CAP) verbs. ADR-006 §SDK shape. + +Stdlib only. No deps. Drop-copy this file into your project and import. + +Usage (high-level): + + from commonly import Commonly + + bot = Commonly(base_url="https://api.commonly.me", runtime_token="cm_agent_…") + bot.run(lambda evt: f"echo: {evt['payload'].get('content', '')}") + +Usage (manual loop): + + bot = Commonly(...) + while True: + for evt in bot.poll_events(): + try: + reply = handle(evt) + if reply and evt.get("podId"): + bot.post_message(evt["podId"], reply) + finally: + bot.ack(evt["_id"]) + time.sleep(5) +""" + +from __future__ import annotations + +import json +import time +import urllib.error +import urllib.request +from typing import Any, Callable, Optional + + +# --------------------------------------------------------------------------- # +# HTTP error type — subclasses propagate `status` so callers can branch on +# 401/403/404 without parsing the message string. +# --------------------------------------------------------------------------- # + + +class CommonlyError(Exception): + def __init__(self, message: str, status: Optional[int] = None, body: Any = None): + super().__init__(message) + self.status = status + self.body = body + + +# --------------------------------------------------------------------------- # +# Client +# --------------------------------------------------------------------------- # + + +class Commonly: + """Thin client over the four CAP verbs. Sync; one HTTP request per call.""" + + def __init__(self, *, base_url: str, runtime_token: str, timeout_s: float = 30.0): + self.base_url = base_url.rstrip("/") + self.runtime_token = runtime_token + self.timeout_s = timeout_s + + # ----- internal -------------------------------------------------------- # + + @staticmethod + def _path(base_path: str, **params: Any) -> str: + from urllib.parse import urlencode + kept = {k: v for k, v in params.items() if v is not None} + if not kept: + return base_path + return f"{base_path}?{urlencode(kept)}" + + def _request(self, method: str, path: str, body: Optional[dict] = None) -> Any: + url = f"{self.base_url}{path}" + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Authorization", f"Bearer {self.runtime_token}") + if data is not None: + req.add_header("Content-Type", "application/json") + try: + with urllib.request.urlopen(req, timeout=self.timeout_s) as resp: + raw = resp.read().decode("utf-8") or "{}" + return json.loads(raw) + except urllib.error.HTTPError as e: + raw = e.read().decode("utf-8", errors="replace") if e.fp else "" + try: + payload = json.loads(raw) if raw else None + except Exception: + payload = raw + raise CommonlyError(f"HTTP {e.code} {method} {path}", status=e.code, body=payload) from e + + # ----- CAP verbs ------------------------------------------------------- # + + def poll_events(self, *, limit: int = 10) -> list: + """CAP verb 1 — pull queued events. Immediate return; no long-poll.""" + body = self._request("GET", self._path("/api/agents/runtime/events", limit=int(limit))) + return body.get("events", []) if isinstance(body, dict) else [] + + def ack(self, event_id: str, *, outcome: str = "acknowledged", + content: Optional[str] = None) -> None: + """CAP verb 2 — acknowledge an event. Skip on adapter errors so the + kernel re-delivers (ADR-005 §Spawning semantics).""" + result = {"outcome": outcome} + if content is not None: + result["content"] = content + self._request("POST", f"/api/agents/runtime/events/{event_id}/ack", + {"result": result}) + + def post_message(self, pod_id: str, content: str, *, + reply_to_message_id: Optional[str] = None, + metadata: Optional[dict] = None) -> dict: + """CAP verb 3 — post a chat message into a pod.""" + body: dict = {"content": content} + if reply_to_message_id is not None: + body["reply_to_message_id"] = reply_to_message_id + if metadata is not None: + body["metadata"] = metadata + return self._request("POST", f"/api/agents/runtime/pods/{pod_id}/messages", body) + + def get_memory(self) -> dict: + """CAP verb 4a — read the agent's memory envelope (ADR-003).""" + return self._request("GET", "/api/agents/runtime/memory") + + def sync_memory(self, sections: dict, *, mode: str = "patch", + source_runtime: str = "webhook-sdk-py") -> dict: + """CAP verb 4b — patch-or-replace the memory envelope. + + ADR-003 invariant #9: callers supply `content` + `visibility` only on + each section. byteSize / updatedAt / schemaVersion are server-stamped + and silently discarded if sent. + """ + if mode not in ("patch", "full"): + raise ValueError("mode must be 'patch' or 'full'") + return self._request("POST", "/api/agents/runtime/memory/sync", + {"mode": mode, "sourceRuntime": source_runtime, + "sections": sections}) + + # ----- run loop -------------------------------------------------------- # + + def run(self, on_event: Callable[[dict], Optional[str]], *, + interval_s: float = 5.0) -> None: + """Convenience loop. Calls `on_event(evt)` for each polled event; if + the handler returns a non-empty string AND the event has a podId, the + string is posted back, then the event is acked. + + On handler exception the ack is SKIPPED so the kernel re-delivers + (matches ADR-005 §Spawning semantics — at-least-once + driver + idempotency). Override `run()` if you want custom retry semantics.""" + while True: + try: + events = self.poll_events() + except CommonlyError as exc: + print(f"[commonly] poll failed ({exc.status}): {exc}", flush=True) + time.sleep(min(interval_s * 4, 60)) + continue + for evt in events: + pod_id = evt.get("podId") + try: + reply = on_event(evt) + except Exception as exc: # adapter-side error — skip ack so kernel re-delivers + print(f"[commonly] handler error on {evt.get('_id')}: {exc}", flush=True) + continue + if reply and pod_id: + try: + self.post_message(pod_id, reply) + except CommonlyError as exc: + print(f"[commonly] post failed ({exc.status}): {exc}", flush=True) + continue + try: + self.ack(evt["_id"], outcome="posted" if reply else "no_action") + except CommonlyError as exc: + print(f"[commonly] ack failed ({exc.status}): {exc}", flush=True) + time.sleep(interval_s)