kagura-memory 0.1.0 → 0.2.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 CHANGED
@@ -12,6 +12,7 @@ This SDK connects your TypeScript/JavaScript code to [Kagura Memory Cloud](https
12
12
  | **`ResourceClient`** | REST API | External data ingestion — push data from Slack, CI/CD, CRM into Kagura |
13
13
  | **`FilesClient`** | REST + presigned PUT | File uploads with sha256 integrity binding (R2) |
14
14
  | **`WorkspaceClient`** | REST API | Workspace member, invitation, and API key management |
15
+ | **`AgentsClient`** | REST API | Agent bootstrap for API-key-only callers (no MCP session) |
15
16
 
16
17
  ## Installation
17
18
 
@@ -92,8 +93,50 @@ try {
92
93
  ```
93
94
 
94
95
  Server-side domain errors (`{"status": "error", ...}`) are translated into
95
- exceptions — `KaguraNotFoundError` for missing contexts/memories/reports,
96
- `KaguraError` otherwise — so you never need to inspect `result.status`.
96
+ exceptions — `KaguraNotFoundError` for missing contexts/memories/reports/
97
+ agents/bindings, `KaguraError` otherwise — so you never need to inspect
98
+ `result.status`.
99
+
100
+ ## Agent control plane (memory-cloud v0.49.0+)
101
+
102
+ `KaguraClient` wraps the RFC-0002 agent platform: the **Agent Registry**
103
+ (`registerAgent` / `listAgents` / `getAgent` / `updateAgent` /
104
+ `deleteAgent`), subtractive **context bindings** (`bindAgentContext` /
105
+ `listAgentBindings` / `updateAgentBinding` / `unbindAgentContext`), and
106
+ the session-start **bootstrap** call. Registry and binding methods are
107
+ **owner/admin-gated** server-side; `deleteAgent` is permanent and
108
+ cascades every API key bound to the agent (prefer
109
+ `updateAgent({ status: "retired" })` for operational retirement).
110
+
111
+ ```ts
112
+ // One-time provisioning (owner/admin): register the agent, bind its context
113
+ const agent = await client.registerAgent({ name: "ci-agent", framework: "claude-code" });
114
+ await client.bindAgentContext({ agentId: agent.id, contextId: "ctx-uuid", isDefault: true });
115
+
116
+ // Session start: rehydrate cognitive state in one call
117
+ const bootstrap = await client.getAgentBootstrap({
118
+ agentId: agent.id, // contextId omitted → default binding
119
+ sessionId: "run-42", // echoed in the correlation block
120
+ query: "session summary", // enables the trusted-only recall component
121
+ });
122
+ if (bootstrap.degraded) {
123
+ // some component failed fail-soft; inspect bootstrap.components
124
+ }
125
+ ```
126
+
127
+ Deployed agents holding only an API key (e.g. an agent-bound member key)
128
+ can bootstrap over REST without an MCP session:
129
+
130
+ ```ts
131
+ import { AgentsClient } from "kagura-memory";
132
+
133
+ const agents = AgentsClient.fromMcpUrl();
134
+ const bootstrap = await agents.bootstrap({ agentId: "agent-uuid" });
135
+ ```
136
+
137
+ Requires memory-cloud **v0.49.0+** — older servers return MCP "tool not
138
+ found" / REST 404 on this surface; everything else in the SDK keeps
139
+ working against `MIN_SERVER_VERSION`.
97
140
 
98
141
  ## Relationship to the Python SDK
99
142
 
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AgentsClient: () => AgentsClient,
33
34
  DEFAULT_MCP_URL: () => DEFAULT_MCP_URL,
34
35
  DEFAULT_REST_BASE_URL: () => DEFAULT_REST_BASE_URL,
35
36
  FilesClient: () => FilesClient,
@@ -60,6 +61,33 @@ __export(index_exports, {
60
61
  });
61
62
  module.exports = __toCommonJS(index_exports);
62
63
 
64
+ // src/agentBootstrap.ts
65
+ function buildBootstrapPayload(options) {
66
+ const payload = {};
67
+ if (options.contextId !== void 0) {
68
+ payload.context_id = options.contextId;
69
+ }
70
+ if (options.sessionId !== void 0) {
71
+ payload.session_id = options.sessionId;
72
+ }
73
+ if (options.query !== void 0) {
74
+ payload.query = options.query;
75
+ }
76
+ if (options.recallK !== void 0) {
77
+ payload.recall_k = options.recallK;
78
+ }
79
+ if (options.pinnedCap !== void 0) {
80
+ payload.pinned_cap = options.pinnedCap;
81
+ }
82
+ if (options.upcomingUntil !== void 0) {
83
+ payload.upcoming_until = options.upcomingUntil;
84
+ }
85
+ if (options.include !== void 0) {
86
+ payload.include = options.include;
87
+ }
88
+ return payload;
89
+ }
90
+
63
91
  // src/config.ts
64
92
  var fs = __toESM(require("fs"), 1);
65
93
  var os = __toESM(require("os"), 1);
@@ -1113,7 +1141,7 @@ var KaguraClient = class _KaguraClient {
1113
1141
  }
1114
1142
  const code = typeof result.error === "string" ? result.error : "unknown";
1115
1143
  const message = typeof result.message === "string" ? result.message : "Unknown error";
1116
- if (code === "report_not_found" || code === "context_not_found" || code === "memory_not_found") {
1144
+ if (code === "report_not_found" || code === "context_not_found" || code === "memory_not_found" || code === "agent_not_found" || code === "binding_not_found") {
1117
1145
  throw new KaguraNotFoundError(`${operation}: ${message}`);
1118
1146
  }
1119
1147
  throw new KaguraError(`${operation} failed (${code}): ${message}`);
@@ -1280,6 +1308,254 @@ var KaguraClient = class _KaguraClient {
1280
1308
  }
1281
1309
  return this.callToolChecked("get_state", args);
1282
1310
  }
1311
+ // -------------------------------------------------------------------
1312
+ // Agent control plane (server v0.49.0+, RFC-0002; issues #1/#2/#3)
1313
+ // -------------------------------------------------------------------
1314
+ /**
1315
+ * Unwrap an object envelope (`agent`, `binding`, `report`, …) from a
1316
+ * tool result.
1317
+ *
1318
+ * Match the Python port's `result["<key>"]`: a missing envelope is a
1319
+ * contract violation, surfaced loudly rather than as a partial object.
1320
+ */
1321
+ static expectEnvelope(result, key, operation) {
1322
+ const envelope = result[key];
1323
+ if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) {
1324
+ throw new KaguraConnectionError(
1325
+ `Unexpected ${operation} response: missing '${key}' envelope.`
1326
+ );
1327
+ }
1328
+ return envelope;
1329
+ }
1330
+ /**
1331
+ * Register an AI agent in the workspace Agent Registry.
1332
+ *
1333
+ * Calls the `register_agent` MCP tool (server v0.49.0+, RFC-0002 P0-1,
1334
+ * memory-cloud #1274) — owner/admin only. An agent is a
1335
+ * workspace-scoped registry entry (name unique per workspace) that
1336
+ * anchors context bindings, agent-bound credentials,
1337
+ * {@link getAgentBootstrap}, and audit correlation — it is a resource,
1338
+ * NOT a principal. New agents start with `status="active"` and
1339
+ * `enforcement_mode="enforce"`.
1340
+ *
1341
+ * Requires memory-cloud v0.49.0+ — older servers return an MCP
1342
+ * "tool not found" error ({@link MIN_SERVER_VERSION} is deliberately
1343
+ * not bumped; only the agent control plane needs the newer server).
1344
+ *
1345
+ * @throws KaguraError on name conflict, agent quota, or insufficient
1346
+ * role (owner/admin required).
1347
+ */
1348
+ async registerAgent(options) {
1349
+ const args = { name: options.name };
1350
+ if (options.description !== void 0) {
1351
+ args.description = options.description;
1352
+ }
1353
+ if (options.framework !== void 0) {
1354
+ args.framework = options.framework;
1355
+ }
1356
+ if (options.environment !== void 0) {
1357
+ args.environment = options.environment;
1358
+ }
1359
+ if (options.version !== void 0) {
1360
+ args.version = options.version;
1361
+ }
1362
+ const result = await this.callToolChecked("register_agent", args);
1363
+ return _KaguraClient.expectEnvelope(result, "agent", "register_agent");
1364
+ }
1365
+ /**
1366
+ * Fetch one registered agent by id (owner/admin only).
1367
+ *
1368
+ * @throws KaguraNotFoundError when the agent does not exist. The 404 is
1369
+ * uniform (CWE-639) — nonexistent and not-yours are indistinguishable
1370
+ * by design, so it does NOT prove the agent is absent.
1371
+ */
1372
+ async getAgent(agentId) {
1373
+ const result = await this.callToolChecked("get_agent", { agent_id: agentId });
1374
+ return _KaguraClient.expectEnvelope(result, "agent", "get_agent");
1375
+ }
1376
+ /** List the workspace's registered agents, newest first (owner/admin only). */
1377
+ async listAgents() {
1378
+ const result = await this.callToolChecked("list_agents", {});
1379
+ const agents = result.agents;
1380
+ return Array.isArray(agents) ? agents : [];
1381
+ }
1382
+ /**
1383
+ * Update a registered agent, including lifecycle transitions
1384
+ * (owner/admin only).
1385
+ *
1386
+ * `status` is the **fail-closed kill switch**: `"suspended"` /
1387
+ * `"retired"` agents cause every key bound to them to be rejected at
1388
+ * verify time. Setting `enforcementMode` from `"enforce"` to
1389
+ * `"shadow"` is an audited privilege-widening event.
1390
+ *
1391
+ * Set-only wrapper: omitted fields are left untouched. The server's
1392
+ * null-clears-a-metadata-field semantics is not expressible through
1393
+ * this wrapper — clear fields via the web UI or the raw API.
1394
+ *
1395
+ * @throws Error when no update field is provided (the call would be an
1396
+ * empty no-op request).
1397
+ */
1398
+ async updateAgent(options) {
1399
+ const changes = {};
1400
+ if (options.name !== void 0) {
1401
+ changes.name = options.name;
1402
+ }
1403
+ if (options.description !== void 0) {
1404
+ changes.description = options.description;
1405
+ }
1406
+ if (options.framework !== void 0) {
1407
+ changes.framework = options.framework;
1408
+ }
1409
+ if (options.environment !== void 0) {
1410
+ changes.environment = options.environment;
1411
+ }
1412
+ if (options.version !== void 0) {
1413
+ changes.version = options.version;
1414
+ }
1415
+ if (options.status !== void 0) {
1416
+ changes.status = options.status;
1417
+ }
1418
+ if (options.enforcementMode !== void 0) {
1419
+ changes.enforcement_mode = options.enforcementMode;
1420
+ }
1421
+ if (Object.keys(changes).length === 0) {
1422
+ throw new Error("updateAgent requires at least one field to update");
1423
+ }
1424
+ const result = await this.callToolChecked("update_agent", {
1425
+ agent_id: options.agentId,
1426
+ ...changes
1427
+ });
1428
+ return _KaguraClient.expectEnvelope(result, "agent", "update_agent");
1429
+ }
1430
+ /**
1431
+ * Hard-delete an Agent Registry row (owner/admin only). Returns true
1432
+ * once the server confirms deletion.
1433
+ *
1434
+ * Permanent, and cascades every API key bound to the agent
1435
+ * (fail-closed). Prefer `updateAgent({status: "retired"})` for
1436
+ * operational retirement.
1437
+ */
1438
+ async deleteAgent(agentId) {
1439
+ const result = await this.callToolChecked("delete_agent", { agent_id: agentId });
1440
+ return result.deleted === void 0 ? true : Boolean(result.deleted);
1441
+ }
1442
+ /**
1443
+ * Build the omit-when-undefined binding scope trio shared by
1444
+ * {@link bindAgentContext} and {@link updateAgentBinding} — the port of
1445
+ * the Python SDK's `_binding_scope_payload`. When memory-cloud #1286
1446
+ * ships the reserved filters, extend {@link AgentBindingScopeOptions}
1447
+ * and map the new fields here.
1448
+ */
1449
+ static bindingScopeArgs(options) {
1450
+ const args = {};
1451
+ if (options.canRead !== void 0) {
1452
+ args.can_read = options.canRead;
1453
+ }
1454
+ if (options.writePolicy !== void 0) {
1455
+ args.write_policy = options.writePolicy;
1456
+ }
1457
+ if (options.isDefault !== void 0) {
1458
+ args.is_default = options.isDefault;
1459
+ }
1460
+ return args;
1461
+ }
1462
+ /**
1463
+ * Bind an agent to a context — purely subtractive scoping.
1464
+ *
1465
+ * Calls the `bind_agent_context` MCP tool (server v0.49.0+, RFC-0002
1466
+ * P0-2, memory-cloud #1275) — owner/admin only. The effective
1467
+ * permission for an agent-bound request is the existing RBAC decision
1468
+ * ∩ binding. Under `enforcement_mode="enforce"`, contexts WITHOUT a
1469
+ * binding row are denied for the agent (default-deny); under
1470
+ * `"shadow"`, violations are only logged.
1471
+ *
1472
+ * @throws KaguraNotFoundError when the agent or context is not found.
1473
+ * @throws KaguraError on duplicate binding or other server-side error.
1474
+ */
1475
+ async bindAgentContext(options) {
1476
+ const result = await this.callToolChecked("bind_agent_context", {
1477
+ agent_id: options.agentId,
1478
+ context_id: options.contextId,
1479
+ ..._KaguraClient.bindingScopeArgs(options)
1480
+ });
1481
+ return _KaguraClient.expectEnvelope(result, "binding", "bind_agent_context");
1482
+ }
1483
+ /** List an agent's context bindings (owner/admin only). */
1484
+ async listAgentBindings(agentId) {
1485
+ const result = await this.callToolChecked("list_agent_bindings", { agent_id: agentId });
1486
+ const bindings = result.bindings;
1487
+ return Array.isArray(bindings) ? bindings : [];
1488
+ }
1489
+ /**
1490
+ * Update a binding's scoping fields (owner/admin only).
1491
+ *
1492
+ * `context_id` is immutable — {@link unbindAgentContext} and re-
1493
+ * {@link bindAgentContext} to re-target. Changes are audited with
1494
+ * old→new values.
1495
+ *
1496
+ * @throws Error when no scoping field is provided (the call would be
1497
+ * an empty no-op request).
1498
+ */
1499
+ async updateAgentBinding(options) {
1500
+ const changes = _KaguraClient.bindingScopeArgs(options);
1501
+ if (Object.keys(changes).length === 0) {
1502
+ throw new Error(
1503
+ "updateAgentBinding requires at least one of canRead, writePolicy, or isDefault"
1504
+ );
1505
+ }
1506
+ const result = await this.callToolChecked("update_agent_binding", {
1507
+ agent_id: options.agentId,
1508
+ binding_id: options.bindingId,
1509
+ ...changes
1510
+ });
1511
+ return _KaguraClient.expectEnvelope(result, "binding", "update_agent_binding");
1512
+ }
1513
+ /**
1514
+ * Delete a binding — the agent loses that context (owner/admin only).
1515
+ * Returns true once the server confirms deletion.
1516
+ *
1517
+ * Under `enforcement_mode="enforce"` the agent's requests against the
1518
+ * unbound context are denied afterwards (uniform `context_not_found`).
1519
+ */
1520
+ async unbindAgentContext(options) {
1521
+ const result = await this.callToolChecked("unbind_agent_context", {
1522
+ agent_id: options.agentId,
1523
+ binding_id: options.bindingId
1524
+ });
1525
+ return result.deleted === void 0 ? true : Boolean(result.deleted);
1526
+ }
1527
+ /**
1528
+ * Rehydrate an agent's cognitive state in one session-start call.
1529
+ *
1530
+ * Calls the `get_agent_bootstrap` MCP tool (server v0.49.0+, RFC-0002
1531
+ * P0-3, memory-cloud #1276). The server composes existing primitives —
1532
+ * context guide + pinned memories ({@link loadPinned}) + a trusted-only
1533
+ * {@link recall} (only when `query` is supplied) + upcoming time
1534
+ * memories ({@link recallUpcoming}) + the agent-state lane
1535
+ * ({@link getState}) — with bounds, ordering, and trust filtering
1536
+ * inherited from those standalone tools, not re-specified.
1537
+ *
1538
+ * Components are **fail-soft**: a failing component reports
1539
+ * `{"status": "error", ...}` under `components` while the rest still
1540
+ * return, with the top-level `degraded` flag set. Identity and
1541
+ * authorization failures are total and throw instead.
1542
+ *
1543
+ * The REST companion (`POST /api/v1/agents/{agent_id}/bootstrap`) is
1544
+ * available via `AgentsClient` for API-key-only callers such as
1545
+ * agent-bound member keys.
1546
+ *
1547
+ * @throws KaguraNotFoundError when the agent or context is not found
1548
+ * (uniform 404 — nonexistent and not-yours are indistinguishable by
1549
+ * design).
1550
+ * @throws KaguraError on invalid arguments or other server-side error.
1551
+ */
1552
+ async getAgentBootstrap(options) {
1553
+ const result = await this.callToolChecked("get_agent_bootstrap", {
1554
+ agent_id: options.agentId,
1555
+ ...buildBootstrapPayload(options)
1556
+ });
1557
+ return result;
1558
+ }
1283
1559
  /** List available contexts. */
1284
1560
  async listContexts() {
1285
1561
  return this.callToolChecked("list_contexts", {});
@@ -1743,12 +2019,7 @@ var KaguraClient = class _KaguraClient {
1743
2019
  context_id: options.contextId,
1744
2020
  report_id: options.reportId
1745
2021
  });
1746
- const report = result.report;
1747
- if (typeof report !== "object" || report === null || Array.isArray(report)) {
1748
- throw new KaguraConnectionError(
1749
- "Unexpected get_sleep_report response: missing 'report' envelope."
1750
- );
1751
- }
2022
+ const report = _KaguraClient.expectEnvelope(result, "report", "get_sleep_report");
1752
2023
  return {
1753
2024
  ...report,
1754
2025
  actions: result.actions,
@@ -2040,19 +2311,6 @@ var KaguraRestClient = class {
2040
2311
  }
2041
2312
  };
2042
2313
 
2043
- // src/filesClient.ts
2044
- var import_node_crypto = require("crypto");
2045
- var import_promises3 = require("fs/promises");
2046
- var path4 = __toESM(require("path"), 1);
2047
-
2048
- // src/auth/types.ts
2049
- var SOURCE_LABEL = {
2050
- explicit: "explicit apiKey argument",
2051
- env: "KAGURA_API_KEY env",
2052
- config: ".kagura.json",
2053
- oauth: "OAuth profile (~/.kagura/credentials.json)"
2054
- };
2055
-
2056
2314
  // src/uuid.ts
2057
2315
  var CANONICAL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2058
2316
  function parseUuid(value) {
@@ -2084,6 +2342,42 @@ function isUuid(value) {
2084
2342
  }
2085
2343
  }
2086
2344
 
2345
+ // src/agentsClient.ts
2346
+ var AgentsClient = class extends KaguraRestClient {
2347
+ /**
2348
+ * Rehydrate an agent's cognitive state at session start.
2349
+ *
2350
+ * REST companion to `KaguraClient.getAgentBootstrap` — same options,
2351
+ * same composed envelope, same fail-soft component semantics (see that
2352
+ * method for the full contract).
2353
+ */
2354
+ async bootstrap(options) {
2355
+ let agentId;
2356
+ try {
2357
+ agentId = parseUuid(options.agentId);
2358
+ } catch {
2359
+ throw new Error(`agentId must be a UUID, got ${JSON.stringify(options.agentId)}`);
2360
+ }
2361
+ const resp = await this.request("POST", `/api/v1/agents/${agentId}/bootstrap`, {
2362
+ json: buildBootstrapPayload(options)
2363
+ });
2364
+ return this.json(resp);
2365
+ }
2366
+ };
2367
+
2368
+ // src/filesClient.ts
2369
+ var import_node_crypto = require("crypto");
2370
+ var import_promises3 = require("fs/promises");
2371
+ var path4 = __toESM(require("path"), 1);
2372
+
2373
+ // src/auth/types.ts
2374
+ var SOURCE_LABEL = {
2375
+ explicit: "explicit apiKey argument",
2376
+ env: "KAGURA_API_KEY env",
2377
+ config: ".kagura.json",
2378
+ oauth: "OAuth profile (~/.kagura/credentials.json)"
2379
+ };
2380
+
2087
2381
  // src/filesClient.ts
2088
2382
  var CONTENT_TYPE_BY_EXT = {
2089
2383
  ".txt": "text/plain",
@@ -2928,6 +3222,7 @@ function isMintShape(payload) {
2928
3222
  }
2929
3223
  // Annotate the CommonJS export names for ESM import in node:
2930
3224
  0 && (module.exports = {
3225
+ AgentsClient,
2931
3226
  DEFAULT_MCP_URL,
2932
3227
  DEFAULT_REST_BASE_URL,
2933
3228
  FilesClient,