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/dist/index.js CHANGED
@@ -1,3 +1,30 @@
1
+ // src/agentBootstrap.ts
2
+ function buildBootstrapPayload(options) {
3
+ const payload = {};
4
+ if (options.contextId !== void 0) {
5
+ payload.context_id = options.contextId;
6
+ }
7
+ if (options.sessionId !== void 0) {
8
+ payload.session_id = options.sessionId;
9
+ }
10
+ if (options.query !== void 0) {
11
+ payload.query = options.query;
12
+ }
13
+ if (options.recallK !== void 0) {
14
+ payload.recall_k = options.recallK;
15
+ }
16
+ if (options.pinnedCap !== void 0) {
17
+ payload.pinned_cap = options.pinnedCap;
18
+ }
19
+ if (options.upcomingUntil !== void 0) {
20
+ payload.upcoming_until = options.upcomingUntil;
21
+ }
22
+ if (options.include !== void 0) {
23
+ payload.include = options.include;
24
+ }
25
+ return payload;
26
+ }
27
+
1
28
  // src/config.ts
2
29
  import * as fs from "fs";
3
30
  import * as os from "os";
@@ -1051,7 +1078,7 @@ var KaguraClient = class _KaguraClient {
1051
1078
  }
1052
1079
  const code = typeof result.error === "string" ? result.error : "unknown";
1053
1080
  const message = typeof result.message === "string" ? result.message : "Unknown error";
1054
- if (code === "report_not_found" || code === "context_not_found" || code === "memory_not_found") {
1081
+ if (code === "report_not_found" || code === "context_not_found" || code === "memory_not_found" || code === "agent_not_found" || code === "binding_not_found") {
1055
1082
  throw new KaguraNotFoundError(`${operation}: ${message}`);
1056
1083
  }
1057
1084
  throw new KaguraError(`${operation} failed (${code}): ${message}`);
@@ -1218,6 +1245,254 @@ var KaguraClient = class _KaguraClient {
1218
1245
  }
1219
1246
  return this.callToolChecked("get_state", args);
1220
1247
  }
