@sesamespace/hivemind 0.8.4 → 0.8.6

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.
Files changed (41) hide show
  1. package/.pnpmrc.json +1 -0
  2. package/DASHBOARD-PLAN.md +206 -0
  3. package/TOOL-USE-DESIGN.md +173 -0
  4. package/config/default.toml +6 -1
  5. package/dist/{chunk-3CQJQUY3.js → chunk-AYHCHIM2.js} +2 -2
  6. package/dist/{chunk-CSYDOZE6.js → chunk-CJ4Y2BCE.js} +2 -2
  7. package/dist/{chunk-66KRRXVF.js → chunk-K7YQY253.js} +3 -3
  8. package/dist/{chunk-DODOQGIL.js → chunk-LSLF7AGW.js} +42 -13
  9. package/dist/chunk-LSLF7AGW.js.map +1 -0
  10. package/dist/{chunk-6S5UKFTZ.js → chunk-S4QRR3ZJ.js} +917 -48
  11. package/dist/chunk-S4QRR3ZJ.js.map +1 -0
  12. package/dist/{chunk-HNXCZPSX.js → chunk-WIJHKLB3.js} +3 -3
  13. package/dist/commands/fleet.js +3 -4
  14. package/dist/commands/init.js +3 -2
  15. package/dist/commands/start.js +3 -4
  16. package/dist/commands/watchdog.js +3 -4
  17. package/dist/index.js +5 -4
  18. package/dist/main.js +6 -7
  19. package/dist/main.js.map +1 -1
  20. package/dist/start.js +1 -2
  21. package/dist/start.js.map +1 -1
  22. package/docs/TOOL-PARITY-PLAN.md +191 -0
  23. package/package.json +22 -25
  24. package/dist/chunk-6S5UKFTZ.js.map +0 -1
  25. package/dist/chunk-DODOQGIL.js.map +0 -1
  26. package/dist/chunk-GPI4RU7N.js +0 -624
  27. package/dist/chunk-GPI4RU7N.js.map +0 -1
  28. package/install.sh +0 -131
  29. package/packages/memory/Cargo.lock +0 -6480
  30. package/packages/memory/Cargo.toml +0 -21
  31. package/packages/memory/src/src/context.rs +0 -179
  32. package/packages/memory/src/src/embeddings.rs +0 -51
  33. package/packages/memory/src/src/main.rs +0 -626
  34. package/packages/memory/src/src/promotion.rs +0 -637
  35. package/packages/memory/src/src/scoring.rs +0 -131
  36. package/packages/memory/src/src/store.rs +0 -460
  37. package/packages/memory/src/src/tasks.rs +0 -321
  38. /package/dist/{chunk-3CQJQUY3.js.map → chunk-AYHCHIM2.js.map} +0 -0
  39. /package/dist/{chunk-CSYDOZE6.js.map → chunk-CJ4Y2BCE.js.map} +0 -0
  40. /package/dist/{chunk-66KRRXVF.js.map → chunk-K7YQY253.js.map} +0 -0
  41. /package/dist/{chunk-HNXCZPSX.js.map → chunk-WIJHKLB3.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../packages/cli/src/commands/init.ts"],"sourcesContent":["import { resolve, dirname } from \"path\";\nimport { existsSync, writeFileSync, mkdirSync, readFileSync, copyFileSync, realpathSync, chmodSync } from \"fs\";\nimport { createInterface } from \"readline\";\nimport { fileURLToPath } from \"url\";\nimport { execSync } from \"child_process\";\nimport { SesameClient } from \"@sesamespace/sdk\";\nimport { homedir, arch, platform } from \"os\";\n\nconst HIVEMIND_DIR = resolve(process.env.HIVEMIND_HOME || resolve(homedir(), \"hivemind\"));\nconst CONFIG_DIR = resolve(HIVEMIND_DIR, \"config\");\nconst WORKSPACE_DIR = resolve(HIVEMIND_DIR, \"workspace\");\nconst BIN_DIR = resolve(HIVEMIND_DIR, \"bin\");\nconst DATA_DIR = resolve(HIVEMIND_DIR, \"data\");\nconst ENV_FILE = resolve(HIVEMIND_DIR, \".env\");\nconst LOCAL_TOML = resolve(CONFIG_DIR, \"local.toml\");\nconst MEMORY_BIN = resolve(BIN_DIR, \"hivemind-memory\");\n\nconst RELEASES_BASE_URL = \"https://sesame-hivemind-releases.s3.amazonaws.com\";\nconst EMBEDDING_MODEL = \"nomic-embed-text\";\n\nconst VAULT_CONFIG_NAME = \"hivemind-config\";\n\ninterface ProvisioningConfig {\n agentName: string;\n agentHandle: string;\n agentId: string;\n personality?: string;\n llmApiKey?: string;\n llmBaseUrl?: string;\n llmModel?: string;\n fleetRole?: string;\n channels: Array<{ id: string; name: string | null; kind: string }>;\n}\n\nasync function prompt(question: string): Promise<string> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nexport async function runInitCommand(args: string[]): Promise<void> {\n const nonInteractive = args.includes(\"--yes\") || args.includes(\"-y\") || args.includes(\"--non-interactive\");\n const filteredArgs = args.filter((a) => ![\"--yes\", \"-y\", \"--non-interactive\", \"--help\", \"-h\"].includes(a));\n let sesameApiKey = filteredArgs[0];\n\n if (args.includes(\"--help\") || args.includes(\"-h\")) {\n printHelp();\n return;\n }\n\n console.log(`\n ╦ ╦╦╦ ╦╔═╗╔╦╗╦╔╗╔╔╦╗\n ╠═╣║╚╗╔╝║╣ ║║║║║║║ ║║\n ╩ ╩╩ ╚╝ ╚═╝╩ ╩╩╝╚╝═╩╝\n Agent Initialization\n`);\n\n // --- Step 1: Get Sesame API key ---\n // Check existing config if no key provided\n if (!sesameApiKey) {\n // Try .env file\n if (existsSync(ENV_FILE)) {\n try {\n const envContent = readFileSync(ENV_FILE, \"utf-8\");\n const match = envContent.match(/^SESAME_API_KEY=(.+)$/m);\n if (match && match[1].trim()) {\n sesameApiKey = match[1].trim();\n console.log(\" ✓ Found existing API key in .env\");\n }\n } catch {}\n }\n // Try local.toml\n if (!sesameApiKey && existsSync(LOCAL_TOML)) {\n try {\n const tomlContent = readFileSync(LOCAL_TOML, \"utf-8\");\n const match = tomlContent.match(/api_key\\s*=\\s*\"([^\"]+)\"/);\n if (match && match[1].trim()) {\n sesameApiKey = match[1].trim();\n console.log(\" ✓ Found existing API key in local.toml\");\n }\n } catch {}\n }\n // Try environment variable\n if (!sesameApiKey && process.env.SESAME_API_KEY) {\n sesameApiKey = process.env.SESAME_API_KEY;\n console.log(\" ✓ Using API key from SESAME_API_KEY env var\");\n }\n }\n if (!sesameApiKey) {\n sesameApiKey = await prompt(\" Sesame API key: \");\n }\n if (!sesameApiKey) {\n console.error(\"Error: Sesame API key is required\");\n process.exit(1);\n }\n\n // --- Step 2: Connect to Sesame and fetch manifest ---\n console.log(\"\\n→ Connecting to Sesame...\");\n const sdk = new SesameClient({\n apiUrl: \"https://api.sesame.space\",\n wsUrl: \"wss://ws.sesame.space\",\n apiKey: sesameApiKey,\n });\n\n let config: ProvisioningConfig;\n try {\n const manifest = await sdk.getManifest();\n console.log(` ✓ Authenticated as ${manifest.agent.handle} (${manifest.agent.id})`);\n console.log(` ✓ Workspace: ${manifest.workspace.name}`);\n console.log(` ✓ Channels: ${manifest.channels.length}`);\n for (const ch of manifest.channels) {\n console.log(` - ${ch.name || ch.id} (${ch.kind})`);\n }\n\n config = {\n agentName: manifest.agent.handle,\n agentHandle: manifest.agent.handle,\n agentId: manifest.agent.id,\n channels: manifest.channels.map((ch) => ({\n id: ch.id,\n name: ch.name,\n kind: ch.kind,\n })),\n };\n\n // --- Step 3: Check vault for config ---\n console.log(\"\\n→ Checking vault for provisioning config...\");\n try {\n const vaultResp = await sdk.listVaultItems() as any;\n const items = vaultResp.items || vaultResp.data || [];\n const configItem = items.find((i: any) => i.name === VAULT_CONFIG_NAME);\n\n if (configItem) {\n console.log(` ✓ Found ${VAULT_CONFIG_NAME} vault item`);\n const revealResp = await sdk.revealItem(configItem.id) as any;\n const fields = revealResp.data?.fields || revealResp.fields || revealResp.data || {};\n\n config.llmApiKey = fields.llm_api_key || fields.openrouter_api_key;\n config.llmBaseUrl = fields.llm_base_url;\n config.llmModel = fields.llm_model;\n config.personality = fields.agent_personality || fields.personality;\n config.fleetRole = fields.fleet_role;\n\n if (config.llmApiKey) console.log(\" ✓ LLM API key loaded from vault\");\n if (config.llmModel) console.log(` ✓ LLM model: ${config.llmModel}`);\n if (config.personality) console.log(` ✓ Personality: ${config.personality.slice(0, 60)}...`);\n if (config.fleetRole) console.log(` ✓ Fleet role: ${config.fleetRole}`);\n } else {\n console.log(\" ! No hivemind-config vault item found\");\n console.log(\" ! Will prompt for LLM API key instead\");\n }\n } catch (err) {\n console.log(` ! Could not read vault: ${(err as Error).message}`);\n }\n } catch (err) {\n console.error(`\\n ✗ Failed to connect to Sesame: ${(err as Error).message}`);\n console.error(\" Check your API key and try again.\");\n process.exit(1);\n } finally {\n sdk.disconnect();\n }\n\n // --- Step 4: Prompt for anything missing ---\n if (!config.llmApiKey) {\n console.log(\" ! No LLM API key found in vault — set LLM_API_KEY in .env after init\");\n }\n\n // --- Step 5: Write config files ---\n console.log(\"\\n→ Writing configuration...\");\n\n mkdirSync(CONFIG_DIR, { recursive: true });\n mkdirSync(WORKSPACE_DIR, { recursive: true });\n\n // Copy default.toml from installed package if not present\n const defaultToml = resolve(CONFIG_DIR, \"default.toml\");\n if (!existsSync(defaultToml)) {\n // Resolve from the hivemind binary location\n // process.argv[1] may be a symlink, so resolve it first\n const realBin = realpathSync(process.argv[1]);\n // realBin is <pkg>/dist/main.js, so ../config/ gets us to <pkg>/config/\n const packageConfigDir = resolve(dirname(realBin), \"..\", \"config\");\n const packageDefault = resolve(packageConfigDir, \"default.toml\");\n if (existsSync(packageDefault)) {\n copyFileSync(packageDefault, defaultToml);\n console.log(` ✓ ${defaultToml}`);\n // Also copy team charter if available\n const packageCharter = resolve(packageConfigDir, \"TEAM-CHARTER.md\");\n const localCharter = resolve(CONFIG_DIR, \"TEAM-CHARTER.md\");\n if (existsSync(packageCharter) && !existsSync(localCharter)) {\n copyFileSync(packageCharter, localCharter);\n console.log(` ✓ ${localCharter}`);\n }\n } else {\n console.log(` ! default.toml not found in package — you may need to copy it manually`);\n }\n }\n\n // Write workspace identity files\n const soulPath = resolve(WORKSPACE_DIR, \"SOUL.md\");\n if (!existsSync(soulPath)) {\n const personality = config.personality || \"A helpful, capable agent.\";\n writeFileSync(soulPath, `# SOUL.md — Who You Are\n\n${personality}\n\n---\n\n_This file defines your personality and values. Edit it to evolve who you are._\n`);\n console.log(` ✓ ${soulPath}`);\n }\n\n const identityPath = resolve(WORKSPACE_DIR, \"IDENTITY.md\");\n if (!existsSync(identityPath)) {\n writeFileSync(identityPath, `# IDENTITY.md\n\n- **Name:** ${config.agentName}\n- **Handle:** ${config.agentHandle}\n- **Agent ID:** ${config.agentId}\n`);\n console.log(` ✓ ${identityPath}`);\n }\n\n // Write local.toml (overrides)\n const localToml = `# Generated by hivemind init — ${new Date().toISOString()}\n# Overrides config/default.toml with agent-specific settings\n\n[agent]\nname = \"${config.agentName}\"\n${config.personality ? `personality = \"${config.personality.replace(/\"/g, '\\\\\"')}\"` : \"# personality = (using default)\"}\nworkspace = \"workspace\"\n\n${config.llmModel ? `[llm]\\nmodel = \"${config.llmModel}\"` : \"# [llm] using defaults\"}\n${config.llmBaseUrl ? `# base_url = \"${config.llmBaseUrl}\"` : \"\"}\n\n[sesame]\napi_key = \"${sesameApiKey}\"\n`;\n\n writeFileSync(LOCAL_TOML, localToml);\n console.log(` ✓ ${LOCAL_TOML}`);\n\n // Write .env\n const envContent = `# Hivemind Agent — ${config.agentName}\n# Generated by hivemind init — ${new Date().toISOString()}\nSESAME_API_KEY=${sesameApiKey}\nLLM_API_KEY=${config.llmApiKey || \"\"}\nAGENT_NAME=${config.agentName}\n`;\n\n writeFileSync(ENV_FILE, envContent, { mode: 0o600 });\n console.log(` ✓ ${ENV_FILE} (chmod 600)`);\n\n // --- Step 6: Install memory infrastructure ---\n console.log(\"\\n→ Setting up memory system...\");\n mkdirSync(BIN_DIR, { recursive: true });\n mkdirSync(DATA_DIR, { recursive: true });\n\n await installOllama();\n await pullEmbeddingModel();\n await downloadMemoryDaemon();\n\n // --- Done ---\n console.log(`\n ✓ Hivemind initialized for ${config.agentName}!\n\n To start the agent:\n hivemind start\n\n To install as a service:\n hivemind service install\n\n Agent ID: ${config.agentId}\n Channels: ${config.channels.map((c) => c.name || c.id).join(\", \")}\n Fleet role: ${config.fleetRole || \"standalone\"}\n`);\n}\n\n// --- Memory infrastructure helpers ---\n\nasync function installOllama(): Promise<void> {\n try {\n execSync(\"which ollama\", { stdio: \"ignore\" });\n const version = execSync(\"ollama --version\", { encoding: \"utf-8\" }).trim();\n console.log(` ✓ Ollama already installed (${version})`);\n return;\n } catch {}\n\n console.log(\" → Installing Ollama...\");\n try {\n // Try Homebrew first (macOS)\n execSync(\"which brew\", { stdio: \"ignore\" });\n execSync(\"brew install ollama\", { stdio: \"inherit\" });\n console.log(\" ✓ Ollama installed via Homebrew\");\n } catch {\n // Fall back to official installer\n try {\n execSync(\"curl -fsSL https://ollama.com/install.sh | sh\", { stdio: \"inherit\" });\n console.log(\" ✓ Ollama installed via installer script\");\n } catch (err) {\n console.error(` ✗ Failed to install Ollama: ${(err as Error).message}`);\n console.error(\" ! Install manually: https://ollama.com/download\");\n console.error(\" ! Memory system will not work without Ollama\");\n }\n }\n}\n\nasync function pullEmbeddingModel(): Promise<void> {\n console.log(` → Pulling embedding model (${EMBEDDING_MODEL})...`);\n try {\n // Ensure ollama is running\n try {\n execSync(\"curl -sf http://localhost:11434/api/tags > /dev/null\", { stdio: \"ignore\" });\n } catch {\n // Start ollama serve in background\n console.log(\" → Starting Ollama server...\");\n execSync(\"ollama serve &\", { stdio: \"ignore\", shell: \"/bin/sh\" });\n // Wait for it to be ready\n for (let i = 0; i < 15; i++) {\n try {\n execSync(\"curl -sf http://localhost:11434/api/tags > /dev/null\", { stdio: \"ignore\" });\n break;\n } catch {\n execSync(\"sleep 1\");\n }\n }\n }\n\n execSync(`ollama pull ${EMBEDDING_MODEL}`, { stdio: \"inherit\" });\n console.log(` ✓ ${EMBEDDING_MODEL} model ready`);\n } catch (err) {\n console.error(` ✗ Failed to pull model: ${(err as Error).message}`);\n console.error(` ! Run manually: ollama pull ${EMBEDDING_MODEL}`);\n }\n}\n\nasync function downloadMemoryDaemon(): Promise<void> {\n if (existsSync(MEMORY_BIN)) {\n console.log(` ✓ Memory daemon already installed at ${MEMORY_BIN}`);\n return;\n }\n\n const osArch = arch();\n const osPlatform = platform();\n\n if (osPlatform !== \"darwin\") {\n console.log(` ! Memory daemon pre-built binaries only available for macOS currently`);\n console.log(` ! Build from source: cd packages/memory && cargo build --release`);\n return;\n }\n\n const artifactName = osArch === \"arm64\"\n ? \"hivemind-memory-darwin-arm64\"\n : \"hivemind-memory-darwin-x64\";\n\n console.log(` → Downloading memory daemon (${artifactName})...`);\n try {\n // Get latest version from S3\n const latestJson = execSync(\n `curl -sf \"${RELEASES_BASE_URL}/latest.json\"`,\n { encoding: \"utf-8\" },\n );\n const { version } = JSON.parse(latestJson);\n const url = `${RELEASES_BASE_URL}/v${version}/${artifactName}`;\n\n execSync(\n `curl -fSL -o \"${MEMORY_BIN}\" \"${url}\"`,\n { stdio: \"inherit\" },\n );\n chmodSync(MEMORY_BIN, 0o755);\n console.log(` ✓ Memory daemon installed at ${MEMORY_BIN} (v${version})`);\n } catch (err) {\n console.error(` ✗ Failed to download memory daemon: ${(err as Error).message}`);\n console.error(\" ! Build from source: cd packages/memory && cargo build --release\");\n console.error(` ! Then copy to: ${MEMORY_BIN}`);\n }\n}\n\nfunction printHelp(): void {\n console.log(`hivemind init — Initialize a Hivemind agent from Sesame\n\nUsage: hivemind init [sesame-api-key]\n\nThe API key can also be passed as the first argument.\n\nWhat it does:\n 1. Connects to Sesame and fetches agent identity\n 2. Reads provisioning config from Sesame vault (if available)\n 3. Writes config/local.toml and .env\n 4. Installs Ollama + embedding model for memory\n 5. Downloads pre-built memory daemon binary\n\nOptions:\n -h, --help Show this help\n`);\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS,eAAe;AACjC,SAAS,YAAY,eAAe,WAAW,cAAc,cAAc,cAAc,iBAAiB;AAC1G,SAAS,uBAAuB;AAEhC,SAAS,gBAAgB;AAEzB,SAAS,SAAS,MAAM,gBAAgB;AAExC,IAAM,eAAe,QAAQ,QAAQ,IAAI,iBAAiB,QAAQ,QAAQ,GAAG,UAAU,CAAC;AACxF,IAAM,aAAa,QAAQ,cAAc,QAAQ;AACjD,IAAM,gBAAgB,QAAQ,cAAc,WAAW;AACvD,IAAM,UAAU,QAAQ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;AAClE;AAAA,EACF;AAEA,QAAM,SAAS,KAAK;AACpB,QAAM,aAAa,SAAS;AAE5B,MAAI,eAAe,UAAU;AAC3B,YAAQ,IAAI,yEAAyE;AACrF,YAAQ,IAAI,oEAAoE;AAChF;AAAA,EACF;AAEA,QAAM,eAAe,WAAW,UAC5B,iCACA;AAEJ,UAAQ,IAAI,uCAAkC,YAAY,MAAM;AAChE,MAAI;AAEF,UAAM,aAAa;AAAA,MACjB,aAAa,iBAAiB;AAAA,MAC9B,EAAE,UAAU,QAAQ;AAAA,IACtB;AACA,UAAM,EAAE,QAAQ,IAAI,KAAK,MAAM,UAAU;AACzC,UAAM,MAAM,GAAG,iBAAiB,KAAK,OAAO,IAAI,YAAY;AAE5D;AAAA,MACE,iBAAiB,UAAU,MAAM,GAAG;AAAA,MACpC,EAAE,OAAO,UAAU;AAAA,IACrB;AACA,cAAU,YAAY,GAAK;AAC3B,YAAQ,IAAI,uCAAkC,UAAU,MAAM,OAAO,GAAG;AAAA,EAC1E,SAAS,KAAK;AACZ,YAAQ,MAAM,8CAA0C,IAAc,OAAO,EAAE;AAC/E,YAAQ,MAAM,oEAAoE;AAClF,YAAQ,MAAM,qBAAqB,UAAU,EAAE;AAAA,EACjD;AACF;AAEA,SAAS,YAAkB;AACzB,UAAQ,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAeb;AACD;","names":["resolve","envContent"]}