1248
+ // -------------------------------------------------------------------
1249
+ // Agent control plane (server v0.49.0+, RFC-0002; issues #1/#2/#3)
1250
+ // -------------------------------------------------------------------
1251
+ /**
1252
+ * Unwrap an object envelope (`agent`, `binding`, `report`, …) from a
1253
+ * tool result.
1254
+ *
1255
+ * Match the Python port's `result["<key>"]`: a missing envelope is a
1256
+ * contract violation, surfaced loudly rather than as a partial object.
1257
+ */
1258
+ static expectEnvelope(result, key, operation) {
1259
+ const envelope = result[key];
1260
+ if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) {
1261
+ throw new KaguraConnectionError(
1262
+ `Unexpected ${operation} response: missing '${key}' envelope.`
1263
+ );
1264
+ }
1265
+ return envelope;
1266
+ }
1267
+ /**
1268
+ * Register an AI agent in the workspace Agent Registry.
1269
+ *
1270
+ * Calls the `register_agent` MCP tool (server v0.49.0+, RFC-0002 P0-1,
1271
+ * memory-cloud #1274) — owner/admin only. An agent is a
1272
+ * workspace-scoped registry entry (name unique per workspace) that
1273
+ * anchors context bindings, agent-bound credentials,
1274
+ * {@link getAgentBootstrap}, and audit correlation — it is a resource,
1275
+ * NOT a principal. New agents start with `status="active"` and
1276
+ * `enforcement_mode="enforce"`.
1277
+ *
1278
+ * Requires memory-cloud v0.49.0+ — older servers return an MCP
1279
+ * "tool not found" error ({@link MIN_SERVER_VERSION} is deliberately
1280
+ * not bumped; only the agent control plane needs the newer server).
1281
+ *
1282
+ * @throws KaguraError on name conflict, agent quota, or insufficient
1283
+ * role (owner/admin required).
1284
+ */
1285
+ async registerAgent(options) {
1286
+ const args = { name: options.name };
1287
+ if (options.description !== void 0) {
1288
+ args.description = options.description;
1289
+ }
1290
+ if (options.framework !== void 0) {
1291
+ args.framework = options.framework;
1292
+ }
1293
+ if (options.environment !== void 0) {
1294
+ args.environment = options.environment;
1295
+ }
1296
+ if (options.version !== void 0) {
1297
+ args.version = options.version;
1298
+ }
1299
+ const result = await this.callToolChecked("register_agent", args);
1300
+ return _KaguraClient.expectEnvelope(result, "agent", "register_agent");
1301
+ }
1302
+ /**
1303
+ * Fetch one registered agent by id (owner/admin only).
1304
+ *
1305
+ * @throws KaguraNotFoundError when the agent does not exist. The 404 is
1306
+ * uniform (CWE-639) — nonexistent and not-yours are indistinguishable
1307
+ * by design, so it does NOT prove the agent is absent.
1308
+ */
1309
+ async getAgent(agentId) {
1310
+ const result = await this.callToolChecked("get_agent", { agent_id: agentId });
1311
+ return _KaguraClient.expectEnvelope(result, "agent", "get_agent");
1312
+ }
1313
+ /** List the workspace's registered agents, newest first (owner/admin only). */
1314
+ async listAgents() {
1315
+ const result = await this.callToolChecked("list_agents", {});
1316
+ const agents = result.agents;
1317
+ return Array.isArray(agents) ? agents : [];
1318
+ }
1319
+ /**
1320
+ * Update a registered agent, including lifecycle transitions
1321
+ * (owner/admin only).
1322
+ *
1323
+ * `status` is the **fail-closed kill switch**: `"suspended"` /
1324
+ * `"retired"` agents cause every key bound to them to be rejected at
1325
+ * verify time. Setting `enforcementMode` from `"enforce"` to
1326
+ * `"shadow"` is an audited privilege-widening event.
1327
+ *
1328
+ * Set-only wrapper: omitted fields are left untouched. The server's
1329
+ * null-clears-a-metadata-field semantics is not expressible through
1330
+ * this wrapper — clear fields via the web UI or the raw API.
1331
+ *
1332
+ * @throws Error when no update field is provided (the call would be an
1333
+ * empty no-op request).
1334
+ */
1335
+ async updateAgent(options) {
1336
+ const changes = {};
1337
+ if (options.name !== void 0) {
1338
+ changes.name = options.name;
1339
+ }
1340
+ if (options.description !== void 0) {
1341
+ changes.description = options.description;
1342
+ }
1343
+ if (options.framework !== void 0) {
1344
+ changes.framework = options.framework;
1345
+ }
1346
+ if (options.environment !== void 0) {
1347
+ changes.environment = options.environment;
1348
+ }
1349
+ if (options.version !== void 0) {
1350
+ changes.version = options.version;
1351
+ }
1352
+ if (options.status !== void 0) {
1353
+ changes.status = options.status;
1354
+ }
1355
+ if (options.enforcementMode !== void 0) {
1356
+ changes.enforcement_mode = options.enforcementMode;
1357
+ }
1358
+ if (Object.keys(changes).length === 0) {
1359
+ throw new Error("updateAgent requires at least one field to update");
1360
+ }
1361
+ const result = await this.callToolChecked("update_agent", {
1362
+ agent_id: options.agentId,
1363
+ ...changes
1364
+ });
1365
+ return _KaguraClient.expectEnvelope(result, "agent", "update_agent");
1366
+ }
1367
+ /**
1368
+ * Hard-delete an Agent Registry row (owner/admin only). Returns true
1369
+ * once the server confirms deletion.
1370
+ *
1371
+ * Permanent, and cascades every API key bound to the agent
1372
+ * (fail-closed). Prefer `updateAgent({status: "retired"})` for
1373
+ * operational retirement.
1374
+ */
1375
+ async deleteAgent(agentId) {
1376
+ const result = await this.callToolChecked("delete_agent", { agent_id: agentId });
1377
+ return result.deleted === void 0 ? true : Boolean(result.deleted);
1378
+ }
1379
+ /**
1380
+ * Build the omit-when-undefined binding scope trio shared by
1381
+ * {@link bindAgentContext} and {@link updateAgentBinding} — the port of
1382
+ * the Python SDK's `_binding_scope_payload`. When memory-cloud #1286
1383
+ * ships the reserved filters, extend {@link AgentBindingScopeOptions}
1384
+ * and map the new fields here.
1385
+ */
1386
+ static bindingScopeArgs(options) {
1387
+ const args = {};
1388
+ if (options.canRead !== void 0) {
1389
+ args.can_read = options.canRead;
1390
+ }
1391
+ if (options.writePolicy !== void 0) {
1392
+ args.write_policy = options.writePolicy;
1393
+ }
1394
+ if (options.isDefault !== void 0) {
1395
+ args.is_default = options.isDefault;
1396
+ }
1397
+ return args;
1398
+ }
1399
+ /**
1400
+ * Bind an agent to a context — purely subtractive scoping.
1401
+ *
1402
+ * Calls the `bind_agent_context` MCP tool (server v0.49.0+, RFC-0002
1403
+ * P0-2, memory-cloud #1275) — owner/admin only. The effective
1404
+ * permission for an agent-bound request is the existing RBAC decision
1405
+ * ∩ binding. Under `enforcement_mode="enforce"`, contexts WITHOUT a
1406
+ * binding row are denied for the agent (default-deny); under
1407
+ * `"shadow"`, violations are only logged.
1408
+ *
1409
+ * @throws KaguraNotFoundError when the agent or context is not found.
1410
+ * @throws KaguraError on duplicate binding or other server-side error.
1411
+ */
1412
+ async bindAgentContext(options) {
1413
+ const result = await this.callToolChecked("bind_agent_context", {
1414
+ agent_id: options.agentId,
1415
+ context_id: options.contextId,
1416
+ ..._KaguraClient.bindingScopeArgs(options)
1417
+ });
1418
+ return _KaguraClient.expectEnvelope(result, "binding", "bind_agent_context");
1419
+ }
1420
+ /** List an agent's context bindings (owner/admin only). */
1421
+ async listAgentBindings(agentId) {
1422
+ const result = await this.callToolChecked("list_agent_bindings", { agent_id: agentId });
1423
+ const bindings = result.bindings;
1424
+ return Array.isArray(bindings) ? bindings : [];
1425
+ }
1426
+ /**
1427
+ * Update a binding's scoping fields (owner/admin only).
1428
+ *
1429
+ * `context_id` is immutable — {@link unbindAgentContext} and re-
1430
+ * {@link bindAgentContext} to re-target. Changes are audited with
1431
+ * old→new values.
1432
+ *
1433
+ * @throws Error when no scoping field is provided (the call would be
1434
+ * an empty no-op request).
1435
+ */
1436
+ async updateAgentBinding(options) {
1437
+ const changes = _KaguraClient.bindingScopeArgs(options);
1438
+ if (Object.keys(changes).length === 0) {
1439
+ throw new Error(
1440
+ "updateAgentBinding requires at least one of canRead, writePolicy, or isDefault"
1441
+ );
1442
+ }
1443
+ const result = await this.callToolChecked("update_agent_binding", {
1444
+ agent_id: options.agentId,
1445
+ binding_id: options.bindingId,
1446
+ ...changes
1447
+ });
1448
+ return _KaguraClient.expectEnvelope(result, "binding", "update_agent_binding");
1449
+ }
1450
+ /**
1451
+ * Delete a binding — the agent loses that context (owner/admin only).
1452
+ * Returns true once the server confirms deletion.
1453
+ *
1454
+ * Under `enforcement_mode="enforce"` the agent's requests against the
1455
+ * unbound context are denied afterwards (uniform `context_not_found`).
1456
+ */
1457
+ async unbindAgentContext(options) {
1458
+ const result = await this.callToolChecked("unbind_agent_context", {
1459
+ agent_id: options.agentId,
1460
+ binding_id: options.bindingId
1461
+ });
1462
+ return result.deleted === void 0 ? true : Boolean(result.deleted);
1463
+ }
1464
+ /**
1465
+ * Rehydrate an agent's cognitive state in one session-start call.
1466
+ *
1467
+ * Calls the `get_agent_bootstrap` MCP tool (server v0.49.0+, RFC-0002
1468
+ * P0-3, memory-cloud #1276). The server composes existing primitives —
1469
+ * context guide + pinned memories ({@link loadPinned}) + a trusted-only
1470
+ * {@link recall} (only when `query` is supplied) + upcoming time
1471
+ * memories ({@link recallUpcoming}) + the agent-state lane
1472
+ * ({@link getState}) — with bounds, ordering, and trust filtering
1473
+ * inherited from those standalone tools, not re-specified.
1474
+ *
1475
+ * Components are **fail-soft**: a failing component reports
1476
+ * `{"status": "error", ...}` under `components` while the rest still
1477
+ * return, with the top-level `degraded` flag set. Identity and
1478
+ * authorization failures are total and throw instead.
1479
+ *
1480
+ * The REST companion (`POST /api/v1/agents/{agent_id}/bootstrap`) is
1481
+ * available via `AgentsClient` for API-key-only callers such as
1482
+ * agent-bound member keys.
1483
+ *
1484
+ * @throws KaguraNotFoundError when the agent or context is not found
1485
+ * (uniform 404 — nonexistent and not-yours are indistinguishable by
1486
+ * design).
1487
+ * @throws KaguraError on invalid arguments or other server-side error.
1488
+ */
1489
+ async getAgentBootstrap(options) {
1490
+ const result = await this.callToolChecked("get_agent_bootstrap", {
1491
+ agent_id: options.agentId,
1492
+ ...buildBootstrapPayload(options)
1493
+ });
1494
+ return result;
1495
+ }
1221
1496
  /** List available contexts. */
1222
1497
  async listContexts() {
1223
1498
  return this.callToolChecked("list_contexts", {});
@@ -1681,12 +1956,7 @@ var KaguraClient = class _KaguraClient {
1681
1956
  context_id: options.contextId,
1682
1957
  report_id: options.reportId
1683
1958
  });
1684
- const report = result.report;
1685
- if (typeof report !== "object" || report === null || Array.isArray(report)) {
1686
- throw new KaguraConnectionError(
1687
- "Unexpected get_sleep_report response: missing 'report' envelope."
1688
- );
1689
- }
1959
+ const report = _KaguraClient.expectEnvelope(result, "report", "get_sleep_report");
1690
1960
  return {
1691
1961
  ...report,
1692
1962
  actions: result.actions,
@@ -1978,19 +2248,6 @@ var KaguraRestClient = class {
1978
2248
  }
1979
2249
  };
1980
2250
 
1981
- // src/filesClient.ts
1982
- import { createHash } from "crypto";
1983
- import { readFile } from "fs/promises";
1984
- import * as path4 from "path";
1985
-
1986
- // src/auth/types.ts
1987
- var SOURCE_LABEL = {
1988
- explicit: "explicit apiKey argument",
1989
- env: "KAGURA_API_KEY env",
1990
- config: ".kagura.json",
1991
- oauth: "OAuth profile (~/.kagura/credentials.json)"
1992
- };
1993
-
1994
2251
  // src/uuid.ts