@@ -1,624 +0,0 @@
1
- // node_modules/.pnpm/@sesamespace+sdk@0.1.6/node_modules/@sesamespace/sdk/dist/client.js
2
- import WebSocket from "ws";
3
-
4
- // node_modules/.pnpm/@sesamespace+sdk@0.1.6/node_modules/@sesamespace/sdk/dist/auth.js
5
- import { sign } from "crypto";
6
- function createAuthSignature(handle, privateKeyBase64url) {
7
- const timestamp = Date.now();
8
- const message = `AUTH:${handle}:${timestamp}`;
9
- const privateKeyDer = Buffer.from(privateKeyBase64url, "base64url");
10
- const privateKey = {
11
- key: privateKeyDer,
12
- format: "der",
13
- type: "pkcs8"
14
- };
15
- const sig = sign(null, Buffer.from(message), privateKey);
16
- return {
17
- signature: sig.toString("base64url"),
18
- timestamp
19
- };
20
- }
21
-
22
- // node_modules/.pnpm/@sesamespace+sdk@0.1.6/node_modules/@sesamespace/sdk/dist/client.js
23
- var SesameClient = class {
24
- config;
25
- ws = null;
26
- eventHandlers = /* @__PURE__ */ new Map();
27
- reconnectAttempts = 0;
28
- reconnectTimer = null;
29
- heartbeatTimer = null;
30
- cursors = /* @__PURE__ */ new Map();
31
- authenticated = false;
32
- constructor(config) {
33
- this.config = {
34
- autoReconnect: true,
35
- maxReconnectAttempts: 10,
36
- ...config
37
- };
38
- }
39
- // ── HTTP Methods ──
40
- async fetch(path, options = {}) {
41
- const headers = {
42
- "Content-Type": "application/json",
43
- ...options.headers ?? {}
44
- };
45
- if (this.config.apiKey) {
46
- headers["Authorization"] = `Bearer ${this.config.apiKey}`;
47
- } else if (this.config.token) {
48
- headers["Authorization"] = `Bearer ${this.config.token}`;
49
- } else if (this.config.agent) {
50
- const { signature, timestamp } = createAuthSignature(this.config.agent.handle, this.config.agent.privateKey);
51
- headers["Authorization"] = `Signature ${this.config.agent.handle}.${signature}.${timestamp}`;
52
- }
53
- const response = await globalThis.fetch(`${this.config.apiUrl}${path}`, {
54
- ...options,
55
- headers
56
- });
57
- if (!response.ok) {
58
- const error = await response.json().catch(() => ({ error: response.statusText }));
59
- throw new SesameApiError(response.status, error.error ?? "Request failed");
60
- }
61
- return response.json();
62
- }
63
- get(path) {
64
- return this.fetch(path);
65
- }
66
- post(path, body) {
67
- return this.fetch(path, {
68
- method: "POST",
69
- body: body ? JSON.stringify(body) : void 0
70
- });
71
- }
72
- patch(path, body) {
73
- return this.fetch(path, {
74
- method: "PATCH",
75
- body: JSON.stringify(body)
76
- });
77
- }
78
- del(path) {
79
- return this.fetch(path, { method: "DELETE" });
80
- }
81
- // ── Auth ──
82
- async login(email, password) {
83
- const result = await this.post("/api/v1/auth/login", { email, password });
84
- this.config.token = result.accessToken;
85
- return result;
86
- }
87
- // ── Channels ──
88
- async listChannels() {
89
- const result = await this.get("/api/v1/channels");
90
- const channels = result.data ?? result.channels ?? result;
91
- return { channels: Array.isArray(channels) ? channels : [] };
92
- }
93
- async getChannel(id) {
94
- const result = await this.get(`/api/v1/channels/${id}`);
95
- const channel = result.data ?? result.channel ?? result;
96
- return { channel };
97
- }
98
- async createChannel(data) {
99
- const result = await this.post("/api/v1/channels", data);
100
- const channel = result.data ?? result.channel ?? result;
101
- return { channel };
102
- }
103
- async getOrCreateDM(principalId) {
104
- const result = await this.post("/api/v1/channels/dm", { principalId });
105
- const channel = result.data ?? result.channel ?? result;
106
- return { channel };
107
- }
108
- async getUnread() {
109
- return this.get("/api/v1/channels/unread");
110
- }
111
- // ── Messages ──
112
- async sendMessage(channelId, options) {
113
- const result = await this.post(`/api/v1/channels/${channelId}/messages`, options);
114
- const message = this.normalizeMessage(result.data ?? result.message ?? result);
115
- if (message.seq) {
116
- this.cursors.set(channelId, message.seq);
117
- }
118
- return { message };
119
- }
120
- async getMessages(channelId, options) {
121
- const params = new URLSearchParams();
122
- if (options?.cursor)
123
- params.set("cursor", options.cursor.toString());
124
- if (options?.limit)
125
- params.set("limit", options.limit.toString());
126
- if (options?.direction)
127
- params.set("direction", options.direction);
128
- if (options?.threadRootId)
129
- params.set("threadRootId", options.threadRootId);
130
- const qs = params.toString();
131
- const result = await this.get(`/api/v1/channels/${channelId}/messages${qs ? `?${qs}` : ""}`);
132
- const messages = (result.data ?? result.messages ?? []).map((m) => this.normalizeMessage(m));
133
- if (messages.length > 0) {
134
- const maxSeq = Math.max(...messages.map((m) => m.seq));
135
- const current = this.cursors.get(channelId) ?? 0;
136
- if (maxSeq > current)
137
- this.cursors.set(channelId, maxSeq);
138
- }
139
- return {
140
- messages,
141
- cursor: result.pagination?.cursor ? Number(result.pagination.cursor) : 0,
142
- hasMore: result.pagination?.hasMore ?? false
143
- };
144
- }
145
- async editMessage(channelId, messageId, content) {
146
- const result = await this.patch(`/api/v1/channels/${channelId}/messages/${messageId}`, { content });
147
- const message = this.normalizeMessage(result.data ?? result.message ?? result);
148
- return { message };
149
- }
150
- async deleteMessage(channelId, messageId) {
151
- await this.del(`/api/v1/channels/${channelId}/messages/${messageId}`);
152
- }
153
- async markRead(channelId, seq) {
154
- await this.post(`/api/v1/channels/${channelId}/messages/read`, { seq });
155
- }
156
- async addReaction(channelId, messageId, emoji) {
157
- await this.post(`/api/v1/channels/${channelId}/messages/${messageId}/reactions`, { emoji });
158
- }
159
- async removeReaction(channelId, messageId, emoji) {
160
- await this.del(`/api/v1/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`);
161
- }
162
- // ── Vault ──
163
- async listVaults() {
164
- return this.get("/api/v1/vault/vaults");
165
- }
166
- async listVaultItems(vaultId) {
167
- const qs = vaultId ? `?vaultId=${vaultId}` : "";
168
- return this.get(`/api/v1/vault/items${qs}`);
169
- }
170
- async getVaultItem(id) {
171
- return this.get(`/api/v1/vault/items/${id}`);
172
- }
173
- async createVaultItem(options) {
174
- return this.post("/api/v1/vault/items", options);
175
- }
176
- async revealItem(id, fields) {
177
- return this.post(`/api/v1/vault/items/${id}/reveal`, fields ? { fields } : void 0);
178
- }
179
- async shareItem(itemId, principalId, options) {
180
- await this.post(`/api/v1/vault/items/${itemId}/share`, {
181
- principalId,
182
- ...options
183
- });
184
- }
185
- async revokeShare(itemId, principalId) {
186
- await this.del(`/api/v1/vault/items/${itemId}/share/${principalId}`);
187
- }
188
- async getWallet() {
189
- return this.get("/api/v1/vault/wallet");
190
- }
191
- // ── Leases ──
192
- async requestLease(options) {
193
- return this.post("/api/v1/vault/leases/request", options);
194
- }
195
- async approveLease(leaseId, options) {
196
- return this.post(`/api/v1/vault/leases/${leaseId}/approve`, options ?? {});
197
- }
198
- async denyLease(leaseId) {
199
- return this.post(`/api/v1/vault/leases/${leaseId}/deny`, {});
200
- }
201
- async useSecret(leaseId) {
202
- return this.post(`/api/v1/vault/leases/${leaseId}/use`, {});
203
- }
204
- async revokeLease(leaseId) {
205
- await this.del(`/api/v1/vault/leases/${leaseId}`);
206
- }
207
- // ── HTTP helper: PUT ──
208
- put(path, body) {
209
- return this.fetch(path, {
210
- method: "PUT",
211
- body: body ? JSON.stringify(body) : void 0
212
- });
213
- }
214
- // ── Agents ──
215
- async listAgents() {
216
- return this.get("/api/v1/agents");
217
- }
218
- async provisionAgent(data) {
219
- return this.post("/api/v1/agents", data);
220
- }
221
- async generateApiKey(agentId, label) {
222
- const res = await this.post(`/api/v1/agents/${agentId}/api-keys`, { label });
223
- return res.data ?? res;
224
- }
225
- // ── Capabilities ──
226
- async registerCapabilities(capabilities) {
227
- const agentId = this.getAgentId();
228
- const result = await this.put(`/api/v1/agents/${agentId}/capabilities`, { capabilities });
229
- return { capabilities: result.data ?? result };
230
- }
231
- async addCapability(capability) {
232
- const agentId = this.getAgentId();
233
- const result = await this.post(`/api/v1/agents/${agentId}/capabilities`, capability);
234
- return { capability: result.data ?? result };
235
- }
236
- async getCapabilities(agentId) {
237
- const id = agentId ?? this.getAgentId();
238
- const result = await this.get(`/api/v1/agents/${id}/capabilities`);
239
- return { capabilities: result.data ?? result };
240
- }
241
- async removeCapability(capabilityId) {
242
- const agentId = this.getAgentId();
243
- await this.del(`/api/v1/agents/${agentId}/capabilities/${capabilityId}`);
244
- }
245
- // ── Discovery ──
246
- async discoverAgents(query = {}) {
247
- const params = new URLSearchParams();
248
- if (query.namespace)
249
- params.set("namespace", query.namespace);
250
- if (query.name)
251
- params.set("name", query.name);
252
- if (query.capability) {
253
- const caps = Array.isArray(query.capability) ? query.capability : [query.capability];
254
- for (const cap of caps) {
255
- params.append("capability", cap);
256
- }
257
- }
258
- if (query.active !== void 0)
259
- params.set("active", String(query.active));
260
- const qs = params.toString();
261
- const result = await this.get(`/api/v1/agents/discover${qs ? `?${qs}` : ""}`);
262
- return { agents: result.data ?? result };
263
- }
264
- // ── Manifest & Context ──
265
- async getManifest() {
266
- if (!this._principalId) {
267
- const me = await this.get("/api/v1/auth/me");
268
- this.setPrincipalId(me.data?.id ?? me.id);
269
- }
270
- const agentId = this.getAgentId();
271
- const result = await this.get(`/api/v1/agents/${agentId}/manifest`);
272
- return result.data ?? result;
273
- }
274
- async getChannelContext(channelId, options) {
275
- const agentId = this.getAgentId();
276
- const params = new URLSearchParams();
277
- if (options?.strategy)
278
- params.set("strategy", options.strategy);
279
- if (options?.window)
280
- params.set("window", String(options.window));
281
- const qs = params.toString();
282
- const result = await this.get(`/api/v1/agents/${agentId}/channels/${channelId}/context${qs ? `?${qs}` : ""}`);
283
- return result.data ?? result;
284
- }
285
- // ── Channel Config ──
286
- async setChannelConfig(channelId, config) {
287
- const agentId = this.getAgentId();
288
- const result = await this.put(`/api/v1/agents/${agentId}/channels/${channelId}/config`, config);
289
- return result.data ?? result;
290
- }
291
- async getChannelConfig(channelId) {
292
- const agentId = this.getAgentId();
293
- const result = await this.get(`/api/v1/agents/${agentId}/channels/${channelId}/config`);
294
- return result.data ?? result;
295
- }
296
- async deleteChannelConfig(channelId) {
297
- const agentId = this.getAgentId();
298
- await this.del(`/api/v1/agents/${agentId}/channels/${channelId}/config`);
299
- }
300
- // ── Collaboration ──
301
- async createCollaborationChannel(options) {
302
- const result = await this.createChannel({
303
- kind: "topic",
304
- name: options.name,
305
- description: options.description,
306
- memberIds: options.memberIds
307
- });
308
- const channel = result.data ?? result.channel ?? result;
309
- const channelId = channel.id;
310
- if (options.context) {
311
- await this.put(`/api/v1/channels/${channelId}/context`, { context: options.context });
312
- }
313
- if (options.visibility) {
314
- await this.patch(`/api/v1/channels/${channelId}`, { visibility: options.visibility });
315
- }
316
- if (options.coordinationMode) {
317
- await this.put(`/api/v1/channels/${channelId}/coordination`, {
318
- mode: options.coordinationMode
319
- });
320
- }
321
- return { channel };
322
- }
323
- // ── Tasks ──
324
- async createTask(channelId, options) {
325
- const result = await this.post(`/api/v1/channels/${channelId}/tasks`, options);
326
- return { task: result.data ?? result };
327
- }
328
- async listTasks(channelId, filters) {
329
- const params = new URLSearchParams();
330
- if (filters?.status)
331
- params.set("status", filters.status);
332
- if (filters?.priority)
333
- params.set("priority", filters.priority);
334
- if (filters?.assigneeId)
335
- params.set("assigneeId", filters.assigneeId);
336
- const qs = params.toString();
337
- const result = await this.get(`/api/v1/channels/${channelId}/tasks${qs ? `?${qs}` : ""}`);
338
- return { tasks: result.data ?? result };
339
- }
340
- async updateTask(channelId, taskId, updates) {
341
- const result = await this.patch(`/api/v1/channels/${channelId}/tasks/${taskId}`, updates);
342
- return { task: result.data ?? result };
343
- }
344
- async claimTask(channelId, taskId) {
345
- const result = await this.post(`/api/v1/channels/${channelId}/tasks/${taskId}/claim`);
346
- return { task: result.data ?? result };
347
- }
348
- async addTaskAssignee(channelId, taskId, principalId, role) {
349
- const result = await this.post(`/api/v1/channels/${channelId}/tasks/${taskId}/assignees`, { principalId, role });
350
- return { task: result.data ?? result };
351
- }
352
- async removeTaskAssignee(channelId, taskId, principalId) {
353
- const result = await this.del(`/api/v1/channels/${channelId}/tasks/${taskId}/assignees/${principalId}`);
354
- return { task: result.data ?? result };
355
- }
356
- async createTaskChannel(channelId, taskId, options) {
357
- const result = await this.post(`/api/v1/channels/${channelId}/tasks/${taskId}/channel`, options ?? {});
358
- return result.data ?? result;
359
- }
360
- // ── Webhooks ──
361
- async createWebhook(options) {
362
- const agentId = this.getAgentId();
363
- const result = await this.post(`/api/v1/agents/${agentId}/webhooks`, options);
364
- return { webhook: result.data ?? result };
365
- }
366
- async listWebhooks() {
367
- const agentId = this.getAgentId();
368
- const result = await this.get(`/api/v1/agents/${agentId}/webhooks`);
369
- return { webhooks: result.data ?? result };
370
- }
371
- async updateWebhook(webhookId, updates) {
372
- const agentId = this.getAgentId();
373
- const result = await this.patch(`/api/v1/agents/${agentId}/webhooks/${webhookId}`, updates);
374
- return { webhook: result.data ?? result };
375
- }
376
- async deleteWebhook(webhookId) {
377
- const agentId = this.getAgentId();
378
- await this.del(`/api/v1/agents/${agentId}/webhooks/${webhookId}`);
379
- }
380
- async rotateWebhookSecret(webhookId) {
381
- const agentId = this.getAgentId();
382
- const result = await this.post(`/api/v1/agents/${agentId}/webhooks/${webhookId}/rotate-secret`);
383
- return result.data ?? result;
384
- }
385
- async listWebhookDeliveries(webhookId, options) {
386
- const agentId = this.getAgentId();
387
- const params = new URLSearchParams();
388
- if (options?.limit)
389
- params.set("limit", String(options.limit));
390
- if (options?.status)
391
- params.set("status", options.status);
392
- const qs = params.toString();
393
- const result = await this.get(`/api/v1/agents/${agentId}/webhooks/${webhookId}/deliveries${qs ? `?${qs}` : ""}`);
394
- return { deliveries: result.data ?? result };
395
- }
396
- // ── Profile ──
397
- async setReadReceiptEmoji(emoji) {
398
- const agentId = this.getAgentId();
399
- const result = await this.put(`/api/v1/agents/${agentId}/read-receipt-emoji`, { emoji });
400
- return { emoji: result.data?.emoji ?? emoji };
401
- }
402
- async getReadReceiptEmoji() {
403
- const agentId = this.getAgentId();
404
- const result = await this.get(`/api/v1/agents/${agentId}/read-receipt-emoji`);
405
- return { emoji: result.data?.emoji ?? "\u{1F440}" };
406
- }
407
- // ── Internal helpers ──
408
- normalizeMessage(msg) {
409
- return {
410
- ...msg,
411
- content: msg.content ?? msg.plaintext ?? null
412
- };
413
- }
414
- getAgentId() {
415
- const principal = this._principalId;
416
- if (principal)
417
- return principal;
418
- throw new SesameApiError(400, "Agent ID not resolved. Call boot() or setPrincipalId(id) first.");
419
- }
420
- /**
421
- * Set the current agent's principal ID (resolved after auth).
422
- */
423
- setPrincipalId(id) {
424
- this._principalId = id;
425
- }
426
- /**
427
- * Bootstrap the agent: resolves identity via /auth/me and loads manifest.
428
- */
429
- async boot() {
430
- const me = await this.get("/api/v1/auth/me");
431
- const principal = me.data ?? me;
432
- this.setPrincipalId(principal.id);
433
- const manifest = await this.getManifest();
434
- return manifest;
435
- }
436
- // ── WebSocket ──
437
- /**
438
- * Connect to the real-time WebSocket gateway.
439
- */
440
- connect() {
441
- return new Promise((resolve, reject) => {
442
- try {
443
- this.ws = new WebSocket(`${this.config.wsUrl}/v1/connect`);
444
- this.ws.on("open", () => {
445
- this.reconnectAttempts = 0;
446
- this.sendAuth();
447
- });
448
- this.ws.on("message", (data) => {
449
- try {
450
- const event = JSON.parse(data.toString());
451
- if (event.type === "authenticated") {
452
- this.authenticated = true;
453
- this.startHeartbeat(event.heartbeatIntervalMs ?? 3e4);
454
- this.sendReplay();
455
- resolve();
456
- return;
457
- }
458
- if (event.type === "pong")
459
- return;
460
- if (event.type === "error") {
461
- console.error("WS error:", event.message);
462
- return;
463
- }
464
- if (event.type === "message" && event.data) {
465
- event.data = this.normalizeMessage(event.data);
466
- const seq = event.data.seq;
467
- if (seq) {
468
- const channelId = event.data.channelId;
469
- const current = this.cursors.get(channelId) ?? 0;
470
- if (seq > current)
471
- this.cursors.set(channelId, seq);
472
- }
473
- }
474
- this.emit(event);
475
- } catch {
476
- }
477
- });
478
- this.ws.on("close", () => {
479
- this.authenticated = false;
480
- this.stopHeartbeat();
481
- if (this.config.autoReconnect) {
482
- this.scheduleReconnect();
483
- }
484
- });
485
- this.ws.on("error", (err) => {
486
- if (!this.authenticated) {
487
- reject(err);
488
- }
489
- });
490
- } catch (err) {
491
- reject(err);
492
- }
493
- });
494
- }
495
- /**
496
- * Disconnect from the WebSocket gateway.
497
- */
498
- disconnect() {
499
- this.config.autoReconnect = false;
500
- this.stopHeartbeat();
501
- if (this.reconnectTimer) {
502
- clearTimeout(this.reconnectTimer);
503
- this.reconnectTimer = null;
504
- }
505
- if (this.ws) {
506
- this.ws.close();
507
- this.ws = null;
508
- }
509
- }
510
- /**
511
- * Subscribe to WebSocket events.
512
- */
513
- on(eventType, handler) {
514
- if (!this.eventHandlers.has(eventType)) {
515
- this.eventHandlers.set(eventType, /* @__PURE__ */ new Set());
516
- }
517
- this.eventHandlers.get(eventType).add(handler);
518
- return () => {
519
- this.eventHandlers.get(eventType)?.delete(handler);
520
- };
521
- }
522
- /**
523
- * Subscribe to all events.
524
- */
525
- onAny(handler) {
526
- return this.on("*", handler);
527
- }
528
- emit(event) {
529
- this.eventHandlers.get(event.type)?.forEach((h) => h(event));
530
- this.eventHandlers.get("*")?.forEach((h) => h(event));
531
- }
532
- sendAuth() {
533
- if (!this.ws)
534
- return;
535
- if (this.config.apiKey) {
536
- this.ws.send(JSON.stringify({ type: "auth", apiKey: this.config.apiKey }));
537
- } else if (this.config.token) {
538
- this.ws.send(JSON.stringify({ type: "auth", token: this.config.token }));
539
- } else if (this.config.agent) {
540
- const { signature, timestamp } = createAuthSignature(this.config.agent.handle, this.config.agent.privateKey);
541
- this.ws.send(JSON.stringify({
542
- type: "auth",
543
- signature: {
544
- handle: this.config.agent.handle,
545
- sig: signature,
546
- timestamp
547
- }
548
- }));
549
- }
550
- }
551
- sendReplay() {
552
- if (!this.ws || this.cursors.size === 0)
553
- return;
554
- const cursors = {};
555
- this.cursors.forEach((seq, channelId) => {
556
- cursors[channelId] = seq;
557
- });
558
- this.ws.send(JSON.stringify({ type: "replay", cursors }));
559
- }
560
- startHeartbeat(intervalMs) {
561
- this.stopHeartbeat();
562
- this.heartbeatTimer = setInterval(() => {
563
- if (this.ws?.readyState === WebSocket.OPEN) {
564
- this.ws.send(JSON.stringify({ type: "ping" }));
565
- }
566
- }, intervalMs);
567
- }
568
- stopHeartbeat() {
569
- if (this.heartbeatTimer) {
570
- clearInterval(this.heartbeatTimer);
571
- this.heartbeatTimer = null;
572
- }
573
- }
574
- scheduleReconnect() {
575
- if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {
576
- console.error("Max reconnect attempts reached");
577
- return;
578
- }
579
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
580
- this.reconnectAttempts++;
581
- this.reconnectTimer = setTimeout(() => {
582
- this.connect().catch(() => {
583
- this.scheduleReconnect();
584
- });
585
- }, delay);
586
- }
587
- /**
588
- * Send a typing indicator for a channel.
589
- */
590
- sendTyping(channelId) {
591
- if (this.ws?.readyState === WebSocket.OPEN) {
592
- this.ws.send(JSON.stringify({ type: "typing", channelId }));
593
- }
594
- }
595
- /**
596
- * Send a message via WebSocket (alternative to HTTP).
597
- */
598
- sendWsMessage(channelId, content, options) {
599
- if (this.ws?.readyState === WebSocket.OPEN) {
600
- this.ws.send(JSON.stringify({
601
- type: "send",
602
- channelId,
603
- content,
604
- ...options
605
- }));
606
- }
607
- }
608
- };
609
- var SesameApiError = class extends Error {
610
- status;
611
- constructor(status, message) {
612
- super(message);
613
- this.status = status;
614
- this.name = "SesameApiError";
615
- }
616
- };
617
-
618
- // node_modules/.pnpm/@sesamespace+sdk@0.1.6/node_modules/@sesamespace/sdk/dist/verify-webhook.js
619
- import { createHmac, timingSafeEqual } from "crypto";
620
-
621
- export {
622
- SesameClient
623
- };
624
- //# sourceMappingURL=chunk-GPI4RU7N.js.map