1995
2252
  var CANONICAL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1996
2253
  function parseUuid(value) {
@@ -2022,6 +2279,42 @@ function isUuid(value) {
2022
2279
  }
2023
2280
  }
2024
2281
 
2282
+ // src/agentsClient.ts
2283
+ var AgentsClient = class extends KaguraRestClient {
2284
+ /**
2285
+ * Rehydrate an agent's cognitive state at session start.
2286
+ *
2287
+ * REST companion to `KaguraClient.getAgentBootstrap` — same options,
2288
+ * same composed envelope, same fail-soft component semantics (see that
2289
+ * method for the full contract).
2290
+ */
2291
+ async bootstrap(options) {
2292
+ let agentId;
2293
+ try {
2294
+ agentId = parseUuid(options.agentId);
2295
+ } catch {
2296
+ throw new Error(`agentId must be a UUID, got ${JSON.stringify(options.agentId)}`);
2297
+ }
2298
+ const resp = await this.request("POST", `/api/v1/agents/${agentId}/bootstrap`, {
2299
+ json: buildBootstrapPayload(options)
2300
+ });
2301
+ return this.json(resp);
2302
+ }
2303
+ };
2304
+
2305
+ // src/filesClient.ts
2306
+ import { createHash } from "crypto";
2307
+ import { readFile } from "fs/promises";
2308
+ import * as path4 from "path";
2309
+
2310
+ // src/auth/types.ts
2311
+ var SOURCE_LABEL = {
2312
+ explicit: "explicit apiKey argument",
2313
+ env: "KAGURA_API_KEY env",
2314
+ config: ".kagura.json",
2315
+ oauth: "OAuth profile (~/.kagura/credentials.json)"
2316
+ };
2317
+
2025
2318
  // src/filesClient.ts
2026
2319
  var CONTENT_TYPE_BY_EXT = {
2027
2320
  ".txt": "text/plain",
@@ -2865,6 +3158,7 @@ function isMintShape(payload) {
2865
3158
  return typeof rec.id === "number" && typeof rec.name === "string" && typeof rec.key_prefix === "string";
2866
3159
  }
2867
3160
  export {
3161
+ AgentsClient,
2868
3162
  DEFAULT_MCP_URL,
2869
3163
  DEFAULT_REST_BASE_URL,
2870
3164
  FilesClient,